Skip to content

API Reference parrot_tools.o365.delta

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot_tools.o365.delta

View source

Microsoft Graph drive delta support for AI-Parrot O365 tools.

This module owns the transport half of drive change tracking:

  • Typed, O365-owned models for delta items and delta pages (:class:DeltaItem, :class:DeltaPage, :class:DeltaEnumeration).
  • A shared, authenticated drive-level enumeration helper (:class:DriveDeltaHelper) that follows @odata.nextLink continuations until the final @odata.deltaLink is reached.

Microsoft Graph v1.0 semantics implemented here:

  • GET /drives/{drive-id}/items/root/delta starts a full enumeration; passing a previously stored deltaLink resumes from that cursor.
  • Responses carry either @odata.nextLink (more pages) or @odata.deltaLink (final cursor for the next round).
  • Deleted items are returned with the deleted facet (tombstones); they are surfaced as :attr:DeltaItem.deleted rather than dropped.
  • 410 Gone invalidates the supplied cursor and requires restarting the enumeration from scratch (a rescan). A rescan is explicitly flagged so a consumer never mistakes a partial listing for mass deletion.
  • 429 / 5xx responses are retried with bounded backoff that honours the Retry-After header in full.

Retry layering: the installed msgraph/Kiota stack ships its own RetryHandler middleware (3 retries by default, also honouring Retry-After). The bound configured here therefore counts this layer's attempts, not raw HTTP requests — the two multiply. Set the SDK's RetryHandlerOption if a single owner of retry policy is required.

Security: continuation links are opaque, but they are still URLs that this process would send an access token to, and DeltaRequestBuilder.with_url() replaces the entire URL rather than just its query string. Every nextLink / deltaLink — including a caller-supplied stored cursor — is therefore validated before the request is issued: it must sit on a configured Microsoft Graph origin and address the delta endpoint of the drive being enumerated. A poisoned feed can neither exfiltrate credentials to a foreign host nor redirect the authenticated request at another resource.

Scope: this helper is deliberately transport-only. It never commits a delta cursor, never downloads file content and never ingests documents — those are the consumer's responsibility.

Reference: https://learn.microsoft.com/en-us/graph/api/driveitem-delta?view=graph-rest-1.0

Attribute DEFAULT_GRAPH_ORIGINS

Type: Tuple[str, ...]

Attribute DEFAULT_MAX_ANCESTRY_DEPTH

Type: int

Attribute DEFAULT_MAX_PAGES

Type: int

Attribute DEFAULT_MAX_RETRIES

Type: int

Attribute DEFAULT_MAX_RETRY_AFTER

Type: float

Class DeltaEnumeration

Aggregated result of following a delta feed to its final cursor.

delta_link is the cursor the consumer may commit — this helper never commits it. When :attr:complete is False the enumeration stopped early (page bound reached) and the previous cursor must be retained for an idempotent replay.

Fields:

Field Type Default Description
drive_id str Drive that was enumerated.
items List[DeltaItem] Changed items, de-duplicated by item_id with the latest occurrence winning, in first-seen order.
delta_link Optional[str] None Final cursor, or None if enumeration was truncated.
pages_fetched int 0 Number of delta pages retrieved.
complete bool False True when the final delta link was reached.
reset_performed bool False True when a 410 Gone invalidated the supplied cursor and the drive was re-enumerated from scratch. The listing is then a full rescan, NOT a set of deletions.
full_enumeration bool False True when enumeration started without a stored cursor.
folder_path Optional[str] None Drive-relative folder path filter applied locally, if any. Graph omits parentReference.path from delta responses, so this filter is best-effort — see unresolved_parent / folder_filter_reliable.
folder_id Optional[str] None Stable folder item id filter applied locally, if any. Exact, but matches direct children only.
filtered_out int 0 Items positively excluded by the local folder filter.
skipped_entries int 0 Entries dropped because Graph reported no stable item id. Non-zero means this enumeration is incomplete: the cursor should not be committed without investigating.
unresolved_parent int 0 Items KEPT because their folder membership could not be decided (Graph reported neither a usable parent path nor a parent id). Non-zero means the folder filter did not fully apply.

Attributes:

Attribute Type Description
deleted_items List[DeltaItem] Tombstones present in this enumeration.
changed_items List[DeltaItem] Non-deleted items present in this enumeration.
folder_filter_reliable bool True when every returned item's folder membership was decidable. False means at least one item was kept without being able to confirm it belongs to the requested folder, so the caller must re-check membership by item id before treating the result as folder-scoped.

