Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python

feat: periodic webhook subscription renewal + full delete-event coverage (#1852)

Edwin Jose5029dba1348f
diff --git a/src/app/lifespan.py b/src/app/lifespan.py
index ca0c3bab7..42d45e426 100644
--- a/src/app/lifespan.py
+++ b/src/app/lifespan.py
@@ -106,6 +106,41 @@ async def _periodic_backup(services):
logger.error(f"Error in periodic backup task: {str(e)}")
+async def _periodic_webhook_renewal(services):
+ """Renew connector webhook subscriptions before they expire.
+
+ Checks immediately at startup (subscriptions may have lapsed while the
+ app was down), then on a fixed interval. Provider subscriptions are
+ short-lived (Google Drive ~24h, Microsoft Graph 3 days) and go silent
+ without renewal.
+ """
+ from config.settings import (
+ WEBHOOK_RENEWAL_INTERVAL_SECONDS,
+ WEBHOOK_RENEWAL_THRESHOLD_SECONDS,
+ )
+
+ # Let startup_tasks finish loading connections before the first pass
+ await asyncio.sleep(60)
+
+ while True:
+ try:
+ connector_service = services.get("connector_service")
+ if connector_service:
+ stats = await connector_service.connection_manager.renew_expiring_subscriptions(
+ WEBHOOK_RENEWAL_THRESHOLD_SECONDS
+ )
+ if stats["renewed"] or stats["failed"]:
+ logger.info("Webhook subscription renewal pass completed", **stats)
+ else:
+ logger.debug("Webhook subscription renewal pass completed", **stats)
+ except asyncio.CancelledError:
+ logger.info("Webhook renewal task cancelled")
+ break
+ except Exception as e:
+ logger.error(f"Error in webhook renewal task: {str(e)}")
+ await asyncio.sleep(WEBHOOK_RENEWAL_INTERVAL_SECONDS)
+
+
async def run_startup(app: FastAPI):
"""Single source of truth for startup work.
@@ -279,6 +314,11 @@ async def run_startup(app: FastAPI):
app.state.background_tasks.add(backup_task)
backup_task.add_done_callback(app.state.background_tasks.discard)
+ # Start periodic webhook subscription renewal task
+ renewal_task = asyncio.create_task(_periodic_webhook_renewal(services))
+ app.state.background_tasks.add(renewal_task)
+ renewal_task.add_done_callback(app.state.background_tasks.discard)
+
async def run_shutdown(app: FastAPI):
"""Single source of truth for shutdown work."""
diff --git a/src/config/settings.py b/src/config/settings.py
index 33da28b16..4da085ce6 100644
--- a/src/config/settings.py
+++ b/src/config/settings.py
@@ -526,6 +526,15 @@ WEBHOOK_BASE_URL = os.getenv("WEBHOOK_BASE_URL") # No default - must be explici
# Legacy per-connector webhook URL override (takes precedence over WEBHOOK_BASE_URL)
GOOGLE_DRIVE_WEBHOOK_URL = os.getenv("GOOGLE_DRIVE_WEBHOOK_URL")
+# Webhook subscription renewal: how often to check, and how close to expiry a
+# subscription must be before it is renewed. Google Drive channels live ~24h,
+# Microsoft Graph subscriptions 3 days; 6h checks with a 12h threshold give at
+# least two renewal opportunities before either expires.
+_raw_webhook_renewal_interval = get_env_int("WEBHOOK_RENEWAL_INTERVAL_SECONDS", 6 * 3600)
+WEBHOOK_RENEWAL_INTERVAL_SECONDS = max(60, _raw_webhook_renewal_interval)
+_raw_webhook_renewal_threshold = get_env_int("WEBHOOK_RENEWAL_THRESHOLD_SECONDS", 12 * 3600)
+WEBHOOK_RENEWAL_THRESHOLD_SECONDS = max(60, _raw_webhook_renewal_threshold)
+
# OAuth callback broker URL -- when set, Google (and other providers) redirect
# here instead of directly to the frontend. The broker then forwards to the
# actual frontend origin that is carried in the OAuth state parameter.
diff --git a/src/connectors/base.py b/src/connectors/base.py
index 4fb79f19a..7a9b6b412 100644
--- a/src/connectors/base.py
+++ b/src/connectors/base.py
@@ -167,6 +167,14 @@ class BaseConnector(ABC):
"""Clean up subscription"""
pass
+ async def renew_subscription(self, subscription_id: str) -> str | None:
+ """Extend an existing subscription in place.
+
+ Returns the new expiration (ISO-8601) on success, or None if the
+ connector does not support in-place renewal — the caller then falls
+ back to cleanup_subscription + setup_subscription."""
+ return None
+
@property
def is_authenticated(self) -> bool:
return self._authenticated
diff --git a/src/connectors/connection_manager.py b/src/connectors/connection_manager.py
index a087eb1e6..d81851ae6 100644
--- a/src/connectors/connection_manager.py
+++ b/src/connectors/connection_manager.py
@@ -1,8 +1,9 @@
import json
import os
+import re
import uuid
from dataclasses import asdict, dataclass
-from datetime import datetime
+from datetime import UTC, datetime
from pathlib import Path
from typing import Any
@@ -34,6 +35,53 @@ class ConnectionConfig:
self.created_at = datetime.now()
+def _parse_webhook_expiration(value: Any) -> datetime | None:
+ """Parse a stored webhook expiration into an aware UTC datetime.
+
+ Accepts ISO-8601 strings (Microsoft Graph, including 7-digit fractional
+ seconds and trailing 'Z') and epoch-milliseconds (legacy raw Google Drive
+ values). Returns None for missing/unparseable values, which callers treat
+ as unknown expiry (renew now).
+ """
+ if value is None:
+ return None
+ if isinstance(value, (int, float)):
+ try:
+ return datetime.fromtimestamp(float(value) / 1000, tz=UTC)
+ except (ValueError, OSError, OverflowError):
+ return None
+ if not isinstance(value, str) or not value.strip():
+ return None
+ text = value.strip()
+ if text.isdigit():
+ try:
+ return datetime.fromtimestamp(int(text) / 1000, tz=UTC)
+ except (ValueError, OSError, OverflowError):
+ return None
+ if text.endswith(("Z", "z")):
+ text = text[:-1] + "+00:00"
+ # Graph returns 7-digit fractional seconds; fromisoformat needs <= 6
+ text = re.sub(r"(\.\d{6})\d+", r"\1", text)
+ try:
+ parsed = datetime.fromisoformat(text)
+ except ValueError:
+ return None
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=UTC)
+ return parsed
+
+
+def _stored_webhook_subscription_id(config: dict[str, Any]) -> Any:
+ """Return the persisted webhook id, honoring legacy config aliases."""
+ channel_id = config.get("webhook_channel_id")
+ if channel_id and channel_id != "no-webhook-configured":
+ return channel_id
+ subscription_id = config.get("subscription_id")
+ if subscription_id and subscription_id != "no-webhook-configured":
+ return subscription_id
+ return None
+
+
class ConnectionManager:
"""Manages multiple connector connections with persistence"""
@@ -543,15 +591,8 @@ class ConnectionManager:
logger.info("Setting up webhook subscription", connection_id=connection_id)
subscription_id = await connector.setup_subscription()
- # Store the subscription and resource IDs in connection config
- connection_config.config["webhook_channel_id"] = subscription_id
- connection_config.config["subscription_id"] = subscription_id # Alternative field
- resource_id = getattr(connector, "webhook_resource_id", None)
- if resource_id:
- connection_config.config["resource_id"] = resource_id
-
- # Save updated connection config
- await self.save_connections()
+ # Store the subscription state in connection config and save
+ await self._persist_subscription_state(connection_config, connector, subscription_id)
logger.info(
"Successfully set up webhook subscription",
@@ -589,15 +630,8 @@ class ConnectionManager:
# Setup subscription
subscription_id = await connector.setup_subscription()
- # Store the subscription and resource IDs in connection config
- connection_config.config["webhook_channel_id"] = subscription_id
- connection_config.config["subscription_id"] = subscription_id
- resource_id = getattr(connector, "webhook_resource_id", None)
- if resource_id:
- connection_config.config["resource_id"] = resource_id
-
- # Save updated connection config
- await self.save_connections()
+ # Store the subscription state in connection config and save
+ await self._persist_subscription_state(connection_config, connector, subscription_id)
logger.info(
"Successfully set up webhook subscription",
@@ -612,3 +646,129 @@ class ConnectionManager:
error=str(e),
)
# Don't fail the connection setup if webhook fails
+
+ async def _persist_subscription_state(
+ self,
+ connection_config: ConnectionConfig,
+ connector: BaseConnector,
+ subscription_id: str,
+ ) -> None:
+ """Store subscription identifiers/expiration on the connection and save."""
+ cfg = connection_config.config
+ cfg["webhook_channel_id"] = subscription_id
+ cfg["subscription_id"] = subscription_id # Alternative field
+ resource_id = getattr(connector, "webhook_resource_id", None)
+ if resource_id:
+ cfg["resource_id"] = resource_id
+ expiration = getattr(connector, "webhook_expiration", None)
+ if expiration:
+ cfg["webhook_expiration"] = expiration
+ # Google Drive: keep the changes cursor across restarts (the connector
+ # reads it from config at construction time)
+ page_token = getattr(getattr(connector, "cfg", None), "changes_page_token", None)
+ if page_token:
+ cfg["changes_page_token"] = page_token
+ await self.save_connections()
+
+ async def renew_expiring_subscriptions(self, threshold_seconds: int) -> dict[str, int]:
+ """Renew webhook subscriptions that are expired, near expiry, or missing.
+
+ Connections with a webhook_url but no live subscription (failed initial
+ setup) are healed here too. Failures are per-connection; one bad
+ connection never blocks the rest. Returns counters for logging.
+ """
+ stats = {"checked": 0, "renewed": 0, "failed": 0, "skipped": 0}
+ now = datetime.now(UTC)
+
+ for connection in list(self.connections.values()):
+ if not connection.is_active or not connection.config.get("webhook_url"):
+ continue
+
+ stats["checked"] += 1
+
+ channel_id = _stored_webhook_subscription_id(connection.config)
+ has_subscription = bool(channel_id)
+ if has_subscription:
+ expiration = _parse_webhook_expiration(connection.config.get("webhook_expiration"))
+ if expiration and (expiration - now).total_seconds() > threshold_seconds:
+ stats["skipped"] += 1
+ continue
+
+ try:
+ renewed = await self._renew_subscription(connection)
+ except Exception as e:
+ logger.error(
+ "Webhook subscription renewal failed",
+ connection_id=connection.connection_id,
+ error=str(e),
+ )
+ renewed = False
+ stats["renewed" if renewed else "failed"] += 1
+
+ return stats
+
+ async def _renew_subscription(self, connection: ConnectionConfig) -> bool:
+ """Renew (extend or recreate) the webhook subscription for one connection."""
+ connector = await self.get_connector(connection.connection_id)
+ if not connector:
+ logger.warning(
+ "Cannot renew webhook subscription: connector authentication failed",
+ connection_id=connection.connection_id,
+ )
+ return False
+
+ old_id = _stored_webhook_subscription_id(connection.config)
+ has_old = bool(old_id)
+
+ if has_old:
+ # Cheap path: extend in place (Microsoft Graph PATCH). Connectors
+ # without in-place renewal (Google Drive) return None.
+ new_expiration = await connector.renew_subscription(old_id)
+ if new_expiration:
+ connection.config["webhook_expiration"] = new_expiration
+ await self.save_connections()
+ logger.info(
+ "Webhook subscription extended",
+ connection_id=connection.connection_id,
+ expiration=new_expiration,
+ )
+ return True
+
+ # Recreate only after the old subscription is confirmed stopped.
+ # Google Drive requires both channel id and resource_id to stop a
+ # channel; if either is missing, creating a replacement would leak
+ # duplicate notifications until the old channel expires.
+ try:
+ cleanup_ok = await connector.cleanup_subscription(old_id)
+ except Exception as e:
+ logger.warning(
+ "Old webhook subscription cleanup failed; skipping recreation",
+ connection_id=connection.connection_id,
+ subscription_id=old_id,
+ error=str(e),
+ )
+ return False
+
+ if not cleanup_ok:
+ logger.warning(
+ "Old webhook subscription cleanup was not confirmed; skipping recreation",
+ connection_id=connection.connection_id,
+ subscription_id=old_id,
+ )
+ return False
+
+ subscription_id = await connector.setup_subscription()
+ if not subscription_id or subscription_id == "no-webhook-configured":
+ logger.warning(
+ "Webhook subscription recreation returned no subscription",
+ connection_id=connection.connection_id,
+ )
+ return False
+
+ await self._persist_subscription_state(connection, connector, subscription_id)
+ logger.info(
+ "Webhook subscription recreated",
+ connection_id=connection.connection_id,
+ subscription_id=subscription_id,
+ )
+ return True
diff --git a/src/connectors/google_drive/connector.py b/src/connectors/google_drive/connector.py
index ebd0320e6..acd5b1257 100644
--- a/src/connectors/google_drive/connector.py
+++ b/src/connectors/google_drive/connector.py
@@ -5,6 +5,7 @@ import time
from collections import deque
from collections.abc import Iterable
from dataclasses import dataclass
+from datetime import UTC
from pathlib import Path
from typing import Any
@@ -195,6 +196,10 @@ class GoogleDriveConnector(BaseConnector):
# Authentication state
self._authenticated: bool = False
+ # Set by setup_subscription; read by the connection manager to persist
+ self.webhook_resource_id: str | None = None
+ self.webhook_expiration: str | None = None
+
# -------------------------
# Helpers
# -------------------------
@@ -959,6 +964,20 @@ class GoogleDriveConnector(BaseConnector):
"page_token": self.cfg.changes_page_token,
}
+ # Expose for the connection manager to persist (Drive returns
+ # expiration as an epoch-ms string; normalize to ISO-8601 UTC).
+ self.webhook_resource_id = resource_id
+ self.webhook_expiration = None
+ if expiration:
+ from datetime import datetime
+
+ try:
+ self.webhook_expiration = datetime.fromtimestamp(
+ int(expiration) / 1000, tz=UTC
+ ).isoformat()
+ except (TypeError, ValueError):
+ pass
+
if not isinstance(channel_id, str) or not channel_id:
raise RuntimeError(f"Drive watch returned invalid channel id: {channel_id!r}")
@@ -1099,7 +1118,7 @@ class GoogleDriveConnector(BaseConnector):
pageToken=page_token,
fields=(
"nextPageToken, newStartPageToken, "
- "changes(fileId, file(id, name, mimeType, trashed, parents, "
+ "changes(fileId, removed, file(id, name, mimeType, trashed, parents, "
"shortcutDetails, driveId, modifiedTime, webViewLink))"
),
supportsAllDrives=True,
@@ -1112,9 +1131,16 @@ class GoogleDriveConnector(BaseConnector):
fid = ch.get("fileId")
fobj = ch.get("file") or {}
- # Skip if no file or explicitly trashed (you can choose to still return these IDs)
- if not fid or fobj.get("trashed"):
- # If you want to *include* deletions, collect fid here instead of skipping.
+ if not fid:
+ continue
+
+ if ch.get("removed") or fobj.get("trashed"):
+ # Deletion/trash: include unconditionally so downstream
+ # cleanup runs. Scope filtering is impossible here (a
+ # removed file has no metadata; a trashed file is
+ # excluded from the selected-scope set) and cleanup of
+ # a never-indexed id is a harmless no-op.
+ affected.append(fid)
continue
# Resolve shortcuts to target
diff --git a/src/connectors/onedrive/connector.py b/src/connectors/onedrive/connector.py
index e14eb9d2a..9257bd0ed 100644
--- a/src/connectors/onedrive/connector.py
+++ b/src/connectors/onedrive/connector.py
@@ -115,6 +115,11 @@ class OneDriveConnector(BaseConnector):
# Track subscription ID for webhooks (note: change notifications might not be available for personal accounts)
self._subscription_id: str | None = None
+ # Set by setup_subscription/renew_subscription; read by the
+ # connection manager to persist
+ self.webhook_resource_id: str | None = None
+ self.webhook_expiration: str | None = None
+
# Graph API defaults
self._graph_api_version = "v1.0"
self._default_params: dict[str, Any] = {
@@ -379,6 +384,7 @@ class OneDriveConnector(BaseConnector):
if subscription_id:
self._subscription_id = subscription_id
+ self.webhook_expiration = result.get("expirationDateTime")
logger.info(f"OneDrive subscription created: {subscription_id}")
return subscription_id
else:
@@ -1119,3 +1125,45 @@ class OneDriveConnector(BaseConnector):
except Exception as e:
logger.error(f"Failed to cleanup OneDrive subscription {subscription_id}: {e}")
return False
+
+ async def renew_subscription(self, subscription_id: str) -> str | None:
+ """Extend the Graph subscription in place (PATCH avoids re-validation).
+
+ Returns the new expirationDateTime, or None to signal the caller to
+ fall back to delete + recreate."""
+ if subscription_id == "no-webhook-configured":
+ return None
+
+ try:
+ if not await self.authenticate():
+ logger.error("OneDrive authentication failed during subscription renewal")
+ return None
+
+ token = self.oauth.get_access_token()
+ headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
+
+ url = f"{self._graph_base_url}/subscriptions/{subscription_id}"
+ body = {"expirationDateTime": self._get_subscription_expiry()}
+
+ async with httpx.AsyncClient() as client:
+ response = await client.patch(url, json=body, headers=headers, timeout=30)
+
+ if response.status_code == 404:
+ # Subscription already expired/deleted at Graph; recreate.
+ logger.info(f"OneDrive subscription {subscription_id} not found, will recreate")
+ return None
+ if response.status_code not in [200, 201]:
+ logger.warning(
+ f"Unexpected response renewing OneDrive subscription: "
+ f"{response.status_code}"
+ )
+ return None
+
+ expiration = response.json().get("expirationDateTime")
+ self.webhook_expiration = expiration
+ logger.info(f"OneDrive subscription {subscription_id} renewed until {expiration}")
+ return expiration
+
+ except Exception as e:
+ logger.error(f"Failed to renew OneDrive subscription {subscription_id}: {e}")
+ return None
diff --git a/src/connectors/service.py b/src/connectors/service.py
index 84c36a3ee..ade3f9e91 100644
--- a/src/connectors/service.py
+++ b/src/connectors/service.py
@@ -520,6 +520,27 @@ class ConnectorService:
for f in expanded_files:
expanded_files_info.append(f)
+ # Requested IDs that vanished during expansion are either
+ # folders (replaced by their children) or gone at the source
+ # (deleted/trashed). Re-add the non-folder ones so the
+ # processor can run its deleted-at-source cleanup
+ # (get_file_content -> 404 -> delete indexed chunks).
+ expanded_set = set(expanded_file_ids)
+ known_folder_ids = {
+ f["id"] for f in (file_infos or []) if f.get("isFolder") and f.get("id")
+ }
+ missing_ids = [
+ fid
+ for fid in file_ids
+ if fid not in expanded_set and fid not in known_folder_ids
+ ]
+ if missing_ids:
+ logger.info(
+ f"Re-adding {len(missing_ids)} file id(s) missing after expansion "
+ f"(possibly deleted at source)"
+ )
+ expanded_file_ids = expanded_file_ids + missing_ids
+
if not expanded_file_ids:
logger.warning(
f"No files found after expanding file_ids. "
diff --git a/src/connectors/sharepoint/connector.py b/src/connectors/sharepoint/connector.py
index 09a2c3965..6f2a1b33b 100644
--- a/src/connectors/sharepoint/connector.py
+++ b/src/connectors/sharepoint/connector.py
@@ -125,6 +125,11 @@ class SharePointConnector(BaseConnector):
# Track subscription ID for webhooks
self._subscription_id: str | None = None
+ # Set by setup_subscription/renew_subscription; read by the
+ # connection manager to persist
+ self.webhook_resource_id: str | None = None
+ self.webhook_expiration: str | None = None
+
# Add Graph API defaults similar to Google Drive flags
self._graph_api_version = "v1.0"
self._default_params = {
@@ -414,6 +419,7 @@ class SharePointConnector(BaseConnector):
if subscription_id:
self._subscription_id = subscription_id
+ self.webhook_expiration = result.get("expirationDateTime")
logger.info(f"SharePoint subscription created: {subscription_id}")
return subscription_id
else:
@@ -1062,3 +1068,47 @@ class SharePointConnector(BaseConnector):
except Exception as e:
logger.error(f"Failed to cleanup SharePoint subscription {subscription_id}: {e}")
return False
+
+ async def renew_subscription(self, subscription_id: str) -> str | None:
+ """Extend the Graph subscription in place (PATCH avoids re-validation).
+
+ Returns the new expirationDateTime, or None to signal the caller to
+ fall back to delete + recreate."""
+ if subscription_id == "no-webhook-configured":
+ return None
+
+ try:
+ if not await self.authenticate():
+ logger.error("SharePoint authentication failed during subscription renewal")
+ return None
+
+ token = self.oauth.get_access_token()
+ headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
+
+ url = f"{self._graph_base_url}/subscriptions/{subscription_id}"
+ body = {"expirationDateTime": self._get_subscription_expiry()}
+
+ async with httpx.AsyncClient() as client:
+ response = await client.patch(url, json=body, headers=headers, timeout=30)
+
+ if response.status_code == 404:
+ # Subscription already expired/deleted at Graph; recreate.
+ logger.info(
+ f"SharePoint subscription {subscription_id} not found, will recreate"
+ )
+ return None
+ if response.status_code not in [200, 201]:
+ logger.warning(
+ f"Unexpected response renewing SharePoint subscription: "
+ f"{response.status_code}"
+ )
+ return None
+
+ expiration = response.json().get("expirationDateTime")
+ self.webhook_expiration = expiration
+ logger.info(f"SharePoint subscription {subscription_id} renewed until {expiration}")
+ return expiration
+
+ except Exception as e:
+ logger.error(f"Failed to renew SharePoint subscription {subscription_id}: {e}")
+ return None
diff --git a/tests/unit/connectors/test_google_drive_webhook_events.py b/tests/unit/connectors/test_google_drive_webhook_events.py
new file mode 100644
index 000000000..718b5d197
--- /dev/null
+++ b/tests/unit/connectors/test_google_drive_webhook_events.py
@@ -0,0 +1,74 @@
+"""Google Drive webhook event coverage.
+
+Pins that `handle_webhook` reports ALL events: created/updated files in the
+selected scope AND deletions (`removed` changes and trashed files). Deletions
+used to be skipped client-side, so removing a file in Drive never cleaned up
+its indexed chunks. Deletions bypass the selected-scope filter deliberately:
+a removed file has no metadata and a trashed file is excluded from the
+selected-scope set, so neither could ever pass the membership test — and
+downstream cleanup of a never-indexed id is a harmless no-op.
+"""
+
+import sys
+import threading
+from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent.parent.parent
+SRC = ROOT / "src"
+if str(SRC) not in sys.path:
+ sys.path.insert(0, str(SRC))
+
+
+def _make_connector(changes_response: dict):
+ from connectors.google_drive.connector import GoogleDriveConfig, GoogleDriveConnector
+
+ connector = GoogleDriveConnector.__new__(GoogleDriveConnector)
+ connector.cfg = GoogleDriveConfig(
+ client_id="fake-client-id",
+ client_secret="fake-client-secret",
+ token_file="/tmp/fake-token.json",
+ changes_page_token="token-1",
+ )
+ connector.authenticate = AsyncMock(return_value=True)
+ connector._iter_selected_items = MagicMock(return_value=[{"id": "in-scope-live"}])
+ connector._resolve_shortcut = lambda meta: meta
+ connector._lock = threading.Lock()
+ connector._shortcut_cache = {}
+
+ service = MagicMock()
+ service.changes.return_value.list.return_value.execute.return_value = changes_response
+ connector.service = service
+ return connector
+
+
+async def test_handle_webhook_includes_removed_and_trashed_files():
+ connector = _make_connector(
+ {
+ "changes": [
+ # Hard delete: no file metadata at all
+ {"fileId": "removed-1", "removed": True},
+ # Soft delete: file moved to trash
+ {"fileId": "trashed-1", "file": {"id": "trashed-1", "trashed": True}},
+ # Live change inside the selected scope
+ {"fileId": "in-scope-live", "file": {"id": "in-scope-live"}},
+ # Live change outside the selected scope: filtered out
+ {"fileId": "out-of-scope", "file": {"id": "out-of-scope"}},
+ # No fileId at all: ignored
+ {"file": {"id": "nameless"}},
+ ],
+ "newStartPageToken": "token-2",
+ }
+ )
+
+ affected = await connector.handle_webhook({})
+
+ assert affected == ["removed-1", "trashed-1", "in-scope-live"]
+ # Checkpoint advanced for the next notification
+ assert connector.cfg.changes_page_token == "token-2"
+ # The changes query must request the `removed` flag
+ list_kwargs = connector.service.changes.return_value.list.call_args.kwargs
+ assert "removed" in list_kwargs["fields"]
diff --git a/tests/unit/connectors/test_sync_specific_files_deleted_ids.py b/tests/unit/connectors/test_sync_specific_files_deleted_ids.py
new file mode 100644
index 000000000..29936d45d
--- /dev/null
+++ b/tests/unit/connectors/test_sync_specific_files_deleted_ids.py
@@ -0,0 +1,93 @@
+"""sync_specific_files must not drop IDs of files deleted at the source.
+
+Webhook delete events arrive as bare file IDs. `sync_specific_files`
+re-expands IDs via the connector's `list_files()`, which only returns files
+that still exist — so deleted IDs used to vanish from the batch (and a
+delete-only batch raised "No files to sync after expanding folders"). The
+fix re-adds requested IDs that are missing after expansion (excluding known
+folders), so `ConnectorFileProcessor` can run its deleted-at-source cleanup
+(get_file_content -> 404 -> delete indexed chunks).
+"""
+
+import sys
+from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent.parent.parent
+SRC = ROOT / "src"
+if str(SRC) not in sys.path:
+ sys.path.insert(0, str(SRC))
+
+
+def _make_service(live_files: list[dict]):
+ from connectors.service import ConnectorService
+
+ service = ConnectorService.__new__(ConnectorService)
+ service.session_manager = None
+ service.models_service = MagicMock()
+
+ service.task_service = MagicMock()
+ service.task_service.document_service = MagicMock()
+ service.task_service.create_custom_task = AsyncMock(return_value="task-1")
+
+ connector = MagicMock()
+ connector.is_authenticated = True
+ connector.cfg = MagicMock()
+ connector.list_files = AsyncMock(return_value={"files": live_files})
+ service.get_connector = AsyncMock(return_value=connector)
+
+ return service
+
+
+def _synced_ids(service) -> list[str]:
+ args = service.task_service.create_custom_task.await_args.args
+ return args[1]
+
+
+async def test_deleted_ids_are_kept_alongside_live_files():
+ service = _make_service(live_files=[{"id": "live-1", "name": "a.pdf"}])
+
+ task_id = await service.sync_specific_files(
+ connection_id="conn-1",
+ user_id="user-1",
+ file_ids=["live-1", "deleted-1"],
+ jwt_token="jwt",
+ )
+
+ assert task_id == "task-1"
+ assert _synced_ids(service) == ["live-1", "deleted-1"]
+
+
+async def test_delete_only_batch_no_longer_raises():
+ service = _make_service(live_files=[])
+
+ task_id = await service.sync_specific_files(
+ connection_id="conn-1",
+ user_id="user-1",
+ file_ids=["deleted-1", "deleted-2"],
+ jwt_token="jwt",
+ )
+
+ assert task_id == "task-1"
+ assert _synced_ids(service) == ["deleted-1", "deleted-2"]
+
+
+async def test_known_folder_ids_are_not_readded():
+ """A folder ID is legitimately replaced by its children during expansion;
+ it must not be re-added as a phantom deleted file."""
+ service = _make_service(live_files=[{"id": "child-1", "name": "inside.pdf"}])
+
+ await service.sync_specific_files(
+ connection_id="conn-1",
+ user_id="user-1",
+ file_ids=["folder-1"],
+ jwt_token="jwt",
+ file_infos=[{"id": "folder-1", "name": "Folder", "isFolder": True}],
+ )
+
+ assert _synced_ids(service) == ["child-1"]
diff --git a/tests/unit/connectors/test_webhook_notification_url.py b/tests/unit/connectors/test_webhook_notification_url.py
index b9f51d815..8ea746c61 100644
--- a/tests/unit/connectors/test_webhook_notification_url.py
+++ b/tests/unit/connectors/test_webhook_notification_url.py
@@ -55,7 +55,7 @@ class _FakeAsyncClient:
async def post(self, url, json=None, headers=None, timeout=None):
self._captured["url"] = url
self._captured["json"] = json
- return _FakeResponse({"id": "sub-123"})
+ return _FakeResponse({"id": "sub-123", "expirationDateTime": "2026-06-14T00:00:00Z"})
class _FakeOAuth:
@@ -109,6 +109,8 @@ async def test_graph_notification_url_is_config_webhook_url_verbatim(
# Regression: must not re-append a /webhook/<type> segment to the
# already-complete endpoint (yields a 404 route, Graph rejects it).
assert f"/webhook/{connector_type}" not in body["notificationUrl"]
+ # The Graph-reported expiration is exposed for persistence/renewal
+ assert connector.webhook_expiration == "2026-06-14T00:00:00Z"
@pytest.mark.asyncio
diff --git a/tests/unit/connectors/test_webhook_renewal.py b/tests/unit/connectors/test_webhook_renewal.py
new file mode 100644
index 000000000..f04318529
--- /dev/null
+++ b/tests/unit/connectors/test_webhook_renewal.py
@@ -0,0 +1,440 @@
+"""Webhook subscription renewal.
+
+Pins the periodic-renewal machinery: provider subscriptions are short-lived
+(Google Drive channels ~24h, Microsoft Graph 3 days) and previously nothing
+renewed them, so change notifications went silent days after connecting.
+
+Covers `_parse_webhook_expiration`, `ConnectionManager.renew_expiring_
+subscriptions` / `_renew_subscription` / `_persist_subscription_state`, and
+the Graph PATCH `renew_subscription` on SharePoint/OneDrive.
+"""
+
+import sys
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent.parent.parent
+SRC = ROOT / "src"
+if str(SRC) not in sys.path:
+ sys.path.insert(0, str(SRC))
+
+
+THRESHOLD = 12 * 3600
+
+
+def _iso_in(hours: float) -> str:
+ return (datetime.now(UTC) + timedelta(hours=hours)).isoformat()
+
+
+# ---------------------------------------------------------------------------
+# _parse_webhook_expiration
+# ---------------------------------------------------------------------------
+
+
+def test_parse_expiration_formats():
+ from connectors.connection_manager import _parse_webhook_expiration as parse
+
+ # ISO with offset
+ assert parse("2026-06-14T12:00:00+00:00") == datetime(2026, 6, 14, 12, 0, 0, tzinfo=UTC)
+ # ISO with trailing Z
+ assert parse("2026-06-14T12:00:00Z") == datetime(2026, 6, 14, 12, 0, 0, tzinfo=UTC)
+ # Graph 7-digit fractional seconds
+ assert parse("2026-06-14T12:00:00.9356913Z") == datetime(
+ 2026, 6, 14, 12, 0, 0, 935691, tzinfo=UTC
+ )
+ # Naive ISO assumed UTC
+ assert parse("2026-06-14T12:00:00").tzinfo is not None
+ # Epoch-milliseconds (legacy raw Google Drive value), string and int
+ epoch_ms = int(datetime(2026, 6, 14, 12, 0, 0, tzinfo=UTC).timestamp() * 1000)
+ assert parse(str(epoch_ms)) == datetime(2026, 6, 14, 12, 0, 0, tzinfo=UTC)
+ assert parse(epoch_ms) == datetime(2026, 6, 14, 12, 0, 0, tzinfo=UTC)
+ # Missing / garbage -> None (treated as unknown -> renew)
+ assert parse(None) is None
+ assert parse("") is None
+ assert parse("not-a-date") is None
+
+
+# ---------------------------------------------------------------------------
+# renew_expiring_subscriptions / _renew_subscription
+# ---------------------------------------------------------------------------
+
+
+def _make_manager(tmp_path, connections):
+ from connectors.connection_manager import ConnectionManager
+
+ manager = ConnectionManager(connections_file=str(tmp_path / "connections.json"))
+ manager.connections = {c.connection_id: c for c in connections}
+ manager.save_connections = AsyncMock()
+ return manager
+
+
+def _make_connection(connection_id="conn-1", **config_overrides):
+ from connectors.connection_manager import ConnectionConfig
+
+ config = {
+ "token_file": "token.json",
+ "webhook_url": "https://api.example.com/connectors/google_drive/webhook",
+ "webhook_channel_id": "old-channel",
+ "subscription_id": "old-channel",
+ "webhook_expiration": _iso_in(1), # near expiry by default
+ }
+ config.update(config_overrides)
+ config = {k: v for k, v in config.items() if v is not None}
+ return ConnectionConfig(
+ connection_id=connection_id,
+ connector_type="google_drive",
+ name="Test",
+ config=config,
+ )
+
+
+def _make_connector(
+ renew_result=None,
+ setup_result="new-channel",
+ resource_id="new-resource",
+ expiration=None,
+):
+ connector = MagicMock()
+ connector.renew_subscription = AsyncMock(return_value=renew_result)
+ connector.cleanup_subscription = AsyncMock(return_value=True)
+ connector.setup_subscription = AsyncMock(return_value=setup_result)
+ connector.webhook_resource_id = resource_id
+ connector.webhook_expiration = expiration or _iso_in(24)
+ connector.cfg = MagicMock()
+ connector.cfg.changes_page_token = "page-token-42"
+ return connector
+
+
+async def test_healthy_subscription_is_skipped(tmp_path):
+ connection = _make_connection(webhook_expiration=_iso_in(48))
+ manager = _make_manager(tmp_path, [connection])
+ manager.get_connector = AsyncMock()
+
+ stats = await manager.renew_expiring_subscriptions(THRESHOLD)
+
+ assert stats == {"checked": 1, "renewed": 0, "failed": 0, "skipped": 1}
+ manager.get_connector.assert_not_awaited()
+
+
+ "expiration",
+ [_iso_in(1), _iso_in(-1), None],
+ ids=["near-expiry", "expired", "unknown-expiry"],
+)
+async def test_near_expired_or_unknown_expiry_is_renewed(tmp_path, expiration):
+ connection = _make_connection(webhook_expiration=expiration)
+ connector = _make_connector()
+ manager = _make_manager(tmp_path, [connection])
+ manager.get_connector = AsyncMock(return_value=connector)
+
+ stats = await manager.renew_expiring_subscriptions(THRESHOLD)
+
+ assert stats["renewed"] == 1
+
+
+async def test_missing_subscription_is_healed(tmp_path):
+ """webhook_url set but no channel id (failed initial setup) -> recreated."""
+ connection = _make_connection(
+ webhook_channel_id=None, subscription_id=None, webhook_expiration=None
+ )
+ connector = _make_connector()
+ manager = _make_manager(tmp_path, [connection])
+ manager.get_connector = AsyncMock(return_value=connector)
+
+ stats = await manager.renew_expiring_subscriptions(THRESHOLD)
+
+ assert stats["renewed"] == 1
+ # No old subscription to extend or clean up
+ connector.renew_subscription.assert_not_awaited()
+ connector.cleanup_subscription.assert_not_awaited()
+ connector.setup_subscription.assert_awaited_once()
+ assert connection.config["webhook_channel_id"] == "new-channel"
+
+
+async def test_legacy_subscription_id_is_renewed(tmp_path):
+ """Legacy configs may only have subscription_id; renew that id instead of duplicating."""
+ new_expiration = _iso_in(72)
+ connection = _make_connection(
+ webhook_channel_id=None,
+ subscription_id="legacy-subscription",
+ webhook_expiration=_iso_in(1),
+ )
+ connector = _make_connector(renew_result=new_expiration)
+ manager = _make_manager(tmp_path, [connection])
+ manager.get_connector = AsyncMock(return_value=connector)
+
+ stats = await manager.renew_expiring_subscriptions(THRESHOLD)
+
+ assert stats["renewed"] == 1
+ connector.renew_subscription.assert_awaited_once_with("legacy-subscription")
+ connector.cleanup_subscription.assert_not_awaited()
+ connector.setup_subscription.assert_not_awaited()
+ assert connection.config["webhook_expiration"] == new_expiration
+
+
+async def test_connection_without_webhook_url_is_ignored(tmp_path):
+ connection = _make_connection(webhook_url=None)
+ manager = _make_manager(tmp_path, [connection])
+ manager.get_connector = AsyncMock()
+
+ stats = await manager.renew_expiring_subscriptions(THRESHOLD)
+
+ assert stats == {"checked": 0, "renewed": 0, "failed": 0, "skipped": 0}
+
+
+async def test_inactive_connection_is_ignored(tmp_path):
+ connection = _make_connection()
+ connection.is_active = False
+ manager = _make_manager(tmp_path, [connection])
+ manager.get_connector = AsyncMock()
+
+ stats = await manager.renew_expiring_subscriptions(THRESHOLD)
+
+ assert stats["checked"] == 0
+
+
+async def test_auth_failure_leaves_config_untouched(tmp_path):
+ connection = _make_connection()
+ original_config = dict(connection.config)
+ manager = _make_manager(tmp_path, [connection])
+ manager.get_connector = AsyncMock(return_value=None)
+
+ stats = await manager.renew_expiring_subscriptions(THRESHOLD)
+
+ assert stats["failed"] == 1
+ assert connection.config == original_config
+ manager.save_connections.assert_not_awaited()
+
+
+async def test_inplace_extension_skips_recreate(tmp_path):
+ """Graph PATCH success: only the expiration is updated, no delete+create."""
+ new_expiration = _iso_in(72)
+ connection = _make_connection()
+ connector = _make_connector(renew_result=new_expiration)
+ manager = _make_manager(tmp_path, [connection])
+ manager.get_connector = AsyncMock(return_value=connector)
+
+ stats = await manager.renew_expiring_subscriptions(THRESHOLD)
+
+ assert stats["renewed"] == 1
+ connector.renew_subscription.assert_awaited_once_with("old-channel")
+ connector.cleanup_subscription.assert_not_awaited()
+ connector.setup_subscription.assert_not_awaited()
+ assert connection.config["webhook_expiration"] == new_expiration
+ assert connection.config["webhook_channel_id"] == "old-channel" # unchanged
+ manager.save_connections.assert_awaited()
+
+
+async def test_recreate_path_cleans_up_and_persists(tmp_path):
+ """No in-place renewal (Google Drive): stop old channel, create new one,
+ persist new ids + expiration + changes page token."""
+ new_expiration = _iso_in(24)
+ connection = _make_connection()
+ connector = _make_connector(renew_result=None, expiration=new_expiration)
+ manager = _make_manager(tmp_path, [connection])
+ manager.get_connector = AsyncMock(return_value=connector)
+
+ stats = await manager.renew_expiring_subscriptions(THRESHOLD)
+
+ assert stats["renewed"] == 1
+ connector.cleanup_subscription.assert_awaited_once_with("old-channel")
+ connector.setup_subscription.assert_awaited_once()
+ cfg = connection.config
+ assert cfg["webhook_channel_id"] == "new-channel"
+ assert cfg["subscription_id"] == "new-channel"
+ assert cfg["resource_id"] == "new-resource"
+ assert cfg["webhook_expiration"] == new_expiration
+ assert cfg["changes_page_token"] == "page-token-42"
+ manager.save_connections.assert_awaited()
+
+
+async def test_recreate_skips_setup_when_cleanup_returns_false(tmp_path):
+ """Avoid duplicate/leaked provider webhooks when the old one cannot be stopped."""
+ connection = _make_connection()
+ connector = _make_connector(renew_result=None)
+ connector.cleanup_subscription = AsyncMock(return_value=False)
+ manager = _make_manager(tmp_path, [connection])
+ manager.get_connector = AsyncMock(return_value=connector)
+
+ stats = await manager.renew_expiring_subscriptions(THRESHOLD)
+
+ assert stats["failed"] == 1
+ connector.cleanup_subscription.assert_awaited_once_with("old-channel")
+ connector.setup_subscription.assert_not_awaited()
+ assert connection.config["webhook_channel_id"] == "old-channel"
+
+
+async def test_recreate_skips_setup_when_cleanup_raises(tmp_path):
+ connection = _make_connection()
+ connector = _make_connector(renew_result=None)
+ connector.cleanup_subscription = AsyncMock(side_effect=RuntimeError("missing resource id"))
+ manager = _make_manager(tmp_path, [connection])
+ manager.get_connector = AsyncMock(return_value=connector)
+
+ stats = await manager.renew_expiring_subscriptions(THRESHOLD)
+
+ assert stats["failed"] == 1
+ connector.cleanup_subscription.assert_awaited_once_with("old-channel")
+ connector.setup_subscription.assert_not_awaited()
+ assert connection.config["webhook_channel_id"] == "old-channel"
+
+
+async def test_no_webhook_configured_sentinel_counts_as_failure(tmp_path):
+ connection = _make_connection()
+ connector = _make_connector(renew_result=None, setup_result="no-webhook-configured")
+ manager = _make_manager(tmp_path, [connection])
+ manager.get_connector = AsyncMock(return_value=connector)
+
+ stats = await manager.renew_expiring_subscriptions(THRESHOLD)
+
+ assert stats["failed"] == 1
+ # Old channel id never cleared on failure
+ assert connection.config["webhook_channel_id"] == "old-channel"
+
+
+async def test_one_failing_connection_does_not_block_others(tmp_path):
+ bad = _make_connection(connection_id="bad")
+ good = _make_connection(connection_id="good")
+ good_connector = _make_connector()
+ manager = _make_manager(tmp_path, [bad, good])
+
+ async def _get_connector(connection_id):
+ if connection_id == "bad":
+ raise RuntimeError("boom")
+ return good_connector
+
+ manager.get_connector = AsyncMock(side_effect=_get_connector)
+
+ stats = await manager.renew_expiring_subscriptions(THRESHOLD)
+
+ assert stats["failed"] == 1
+ assert stats["renewed"] == 1
+
+
+# ---------------------------------------------------------------------------
+# SharePoint / OneDrive — Graph PATCH renew_subscription
+# ---------------------------------------------------------------------------
+
+
+class _FakeResponse:
+ def __init__(self, status_code: int, payload: dict | None = None):
+ self.status_code = status_code
+ self._payload = payload or {}
+
+ def json(self) -> dict:
+ return self._payload
+
+
+class _FakePatchClient:
+ def __init__(self, captured: dict, response: _FakeResponse):
+ self._captured = captured
+ self._response = response
+
+ def __call__(self, *args, **kwargs):
+ return self
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *exc):
+ return False
+
+ async def patch(self, url, json=None, headers=None, timeout=None):
+ self._captured["url"] = url
+ self._captured["json"] = json
+ return self._response
+
+
+class _FakeOAuth:
+ def get_access_token(self) -> str:
+ return "access-token"
+
+
+GRAPH_CONNECTORS = [
+ ("connectors.sharepoint.connector", "SharePointConnector"),
+ ("connectors.onedrive.connector", "OneDriveConnector"),
+]
+
+
+def _graph_connector(module_path: str, cls_name: str, tmp_path):
+ import importlib
+
+ cls = getattr(importlib.import_module(module_path), cls_name)
+ connector = cls({"token_file": str(tmp_path / "token.json")})
+ connector.authenticate = AsyncMock(return_value=True)
+ connector.oauth = _FakeOAuth()
+ return connector
+
+
[email protected]("module_path,cls_name", GRAPH_CONNECTORS)
+async def test_graph_renew_patches_subscription(tmp_path, monkeypatch, module_path, cls_name):
+ import httpx
+
+ connector = _graph_connector(module_path, cls_name, tmp_path)
+ captured = {}
+ monkeypatch.setattr(
+ httpx,
+ "AsyncClient",
+ _FakePatchClient(
+ captured, _FakeResponse(200, {"expirationDateTime": "2026-06-17T00:00:00Z"})
+ ),
+ )
+
+ expiration = await connector.renew_subscription("sub-123")
+
+ assert expiration == "2026-06-17T00:00:00Z"
+ assert connector.webhook_expiration == "2026-06-17T00:00:00Z"
+ assert captured["url"].endswith("/subscriptions/sub-123")
+ assert "expirationDateTime" in captured["json"]
+
+
[email protected]("module_path,cls_name", GRAPH_CONNECTORS)
+async def test_graph_renew_returns_none_on_404(tmp_path, monkeypatch, module_path, cls_name):
+ import httpx
+
+ connector = _graph_connector(module_path, cls_name, tmp_path)
+ monkeypatch.setattr(httpx, "AsyncClient", _FakePatchClient({}, _FakeResponse(404)))
+
+ assert await connector.renew_subscription("sub-123") is None
+
+
[email protected]("module_path,cls_name", GRAPH_CONNECTORS)
+async def test_graph_renew_sentinel_skips_http(tmp_path, module_path, cls_name):
+ connector = _graph_connector(module_path, cls_name, tmp_path)
+ connector.authenticate = AsyncMock(side_effect=AssertionError("must not authenticate"))
+
+ assert await connector.renew_subscription("no-webhook-configured") is None
+
+
+async def test_google_drive_has_no_inplace_renewal(tmp_path):
+ """Drive inherits the base hook: None -> caller recreates the channel."""
+ from connectors.google_drive.connector import GoogleDriveConfig, GoogleDriveConnector
+
+ connector = GoogleDriveConnector.__new__(GoogleDriveConnector)
+ connector.cfg = GoogleDriveConfig(
+ client_id="fake-client-id",
+ client_secret="fake-client-secret",
+ token_file="/tmp/fake-token.json",
+ )
+
+ assert await connector.renew_subscription("channel-1") is None