Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
6dbd0ff
fix(exchange): decouple Parallel Batches slider from Graph $batch size
NityamPareek Nov 17, 2026
ac3912b
refactor: separate graph_batch_size from parallel_batches in ScanConfig
NityamPareek Nov 17, 2026
7389a97
Merge pull request #220 from google/eo-decouple-parallel-batches
NityamPareek Nov 17, 2026
be96699
feat(exchange): Recoverable Items estimator - $count mode
NityamPareek Nov 17, 2026
cf1e880
chore(exchange): trim Recoverable Items constant comments
NityamPareek Nov 17, 2026
7d30816
refactor(exchange): size Recoverable Items work by concurrency like o…
NityamPareek Nov 17, 2026
5da6ba3
Merge pull request #221 from google/eo-recoverable-items-count-mode
NityamPareek Nov 17, 2026
362edc9
feat(exchange): Recoverable Items estimator - folder hierarchy mode
NityamPareek Nov 17, 2026
91bd0a4
refactor(exchange): mirror primary mailbox estimators for Recoverable…
NityamPareek Nov 17, 2026
b4aa3ad
refactor(exchange): single IPM.Note $count request for Recoverable Items
NityamPareek Nov 17, 2026
1acd547
Merge pull request #222 from google/eo-recoverable-items-hierarchy-mode
NityamPareek Nov 17, 2026
451c95b
feat(exchange): Recoverable Items scan phase, progress and logging
NityamPareek Nov 17, 2026
1ced62f
refactor(exchange): rename to Recoverable Emails, run after primary s…
NityamPareek Nov 17, 2026
f31253f
Merge pull request #223 from google/eo-recoverable-items-scan
NityamPareek Nov 17, 2026
f48db32
feat(exchange): Recoverable Emails columns in the user report and CSV…
NityamPareek Nov 17, 2026
83561c0
refactor(exchange): single Recoverable Email Count column, integrated…
NityamPareek Nov 17, 2026
89cc2ea
Merge pull request #224 from google/eo-recoverable-items-csv
NityamPareek Nov 17, 2026
69241c4
feat(exchange): Recoverable Emails in ETAs, batches and the dashboard
NityamPareek Nov 17, 2026
3df79e1
fix(exchange): use the scales icon for Recoverable Emails
NityamPareek Nov 17, 2026
d30db48
docs: drop Recoverable Emails ETA note from README
NityamPareek Nov 17, 2026
12ab816
Merge pull request #225 from google/eo-recoverable-items-eta
NityamPareek Nov 17, 2026
9314584
fix(connectors): retry 429/5xx $batch sub-responses and log every fai…
NityamPareek Nov 18, 2026
bef670e
feat(exchange): always log partial failures in run_batch_scan summary…
NityamPareek Nov 18, 2026
2d405fd
refactor(exchange): report failed folders in run_batch_scan summary l…
NityamPareek Nov 18, 2026
9a9a922
Merge pull request #226 from google/eo-url-invoker-failure-logging
NityamPareek Nov 18, 2026
d9148b2
fix(exchange): load Encrypted Email Count from the input CSV
NityamPareek Nov 20, 2026
3fd4377
Merge pull request #227 from google/eo-fix-encrypted-csv-load
NityamPareek Nov 20, 2026
6a8b6c6
feat(exchange): count meeting, secure and resent emails in Recoverabl…
NityamPareek Nov 20, 2026
b2e3a24
Merge pull request #228 from google/eo-recoverable-item-types
NityamPareek Nov 20, 2026
7ecb79e
refactor(exchange): rename Recoverable Emails to Recoverable Items
NityamPareek Nov 26, 2026
7710151
Merge pull request #229 from google/eo-rename-recoverable-items
NityamPareek Nov 26, 2026
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ In your new app, go to **API permissions > Add a permission > Microsoft Graph >
* `Contacts.Read` (To count contacts)
* `Calendars.Read` (To count calendar events)
* `MailboxFolder.Read.All` (To count emails in in-place archives)
* `MailboxItem.Read.All` (To count emails in Recoverable Items / litigation hold folders; only needed when **Recoverable Items** is selected)
* `MailboxSettings.Read` (To distinguish user and shared mailboxes)

#### Chat & Teams Planner Specific Permissions
Expand Down Expand Up @@ -249,6 +250,7 @@ The **Concurrency** value (under **"Show Advanced Settings"**) controls how many
#### 2. Advanced Settings (Exchange)
Click **"Show Advanced Settings"** to tune the performance:
* **Sources**: Check/Uncheck Emails, Contacts, Calendars, In-Place Archives and Group Mails to define what you want to scan.
* **Recoverable Items**: Counts emails in the Recoverable Items folders that hold litigation-hold content (Deletions, Purges, DiscoveryHolds and Versions) of user and shared mailboxes. Counted item types: `IPM.Note`, `IPM.Note.Secure`, `IPM.Note.Secure.Sign`, `IPM.Resend` and the meeting messages `IPM.Schedule.Meeting.Request`, `IPM.Schedule.Meeting.Canceled`, `IPM.Schedule.Meeting.Resp.Pos`, `IPM.Schedule.Meeting.Resp.Neg` and `IPM.Schedule.Meeting.Resp.Tent`. Not applied to In-Place Archives or Group Mailboxes. Off by default; requires `MailboxItem.Read.All`.
* **Concurrency**: Controls how many parallel threads the tool runs.
* **Recommendation**: For a standard machine (8 Core, 16GB+ RAM), set this to **30**. Setting it too high may cause more frequent throttling errors from Microsoft and consume more resources from your system. See [Recommended Concurrency Settings](#recommended-concurrency-settings).
* **Max Batches**: Defines the upper cap for the number of batches to be generated by the migration plan. In case of very large corpuses, it might not be possible to adhere to this number.
Expand Down Expand Up @@ -352,6 +354,7 @@ Once started, you will see a real-time progress screen:
The top cards display the total scope of the migration:
* **Users**: Total distinct users identified/scanned.
* **Emails / Events / Contacts / In-Place Archives / Group Mailboxes**: The aggregate sum of items across all users.
* **Recoverable Items**: Shown when the Recoverable Items source is selected. The total of emails (see **Recoverable Items** under Sources for the counted item types) in the Recoverable Items folders of user and shared mailboxes, also included in **Total Items**.

The CSV report would include additional details at the more granular site level.

Expand Down Expand Up @@ -416,6 +419,7 @@ Once the scan completes, the tool creates a folder in the `/outputs` directory n

It contains:
1. **User Report (`user_report.csv`)**: A master list of all users, their item counts, and their suggested Batch (e.g., "Batch 1").
* When **Recoverable Items** is selected, the report has a `Recoverable Items Count` column: the total emails (the item types listed under **Recoverable Items** in Sources) across the Deletions, Purges, DiscoveryHolds and Versions folders. A folder that couldn't be scanned counts as `0` (see the failure sections in the logs). Like the other count columns, it can be fed back in a CSV upload to skip re-scanning; older reports without this column simply trigger a scan for it.
2. **Batch Files (`suggested batches/`)**: Individual CSV files (Batch1.csv, Batch2.csv) ready for use in migration tool. Headers are formatted as **Source Exchange Email**.

Execution logs are written live to `/logs/exchange_<timestamp>.log`, with each line flushed to disk as soon as it's logged, so the log survives crashes and force-quits. A new log file is created each time **Start scan** is clicked. The log contains detailed execution steps, system resource metrics (CPU/RAM), API errors, and full tracebacks of any unhandled exceptions.
Expand Down
4 changes: 2 additions & 2 deletions estimators/eo_email_estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def get_email_count(self, user_ids: List[str], failures: List[Dict[str, str]]) -
folder_api = "users/{userId}/mailFolders?$select=id,displayName,childFolderCount,totalItemCount&$top=999"

top_level_folders: Dict[str, List[Dict[str, Any]]] = {} # Map of User to top level folder list.
user_batches = create_batches(folder_api, user_id_maps, self.config.parallel_batches, True)
user_batches = create_batches(folder_api, user_id_maps, self.config.graph_batch_size, True)

futures_map: Dict[int, Future[List[Dict[str, Any]]]] = {}
batch_id_to_batch_map: Dict[int, List[Dict[str, Any]]] = {}
Expand Down Expand Up @@ -110,7 +110,7 @@ def get_email_count(self, user_ids: List[str], failures: List[Dict[str, str]]) -
})

while pending_next_items and not self.is_hard_stop_requested():
batches = create_batches("{url}", pending_next_items, self.config.parallel_batches, True)
batches = create_batches("{url}", pending_next_items, self.config.graph_batch_size, True)

next_futures_map: Dict[int, Future[List[Dict[str, Any]]]] = {}
next_batch_id_to_batch_map: Dict[int, List[Dict[str, Any]]] = {}
Expand Down
10 changes: 5 additions & 5 deletions estimators/eo_group_mailbox_estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def _get_group_ids_for_tenant(self) -> List:
# We use a dummy placeholder to create a batch request.
# This allows us to reuse the batching and pagination utilities.
placeholders = [{"tenant_query": "all_groups"}]
user_batches = create_batches(graph_user_endpoint, placeholders, self.config.parallel_batches, True)
user_batches = create_batches(graph_user_endpoint, placeholders, self.config.graph_batch_size, True)

futures_map: Dict[int, Future[List[Dict[str, Any]]]] = {}
batch_id_to_batch_map: Dict[int, List[Dict[str, Any]]] = {}
Expand Down Expand Up @@ -124,7 +124,7 @@ def _get_group_ids_for_tenant(self) -> List:
self.logger("[WARNING] No response found for group API.")

while pending_next_items and not self.is_hard_stop_requested():
batches = create_batches("{url}", pending_next_items, self.config.parallel_batches, True)
batches = create_batches("{url}", pending_next_items, self.config.graph_batch_size, True)

next_futures_map: Dict[int, Future[List[Dict[str, Any]]]] = {}
next_batch_id_to_batch_map: Dict[int, List[Dict[str, Any]]] = {}
Expand Down Expand Up @@ -167,7 +167,7 @@ def _get_thread_ids_for_groups(self, group_ids: List[str], failures: List[Dict[s
thread_api = "groups/{group_id}/threads?$select=id&$top=10"

group_id_maps = [{"group_id": group_id} for group_id in group_ids]
group_batches = create_batches(thread_api, group_id_maps, self.config.parallel_batches, True)
group_batches = create_batches(thread_api, group_id_maps, self.config.graph_batch_size, True)

futures_map: Dict[int, Future[List[Dict[str, Any]]]] = {}
batch_id_to_batch_map: Dict[int, List[Dict[str, Any]]] = {}
Expand Down Expand Up @@ -219,7 +219,7 @@ def _get_thread_ids_for_groups(self, group_ids: List[str], failures: List[Dict[s
})

while pending_next_items and not self.is_hard_stop_requested():
batches = create_batches("{url}", pending_next_items, self.config.parallel_batches, True)
batches = create_batches("{url}", pending_next_items, self.config.graph_batch_size, True)

next_futures_map: Dict[int, Future[List[Dict[str, Any]]]] = {}
next_batch_id_to_batch_map: Dict[int, List[Dict[str, Any]]] = {}
Expand Down Expand Up @@ -281,7 +281,7 @@ def _get_post_count_for_threads(self, group_id_to_thread_ids: Dict[str, List[str
post_api = "groups/{group_id}/threads/{thread_id}/posts?$count=true&$select=id&$top=1"

# Optimize Batch Size
optimal_batch_size = min(self.config.parallel_batches, min(20, len(group_id_to_thread_ids)))
optimal_batch_size = min(self.config.graph_batch_size, min(20, len(group_id_to_thread_ids)))
batches = create_batches(post_api, flattened_items, optimal_batch_size, True)

# Refine batches to ensure no duplicate groups in any batch
Expand Down
6 changes: 3 additions & 3 deletions estimators/eo_in_place_archive_estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def get_in_place_archive_count(self, user_ids: List[str], failures: List[Dict[st
exchange_api = "users/{userId}/settings/exchange"

user_id_maps = [{"userId": user_id} for user_id in user_ids]
user_batches = create_batches(exchange_api, user_id_maps, self.config.parallel_batches, True)
user_batches = create_batches(exchange_api, user_id_maps, self.config.graph_batch_size, True)

futures_map: Dict[int, Future[List[Dict[str, Any]]]] = {}
batch_id_to_batch_map: Dict[int, List[Dict[str, Any]]] = {}
Expand Down Expand Up @@ -167,7 +167,7 @@ def parse_and_count_in_place_archive_mail_box(self, mail_box_ids: List[str], fai
folder_api = "admin/exchange/mailboxes/{mailboxId}/folders?$select=id,parentMailboxUrl,displayName,childFolderCount,totalItemCount&$top=999"

top_level_folders: Dict[str, List[Dict[str, Any]]] = {} # Map of Mail box to top level folder list.
mail_box_batches = create_batches(folder_api, mail_box_id_maps, self.config.parallel_batches, True)
mail_box_batches = create_batches(folder_api, mail_box_id_maps, self.config.graph_batch_size, True)

futures_map: Dict[int, Future[List[Dict[str, Any]]]] = {}
batch_id_to_batch_map: Dict[int, List[Dict[str, Any]]] = {}
Expand Down Expand Up @@ -223,7 +223,7 @@ def parse_and_count_in_place_archive_mail_box(self, mail_box_ids: List[str], fai
})

while pending_next_items and not self.is_hard_stop_requested():
batches = create_batches("{url}", pending_next_items, self.config.parallel_batches, True)
batches = create_batches("{url}", pending_next_items, self.config.graph_batch_size, True)

next_futures_map: Dict[int, Future[List[Dict[str, Any]]]] = {}
next_batch_id_to_batch_map: Dict[int, List[Dict[str, Any]]] = {}
Expand Down
199 changes: 199 additions & 0 deletions estimators/eo_recoverable_items_estimator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
from concurrent.futures import Future, ThreadPoolExecutor
import threading
from typing import Any, Callable, Dict, List, Optional, Tuple
import urllib.parse

from estimators.estimator import Estimator
from util.connectors import UrlInvoker
from util.constants import (
GRAPH_BASE_URL,
RECOVERABLE_ITEMS_FOLDERS,
RECOVERABLE_ITEMS_ITEM_TYPES,
RECOVERABLE_ITEMS_MAX_REQUESTS_PER_MAILBOX_PER_BATCH,
)
from util.enums import FailureType
from util.thread_safe_ds import AtomicInt
from util.utils import ScanConfig, create_batches, get_batch_responses_map

# The admin API rejects `type in (...)`, so the item types are or-ed together.
ITEM_TYPE_FILTER = " or ".join(f"type eq '{item_type}'" for item_type in RECOVERABLE_ITEMS_ITEM_TYPES)
FOLDER_COUNT_API = (
"admin/exchange/mailboxes/{mailbox}/folders/{folder}/items?$filter="
+ urllib.parse.quote(ITEM_TYPE_FILTER, safe="")
+ "&$count=true&$top=1&$select=id"
)


class EORecoverableItemsEstimator(Estimator):
"""Counts emails in the Recoverable Items folders of primary mailboxes.

Mailboxes are identified by UPN. These folders never contain subfolders, so
each folder needs a single server-side $count request over the item types in
RECOVERABLE_ITEMS_ITEM_TYPES, whatever the Recursive setting (totalItemCount
can't be filtered by item type).

The folders are requested in sequential rounds of
RECOVERABLE_ITEMS_MAX_REQUESTS_PER_MAILBOX_PER_BATCH folders, so a mailbox
never has more than that many requests in flight. Callers must not pass the
same mailbox to two concurrent calls.
"""

def __init__(
self,
config: ScanConfig,
url_invoker: UrlInvoker,
logger: Optional[Callable[[str], None]] = None,
stop_event: Optional[threading.Event] = None
):
super().__init__()
self.config = config
self.url_invoker = url_invoker
self.logger = logger
self.stop_event = stop_event
self.archive_executor = ThreadPoolExecutor(max_workers=self.config.concurrency)
self.folder_totals: Dict[str, AtomicInt] = {
label: AtomicInt(0) for label in RECOVERABLE_ITEMS_FOLDERS
}

def calculate_migration_eta(self, data: Dict[str, Any]) -> float:
return super().calculate_migration_eta(data)

def get_resource_type(self):
return "EO_RECOVERABLE_ITEMS"

def get_migration_type(self):
return "EXCHANGE_ONLINE"

def is_hard_stop_requested(self):
if self.stop_event is None:
return False
return self.stop_event.is_set()

def calculate_resource_count(self, data: Dict[str, Any], failures: List[Dict[str, Any]]) -> Dict[str, int]:
"""@returns Map of UPN to its total Recoverable Items count."""
folder_counts = self.get_folder_counts(data["user_ids"], failures)
return {upn: sum(counts.values()) for upn, counts in folder_counts.items()}

def get_folder_counts(self, mailboxes: List[str], failures: List[Dict[str, Any]]) -> Dict[str, Dict[str, int]]:
"""@returns Map of UPN to {folder label: count}. Failed or unscanned folders count 0."""
if not mailboxes or None in mailboxes:
raise Exception("Invalid user ids provided. Please check the list and ensure all the IDs are non-null.")

# De-duplicate case-insensitively so a mailbox is only requested once.
unique_mailboxes: Dict[str, str] = {}
for mailbox in mailboxes:
unique_mailboxes.setdefault(mailbox.strip().lower(), mailbox.strip())

counts: Dict[str, Dict[str, int]] = {
key: {label: 0 for label in RECOVERABLE_ITEMS_FOLDERS} for key in unique_mailboxes
}
folder_failures: Dict[str, List[Dict[str, Any]]] = {key: [] for key in unique_mailboxes}

labels = list(RECOVERABLE_ITEMS_FOLDERS)
for start in range(0, len(labels), RECOVERABLE_ITEMS_MAX_REQUESTS_PER_MAILBOX_PER_BATCH):
if self.is_hard_stop_requested():
break
round_labels = labels[start:start + RECOVERABLE_ITEMS_MAX_REQUESTS_PER_MAILBOX_PER_BATCH]
self._count_round(unique_mailboxes, round_labels, counts, folder_failures)

for key, mailbox_failures in folder_failures.items():
if not mailbox_failures:
continue
if len(mailbox_failures) == len(RECOVERABLE_ITEMS_FOLDERS):
first = mailbox_failures[0]
failures.append({
"userId": unique_mailboxes[key],
"isPartial": False,
"type": first["type"],
"statusCode": first["statusCode"],
"message": f"All Recoverable Items folders failed. First error: {first['message']}"
})
else:
failures.extend(mailbox_failures)

for folder_counts in counts.values():
for label, count in folder_counts.items():
self.folder_totals[label].increment(count)

return {mailbox: dict(counts[mailbox.strip().lower()]) for mailbox in mailboxes}

def get_folder_totals(self) -> Dict[str, int]:
"""@returns Aggregate count per folder label across all calls."""
return {label: total.get_value() for label, total in self.folder_totals.items()}

def _count_round(
self,
unique_mailboxes: Dict[str, str],
round_labels: List[str],
counts: Dict[str, Dict[str, int]],
folder_failures: Dict[str, List[Dict[str, Any]]]
) -> None:
# Map each request's identification headers back to (mailbox key, folder label).
placeholder_to_target: Dict[Tuple[str, str], Tuple[str, str]] = {}
placeholders = []
for key, mailbox in unique_mailboxes.items():
encoded_mailbox = urllib.parse.quote(mailbox, safe="@")
for label in round_labels:
well_known_name = RECOVERABLE_ITEMS_FOLDERS[label]
placeholders.append({"mailbox": encoded_mailbox, "folder": well_known_name})
placeholder_to_target[(encoded_mailbox, well_known_name)] = (key, label)

batches = create_batches(FOLDER_COUNT_API, placeholders, self.config.graph_batch_size, True)

futures_map: Dict[int, Future[List[Dict[str, Any]]]] = {}
batch_id_to_batch_map: Dict[int, List[Dict[str, Any]]] = {}
idx = 0
for batch in batches:
futures_map[idx] = self.archive_executor.submit(self.url_invoker.invoke, GRAPH_BASE_URL, batch, self.logger, self.stop_event, self.get_resource_type())
batch_id_to_batch_map[idx] = batch
idx += 1

for batch_id, future in futures_map.items():
try:
responses = future.result()
except Exception as e:
if self.logger:
self.logger(f"Error in {self.get_resource_type()}: {e}")
responses = []

batch_responses_map = get_batch_responses_map(responses, self.logger)
for req in batch_id_to_batch_map[batch_id]:
key, label = placeholder_to_target[(req["headers"]["mailbox"], req["headers"]["folder"])]
count, failure = self._parse_response(batch_responses_map.get(req["id"]), unique_mailboxes[key], label)
if failure is not None:
folder_failures[key].append(failure)
else:
counts[key][label] = count

def _parse_response(
self,
response: Optional[Dict[str, Any]],
mailbox: str,
label: str
) -> Tuple[int, Optional[Dict[str, Any]]]:
"""@returns (count, None) on success, or (0, failure) on any error."""
def failure(failure_type: FailureType, status_code: Optional[int], message: str):
return 0, {
"userId": mailbox,
"folderId": label,
"isPartial": True,
"type": failure_type,
"statusCode": status_code,
"message": message
}

if not response:
return failure(FailureType.NOT_FOUND, None, "No response found for the request")

status = response.get("status")
body = response.get("body") or {}
if not isinstance(status, int) or status < 200 or status >= 300:
error_message = body.get("error", {}).get("message") if isinstance(body, dict) else None
return failure(FailureType.FAILURE_STATUS_CODE_ERROR, status, error_message or "Unknown error")

if "@odata.count" not in body:
return failure(FailureType.INVALID_DATA, status, "No @odata.count in response")
try:
return int(body["@odata.count"]), None
except (ValueError, TypeError):
return failure(FailureType.INVALID_DATA, status, f"Invalid @odata.count '{body['@odata.count']}'")
Loading
Loading