Class DeltaItem

A single drive item reported by a Microsoft Graph delta page.

Stable identity is (drive_id, item_id); name/parent_path may change across rounds when the item is renamed or moved, which is exactly how a consumer detects those events.

Fields:

Field Type Default Description
drive_id str Stable Graph drive identifier.
item_id str Stable Graph driveItem identifier.
name Optional[str] None Item name at the time of this change.
deleted bool False True when Graph reported the item with the deleted facet.
is_folder bool False True when the item is a folder, not a file.
is_root bool False True when Graph reported the drive root facet. The root has no parent, so it must not be mistaken for an item whose membership could not be resolved.
parent_id Optional[str] None Identifier of the containing folder.
parent_path Optional[str] None Drive-relative parent path (Graph's '/drive/root:' prefix removed). Usually None: the Graph v1.0 delta API documents that parentReference omits 'path'. Track items by item_id/parent_id.
size Optional[int] None Item size in bytes.
etag Optional[str] None Graph eTag, if reported.
ctag Optional[str] None Graph cTag, if reported.
web_url Optional[str] None Browser URL, if reported.
last_modified Optional[datetime] None Last modification timestamp, if reported.
content_hashes Dict[str, str] File content hashes reported by Graph (quickXor, sha256, ...).

Attributes:

Attribute Type Description
path Optional[str] Drive-relative path of the item, when the parent path is known.

Class DeltaLinkValidationError

Raised when a continuation link does not point at the Graph origin.

The request is rejected before it is issued, so the access token is never forwarded to the offending host.

Class DeltaPage

One page of a Microsoft Graph delta response.

Fields:

Field Type Default Description
drive_id str Drive the page was enumerated from.
items List[DeltaItem] Items reported on this page.
next_link Optional[str] None Opaque '@odata.nextLink' continuation, when more pages follow.
delta_link Optional[str] None Opaque '@odata.deltaLink' final cursor, when enumeration ended.
skipped_entries int 0 Entries on this page that carried no stable item id and could not be reconciled, so were dropped.

Attributes:

Attribute Type Description
is_final bool True when this page carries the final delta cursor.

Class DeltaResetRequiredError

Raised internally when Graph answers 410 Gone for a delta cursor.

:meth:DriveDeltaHelper.enumerate handles this by restarting a full rescan; it only escapes from :meth:DriveDeltaHelper.fetch_page, where the caller owns the reset decision.

Parameter Type Default Description
drive_id str Drive whose delta cursor was invalidated.

Class DeltaRetryExhaustedError

Raised when throttling/transient retries hit their bound.

Parameter Type Default Description
attempts int Number of attempts performed before giving up.
last_error BaseException The final underlying error.
reason str 'retries exhausted' Why the helper stopped — distinguishes a genuinely exhausted retry budget from a throttle longer than max_retry_after, which a caller may want to defer on rather than treat as a failure.

Class DriveDeltaHelper

Authenticated, drive-level Microsoft Graph delta enumeration helper.

The helper is shared by the SharePoint and OneDrive delta tools. It takes an already-authenticated client (anything exposing graph_client) and walks the delta feed for one drive.

It is transport-only: it does not persist cursors, does not download file content and does not ingest documents.

Parameter Type Default Description
allowed_origins Sequence[str] DEFAULT_GRAPH_ORIGINS Graph origins credentials may be forwarded to.
max_retries int DEFAULT_MAX_RETRIES Bound on retries per page for throttling/transient failures. 0 disables retrying.
initial_backoff float DEFAULT_INITIAL_BACKOFF First backoff delay, in seconds.
max_backoff float DEFAULT_MAX_BACKOFF Upper bound for a self-computed backoff delay, in seconds. It never truncates a server-supplied Retry-After.
max_retry_after float DEFAULT_MAX_RETRY_AFTER Longest server-requested Retry-After to wait out. A larger interval abandons the round instead of retrying early.
max_pages int DEFAULT_MAX_PAGES Hard bound on pages followed in one enumeration.
sleep Optional[Callable[[float], Awaitable[None]]] None Awaitable sleep function; injectable for deterministic tests. Defaults to :func:asyncio.sleep.
logger_instance Optional[Any] None Optional logger override.

Method DriveDeltaHelper.validate_link

Validate a continuation link before it is dereferenced.

validate_link(link: str, drive_id: str) -> str

Parameter Type Default Description
link str Opaque nextLink/deltaLink value.
drive_id str Drive the enumeration is confined to. The link must address that drive's delta endpoint, not merely a trusted Graph origin.

Returns: str — The validated link.

Raises:

  • DeltaLinkValidationError — If the link is not a trusted Graph delta URL for drive_id.

Method DriveDeltaHelper.fetch_page

Fetch a single delta page, with bounded retry on throttling.

fetch_page(client: Any, drive_id: str, *, link: Optional[str] = None) -> DeltaPage

Parameter Type Default Description
client Any Authenticated client exposing graph_client.
drive_id str Target drive identifier.
link Optional[str] None Opaque nextLink/deltaLink to resume from. When None a fresh enumeration of the drive is started.

Returns: DeltaPage — The typed delta page.

Raises:

  • DeltaLinkValidationError — If link is not this drive's delta endpoint on a trusted Graph origin. Raised before any request is issued.
  • DeltaResetRequiredError — If Graph answered 410 Gone.
  • DeltaRetryExhaustedError — If retries hit their bound.

Method DriveDeltaHelper.enumerate

Follow a drive's delta feed until the final cursor is reached.

On 410 Gone the supplied cursor is discarded and the drive is re-enumerated from scratch exactly once; the result is flagged with :attr:DeltaEnumeration.reset_performed so the consumer treats it as a full rescan rather than as mass deletion.

enumerate(client: Any, drive_id: str, *, delta_link: Optional[str] = None, folder_path: Optional[str] = None, folder_id: Optional[str] = None, resolve_ancestry: bool = True, max_pages: Optional[int] = None) -> DeltaEnumeration

Parameter Type Default Description
client Any Authenticated client exposing graph_client.
drive_id str Target drive identifier.
delta_link Optional[str] None Previously committed cursor to resume from, if any.
folder_path Optional[str] None Drive-relative folder path to filter items to, applied locally because Graph delta is drive-level. Graph omits parentReference.path from delta responses, so prefer folder_id; see :attr:DeltaEnumeration.unresolved_parent.
folder_id Optional[str] None Stable folder item id to filter items to. With resolve_ancestry this scopes to the whole subtree.
resolve_ancestry bool True When a folder_id is given, walk each unmatched item's parent chain through Graph (cached) so nested descendants are included, not just direct children. Disable to stay offline and match direct children only.
max_pages Optional[int] None Per-call override of the page bound.

Returns: DeltaEnumeration — The aggregated :class:DeltaEnumeration.

Raises:

  • DeltaLinkValidationError — If a continuation link is untrusted.
  • DeltaRetryExhaustedError — If retries hit their bound.

Attribute FOLDER_MATCH

Type: str

Attribute FOLDER_MISS

Type: str

Attribute FOLDER_UNKNOWN

Type: str

Class FolderAncestryResolver

Decide subtree membership by walking parentReference.id upwards.

Graph's delta feed omits parentReference.path but does report parentReference.id, so the only exact way to scope a delta round to a folder subtree is to follow each item's parent chain until the target folder or the drive root is reached. Microsoft's own guidance for delta is "always track items by id"; this is that, applied to folder scoping.

Results are cached per instance — one resolver per enumeration — so a change set with many files in a handful of folders costs a handful of lookups, not one per file.

Parameter Type Default Description
client Any Authenticated client exposing graph_client.
drive_id str Drive the enumeration is confined to.
folder_id str Stable item id of the folder being scoped to.
max_depth int DEFAULT_MAX_ANCESTRY_DEPTH Bound on the upward walk, so a cycle or a pathological hierarchy cannot loop forever.
logger_instance Optional[Any] None Optional logger override.

Method FolderAncestryResolver.is_within

Whether parent_id sits at or beneath the target folder.

is_within(parent_id: Optional[str]) -> Optional[bool]

Parameter Type Default Description
parent_id Optional[str] The item's immediate parent id, if Graph reported one.

Returns: Optional[bool] — True/False when the chain could be walked, or None when it could not be decided (unknown parent, depth bound, or a failed lookup). None is deliberately distinct from False: the caller keeps undecidable items rather than dropping them.

Attribute RESET_STATUS_CODE

Type: int

Attribute RETRYABLE_STATUS_CODES

Type: frozenset[int]

Function classify_folder_membership

Classify an item against a folder filter as match / miss / unknown.

Graph delta is drive-level, so folder scoping has to be applied locally — but the two available signals are not equally trustworthy:

  • folder_id compares against parentReference.id, which delta does report. It is exact, but only identifies direct children of that folder; deeper descendants must be reconciled by the consumer, which Microsoft's guidance ("always track items by id") expects anyway.
  • folder_path compares against parentReference.path, which the Graph v1.0 delta API documents as omitted: "The parentReference property on items won't include a value for path." Against real Graph this therefore usually classifies as unknown, not as a match. It remains useful for feeds that do carry a path (and for tests), but it must never be relied on alone.

classify_folder_membership(item: DeltaItem, folder_path: Optional[str] = None, folder_id: Optional[str] = None) -> str

Parameter Type Default Description
item DeltaItem The typed delta item.
folder_path Optional[str] None Drive-relative folder path filter, if any.
folder_id Optional[str] None Stable folder item id filter, if any.

Returns: str — FOLDER_MATCH when the item is known to be inside the folder, FOLDER_MISS when it is known to be outside, and FOLDER_UNKNOWN when Graph reported nothing to decide with. With no filter configured every item is a match.

Function drive_item_to_delta_item

Project a Graph driveItem onto the typed :class:DeltaItem model.

drive_item_to_delta_item(drive_item: Any, drive_id: str) -> Optional[DeltaItem]

Parameter Type Default Description
drive_item Any A msgraph DriveItem (or any object exposing the same attributes).
drive_id str Drive the item belongs to, used when the item's own parentReference.driveId is absent.

Returns: Optional[DeltaItem] — The typed item, or None when Graph reported no stable item id (such an entry cannot be reconciled and is skipped).

Function item_in_folder

Decide whether an item should be kept under a folder filter.

Undecidable items are kept, not dropped: Graph omits parentReference.path from delta responses and may report a tombstone with no locatable parent, so dropping them would silently lose a retraction. Reconciling an item the consumer never indexed is a no-op, whereas losing one is data corruption.

Use :func:classify_folder_membership when the distinction between a genuine match and an undecidable item matters — :attr:DeltaEnumeration.unresolved_parent reports exactly that count.

item_in_folder(item: DeltaItem, folder_path: Optional[str] = None, folder_id: Optional[str] = None) -> bool

Parameter Type Default Description
item DeltaItem The typed delta item.
folder_path Optional[str] None Drive-relative folder path filter, if any.
folder_id Optional[str] None Stable folder item id filter, if any.

Returns: bool — True when the item is inside the folder or its membership is unknown.

Function normalize_drive_path

Convert a Graph parentReference.path into a drive-relative path.

Graph reports parent paths as /drive/root:/Folder/Sub or /drives/{drive-id}/root:/Folder/Sub. Both collapse to Folder/Sub; the drive root collapses to the empty string.

normalize_drive_path(raw_path: Optional[str]) -> Optional[str]

Parameter Type Default Description
raw_path Optional[str] Raw parentReference.path value, possibly None.

Returns: Optional[str] — The drive-relative path, "" for the root, or None when unknown.

Function validate_continuation_link

Validate an opaque delta continuation link before using it.

Continuation links come from the remote feed (or, for a stored cursor, from the caller). Because the request carries an access token, and because DeltaRequestBuilder.with_url() replaces the entire URL — not just its query string — the link must be proven to be a delta endpoint on the intended drive at a configured Microsoft Graph origin before it is ever dereferenced.

Origin validation alone is not enough: a link such as https://graph.microsoft.com/v1.0/drives/<other>/items/<x>/content passes an origin check yet points the authenticated request at an entirely different resource. When drive_id is supplied the path is therefore confined to that drive's delta operation as well.

validate_continuation_link(link: str, drive_id: str, allowed_origins: Sequence[str] = DEFAULT_GRAPH_ORIGINS) -> str

Parameter Type Default Description
link str The opaque @odata.nextLink / @odata.deltaLink value.
drive_id str Drive the enumeration is confined to. The link's path must name this drive and a delta operation. It is deliberately a required argument: an origin-only check is the very weakness this function exists to close, so it must not be reachable by omission.
allowed_origins Sequence[str] DEFAULT_GRAPH_ORIGINS Origins credentials may be forwarded to.

Returns: str — The validated link, unchanged.

Raises:

  • DeltaLinkValidationError — If the link is empty, is not absolute HTTPS, its origin is not in allowed_origins, or it does not address the drive_id delta endpoint.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally