:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): resume zendesk, attio, intercom and mongodb syncs (#109062)
Tom Owersfa2d3b8ae37d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.pyindex 2933c10867df..f466a14fec1e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py@@ -994,6 +994,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):is_resumable_source = isinstance(source, ResumableSource) and source.resume_covers_run(incremental_or_append=incremental_or_append,keyset_full_load_enabled=keyset_full_load_enabled,+ schema_name=schema_name,)max_resumable_attempts = MAX_RESUMABLE_SOURCE_RETRIESdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.pyindex b90f62ae1d61..7eccca3970a7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py@@ -330,7 +330,6 @@ class PipelineNonDLT(Generic[ResumableData]):safe_point_scope.close()await write_remaining_rows()-await self._persist_observed_columns()prepared_queryable_folder = await self._post_run_operations(row_count=row_count)@@ -340,6 +339,11 @@ class PipelineNonDLT(Generic[ResumableData]):result = PipelineResult(should_trigger_cdp_producer=await self._sinks.cdp_producer.should_run())if isinstance(prepared_queryable_folder, str):result["prepared_queryable_folder"] = prepared_queryable_folder+ if self._resource.on_complete is not None:+ try:+ await asyncio.to_thread(self._resource.on_complete)+ except Exception:+ await self._logger.aexception("Failed to clean up completed source state")return resultfinally:# Help reduce the memory footprint of each job. This is best-effort cleanup ofdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.pyindex 3f308cbff57b..1d59db73de3e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py@@ -556,7 +556,6 @@ class PipelineV3(Generic[ResumableData]):safe_point_scope.close()await stage_remaining_rows()-await self._finalize(row_count=row_count)# With zero batches, `_finalize` sent no final-batch notification, so the load@@ -564,10 +563,16 @@ class PipelineV3(Generic[ResumableData]):# See the PipelineResult docstring for the full ownership contract.consumer_will_hear_about_this_run = self._consumer_finalizes_this_run()- return {- "should_trigger_cdp_producer": await self._sinks.cdp_producer.should_run(),- "consumer_manages_job_status": consumer_will_hear_about_this_run,- }+ result = PipelineResult(+ should_trigger_cdp_producer=await self._sinks.cdp_producer.should_run(),+ consumer_manages_job_status=consumer_will_hear_about_this_run,+ )+ if self._resource.on_complete is not None:+ try:+ await asyncio.to_thread(self._resource.on_complete)+ except Exception:+ await self._logger.aexception("Failed to clean up completed source state")+ return resultexcept Exception:status = "error"self._logger.exception("V3 Pipeline: Extraction failed")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/attio/attio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/attio/attio.pyindex a6ee64230045..f990da3b0d81 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/attio/attio.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/attio/attio.py@@ -2,6 +2,8 @@ from typing import Any, Optionalfrom requests import Request, Response+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.attio.settings import ATTIO_ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (@@ -13,9 +15,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resEndpoint,EndpointResource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+@frozen+class AttioResumeConfig:+ # Row offset of the next page to fetch. The Redis key is per job, so one job never reads+ # another endpoint's offset.+ offset: int++class AttioOffsetPaginator(BasePaginator):"""Paginator for Attio endpoints using offset-based pagination.@@ -81,6 +91,17 @@ class AttioOffsetPaginator(BasePaginator):request.params["offset"] = self._current_offsetrequest.params["limit"] = self._limit+ def get_resume_state(self) -> Optional[dict[str, Any]]:+ # update_request has already moved _current_offset to the next page.+ return {"offset": self._current_offset} if self._has_next_page else None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ offset = state.get("offset")+ if offset is not None:+ self._current_offset = int(offset)+ self._next_offset = self._current_offset+ self._has_next_page = True+def _flatten_item(item: dict[str, Any]) -> dict[str, Any]:"""Flatten the nested 'id' object into the root level."""@@ -160,6 +181,7 @@ def attio_source(endpoint: str,team_id: int,job_id: str,+ resumable_source_manager: ResumableSourceManager[AttioResumeConfig],should_use_incremental_field: bool = False,db_incremental_field_last_value: Optional[Any] = None,incremental_field: str | None = None,@@ -189,7 +211,30 @@ def attio_source("resources": [get_resource(endpoint)],}- resource = rest_api_resource(config, team_id, job_id, None).add_map(_flatten_item)+ # Attio's GET endpoints do not expose a stable ordering. Their numeric offsets can skip a+ # live row when an earlier item is deleted between attempts, so only the explicitly sorted+ # POST endpoints may restore and save offsets.+ supports_resume = endpoint_config.method == "POST"+ initial_paginator_state: Optional[dict[str, Any]] = None+ if supports_resume and resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_paginator_state = {"offset": resume.offset}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # The framework calls this after it yields a page, and the offset points at the page after+ # it, so a resume never skips a page that the pipeline has not written.+ if state and state.get("offset") is not None:+ resumable_source_manager.save_state(AttioResumeConfig(offset=int(state["offset"])))++ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint if supports_resume else None,+ initial_paginator_state=initial_paginator_state,+ ).add_map(_flatten_item)return SourceResponse(name=endpoint,@@ -201,4 +246,5 @@ def attio_source(partition_format="week",partition_keys=[endpoint_config.partition_key],sort_mode="asc",+ supports_resume=supports_resume,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/attio/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/attio/source.pyindex 71862b38c292..49d24e313785 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/attio/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/attio/source.py@@ -7,15 +7,17 @@ from products.warehouse_sources.backend.facade.source_config import (SourceFieldInputConfigType,)from products.warehouse_sources.backend.temporal.data_imports.sources.attio.attio import (+ AttioResumeConfig,attio_source,validate_credentials as validate_attio_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.attio.settings import ATTIO_ENDPOINTS-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.attio import AttioSourceConfig@@ -23,7 +25,7 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AttioSource(SimpleSource[AttioSourceConfig]):+class AttioSource(ResumableSource[AttioSourceConfig, AttioResumeConfig]):supported_versions = ("v2",)default_version = "v2"api_docs_url = "https://developers.attio.com"@@ -41,6 +43,16 @@ class AttioSource(SimpleSource[AttioSourceConfig]):return CANONICAL_DESCRIPTIONS+ def resume_covers_run(+ self,+ *,+ incremental_or_append: bool,+ keyset_full_load_enabled: bool = False,+ schema_name: str | None = None,+ ) -> bool:+ endpoint = ATTIO_ENDPOINTS.get(schema_name or "")+ return endpoint is None or endpoint.method == "POST"+def get_non_retryable_errors(self) -> dict[str, str | None]:return {"401 Client Error: Unauthorized for url: https://api.attio.com": "Your Attio API key is invalid or expired. Please generate a new key and reconnect.",@@ -116,12 +128,21 @@ You can generate an API key in your Attio workspace settings. Check out [this gu) -> tuple[bool, str | None]:return validate_attio_credentials(config.api_key)- def source_for_pipeline(self, config: AttioSourceConfig, inputs: SourceInputs) -> SourceResponse:+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AttioResumeConfig]:+ return ResumableSourceManager[AttioResumeConfig](inputs, AttioResumeConfig)++ def source_for_pipeline(+ self,+ config: AttioSourceConfig,+ resumable_source_manager: ResumableSourceManager[AttioResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:return attio_source(api_key=config.api_key,endpoint=inputs.schema_name,team_id=inputs.team_id,job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,should_use_incremental_field=inputs.should_use_incremental_field,db_incremental_field_last_value=inputs.db_incremental_field_last_valueif inputs.should_use_incremental_fielddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/attio/tests/test_attio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/attio/tests/test_attio.pyindex 9e5da70747cf..4fe9f15e20e0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/attio/tests/test_attio.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/attio/tests/test_attio.py@@ -1,4 +1,20 @@-from products.warehouse_sources.backend.temporal.data_imports.sources.attio.attio import validate_credentials+import copy+import json+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.attio.attio import (+ AttioResumeConfig,+ attio_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.attio.settings import ATTIO_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerclass TestValidateCredentials:@@ -12,3 +28,112 @@ class TestValidateCredentials:assert "Retype it by hand" in (msg or "")assert "latin-1" not in (msg or "")assert "ordinal not in range" not in (msg or "")+++def _page(endpoint: str, start: int, count: int) -> Response:+ primary_key = ATTIO_ENDPOINTS[endpoint].primary_key+ rows = [+ {"id": {"workspace_id": "ws", primary_key: f"row-{i}"}, "created_at": "2024-01-01"}+ for i in range(start, start + count)+ ]+ resp = Response()+ resp.status_code = 200+ resp._content = json.dumps({"data": rows}).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++def _make_manager(resume: AttioResumeConfig | None = None) -> MagicMock:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = resume is not None+ manager.load_state.return_value = resume+ return manager+++class TestAttioResume:+ def _drive(+ self, endpoint: str, manager: MagicMock, responses: list[Response]+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:+ sent: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ # The paginator mutates one request object across pages, so copy what each send carries.+ sent.append(copy.deepcopy(request.json if request.method == "POST" else request.params))+ return next(response_iter)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ response = attio_source(+ api_key="key",+ endpoint=endpoint,+ team_id=1,+ job_id="job",+ resumable_source_manager=manager,+ )+ rows = [row for page in cast(Iterable[list[dict[str, Any]]], response.items()) for row in page]+ return sent, rows++ @pytest.mark.parametrize("endpoint", ["companies", "people", "deals"])+ def test_fresh_run_stages_next_offset_after_each_page(self, endpoint: str) -> None:+ limit = ATTIO_ENDPOINTS[endpoint].page_size+ manager = _make_manager()+ responses = [_page(endpoint, 0, limit), _page(endpoint, limit, limit), _page(endpoint, 2 * limit, 3)]++ sent, rows = self._drive(endpoint, manager, responses)++ assert [request["offset"] for request in sent] == [0, limit, 2 * limit]+ assert all(request["limit"] == limit for request in sent)+ assert len(rows) == 2 * limit + 3+ assert rows[-1][ATTIO_ENDPOINTS[endpoint].primary_key] == f"row-{2 * limit + 2}"+ assert [call.args[0] for call in manager.save_state.call_args_list] == [+ AttioResumeConfig(offset=limit),+ AttioResumeConfig(offset=2 * limit),+ ]+ manager.load_state.assert_not_called()++ @pytest.mark.parametrize("endpoint", ["companies", "notes"])+ def test_single_short_page_stages_nothing(self, endpoint: str) -> None:+ manager = _make_manager()++ sent, rows = self._drive(endpoint, manager, [_page(endpoint, 0, 2)])++ assert [request["offset"] for request in sent] == [0]+ assert len(rows) == 2+ manager.save_state.assert_not_called()++ @pytest.mark.parametrize("endpoint", ["companies", "people"])+ def test_resumed_run_starts_from_saved_offset(self, endpoint: str) -> None:+ limit = ATTIO_ENDPOINTS[endpoint].page_size+ manager = _make_manager(AttioResumeConfig(offset=2 * limit))+ responses = [_page(endpoint, 2 * limit, limit), _page(endpoint, 3 * limit, 1)]++ sent, rows = self._drive(endpoint, manager, responses)++ assert [request["offset"] for request in sent] == [2 * limit, 3 * limit]+ assert rows[0][ATTIO_ENDPOINTS[endpoint].primary_key] == f"row-{2 * limit}"+ assert [call.args[0] for call in manager.save_state.call_args_list] == [AttioResumeConfig(offset=3 * limit)]++ @pytest.mark.parametrize("endpoint", ["lists", "notes", "tasks", "workspace_members"])+ def test_get_endpoint_ignores_offset_checkpoint(self, endpoint: str) -> None:+ manager = _make_manager(AttioResumeConfig(offset=ATTIO_ENDPOINTS[endpoint].page_size))++ sent, _ = self._drive(endpoint, manager, [_page(endpoint, 0, 1)])++ assert sent[0]["offset"] == 0+ manager.load_state.assert_not_called()+ manager.save_state.assert_not_called()++ def test_resumed_query_keeps_sort_order_in_body(self) -> None:+ # Offsets only line up across runs when every run asks for the same order.+ manager = _make_manager(AttioResumeConfig(offset=500))++ sent, _ = self._drive("companies", manager, [_page("companies", 500, 1)])++ assert sent == [{"sorts": [{"attribute": "created_at", "direction": "asc"}], "offset": 500, "limit": 500}]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/attio/tests/test_attio_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/attio/tests/test_attio_source.pyindex effc5f001b27..ace6ac21b6e9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/attio/tests/test_attio_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/attio/tests/test_attio_source.py@@ -9,6 +9,13 @@ class TestAttioSource:def setup_method(self):self.source = AttioSource()+ @pytest.mark.parametrize(+ "schema_name,expected",+ [("companies", True), ("notes", False), ("tasks", False)],+ )+ def test_retry_budget_only_covers_sorted_post_endpoints(self, schema_name, expected):+ assert self.source.resume_covers_run(incremental_or_append=False, schema_name=schema_name) is expected+@pytest.mark.parametrize("pattern",[diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.pyindex 2b0728bdb0d8..cb0655926d3a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py@@ -499,7 +499,13 @@ class SimpleSource(_BaseSource[ConfigType], Generic[ConfigType]):class ResumableSource(_BaseSource[ConfigType], Generic[ConfigType, ResumableData]):"""Base class for sources that support resumable full-refresh imports."""- def resume_covers_run(self, *, incremental_or_append: bool, keyset_full_load_enabled: bool = False) -> bool:+ def resume_covers_run(+ self,+ *,+ incremental_or_append: bool,+ keyset_full_load_enabled: bool = False,+ schema_name: str | None = None,+ ) -> bool:"""Whether this source's resume mechanism covers a run of this shape.Only the retry budget reads this. A run it covers gets the resumable allowance, which is much@@ -508,8 +514,9 @@ class ResumableSource(_BaseSource[ConfigType], Generic[ConfigType, ResumableDataordinary budgets, because extra attempts would each redo the whole read.Default True: a REST source paginates the same way whichever sync type it runs. A source- whose mechanism is narrower than its class — keyset seeking is a full-load path, and a seek- gated behind a retry fallback covers almost nothing — narrows it here.+ whose mechanism is narrower than its class — keyset seeking is a full-load path, a specific+ endpoint cannot checkpoint, or a seek gated behind a retry fallback covers almost nothing —+ narrows it here. ``schema_name`` identifies the endpoint when that distinction matters."""return Truediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.pyindex 4a94e376b958..5025e607cc8e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py@@ -478,10 +478,12 @@ class RESTClient:if resume_hook is not None:resume_hook(paginator.get_resume_state() if paginator is not None and paginator.has_next_page else None)+ reach_framework_safe_point()# Direct Resource traversal has consumed the page before execution resumes here, so this# is safe even when a dependent resource routes its resume hook only to the child.- reach_framework_safe_point()+ if resume_hook is None:+ reach_framework_safe_point()if paginator is None or not paginator.has_next_page:breakdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.pyindex 191adbe5cd59..f06f55eb9aa7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py@@ -89,7 +89,7 @@ class ResumableSourceManager(Generic[ResumableData]):try:parsed_data = json.loads(data)except Exception as e:- raise ValueError(f"Failed to load resumable data: {data}") from e+ raise ValueError("Failed to load resumable data") from e# Fields the running code does not know come from state a newer deploy wrote. Dropping# them makes a rollback a cache miss; passing them through raises TypeError and fails@@ -121,9 +121,8 @@ class ResumableSourceManager(Generic[ResumableData]):Nothing reaches Redis until commit(), which the pipeline calls right after a write lands.A source with nothing outstanding stages inside committing(), which commits at block end."""- json_data = self._dump_json(data)- self._logger.debug(f"Staging resumable source state. key={self._key}, data={json_data}")- self._staged[self._key] = json_data+ # No log here: a source can stage on every row, and commit() logs each cursor that persists.+ self._staged[self._key] = self._dump_json(data)def has_staged_state(self) -> bool:"""Whether the next `commit` will write anything."""@@ -135,7 +134,7 @@ class ResumableSourceManager(Generic[ResumableData]):returnwith self._get_redis() as redis_client:for key, json_data in list(self._staged.items()):- self._logger.debug(f"Saving resumable source state. key={key}, data={json_data}")+ self._logger.debug(f"Saving resumable source state. key={key}")self._write_with_stale_replica_retry(redis_client,functools.partial(redis_client.set, key, json_data, ex=60 * 60 * 24), # 24 hours expiration@@ -190,7 +189,7 @@ class ResumableSourceManager(Generic[ResumableData]):self._logger.debug(f"No resumable source state found. key={self._key}")return None- self._logger.debug(f"Loading resumable source state. key={self._key}, data={data}")+ self._logger.debug(f"Loading resumable source state. key={self._key}")return self._load_json(data)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.pyindex e5c136d95102..8ca881abe94a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py@@ -79,6 +79,21 @@ class TestResumableSourceManager:"posthog:data_warehouse:resumable_source:1:job-1", '{"cursor":"cus_2"}', ex=60 * 60 * 24)+ def test_save_and_load_logs_do_not_include_cursor_payloads(self):+ manager = _manager()+ redis = MagicMock()+ redis.get.return_value = '{"cursor":"sensitive-customer-id"}'++ with patch.object(ResumableSourceManager, "_get_redis") as get_redis:+ get_redis.return_value.__enter__.return_value = redis+ manager.save_state(_SweepPosition(cursor="sensitive-customer-id"))+ manager.commit()+ manager.load_state()++ logger = typing.cast(MagicMock, manager._logger)+ messages = [str(call.args[0]) for call in logger.debug.call_args_list]+ assert all("sensitive-customer-id" not in message for message in messages)+def test_committing_persists_the_staged_state_even_when_the_block_raises(self):manager = _manager()redis = MagicMock()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.pyindex 3db4e9f3024e..f6a62591902f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py@@ -113,6 +113,9 @@ class SourceResponse:incremental watermark). Gated by the pipeline together with a non-None resumable-source manager,so a resumable-source class whose current table isn't actually resumable (e.g. a SQL full loadwith no orderable primary key) sets this False and is treated as non-resumable for shutdown."""+ on_complete: Optional[Callable[[], None]] = None+ """Called after every yielded row has been durably written or staged. Sources use this to remove+ a final checkpoint without opening a crash window before the pipeline flushes its last batch."""destination_reset_required: bool = False"""Whether source metadata discovered during setup requires rebuilding the destination table."""lanes: Optional[list[OutputLane]] = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.pyindex 483ba7394b7a..2793e80ff3c9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.py@@ -1,6 +1,7 @@import time+import dataclassesfrom collections.abc import AsyncIterable, Callable, Iterable, Iterator-from typing import Any, Optional+from typing import Any, Optional, castimport structlogfrom requests import Request, Response, Session@@ -26,6 +27,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resEndpoint,EndpointResource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.intercom.settings import (INTERCOM_ENDPOINTS,@@ -40,6 +42,49 @@ INTERCOM_API_VERSION = "2.13"logger = structlog.get_logger(__name__)[email protected](frozen=True)+class IntercomResumeConfig:+ # List endpoints whose `pages.next` is a link: the next page to fetch.+ next_url: str | None = None+ # Search endpoints, cursor list endpoints, and the conversation_parts parent walk: the+ # `starting_after` cursor of the next page to fetch.+ cursor: str | None = None+ # The `updated_at >` filter value the search cursor belongs to. A cursor only continues the+ # query that issued it, so a resume replays this value even when the watermark has moved.+ query_value: int | None = None+ # conversation_parts: conversations in the page at `cursor` whose parts are already yielded.+ completed_conversation_ids: list[str] = dataclasses.field(default_factory=list)+ # company_segments: every company id that sorts at or before this one is already yielded.+ last_company_id: str | None = None+++def _load_resume_state(+ resumable_source_manager: ResumableSourceManager[IntercomResumeConfig] | None,+) -> IntercomResumeConfig | None:+ if resumable_source_manager is None or not resumable_source_manager.can_resume():+ return None+ return resumable_source_manager.load_state()+++def _is_invalid_resume_cursor(exc: HTTPError) -> bool:+ """Whether Intercom rejected a persisted pagination cursor rather than the request itself."""+ response = exc.response+ if response is None or response.status_code not in (400, 404, 410):+ return False+ # Persisted next-page URLs can expire without naming their internal cursor in the response.+ if response.status_code in (404, 410):+ return True+ try:+ body = response.json()+ except Exception:+ body = response.text+ text = str(body).lower()+ names_pagination = any(marker in text for marker in ("cursor", "starting_after", "pagination", "page token"))+ return names_pagination and any(+ marker in text for marker in ("invalid", "expired", "not found", "parameter_invalid")+ )++def _is_not_found(exc: HTTPError) -> bool:"""A child row referenced by a parent can vanish (deleted/merged) betweenthe parent listing and the per-row detail fetch — Intercom then returns@@ -155,12 +200,24 @@ class IntercomSearchPaginator(BasePaginator):self._next_cursor = Noneself._has_next_page = False+ def init_request(self, request: Request) -> None:+ self.update_request(request)+def update_request(self, request: Request) -> None:if self._next_cursor is None or request.json is None:returnpagination = request.json.setdefault("pagination", {})pagination["starting_after"] = self._next_cursor+ def get_resume_state(self) -> Optional[dict[str, Any]]:+ return {"cursor": self._next_cursor} if self._has_next_page and self._next_cursor is not None else None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ cursor = state.get("cursor")+ if cursor is not None:+ self._next_cursor = cursor+ self._has_next_page = True+class IntercomPagesPaginator(BaseNextUrlPaginator):"""Paginator for Intercom list endpoints whose ``pages.next`` shape varies.@@ -202,6 +259,9 @@ class IntercomPagesPaginator(BaseNextUrlPaginator):self._cursor = cursor or Noneself._has_next_page = bool(cursor)+ def init_request(self, request: Request) -> None:+ self.update_request(request)+def update_request(self, request: Request) -> None:if self._next_url is not None:super().update_request(request)@@ -211,6 +271,24 @@ class IntercomPagesPaginator(BaseNextUrlPaginator):request.params = {}request.params["starting_after"] = self._cursor+ def get_resume_state(self) -> Optional[dict[str, Any]]:+ if not self._has_next_page:+ return None+ if self._next_url is not None:+ return {"next_url": self._next_url}+ if self._cursor is not None:+ return {"cursor": self._cursor}+ return None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ if state.get("next_url") is not None:+ super().set_resume_state(state)+ return+ cursor = state.get("cursor")+ if cursor is not None:+ self._cursor = cursor+ self._has_next_page = True+def __str__(self) -> str:return "IntercomPagesPaginator()"@@ -382,46 +460,70 @@ def _intercom_post(session: Session, path_or_url: str, body: dict[str, Any]) ->return _request_with_rate_limit_retry(do)-def _iter_conversations(+def _conversation_parts_generator(session: Session,incremental_field: str,db_incremental_field_last_value: Optional[Any],+ resumable_source_manager: ResumableSourceManager[IntercomResumeConfig] | None = None,) -> Iterator[dict[str, Any]]:- """Walk `POST /conversations/search` honoring the same `updated_at >`- server-side filter the conversations endpoint uses, so substreams only- refetch parents whose timestamp advanced."""+ """Yield each conversation part. Parents come from `POST /conversations/search`+ with the same `updated_at >` server-side filter the conversations endpoint uses,+ so only parents whose timestamp advanced are refetched. The part rows carry their+ own `updated_at`, so the pipeline's cursor watermark advances per-part.+ `conversation_id` is injected onto each row for joinability.++ The resume cursor is the parent page plus the conversations in it that are done,+ staged after each conversation's parts are yielded. A resume refetches that page+ and skips the done conversations."""body = _build_search_body(INTERCOM_ENDPOINTS["conversations"], incremental_field, db_incremental_field_last_value)+ completed: list[str] = []+ resume = _load_resume_state(resumable_source_manager)+ if resume is not None and resume.query_value is not None:+ body["query"]["value"] = resume.query_value+ if resume.cursor is not None:+ body["pagination"]["starting_after"] = resume.cursor+ completed = list(resume.completed_conversation_ids)+ query_value = body["query"]["value"]++ def stage(page_cursor: str | None, done: list[str]) -> None:+ if resumable_source_manager is None:+ return+ resumable_source_manager.save_state(+ IntercomResumeConfig(cursor=page_cursor, query_value=query_value, completed_conversation_ids=list(done))+ )+ # Every part the staged cursor covers is yielded and nothing is buffered here. Many+ # conversations have no parts, so the walk can make many requests between rows.+ resumable_source_manager.safe_point()+while True:+ page_cursor = body["pagination"].get("starting_after")payload = _intercom_post(session, "/conversations/search", body)- yield from (payload.get("conversations") or [])+ done_ids = set(completed)+ for conv in payload.get("conversations") or []:+ conversation_id = str(conv["id"])+ if conversation_id in done_ids:+ continue+ try:+ full = _intercom_get(session, f"/conversations/{conv['id']}")+ except HTTPError as exc:+ if not _is_not_found(exc):+ raise+ logger.warning("intercom_conversation_not_found", conversation_id=conv["id"])+ else:+ parts = (full.get("conversation_parts") or {}).get("conversation_parts") or []+ for part in parts:+ part["conversation_id"] = conv["id"]+ yield part+ completed.append(conversation_id)+ done_ids.add(conversation_id)+ stage(page_cursor, completed)next_block = (payload.get("pages") or {}).get("next") or {}cursor = next_block.get("starting_after") if isinstance(next_block, dict) else Noneif not cursor:returnbody["pagination"]["starting_after"] = cursor---def _conversation_parts_generator(- session: Session,- incremental_field: str,- db_incremental_field_last_value: Optional[Any],-) -> Iterator[dict[str, Any]]:- """Yield each conversation part. Parents are server-filtered by- `updated_at >`; the part rows themselves carry their own `updated_at`,- so the pipeline's cursor watermark advances per-part. `conversation_id`- is injected onto each row for joinability."""- for conv in _iter_conversations(session, incremental_field, db_incremental_field_last_value):- try:- full = _intercom_get(session, f"/conversations/{conv['id']}")- except HTTPError as exc:- if _is_not_found(exc):- logger.warning("intercom_conversation_not_found", conversation_id=conv["id"])- continue- raise- parts = (full.get("conversation_parts") or {}).get("conversation_parts") or []- for part in parts:- part["conversation_id"] = conv["id"]- yield part+ completed = []+ stage(cursor, completed)# Intercom expires an idle companies scroll after ~1 minute, so a stale scroll@@ -498,7 +600,7 @@ def _open_companies_scroll(session: Session) -> dict[str, Any]:raise AssertionError("unreachable")-def _iter_companies(session: Session) -> Iterator[dict[str, Any]]:+def _iter_companies(session: Session, after_page: Callable[[], None] | None = None) -> Iterator[dict[str, Any]]:"""Walk every company via `GET /companies/scroll` (full refresh).`POST /companies/list` is hard-capped at 10,000 companies — paging past@@ -518,12 +620,14 @@ def _iter_companies(session: Session) -> Iterator[dict[str, Any]]:if not data:returnyield from data+ if after_page is not None:+ after_page()scroll_param = payload.get("scroll_param")if not scroll_param:return-def _drain_company_ids(session: Session) -> list[str]:+def _drain_company_ids(session: Session, after_page: Callable[[], None] | None = None) -> list[str]:"""Walk the whole companies scroll and collect every id, restarting the walkfrom the beginning if the scroll cursor expires mid-drain (404 on acontinuation — see `_SCROLL_EXPIRED_MAX_RETRIES`).@@ -536,7 +640,7 @@ def _drain_company_ids(session: Session) -> list[str]:and Temporal restarts the whole run from a freshly-wiped table instead.)"""for attempt in range(_SCROLL_EXPIRED_MAX_RETRIES + 1):try:- return [company["id"] for company in _iter_companies(session)]+ return [company["id"] for company in _iter_companies(session, after_page)]except HTTPError as exc:if _is_scroll_expired(exc) and attempt < _SCROLL_EXPIRED_MAX_RETRIES:logger.warning("intercom_companies_scroll_expired_restart", attempt=attempt + 1)@@ -546,7 +650,10 @@ def _drain_company_ids(session: Session) -> list[str]:raise AssertionError("unreachable")-def _company_segments_generator(session: Session) -> Iterator[dict[str, Any]]:+def _company_segments_generator(+ session: Session,+ resumable_source_manager: ResumableSourceManager[IntercomResumeConfig] | None = None,+) -> Iterator[dict[str, Any]]:"""Walk all companies and yield each attached segment with `company_id`injected. Full refresh — Intercom has no server-side timestamp filter oneither parent or child.@@ -558,19 +665,34 @@ def _company_segments_generator(session: Session) -> Iterator[dict[str, Any]]:Draining first keeps the scroll requests back-to-back so it stays alive;only the ids are held, not the full company payloads, so the memoryfootprint stays small. If the cursor is still invalidated mid-drain,- `_drain_company_ids` restarts the walk from scratch."""- company_ids = _drain_company_ids(session)+ `_drain_company_ids` restarts the walk from scratch.++ The ids are sorted so that each attempt walks them in the same order, whatever+ order its scroll returns. The resume cursor is the last company whose segments+ are yielded, and a resume skips every id that sorts at or before it."""+ resume = _load_resume_state(resumable_source_manager)+ last_company_id = resume.last_company_id if resume is not None else None+ # No row is yielded during the drain, and nothing is staged yet, so a hand-off here+ # resumes from the cursor the previous attempt committed.+ safe_point = resumable_source_manager.safe_point if resumable_source_manager is not None else None+ company_ids = sorted(_drain_company_ids(session, safe_point))for company_id in company_ids:+ if last_company_id is not None and company_id <= last_company_id:+ continuetry:payload = _intercom_get(session, f"/companies/{company_id}/segments")except HTTPError as exc:- if _is_not_found(exc):- logger.warning("intercom_company_not_found", company_id=company_id)- continue- raise- for seg in payload.get("data", []) or []:- seg["company_id"] = company_id- yield seg+ if not _is_not_found(exc):+ raise+ logger.warning("intercom_company_not_found", company_id=company_id)+ else:+ for seg in payload.get("data", []) or []:+ seg["company_id"] = company_id+ yield seg+ if resumable_source_manager is not None:+ resumable_source_manager.save_state(IntercomResumeConfig(last_company_id=company_id))+ # Most companies have no segments, so the fan-out can make many requests between rows.+ resumable_source_manager.safe_point()def _substream_items(@@ -578,6 +700,7 @@ def _substream_items(endpoint: str,incremental_field: str | None,db_incremental_field_last_value: Optional[Any],+ resumable_source_manager: ResumableSourceManager[IntercomResumeConfig] | None = None,) -> Iterator[dict[str, Any]]:if endpoint == "conversation_parts":if not incremental_field:@@ -585,9 +708,11 @@ def _substream_items(# walk every conversation. `updated_at` is the only declared# cursor, so default to it for the parent search filter.incremental_field = "updated_at"- return _conversation_parts_generator(session, incremental_field, db_incremental_field_last_value)+ return _conversation_parts_generator(+ session, incremental_field, db_incremental_field_last_value, resumable_source_manager+ )if endpoint == "company_segments":- return _company_segments_generator(session)+ return _company_segments_generator(session, resumable_source_manager)raise ValueError(f"Unknown Intercom substream endpoint: {endpoint}")@@ -627,32 +752,87 @@ def validate_credentials(return False, f"HTTP {response.status_code}: {response.text[:200]}"+def _rest_resume_state(cfg: IntercomEndpointConfig, resume: IntercomResumeConfig | None) -> dict[str, Any] | None:+ if resume is None:+ return None+ if cfg.paginator_kind == "search":+ # A search cursor without the filter it was issued under cannot be replayed safely.+ return {"cursor": resume.cursor} if resume.cursor is not None and resume.query_value is not None else None+ if cfg.paginator_kind in ("cursor", "next_url", "pages"):+ if resume.next_url is not None:+ return {"next_url": resume.next_url}+ if resume.cursor is not None:+ return {"cursor": resume.cursor}+ return None++def intercom_source(access_token: str,endpoint: str,team_id: int,job_id: str,api_version: str,+ resumable_source_manager: ResumableSourceManager[IntercomResumeConfig],should_use_incremental_field: bool = False,incremental_field: str | None = None,db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:cfg = INTERCOM_ENDPOINTS[endpoint]items: Callable[[], Iterable[Any] | AsyncIterable[Any]]+ supports_resume = Trueif cfg.paginator_kind == "substream":# One session built here is reused across the parent walk and every# per-row child fetch, so urllib3 keeps the connection alive instead# of re-handshaking per request.session = _make_intercom_session(access_token, api_version)- items = lambda: _substream_items(session, endpoint, incremental_field, db_incremental_field_last_value)++ def iter_substream() -> Iterator[Any]:+ had_resume_state = resumable_source_manager.can_resume()+ try:+ yield from _substream_items(+ session, endpoint, incremental_field, db_incremental_field_last_value, resumable_source_manager+ )+ except HTTPError as exc:+ if had_resume_state and _is_invalid_resume_cursor(exc):+ resumable_source_manager.clear_state()+ raise++ items = iter_substreamelif cfg.paginator_kind == "scroll":# The Scroll API doesn't fit the framework paginators (the cursor is a# `scroll_param`, not a request mutation), so `companies` walks it with a# custom iterator. One session is reused across the whole scroll walk.session = _make_intercom_session(access_token, api_version)items = lambda: _iter_companies(session)+ # A scroll expires after about a minute idle and only restarts from the beginning,+ # so no cursor outlives the hand-off to another worker.+ supports_resume = Falseelse:+ resource_config = get_resource(+ endpoint,+ should_use_incremental_field,+ incremental_field,+ db_incremental_field_last_value,+ )+ search_body = cast(dict[str, Any], resource_config["endpoint"]).get("json")+ resume = _load_resume_state(resumable_source_manager)+ initial_paginator_state = _rest_resume_state(cfg, resume)+ if search_body is not None and initial_paginator_state is not None and resume is not None:+ search_body["query"]["value"] = resume.query_value+ query_value: int | None = search_body["query"]["value"] if search_body is not None else None++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # The framework calls this after it yields a page, with the state of the next page.+ if not state:+ return+ if state.get("next_url"):+ resumable_source_manager.save_state(IntercomResumeConfig(next_url=state["next_url"]))+ elif state.get("cursor"):+ resumable_source_manager.save_state(+ IntercomResumeConfig(cursor=state["cursor"], query_value=query_value)+ )+config: RESTAPIConfig = {"client": {"base_url": INTERCOM_API_BASE,@@ -663,17 +843,28 @@ def intercom_source("headers": _default_headers(api_version),},"resource_defaults": {},- "resources": [- get_resource(- endpoint,- should_use_incremental_field,- incremental_field,- db_incremental_field_last_value,- )- ],+ "resources": [resource_config],}- resource = rest_api_resource(config, team_id, job_id, db_incremental_field_last_value)- items = lambda: resource+ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ def iter_resource() -> Iterator[Any]:+ try:+ yield from resource+ except HTTPError as exc:+ if initial_paginator_state is not None and _is_invalid_resume_cursor(exc):+ # Fail this attempt after invalidating the poisoned cursor. The next Temporal+ # attempt restarts from the durable watermark (or from the beginning).+ resumable_source_manager.clear_state()+ raise++ items = iter_resourcereturn SourceResponse(name=endpoint,@@ -685,4 +876,5 @@ def intercom_source(partition_count=cfg.partition_count,partition_size=cfg.partition_size,sort_mode=cfg.sort_mode,+ supports_resume=supports_resume,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/source.pyindex c20d4b6b219b..e66b5cf7a1d0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/source.py@@ -6,18 +6,20 @@ from products.warehouse_sources.backend.facade.source_config import (SourceConfig,SourceFieldOauthConfig,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import OAuthMixinfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.intercom import (IntercomSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.intercom.intercom import (+ IntercomResumeConfig,intercom_source,validate_credentials as validate_intercom_credentials,)@@ -29,7 +31,7 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class IntercomSource(SimpleSource[IntercomSourceConfig], OAuthMixin):+class IntercomSource(ResumableSource[IntercomSourceConfig, IntercomResumeConfig], OAuthMixin):lists_tables_without_credentials = True # static endpoint catalog — safe for public docssupported_versions = ("2.13", "2.15", "2.16")default_version = "2.16"@@ -58,6 +60,16 @@ class IntercomSource(SimpleSource[IntercomSourceConfig], OAuthMixin):"Intercom access token not found": "Intercom OAuth access token is missing. Please reconnect your Intercom account.",}+ def resume_covers_run(+ self,+ *,+ incremental_or_append: bool,+ keyset_full_load_enabled: bool = False,+ schema_name: str | None = None,+ ) -> bool:+ # The companies Scroll API cannot preserve a cursor across worker hand-offs.+ return schema_name != "companies"+def get_retryable_errors(self) -> set[str]:# The `companies` table walks Intercom's companies Scroll API (`_iter_companies` in# intercom.py). The scroll cursor expires mid-walk on idle timeout or when a@@ -152,7 +164,15 @@ class IntercomSource(SimpleSource[IntercomSourceConfig], OAuthMixin):integration.access_token, schema_name=schema_name, api_version=self.resolve_api_version(api_version))- def source_for_pipeline(self, config: IntercomSourceConfig, inputs: SourceInputs) -> SourceResponse:+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[IntercomResumeConfig]:+ return ResumableSourceManager[IntercomResumeConfig](inputs, IntercomResumeConfig)++ def source_for_pipeline(+ self,+ config: IntercomSourceConfig,+ resumable_source_manager: ResumableSourceManager[IntercomResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:integration = self.get_oauth_integration(config.intercom_integration_id, inputs.team_id)if not integration.access_token:@@ -164,6 +184,7 @@ class IntercomSource(SimpleSource[IntercomSourceConfig], OAuthMixin):team_id=inputs.team_id,job_id=inputs.job_id,api_version=self.resolve_api_version(inputs.api_version),+ resumable_source_manager=resumable_source_manager,should_use_incremental_field=inputs.should_use_incremental_field,incremental_field=inputs.incremental_field if inputs.should_use_incremental_field else None,db_incremental_field_last_value=inputs.db_incremental_field_last_valuediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom.pyindex 8b4e0aed625c..7e1a218547b8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom.py@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.intercom ifrom products.warehouse_sources.backend.temporal.data_imports.sources.intercom.intercom import (INTERCOM_API_BASE,IntercomPagesPaginator,+ IntercomResumeConfig,IntercomSearchPaginator,_build_paginator,_build_search_body,@@ -59,6 +60,17 @@ SCROLL_EXISTS_BODY = {}+def _manager(state: IntercomResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = state is not None+ manager.load_state.return_value = state+ return manager+++def _staged(manager: mock.MagicMock) -> list[IntercomResumeConfig]:+ return [call.args[0] for call in manager.save_state.call_args_list]++def _http_error(json_body: Any, status_code: int = 400, text: str = "") -> HTTPError:return HTTPError(response=_make_response(json_body, status_code=status_code, text=text))@@ -823,12 +835,15 @@ class TestIntercomSource:team_id=1,job_id="job-1",api_version="2.15",+ resumable_source_manager=_manager(),)assert response.name == endpointassert response.primary_keys == cfg.primary_keysassert response.partition_keys == [cfg.partition_key]assert response.sort_mode == cfg.sort_mode+ # A companies scroll expires within a minute and cannot restart mid-walk.+ assert response.supports_resume is (cfg.paginator_kind != "scroll")def test_companies_routes_through_scroll_api(self):# `companies` must walk the un-capped Scroll API, never `POST /companies/list`@@ -844,7 +859,12 @@ class TestIntercomSource:with mock.patch.object(intercom_module, "make_tracked_session", return_value=mock_session):response = intercom_source(- access_token="token", endpoint="companies", team_id=1, job_id="job-1", api_version="2.15"+ access_token="token",+ endpoint="companies",+ team_id=1,+ job_id="job-1",+ api_version="2.15",+ resumable_source_manager=_manager(),)# `items()` is typed `Iterable | AsyncIterable`; the scroll path yields a sync iterator.companies = list(cast(Iterable[dict[str, Any]], response.items()))@@ -871,7 +891,12 @@ class TestVersionDispatch:with mock.patch.object(intercom_module, "make_tracked_session", side_effect=fake_session):response = intercom_source(- access_token="token", endpoint="companies", team_id=1, job_id="job-1", api_version=api_version+ access_token="token",+ endpoint="companies",+ team_id=1,+ job_id="job-1",+ api_version=api_version,+ resumable_source_manager=_manager(),)list(cast(Iterable[dict[str, Any]], response.items()))@@ -881,8 +906,353 @@ class TestVersionDispatch:def test_rest_path_sends_pinned_version_header(self, api_version: str):with mock.patch.object(intercom_module, "rest_api_resource", return_value=object()) as mock_rest:intercom_source(- access_token="token", endpoint="contacts", team_id=1, job_id="job-1", api_version=api_version+ access_token="token",+ endpoint="contacts",+ team_id=1,+ job_id="job-1",+ api_version=api_version,+ resumable_source_manager=_manager(),)config = mock_rest.call_args.args[0]assert config["client"]["headers"]["Intercom-Version"] == api_version+++REST_CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+NEXT_URL = f"{INTERCOM_API_BASE}/admins/activity_logs?created_at_after=0&page=2"+SECOND_URL = f"{INTERCOM_API_BASE}/news/news_items?page=3"+++def _wire_rest_session(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ # The client mutates one Request across pages, so copy what each send carries.+ session.headers = {}+ sent: list[dict[str, Any]] = []++ def prepare(request: Any) -> mock.MagicMock:+ sent.append(+ {+ "url": request.url,+ "params": dict(request.params or {}),+ "json": json.loads(json.dumps(request.json)) if request.json is not None else None,+ }+ )+ return mock.MagicMock()++ session.prepare_request.side_effect = prepare+ session.send.side_effect = responses+ return sent+++def _run_rest(+ endpoint: str, manager: mock.MagicMock, responses: list[Response], **kwargs: Any+) -> tuple[list[Any], list[dict[str, Any]]]:+ with mock.patch(REST_CLIENT_SESSION_PATCH) as make_session:+ sent = _wire_rest_session(make_session.return_value, responses)+ response = intercom_source(+ access_token="token",+ endpoint=endpoint,+ team_id=1,+ job_id="job-1",+ api_version="2.16",+ resumable_source_manager=manager,+ **kwargs,+ )+ rows = [row["id"] for page in cast(Iterable[list[dict[str, Any]]], response.items()) for row in page]+ return rows, sent+++def _page(selector: str, ids: list[int], next_block: Any) -> Response:+ return _make_response({selector: [{"id": i} for i in ids], "pages": {"next": next_block}})+++class TestResumableRestEndpoints:+ @pytest.mark.parametrize(+ "endpoint,selector,next_blocks,expected_staged",+ [+ (+ "contacts",+ "data",+ [{"starting_after": "c2"}, {"starting_after": "c3"}, None],+ [IntercomResumeConfig(cursor="c2", query_value=0), IntercomResumeConfig(cursor="c3", query_value=0)],+ ),+ (+ "activity_logs",+ "activity_logs",+ [NEXT_URL, f"{NEXT_URL}3", None],+ [IntercomResumeConfig(next_url=NEXT_URL), IntercomResumeConfig(next_url=f"{NEXT_URL}3")],+ ),+ (+ "collections",+ "data",+ [{"starting_after": "c2"}, {"starting_after": "c3"}, None],+ [IntercomResumeConfig(cursor="c2"), IntercomResumeConfig(cursor="c3")],+ ),+ (+ "news_items",+ "data",+ [f"{INTERCOM_API_BASE}/news/news_items?page=2", SECOND_URL, None],+ [+ IntercomResumeConfig(next_url=f"{INTERCOM_API_BASE}/news/news_items?page=2"),+ IntercomResumeConfig(next_url=SECOND_URL),+ ],+ ),+ ],+ )+ def test_fresh_run_stages_the_next_page_after_each_page(+ self, endpoint: str, selector: str, next_blocks: list[Any], expected_staged: list[IntercomResumeConfig]+ ):+ manager = _manager()+ responses = [_page(selector, [i], block) for i, block in enumerate(next_blocks)]++ rows, _ = _run_rest(endpoint, manager, responses)++ assert rows == [0, 1, 2]+ # The last page has no next page, so nothing is staged for it.+ assert _staged(manager) == expected_staged++ def test_resumed_search_replays_the_saved_filter_and_cursor(self):+ # The watermark moved since the cursor was issued. The cursor only continues its own query,+ # so the resume keeps the old filter value, and so do the checkpoints after it.+ manager = _manager(IntercomResumeConfig(cursor="c5", query_value=1600000000))+ responses = [_page("data", [5], {"starting_after": "c6"}), _page("data", [6], None)]++ rows, sent = _run_rest(+ "contacts",+ manager,+ responses,+ should_use_incremental_field=True,+ incremental_field="updated_at",+ db_incremental_field_last_value="1700000000",+ )++ assert rows == [5, 6]+ assert sent[0]["json"]["pagination"]["starting_after"] == "c5"+ assert sent[0]["json"]["query"]["value"] == 1600000000+ assert _staged(manager) == [IntercomResumeConfig(cursor="c6", query_value=1600000000)]++ def test_expired_search_cursor_is_cleared_before_retry(self):+ manager = _manager(IntercomResumeConfig(cursor="expired", query_value=1600000000))+ rejected = _make_response(+ {"type": "error.list", "errors": [{"code": "parameter_invalid", "message": "cursor expired"}]},+ status_code=400,+ )++ with pytest.raises(HTTPError):+ _run_rest(+ "contacts",+ manager,+ [rejected],+ should_use_incremental_field=True,+ incremental_field="updated_at",+ db_incremental_field_last_value="1700000000",+ )++ manager.clear_state.assert_called_once_with()++ @pytest.mark.parametrize(+ "state",+ [+ IntercomResumeConfig(cursor="c5"),+ IntercomResumeConfig(next_url=NEXT_URL),+ ],+ )+ def test_search_ignores_state_it_cannot_replay(self, state: IntercomResumeConfig):+ manager = _manager(state)++ _, sent = _run_rest(+ "contacts",+ manager,+ [_page("data", [1], None)],+ should_use_incremental_field=True,+ incremental_field="updated_at",+ db_incremental_field_last_value="1700000000",+ )++ assert "starting_after" not in sent[0]["json"]["pagination"]+ assert sent[0]["json"]["query"]["value"] == 1700000000++ @pytest.mark.parametrize(+ "endpoint,selector,state,expected_url,expected_params",+ [+ (+ "activity_logs",+ "activity_logs",+ IntercomResumeConfig(next_url=NEXT_URL),+ NEXT_URL,+ {},+ ),+ (+ "collections",+ "data",+ IntercomResumeConfig(cursor="c5"),+ f"{INTERCOM_API_BASE}/help_center/collections",+ {"per_page": 150, "starting_after": "c5"},+ ),+ (+ "news_items",+ "data",+ IntercomResumeConfig(next_url=SECOND_URL),+ SECOND_URL,+ {},+ ),+ ],+ )+ def test_resumed_list_starts_at_the_saved_page(+ self,+ endpoint: str,+ selector: str,+ state: IntercomResumeConfig,+ expected_url: str,+ expected_params: dict[str, Any],+ ):+ rows, sent = _run_rest(endpoint, _manager(state), [_page(selector, [5], None)])++ assert rows == [5]+ assert len(sent) == 1+ assert sent[0]["url"] == expected_url+ assert sent[0]["params"] == expected_params+++def _segments_session(scroll_ids: list[str], segments: dict[str, Any]) -> mock.MagicMock:+ responses: dict[str, Any] = {f"/companies/{cid}/segments": body for cid, body in segments.items()}++ def get(url: str, params: Any = None, timeout: int = 30) -> Response:+ if url.endswith("/companies/scroll"):+ if params is None:+ return _make_response({"data": [{"id": cid} for cid in scroll_ids], "scroll_param": "s1"})+ return _make_response({"data": []})+ body = responses[url.removeprefix(INTERCOM_API_BASE)]+ if body is None:+ return _make_response(None, status_code=404, text="Not Found")+ return _make_response(body)++ session = mock.MagicMock()+ session.get.side_effect = get+ return session+++def _segment_urls(session: mock.MagicMock) -> list[str]:+ return [call.args[0] for call in session.get.call_args_list if call.args[0].endswith("/segments")]+++class TestExpiredSubstreamCursor:+ def test_expired_conversation_search_cursor_is_cleared(self):+ manager = _manager(IntercomResumeConfig(cursor="expired", query_value=1600000000))+ session = mock.MagicMock()+ session.post.return_value = _make_response(+ {"type": "error.list", "errors": [{"code": "parameter_invalid", "message": "cursor expired"}]},+ status_code=400,+ )++ with mock.patch.object(intercom_module, "_make_intercom_session", return_value=session):+ response = intercom_source(+ access_token="token",+ endpoint="conversation_parts",+ team_id=1,+ job_id="job-1",+ api_version="2.16",+ resumable_source_manager=manager,+ incremental_field="updated_at",+ )+ with pytest.raises(HTTPError):+ list(cast(Iterable[Any], response.items()))++ manager.clear_state.assert_called_once_with()+++class TestResumableCompanySegments:+ def test_fresh_run_stages_each_company_in_sorted_order(self):+ # co2 has no segments and co4 was deleted: both still move the cursor and reach a safe+ # point, because a long run of empty companies must still hand off at shutdown.+ session = _segments_session(+ ["co3", "co1", "co4", "co2"],+ {+ "co1": {"data": [{"id": "s1"}]},+ "co2": {"data": []},+ "co3": {"data": [{"id": "s3"}, {"id": "s4"}]},+ "co4": None,+ },+ )+ manager = _manager()++ segments = list(_company_segments_generator(session, manager))++ assert [(s["company_id"], s["id"]) for s in segments] == [("co1", "s1"), ("co3", "s3"), ("co3", "s4")]+ assert _staged(manager) == [IntercomResumeConfig(last_company_id=cid) for cid in ["co1", "co2", "co3", "co4"]]+ # One safe point per drained scroll page, plus one per company.+ assert manager.safe_point.call_count == 1 + 4++ def test_stages_a_company_only_after_its_segments_are_yielded(self):+ session = _segments_session(["co1", "co2"], {"co1": {"data": [{"id": "s1"}]}, "co2": {"data": []}})+ manager = _manager()+ generator = _company_segments_generator(session, manager)++ next(generator)++ manager.save_state.assert_not_called()++ def test_resumed_run_skips_completed_companies(self):+ session = _segments_session(+ ["co3", "co1", "co2"],+ {"co1": {"data": [{"id": "s1"}]}, "co2": {"data": [{"id": "s2"}]}, "co3": {"data": [{"id": "s3"}]}},+ )+ manager = _manager(IntercomResumeConfig(last_company_id="co2"))++ segments = list(_company_segments_generator(session, manager))++ assert [s["id"] for s in segments] == ["s3"]+ assert _segment_urls(session) == [f"{INTERCOM_API_BASE}/companies/co3/segments"]+++def _conversation_page(ids: list[str], next_cursor: str | None) -> Response:+ next_block = {"starting_after": next_cursor} if next_cursor else None+ return _make_response({"conversations": [{"id": cid} for cid in ids], "pages": {"next": next_block}})+++def _parts(*ids: str) -> Response:+ return _make_response({"conversation_parts": {"conversation_parts": [{"id": pid} for pid in ids]}})+++class TestResumableConversationParts:+ def test_fresh_run_stages_after_each_conversation_and_page(self):+ session = mock.MagicMock()+ session.post.side_effect = [_conversation_page(["c1", "c2"], "p2"), _conversation_page(["c3"], None)]+ session.get.side_effect = [_parts("a", "b"), _parts(), _parts("c")]+ manager = _manager()++ parts = list(_conversation_parts_generator(session, "updated_at", None, manager))++ assert [p["id"] for p in parts] == ["a", "b", "c"]+ assert _staged(manager) == [+ IntercomResumeConfig(query_value=0, completed_conversation_ids=["c1"]),+ IntercomResumeConfig(query_value=0, completed_conversation_ids=["c1", "c2"]),+ IntercomResumeConfig(cursor="p2", query_value=0),+ IntercomResumeConfig(cursor="p2", query_value=0, completed_conversation_ids=["c3"]),+ ]+ assert manager.safe_point.call_count == 4++ def test_stages_a_conversation_only_after_its_parts_are_yielded(self):+ session = mock.MagicMock()+ session.post.side_effect = [_conversation_page(["c1"], None)]+ session.get.side_effect = [_parts("a", "b")]+ manager = _manager()+ generator = _conversation_parts_generator(session, "updated_at", None, manager)++ next(generator)+ next(generator)++ manager.save_state.assert_not_called()++ def test_resumed_run_replays_the_saved_page_and_skips_completed_conversations(self):+ session = mock.MagicMock()+ session.post.side_effect = [_conversation_page(["c3", "c4"], None)]+ session.get.side_effect = [_parts("d")]+ manager = _manager(IntercomResumeConfig(cursor="p2", query_value=1600000000, completed_conversation_ids=["c3"]))++ parts = list(_conversation_parts_generator(session, "updated_at", "1700000000", manager))++ assert [(p["conversation_id"], p["id"]) for p in parts] == [("c4", "d")]+ body = session.post.call_args_list[0].kwargs["json"]+ assert body["pagination"]["starting_after"] == "p2"+ assert body["query"]["value"] == 1600000000+ assert [call.args[0] for call in session.get.call_args_list] == [f"{INTERCOM_API_BASE}/conversations/c4"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom_source.pyindex 6cfa1e7108af..bf84326490ea 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom_source.py@@ -15,6 +15,11 @@ class TestIntercomSource:self.source = IntercomSource()self.team_id = 123self.config = IntercomSourceConfig(intercom_integration_id=456)+ self.manager = mock.MagicMock()++ @pytest.mark.parametrize("schema_name,expected", [("contacts", True), ("companies", False)])+ def test_retry_budget_excludes_companies_scroll(self, schema_name, expected):+ assert self.source.resume_covers_run(incremental_or_append=False, schema_name=schema_name) is expecteddef test_default_version_is_latest(self):# New sources are stamped with the default; keep it on the newest supported version.@@ -39,7 +44,7 @@ class TestIntercomSource:inputs.api_version = pinnedinputs.should_use_incremental_field = False- self.source.source_for_pipeline(self.config, inputs)+ self.source.source_for_pipeline(self.config, self.manager, inputs)_, kwargs = mock_intercom_source.call_argsassert kwargs["api_version"] == expected@@ -207,7 +212,7 @@ class TestIntercomSource:inputs.incremental_field = "updated_at"inputs.db_incremental_field_last_value = "1700000000"- result = self.source.source_for_pipeline(self.config, inputs)+ result = self.source.source_for_pipeline(self.config, self.manager, inputs)assert result is sentinelmock_intercom_source.assert_called_once_with(@@ -216,6 +221,7 @@ class TestIntercomSource:team_id=self.team_id,job_id="job-1",api_version="2.13",+ resumable_source_manager=self.manager,should_use_incremental_field=True,incremental_field="updated_at",db_incremental_field_last_value="1700000000",@@ -238,7 +244,7 @@ class TestIntercomSource:inputs.incremental_field = "updated_at"inputs.db_incremental_field_last_value = "1700000000"- self.source.source_for_pipeline(self.config, inputs)+ self.source.source_for_pipeline(self.config, self.manager, inputs)_, kwargs = mock_intercom_source.call_argsassert kwargs["incremental_field"] is None@@ -256,4 +262,4 @@ class TestIntercomSource:inputs.schema_name = "contacts"with pytest.raises(ValueError, match="Intercom access token not found for job job-1"):- self.source.source_for_pipeline(self.config, inputs)+ self.source.source_for_pipeline(self.config, self.manager, inputs)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.pyindex 960ac869d530..e3677c2ac003 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py@@ -3,17 +3,22 @@ from __future__ import annotationsimport mathimport uuidimport base64+import datetimeimport contextlibimport collections-from collections.abc import Callable, Iterator+from collections.abc import Callable, Iterator, Mappingfrom concurrent.futures import ThreadPoolExecutorfrom typing import Any, Optionalfrom urllib.parse import urlparseimport certifiimport structlog-from bson import Binary, DatetimeMS, ObjectId+from bson import Binary, DatetimeMS, Decimal128, ObjectId, Timestamp, json_util+from bson.binary import UuidRepresentation+from bson.code import Codefrom bson.codec_options import DatetimeConversion+from bson.dbref import DBRef+from bson.json_util import JSONMode, JSONOptionsfrom pymongo import ASCENDING, MongoClientfrom pymongo.collection import Collectionfrom pymongo.cursor import Cursor@@ -39,6 +44,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mix_is_host_safe,log_connection_open,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mongodb import (MongoDBSourceConfig,@@ -694,6 +700,113 @@ MONGO_KEYS_UNAVAILABLE_ERROR = (_EXECUTION_TIMEOUT_ERROR_CODE = 50+@frozen+class MongoResumeConfig:+ """Checkpoint of a full-refresh read: the `_id` of the last document handed to the pipeline.++ The value is canonical MongoDB Extended JSON. Plain JSON has no ObjectId, UUID, date or+ Decimal128, and the resume manager writes `str()` of a value it cannot encode, which no later+ attempt can parse. Extended JSON gives back the same BSON type and value, so `$gt` compares it+ the way the server compared the original.+ """++ last_id: str+++# UNSPECIFIED keeps every binary `_id` a `Binary` of its own subtype on decode. A representation+# that turns subtype 3 into `uuid.UUID` would re-encode it as subtype 4, and MongoDB orders binary+# values by subtype, so the seek would skip every remaining subtype 3 `_id`.+_RESUME_ID_JSON_OPTIONS = JSONOptions(+ json_mode=JSONMode.CANONICAL,+ uuid_representation=UuidRepresentation.UNSPECIFIED,+ datetime_conversion=DatetimeConversion.DATETIME_AUTO,+ tz_aware=False,+)++# MongoDB orders values of different BSON types by type bracket first, in this order, and a `$gt`+# only matches values in the bracket of its operand. A seek past a checkpoint therefore also matches+# every bracket that sorts after it, or a collection with mixed `_id` types loses those documents.+_ID_TYPE_BRACKETS: tuple[tuple[str, ...], ...] = (+ ("int", "long", "double", "decimal"),+ ("string", "symbol"),+ ("object",),+ ("binData",),+ ("objectId",),+ ("bool",),+ ("date",),+ ("timestamp",),+ ("regex", "dbPointer", "javascript", "javascriptWithScope", "maxKey"),+)+++def _id_type_bracket(value: Any) -> int | None:+ """Index into `_ID_TYPE_BRACKETS` for a decoded `_id`, or None when no seek can start from it."""+ # bool subclasses int, so it must be checked before the numbers.+ if isinstance(value, bool):+ return 5+ if isinstance(value, float):+ # NaN sorts below every number, but `$gt: NaN` matches none of them.+ return None if math.isnan(value) else 0+ if isinstance(value, Decimal128):+ return None if value.to_decimal().is_nan() else 0+ if isinstance(value, int):+ return 0+ # Code subclasses str, but JavaScript values do not have a safe same-bracket seek.+ if isinstance(value, Code):+ return None+ if isinstance(value, str):+ return 1+ if isinstance(value, Mapping | DBRef):+ return 2+ # Binary subclasses bytes. The client decodes subtype 4 to uuid.UUID.+ if isinstance(value, bytes | uuid.UUID):+ return 3+ if isinstance(value, ObjectId):+ return 4+ if isinstance(value, datetime.datetime | DatetimeMS):+ return 6+ if isinstance(value, Timestamp):+ return 7+ # null, MinKey, MaxKey and the code types. The first three hold at most one document each+ # because `_id` is unique, and nothing is lost when a run cannot resume from them.+ return None+++def _to_exact_bson(value: Any) -> Any:+ # The read client decodes subtype 4 to uuid.UUID. Turn it back into the stored bytes so the+ # checkpoint does not depend on a UUID representation.+ if isinstance(value, uuid.UUID):+ return Binary.from_uuid(value)+ if isinstance(value, Mapping):+ return {key: _to_exact_bson(item) for key, item in value.items()}+ if isinstance(value, list):+ return [_to_exact_bson(item) for item in value]+ return value+++def encode_resume_id(value: Any) -> str | None:+ """Extended JSON for a document `_id`, or None when a resumed read cannot seek past it."""+ if _id_type_bracket(value) is None:+ return None+ try:+ return json_util.dumps(_to_exact_bson(value), json_options=_RESUME_ID_JSON_OPTIONS)+ except (TypeError, ValueError):+ return None+++def decode_resume_id(encoded: str) -> Any:+ return json_util.loads(encoded, json_options=_RESUME_ID_JSON_OPTIONS)+++def _id_seek_filter(last_id: Any) -> dict[str, Any]:+ """Match every document whose `_id` sorts after `last_id` in MongoDB's cross-type order."""+ bracket = _id_type_bracket(last_id)+ if bracket is None:+ raise ValueError(f"Cannot seek past an _id of type {type(last_id).__name__}")+ later_types = [alias for aliases in _ID_TYPE_BRACKETS[bracket + 1 :] for alias in aliases]+ return {"$or": [{"_id": {"$gt": last_id}}, {"_id": {"$type": later_types}}]}++def mongo_source(connection_string: str,collection_name: str,@@ -704,9 +817,16 @@ def mongo_source(incremental_field: Optional[str] = None,incremental_field_type: Optional[IncrementalFieldType] = None,database_name: Optional[str] = None,+ resumable_source_manager: ResumableSourceManager[MongoResumeConfig] | None = None,) -> SourceResponse:connection_params = _parse_connection_string(connection_string, database_name)+ # Only a full refresh resumes. Its read is `find({}).sort(_id)` with no filter, so every document+ # that sorts before the checkpoint was already handed on. An incremental or append read restarts+ # from its incremental watermark instead, and an `_id` seek would have to agree with a filter on+ # another field.+ resume_manager = None if should_use_incremental_field else resumable_source_manager+if not connection_params["database"]:raise ValueError(DATABASE_NAME_REQUIRED_ERROR)@@ -748,6 +868,24 @@ def mongo_source(db_incremental_field_last_value,)+ if resume_manager is not None and resume_manager.can_resume():+ state = resume_manager.load_state()+ if state is not None:+ try:+ resume_after = decode_resume_id(state.last_id)+ query = _id_seek_filter(resume_after)+ except Exception:+ # This attempt already counts as a resume, so it cannot fall back to a+ # fresh read. Clearing the state lets the next attempt start one.+ resume_manager.clear_state()+ raise+ logger.debug(+ f"MongoDB: resuming collection={collection_name} after _id type={type(resume_after).__name__}"+ )++ # Set when the resume state was cleared for an `_id` that cannot be a checkpoint, so a+ # run of such documents costs one Redis delete and not one per document.+ resume_state_cleared = Falselast_id: Any = Nonedef open_resumable_cursor() -> Cursor[Any]:@@ -803,6 +941,19 @@ def mongo_source(result["data"] = processed_doc+ if resume_manager is not None:+ # Staged before the yield, so the pipeline commits this `_id` only+ # after it writes the batch that holds this document.+ encoded_id = encode_resume_id(last_id)+ if encoded_id is not None:+ resume_manager.save_state(MongoResumeConfig(last_id=encoded_id))+ resume_state_cleared = False+ elif not resume_state_cleared:+ # An older checkpoint would re-read the rows written since it,+ # so a retry restarts from the first document instead.+ resume_manager.clear_state()+ resume_state_cleared = True+yield resultreturnexcept CursorNotFound:@@ -812,7 +963,8 @@ def mongo_source(if rows_since_cursor_opened == 0:raiselogger.debug(- f"MongoDB: cursor killed for collection={collection_name}; resuming after _id={last_id}"+ f"MongoDB: cursor killed for collection={collection_name}; "+ f"resuming after _id type={type(last_id).__name__}")cursor.close()cursor = open_resumable_cursor()@@ -825,7 +977,7 @@ def mongo_source(raiselogger.debug(f"MongoDB: operation exceeded time limit for collection={collection_name}; "- f"resuming after _id={last_id}"+ f"resuming after _id type={type(last_id).__name__}")cursor.close()cursor = open_resumable_cursor()@@ -858,4 +1010,6 @@ def mongo_source(rows_to_sync=rows_to_sync,chunk_size=chunk_size,chunk_size_bytes=MONGO_CHUNK_SIZE_BYTES,+ supports_resume=resume_manager is not None,+ on_complete=resume_manager.clear_state if resume_manager is not None else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.pyindex 8a3e6e90248f..42598dc2e6d3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.py@@ -9,7 +9,7 @@ from products.warehouse_sources.backend.facade.source_config import (SourceFieldInputConfig,SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (DATABASE_HOST_NOT_ALLOWED_GUIDANCE,HOST_RESOLUTION_EXHAUSTED_MESSAGE,@@ -17,6 +17,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixValidateDatabaseHostMixin,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mongodb import (@@ -25,6 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mongo import (DATABASE_NAME_REQUIRED_ERROR,MONGO_DOCUMENT_MISSING_ID_ERROR,+ MongoResumeConfig,_parse_connection_string,filter_mongo_incremental_fields,get_collection_names,@@ -149,7 +151,7 @@ _SERVER_TOO_OLD_MARKER = "version of PyMongo requires at least"@SourceRegistry.register-class MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixin):+class MongoDBSource(ResumableSource[MongoDBSourceConfig, MongoResumeConfig], ValidateDatabaseHostMixin):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.MONGODB@@ -442,7 +444,30 @@ class MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixindef get_server_metadata(self, config: MongoDBSourceConfig, team_id: int) -> dict[str, Any]:return get_mongo_server_metadata(config.connection_string, team_id)- def source_for_pipeline(self, config: MongoDBSourceConfig, inputs: SourceInputs) -> SourceResponse:+ def resume_covers_run(+ self,+ *,+ incremental_or_append: bool,+ keyset_full_load_enabled: bool = False,+ schema_name: str | None = None,+ ) -> bool:+ # The `_id` checkpoint covers only a full refresh. An incremental or append run restarts from+ # its watermark, so it keeps the incremental retry budget.+ return not incremental_or_append++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MongoResumeConfig]:+ return ResumableSourceManager[MongoResumeConfig](inputs, MongoResumeConfig)++ def source_for_pipeline(+ self,+ config: MongoDBSourceConfig,+ resumable_source_manager: ResumableSourceManager[MongoResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ # A reset's first attempt must read from the beginning. Later activity attempts share this+ # run's checkpoint and destination, so preserve the progress the failed attempt committed.+ if inputs.reset_pipeline and inputs.activity_attempt == 1:+ resumable_source_manager.clear_state()return mongo_source(connection_string=config.connection_string,collection_name=inputs.schema_name,@@ -453,6 +478,7 @@ class MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixindb_incremental_field_last_value=inputs.db_incremental_field_last_value,team_id=inputs.team_id,database_name=config.database_name,+ resumable_source_manager=resumable_source_manager,)@propertydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_mongo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_mongo.pyindex b41dfed2957d..c5a5cdae12c4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_mongo.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_mongo.py@@ -2,7 +2,7 @@ import uuidimport base64import datetimeimport contextlib-from collections.abc import Iterable, Iterator+from collections.abc import Callable, Iterable, Iteratorfrom typing import Any, castimport pytest@@ -10,8 +10,13 @@ from unittest.mock import MagicMock, patchfrom django.test import SimpleTestCase, override_settings-from bson import Binary, DatetimeMS, ObjectId-from bson.binary import UUID_SUBTYPE+import bson+from bson import Binary, DatetimeMS, Decimal128, Int64, ObjectId, Timestamp+from bson.binary import UUID_SUBTYPE, UuidRepresentation+from bson.code import Code+from bson.codec_options import CodecOptions+from bson.max_key import MaxKey+from bson.min_key import MinKeyfrom parameterized import parameterizedfrom pymongo.errors import CursorNotFound, OperationFailure, ServerSelectionTimeoutErrorfrom pymongo.hello import Hello@@ -23,25 +28,31 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixDATABASE_HOST_NOT_ALLOWED_ERROR,HostNotAllowedError,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mongo import (MONGO_DOCUMENT_MISSING_ID_ERROR,MONGO_KEYS_UNAVAILABLE_ERROR,MONGO_MAX_CHUNK_ROWS,MONGO_MIN_CHUNK_ROWS,+ MongoResumeConfig,_adaptive_chunk_size,_build_query,_get_avg_document_size,_get_partition_settings,_get_rows_to_sync,+ _id_seek_filter,_list_importable_collection_names,_make_safe_server_selector,_process_doc_with_field_logging,_process_nested_value,+ decode_resume_id,+ encode_resume_id,get_index_keys,get_index_keys_by_collection,get_server_metadata,mongo_source,)+from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.source import MongoDBSourcefrom products.warehouse_sources.backend.types import IncrementalFieldType@@ -871,32 +882,50 @@ class _FakeCollection:return len(self._docs)+def _read_rows(+ collection: _FakeCollection,+ *,+ resumable_source_manager: Any = None,+ should_use_incremental_field: bool = False,+ on_row: Callable[[dict[str, Any]], None] | None = None,+) -> tuple[Any, list[dict[str, Any]]]:+ @contextlib.contextmanager+ def fake_mongo_client(connection_string: str, team_id: int) -> Any:+ client = MagicMock()+ client.__getitem__.return_value.__getitem__.return_value = collection+ yield client++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mongo.mongo_client",+ fake_mongo_client,+ ):+ response = mongo_source(+ # nosemgrep: trailofbits.generic.mongodb-insecure-transport.mongodb-insecure-transport+ connection_string="mongodb://host/testdb",+ collection_name="things",+ logger=MagicMock(),+ team_id=1,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=None,+ incremental_field="_id" if should_use_incremental_field else None,+ incremental_field_type=IncrementalFieldType.ObjectID if should_use_incremental_field else None,+ resumable_source_manager=resumable_source_manager,+ )+ rows = []+ for row in cast(Iterable[dict[str, Any]], response.items()):+ if on_row is not None:+ on_row(row)+ rows.append(row)+ return response, rows++class TestMongoSourceCursorLifecycle(SimpleTestCase):"""CursorNotFound (MongoDB error tracking issue) fires when the server expires an idlecursor between chunk writes; no_cursor_timeout prevents that expiry, and closing thecursor explicitly stops it leaking server-side once no_cursor_timeout is set."""def _run_get_rows(self, collection: _FakeCollection) -> list[dict[str, Any]]:- @contextlib.contextmanager- def fake_mongo_client(connection_string: str, team_id: int) -> Any:- client = MagicMock()- client.__getitem__.return_value.__getitem__.return_value = collection- yield client-- with patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mongo.mongo_client",- fake_mongo_client,- ):- response = mongo_source(- # nosemgrep: trailofbits.generic.mongodb-insecure-transport.mongodb-insecure-transport- connection_string="mongodb://host/testdb",- collection_name="things",- logger=MagicMock(),- team_id=1,- should_use_incremental_field=False,- db_incremental_field_last_value=None,- )- return list(cast(Iterable[dict[str, Any]], response.items()))+ return _read_rows(collection)[1]def test_cursor_created_with_no_cursor_timeout(self):collection = _FakeCollection([{"_id": "1"}, {"_id": "2"}])@@ -1092,6 +1121,208 @@ class TestMongoSourceCursorLifecycle(SimpleTestCase):assert len(collection.find_calls) == 2+class _FakeResumeManager:+ def __init__(self, saved: MongoResumeConfig | None = None) -> None:+ self._saved = saved+ self.staged: list[MongoResumeConfig] = []+ self.load_calls = 0+ self.clear_calls = 0++ def can_resume(self) -> bool:+ return self._saved is not None++ def load_state(self) -> MongoResumeConfig | None:+ self.load_calls += 1+ return self._saved++ def save_state(self, data: MongoResumeConfig) -> None:+ self.staged.append(data)++ def clear_state(self) -> None:+ self.clear_calls += 1+++_STANDARD_UUID_CODEC: CodecOptions[dict[str, Any]] = CodecOptions(uuid_representation=UuidRepresentation.STANDARD)+++def _saved_state(value: Any) -> MongoResumeConfig:+ encoded = encode_resume_id(value)+ assert encoded is not None+ return MongoResumeConfig(last_id=encoded)+++def _bson_bytes(value: Any) -> bytes:+ # Equal BSON bytes means the same type, subtype and field order, which is what `$gt` compares.+ return bson.encode({"_id": value}, codec_options=_STANDARD_UUID_CODEC)+++class TestMongoSourceResume(SimpleTestCase):+ @parameterized.expand(+ [+ ("object_id", ObjectId("65f1c2a4e4b0a1b2c3d4e5f6")),+ ("string", "user-42"),+ ("int32", 42),+ ("int64", Int64(2**40)),+ ("double", 1.5),+ ("decimal128", Decimal128("12.50")),+ ("uuid_subtype_4", uuid.UUID("2d3f6db5-ab46-4d58-a383-449ba9b24cf7")),+ ("uuid_subtype_3", Binary(b"0123456789abcdef", 3)),+ ("generic_binary", Binary(b"\x00\x01\x02", 0)),+ ("datetime", datetime.datetime(2024, 5, 1, 12, 30, 15, 123000)),+ ("out_of_range_datetime", DatetimeMS(-(10**15))),+ ("timestamp", Timestamp(1700000000, 3)),+ ("bool", True),+ ("compound", {"tenant": "t1", "seq": 7, "ref": ObjectId("65f1c2a4e4b0a1b2c3d4e5f6")}),+ ]+ )+ def test_resume_id_round_trips_through_the_saved_json(self, _name: str, value: Any) -> None:+ manager = ResumableSourceManager[MongoResumeConfig](MagicMock(), MongoResumeConfig)++ restored = manager._load_json(manager._dump_json(_saved_state(value)))++ assert _bson_bytes(decode_resume_id(restored.last_id)) == _bson_bytes(value)++ @parameterized.expand(+ [+ ("null", None),+ ("min_key", MinKey()),+ ("max_key", MaxKey()),+ ("nan", float("nan")),+ ("decimal_nan", Decimal128("NaN")),+ ("javascript", Code("return 1")),+ ("javascript_with_scope", Code("return x", {"x": 1})),+ ]+ )+ def test_ids_that_cannot_be_seeked_past_have_no_checkpoint(self, _name: str, value: Any) -> None:+ assert encode_resume_id(value) is None++ @parameterized.expand(+ [+ ("object_id", ObjectId("65f1c2a4e4b0a1b2c3d4e5f6"), ["bool", "date", "maxKey"], ["objectId", "string"]),+ ("string", "abc", ["object", "binData", "objectId"], ["string", "int"]),+ ("int", 5, ["string", "objectId"], ["int", "double"]),+ ]+ )+ def test_seek_also_matches_types_that_sort_after_the_checkpoint(+ self, _name: str, value: Any, included: list[str], excluded: list[str]+ ) -> None:+ same_type, later_types = _id_seek_filter(value)["$or"]++ assert same_type == {"_id": {"$gt": value}}+ assert set(included) <= set(later_types["_id"]["$type"])+ assert not set(excluded) & set(later_types["_id"]["$type"])++ def test_fresh_run_stages_each_id_before_its_row_is_yielded(self) -> None:+ ids = [ObjectId("65f1c2a4e4b0a1b2c3d4e5f6"), ObjectId("65f1c2a4e4b0a1b2c3d4e5f7")]+ collection = _FakeCollection([{"_id": oid, "n": i} for i, oid in enumerate(ids)])+ manager = _FakeResumeManager()+ staged_at_yield: list[Any] = []++ def on_row(row: dict[str, Any]) -> None:+ staged_at_yield.append(decode_resume_id(manager.staged[-1].last_id) if manager.staged else None)++ response, rows = _read_rows(collection, resumable_source_manager=manager, on_row=on_row)++ assert [row["_id"] for row in rows] == [str(oid) for oid in ids]+ assert staged_at_yield == ids+ assert collection.find_queries[0] == {}+ assert response.supports_resume is True+ # The pipeline clears this only after it flushes the final incomplete batch.+ assert manager.clear_calls == 0+ assert response.on_complete is not None+ response.on_complete()+ assert manager.clear_calls == 1++ @parameterized.expand(+ [+ ("object_id", ObjectId("65f1c2a4e4b0a1b2c3d4e5f6")),+ ("string", "user-42"),+ ("int", 42),+ ("uuid", uuid.UUID("2d3f6db5-ab46-4d58-a383-449ba9b24cf7")),+ ]+ )+ def test_resumed_run_seeks_past_the_saved_id_with_its_bson_type(self, _name: str, saved_id: Any) -> None:+ collection = _FakeCollection([{"_id": "next"}])+ manager = _FakeResumeManager(_saved_state(saved_id))++ _read_rows(collection, resumable_source_manager=manager)++ assert _bson_bytes(collection.find_queries[0]["$or"][0]["_id"]["$gt"]) == _bson_bytes(saved_id)+ assert collection.find_calls[0]["no_cursor_timeout"] is True+ assert collection.cursors[0].sorted_by == ["_id", 1]++ def test_resumed_run_keeps_the_seek_when_a_killed_cursor_reopens(self) -> None:+ saved_id = ObjectId("65f1c2a4e4b0a1b2c3d4e5f0")+ docs = [{"_id": ObjectId(f"65f1c2a4e4b0a1b2c3d4e5f{i}")} for i in range(1, 4)]+ collection = _FakeCollection(+ docs, error=CursorNotFound("cursor id 123 not found"), error_after=2, fallback_docs=docs+ )+ manager = _FakeResumeManager(_saved_state(saved_id))++ _, rows = _read_rows(collection, resumable_source_manager=manager)++ assert [row["_id"] for row in rows] == [str(doc["_id"]) for doc in docs]+ assert collection.find_queries[1] == {"$and": [_id_seek_filter(saved_id), {"_id": {"$gt": docs[1]["_id"]}}]}++ def test_incremental_run_does_not_resume(self) -> None:+ collection = _FakeCollection([{"_id": ObjectId("65f1c2a4e4b0a1b2c3d4e5f6")}])+ manager = _FakeResumeManager(_saved_state(ObjectId("65f1c2a4e4b0a1b2c3d4e5f0")))++ response, rows = _read_rows(collection, resumable_source_manager=manager, should_use_incremental_field=True)++ assert len(rows) == 1+ assert response.supports_resume is False+ assert "$or" not in collection.find_queries[0]+ assert (manager.load_calls, manager.staged, manager.clear_calls) == (0, [], 0)++ def test_run_without_a_manager_does_not_claim_resume(self) -> None:+ response, _ = _read_rows(_FakeCollection([{"_id": "1"}]))++ assert response.supports_resume is False++ def test_id_without_a_checkpoint_clears_the_state_once_per_run_of_such_ids(self) -> None:+ collection = _FakeCollection([{"_id": None}, {"_id": float("nan")}, {"_id": 1}, {"_id": MaxKey()}])+ manager = _FakeResumeManager()+ clears_at_yield: list[int] = []++ _read_rows(+ collection, resumable_source_manager=manager, on_row=lambda _: clears_at_yield.append(manager.clear_calls)+ )++ assert clears_at_yield == [1, 1, 1, 2]+ assert [decode_resume_id(state.last_id) for state in manager.staged] == [1]+ assert manager.clear_calls == 2++ def test_unreadable_saved_state_is_cleared_before_the_attempt_fails(self) -> None:+ manager = _FakeResumeManager(MongoResumeConfig(last_id="{not json"))++ with self.assertRaises(ValueError):+ _read_rows(_FakeCollection([{"_id": "1"}]), resumable_source_manager=manager)++ assert manager.clear_calls == 1++ @parameterized.expand([("full_refresh", False, True), ("incremental_or_append", True, False)])+ def test_resume_covers_only_full_refresh(self, _name: str, incremental_or_append: bool, expected: bool) -> None:+ assert MongoDBSource().resume_covers_run(incremental_or_append=incremental_or_append) is expected++ @parameterized.expand(+ [("first_reset_attempt", True, 1, 1), ("retried_reset", True, 2, 0), ("no_reset", False, 1, 0)]+ )+ def test_source_for_pipeline_passes_the_manager_and_only_clears_a_reset_on_its_first_attempt(+ self, _name: str, reset_pipeline: bool, activity_attempt: int, expected_clears: int+ ) -> None:+ manager = MagicMock()+ inputs = MagicMock(reset_pipeline=reset_pipeline, activity_attempt=activity_attempt)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.source.mongo_source"+ ) as source_mock:+ MongoDBSource().source_for_pipeline(MagicMock(), manager, inputs)++ assert manager.clear_state.call_count == expected_clears+ assert source_mock.call_args.kwargs["resumable_source_manager"] is manager++class TestGetServerMetadata(SimpleTestCase):@staticmethoddef _server(host: str, max_wire_version: int | None) -> ServerDescription:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.pyindex 1cdcc58610cc..7c57770368c7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py@@ -99,7 +99,13 @@ class MySQLSource(SSHTunnelMixin,ValidateDatabaseHostMixin,):- def resume_covers_run(self, *, incremental_or_append: bool, keyset_full_load_enabled: bool = False) -> bool:+ def resume_covers_run(+ self,+ *,+ incremental_or_append: bool,+ keyset_full_load_enabled: bool = False,+ schema_name: str | None = None,+ ) -> bool:# Keyset seeking is a full-load path, and it is the default one here. An incremental run# resumes from its watermark like any non-resumable source's does, so it takes the# incremental retry budget rather than the much larger resumable one.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.pyindex cdc2e7d1e667..4aeef22cab90 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py@@ -411,7 +411,13 @@ class PostgresSource(def merge_cursors(self, current: XminCursor, candidate: XminCursor) -> XminCursor:return max(current, candidate, key=lambda cursor: cursor.ceiling_xid8)- def resume_covers_run(self, *, incremental_or_append: bool, keyset_full_load_enabled: bool = False) -> bool:+ def resume_covers_run(+ self,+ *,+ incremental_or_append: bool,+ keyset_full_load_enabled: bool = False,+ schema_name: str | None = None,+ ) -> bool:# Both halves. Keyset seeking is a full-load path, so an incremental or xmin run resumes from# its watermark and keeps the incremental budget. And a full load only resumes once the flag# reaches it — before that it still restarts, so the resumable allowance would buy it nothingdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.pyindex 8a497c207ba1..57d6c0bacabd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.py@@ -7,7 +7,7 @@ from products.warehouse_sources.backend.facade.source_config import (SourceFieldInputConfig,SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.regfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (required_parents_from_endpoint_configs,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.zendesk import (@@ -28,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.seZENDESK_ENDPOINTS,)from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.zendesk import (+ ZendeskResumeConfig,normalize_subdomain,validate_credentials,zendesk_source,@@ -36,7 +38,7 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ZendeskSource(SimpleSource[ZendeskSourceConfig]):+class ZendeskSource(ResumableSource[ZendeskSourceConfig, ZendeskResumeConfig]):supported_versions = ("v2",)default_version = "v2"api_docs_url = "https://developer.zendesk.com/api-reference"@@ -62,6 +64,16 @@ class ZendeskSource(SimpleSource[ZendeskSourceConfig]):"401 Client Error": "Zendesk authentication failed. Please check your API token and subdomain.",}+ def resume_covers_run(+ self,+ *,+ incremental_or_append: bool,+ keyset_full_load_enabled: bool = False,+ schema_name: str | None = None,+ ) -> bool:+ endpoint = ZENDESK_ENDPOINTS.get(schema_name or "")+ return endpoint is None or endpoint.fanout is None+def get_required_parent_schemas(self, schema_name: str) -> list[str]:return required_parents_from_endpoint_configs(ZENDESK_ENDPOINTS, schema_name)@@ -159,7 +171,17 @@ class ZendeskSource(SimpleSource[ZendeskSourceConfig]):),)- def source_for_pipeline(self, config: ZendeskSourceConfig, inputs: SourceInputs) -> SourceResponse:+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ZendeskResumeConfig]:+ return ResumableSourceManager[ZendeskResumeConfig](inputs, ZendeskResumeConfig)++ def source_for_pipeline(+ self,+ config: ZendeskSourceConfig,+ resumable_source_manager: ResumableSourceManager[ZendeskResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ endpoint_config = ZENDESK_ENDPOINTS.get(inputs.schema_name)+ is_fanout = endpoint_config is not None and endpoint_config.fanout is not Noneresource = zendesk_source(subdomain=config.subdomain,api_key=config.api_key,@@ -174,16 +196,19 @@ class ZendeskSource(SimpleSource[ZendeskSourceConfig]):incremental_field_name=inputs.incremental_field,source_id=inputs.source_id,use_warehouse_parent=inputs.fanout_warehouse_reuse,+ resumable_source_manager=resumable_source_manager,)# The original nine endpoints aren't in the declarative catalog; they keep the `id`# primary key and ascending sort they have always used.- endpoint_config = ZENDESK_ENDPOINTS.get(inputs.schema_name)response = SourceResponse(name=resource.name,items=lambda: resource,primary_keys=endpoint_config.primary_key if endpoint_config else ["id"],column_hints=resource.column_hints,sort_mode=endpoint_config.sort_mode if endpoint_config else "asc",+ # The fan-out saves no checkpoint (see `zendesk_source`), so a shutdown must not hand it+ # to another worker expecting one.+ supports_resume=not is_fanout,)partition_key = PARTITION_FIELDS.get(inputs.schema_name, None)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/tests/test_zendesk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/tests/test_zendesk.pyindex 84305e2c82a1..8a02ec116c49 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/tests/test_zendesk.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/tests/test_zendesk.py@@ -1,4 +1,5 @@import json+from collections.abc import Sequencefrom datetime import UTC, datetime, timedelta, timezonefrom types import SimpleNamespacefrom typing import Any, cast@@ -16,6 +17,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import (ParentTableRef,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputsfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.zendesk import (ZendeskSourceConfig,@@ -35,6 +37,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.zeZendeskAfterUrlPaginator,ZendeskCursorIncrementalPaginator,ZendeskIncrementalEndpointPaginator,+ ZendeskResumeConfig,get_declarative_resource,get_resource,normalize_subdomain,@@ -44,9 +47,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.ze)-def _make_response(json_body: dict[str, Any] | None = None) -> Response:+def _make_response(json_body: dict[str, Any] | None = None, status_code: int = 200) -> Response:resp = Response()- resp.status_code = 200+ resp.status_code = status_coderesp.headers["Content-Type"] = "application/json"resp._content = json.dumps(json_body or {}).encode()return resp@@ -770,7 +773,7 @@ class TestZendeskRequiredParentSchemas:"products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.source.zendesk_source",return_value=SimpleNamespace(name="ticket_comments", column_hints=None),) as mock_source:- ZendeskSource().source_for_pipeline(config, inputs)+ ZendeskSource().source_for_pipeline(config, MagicMock(spec=ResumableSourceManager), inputs)assert mock_source.call_args.kwargs["source_id"] == "source-1"assert mock_source.call_args.kwargs["use_warehouse_parent"] is True@@ -809,7 +812,9 @@ class TestZendeskSourceForPipeline:"products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.source.zendesk_source",return_value=SimpleNamespace(name=schema_name, column_hints=None),):- return ZendeskSource().source_for_pipeline(config, _source_inputs(schema_name))+ return ZendeskSource().source_for_pipeline(+ config, MagicMock(spec=ResumableSourceManager), _source_inputs(schema_name)+ )@pytest.mark.parametrize("schema_name,primary_keys,partition_key",@@ -846,3 +851,159 @@ class TestZendeskSourceForPipeline:)def test_sort_mode(self, schema_name: str, sort_mode: str) -> None:assert self._response(schema_name).sort_mode == sort_mode++ @pytest.mark.parametrize("schema_name,expected", [("tickets", True), ("ticket_comments", False)])+ def test_retry_budget_excludes_non_resumable_fanout(self, schema_name: str, expected: bool) -> None:+ assert ZendeskSource().resume_covers_run(incremental_or_append=False, schema_name=schema_name) is expected++ @pytest.mark.parametrize(+ "schema_name,supports_resume",+ [+ pytest.param("tickets", True, id="cursor_export"),+ pytest.param("ticket_audits", True, id="declarative_list"),+ # The fan-out saves no checkpoint, so a handoff would restart it from the first ticket.+ pytest.param("ticket_comments", False, id="fanout"),+ ],+ )+ def test_supports_resume(self, schema_name: str, supports_resume: bool) -> None:+ assert self._response(schema_name).supports_resume is supports_resume+++BASE = "https://nibbles.zendesk.com"++# Three pages per endpoint in the paginator's own response shape: two that continue and one that+# ends the stream, plus the resume config each continuing page must stage.+RESUME_CASES: dict[str, tuple[list[dict[str, Any]], list[ZendeskResumeConfig]]] = {+ "tickets": (+ [+ {"tickets": [{"id": 1}], "after_cursor": "c1", "end_of_stream": False},+ {"tickets": [{"id": 2}], "after_cursor": "c2", "end_of_stream": False},+ {"tickets": [{"id": 3}], "after_cursor": "c3", "end_of_stream": True},+ ],+ [ZendeskResumeConfig(cursor="c1"), ZendeskResumeConfig(cursor="c2")],+ ),+ "users": (+ [+ {"users": [{"id": 1}], "after_cursor": "u1", "end_of_stream": False},+ {"users": [{"id": 2}], "after_cursor": "u2", "end_of_stream": False},+ {"users": [{"id": 3}], "after_cursor": "u3", "end_of_stream": True},+ ],+ [ZendeskResumeConfig(cursor="u1"), ZendeskResumeConfig(cursor="u2")],+ ),+ "organizations": (+ [+ {"organizations": [{"id": 1}], "end_of_stream": False, "next_page": f"{BASE}/p2"},+ {"organizations": [{"id": 2}], "end_of_stream": False, "next_page": f"{BASE}/p3"},+ {"organizations": [{"id": 3}], "end_of_stream": True, "next_page": None},+ ],+ [ZendeskResumeConfig(next_url=f"{BASE}/p2"), ZendeskResumeConfig(next_url=f"{BASE}/p3")],+ ),+ "brands": (+ [+ {"brands": [{"id": 1}], "links": {"next": f"{BASE}/p2"}},+ {"brands": [{"id": 2}], "links": {"next": f"{BASE}/p3"}},+ {"brands": [{"id": 3}], "links": {"next": None}},+ ],+ [ZendeskResumeConfig(next_url=f"{BASE}/p2"), ZendeskResumeConfig(next_url=f"{BASE}/p3")],+ ),+ "ticket_audits": (+ [+ {"audits": [{"id": 1}], "after_url": f"{BASE}/p2"},+ {"audits": [{"id": 2}], "after_url": f"{BASE}/p3"},+ {"audits": [], "after_url": f"{BASE}/p4"},+ ],+ [ZendeskResumeConfig(next_url=f"{BASE}/p2"), ZendeskResumeConfig(next_url=f"{BASE}/p3")],+ ),+}+++class TestZendeskResume:+ def _drive(+ self,+ endpoint: str,+ manager: MagicMock,+ bodies: Sequence[dict[str, Any] | Response],+ should_use_incremental_field: bool,+ ) -> list[tuple[str, dict[str, Any]]]:+ sent: list[tuple[str, dict[str, Any]]] = []+ responses = iter(bodies)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent.append((request.url, dict(request.params or {})))+ body = next(responses)+ return body if isinstance(body, Response) else _make_response(body)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as mock_session_factory:+ session = mock_session_factory.return_value+ session.headers = {}+ session.prepare_request.side_effect = lambda req: req+ session.send.side_effect = fake_send++ resource = zendesk_source(+ subdomain="nibbles",+ api_key="token",+ email_address="[email protected]",+ endpoint=endpoint,+ team_id=1,+ job_id="job-1",+ db_incremental_field_last_value=None,+ should_use_incremental_field=should_use_incremental_field,+ resumable_source_manager=manager,+ )+ list(resource)+ return sent++ @pytest.mark.parametrize("should_use_incremental_field", [False, True], ids=["full_refresh", "incremental"])+ @pytest.mark.parametrize("endpoint", sorted(RESUME_CASES))+ def test_fresh_run_stages_the_next_page_after_each_page(+ self, endpoint: str, should_use_incremental_field: bool+ ) -> None:+ bodies, expected = RESUME_CASES[endpoint]+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ sent = self._drive(endpoint, manager, bodies, should_use_incremental_field)++ assert len(sent) == 3+ assert [call.args[0] for call in manager.save_state.call_args_list] == expected+ manager.load_state.assert_not_called()++ @pytest.mark.parametrize("should_use_incremental_field", [False, True], ids=["full_refresh", "incremental"])+ @pytest.mark.parametrize("endpoint", sorted(RESUME_CASES))+ def test_resumed_run_starts_at_the_saved_page(self, endpoint: str, should_use_incremental_field: bool) -> None:+ bodies, expected = RESUME_CASES[endpoint]+ saved = expected[-1]+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = saved++ sent = self._drive(endpoint, manager, bodies[-1:], should_use_incremental_field)++ assert len(sent) == 1+ url, params = sent[0]+ if saved.cursor is not None:+ assert params["cursor"] == saved.cursor+ # The seed `start_time` would restart the export from the watermark, not the cursor.+ assert "start_time" not in params+ else:+ assert url == saved.next_url+ # The saved URL carries its own query string; re-sending the seed params duplicates them.+ assert params == {}+ manager.save_state.assert_not_called()++ def test_expired_cursor_is_cleared_before_retry(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = ZendeskResumeConfig(cursor="expired")++ with pytest.raises(RuntimeError, match="rejected the saved pagination cursor"):+ self._drive(+ "tickets",+ manager,+ [_make_response({"error": "Invalid cursor: cursor has expired"}, status_code=400)],+ False,+ )++ manager.clear_state.assert_called_once_with()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/zendesk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/zendesk.pyindex 1de88eb57b2b..227eb9226bac 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/zendesk.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/zendesk.py@@ -6,6 +6,7 @@ from datetime import UTC, datetimefrom typing import Any, Optional, castfrom requests import Request, Response+from requests.exceptions import HTTPErrorfrom products.warehouse_sources.backend.models.external_table_definitions import get_dlt_mapping_for_external_tablefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_value@@ -34,6 +35,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import (parent_snapshot_covers_through,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.settings import (FANOUT_PARENTS,TICKET_COMMENTS_PARENT_FILTER_FIELD,@@ -48,6 +50,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.seZENDESK_EPOCH_START = "1970-01-01T00:00:00Z"[email protected](frozen=True)+class ZendeskResumeConfig:+ # Next-page URL, for the link paginators and the time-based incremental exports.+ next_url: str | None = None+ # `after_cursor` token, for the cursor-based incremental exports (tickets, users).+ cursor: str | None = None++def to_zendesk_start_time(value: Any) -> int:"""Convert an incremental cursor value to the Unix epoch seconds Zendesk's incrementalexport `start_time` expects. Applied to both the persisted last value (a `datetime` for@@ -455,8 +465,27 @@ class ZendeskCursorIncrementalPaginator(BasePaginator):request.params.pop("start_time", None)request.params["cursor"] = self._after_cursor+ def init_request(self, request: Request) -> None:+ # A resumed run starts at the saved cursor, not at the seed `start_time`.+ if self._after_cursor is not None:+ self.update_request(request)++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ return {"cursor": self._after_cursor} if self._has_next_page and self._after_cursor is not None else None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ cursor = state.get("cursor")+ if cursor is not None:+ # Seeding `_after_cursor` also arms the non-advancing guard for the first resumed page.+ self._after_cursor = str(cursor)+ self._has_next_page = True+class ZendeskIncrementalEndpointPaginator(BasePaginator):+ def __init__(self) -> None:+ super().__init__()+ self._next_page: Optional[str] = None+def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:res = response.json()@@ -489,6 +518,19 @@ class ZendeskIncrementalEndpointPaginator(BasePaginator):# clear params to avoid duplicates when prepare_request merges them.request.params = {}+ def init_request(self, request: Request) -> None:+ if self._next_page is not None:+ self.update_request(request)++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ return {"next_url": self._next_page} if self._has_next_page and self._next_page is not None else None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ next_url = state.get("next_url")+ if next_url is not None:+ self._next_page = str(next_url)+ self._has_next_page = True+class ZendeskAfterUrlPaginator(JSONLinkPaginator):"""Cursor pagination for `/api/v2/ticket_audits`, which returns its next-page link as@@ -595,6 +637,49 @@ def zendesk_fanout_source()+def _initial_paginator_state(+ resumable_source_manager: ResumableSourceManager[ZendeskResumeConfig] | None,+) -> dict[str, Any] | None:+ if resumable_source_manager is None or not resumable_source_manager.can_resume():+ return None+ resume = resumable_source_manager.load_state()+ if resume is None:+ return None+ state = {key: value for key, value in dataclasses.asdict(resume).items() if value is not None}+ return state or None+++def _is_invalid_resume_cursor(exc: HTTPError) -> bool:+ response = exc.response+ if response is None or response.status_code not in (400, 404, 410):+ return False+ # Persisted next-page URLs can expire without naming their internal cursor in the response.+ if response.status_code in (404, 410):+ return True+ try:+ body = response.json()+ except Exception:+ body = response.text+ text = str(body).lower()+ names_pagination = any(marker in text for marker in ("cursor", "pagination", "page token"))+ return names_pagination and any(marker in text for marker in ("invalid", "expired", "not found"))+++def _resume_hook(+ resumable_source_manager: ResumableSourceManager[ZendeskResumeConfig],+) -> Callable[[dict[str, Any] | None], None]:+ def save_checkpoint(state: dict[str, Any] | None) -> None:+ # The framework calls this after it yields a page, with the state that points at the next+ # page. None means the stream has ended, so there is nothing further to resume from.+ if not state:+ return+ resumable_source_manager.save_state(+ ZendeskResumeConfig(next_url=state.get("next_url"), cursor=state.get("cursor"))+ )++ return save_checkpoint++def zendesk_source(subdomain: str,api_key: str,@@ -607,11 +692,15 @@ def zendesk_source(incremental_field_name: str | None = None,source_id: str | None = None,use_warehouse_parent: bool = False,+ resumable_source_manager: ResumableSourceManager[ZendeskResumeConfig] | None = None,):client_config = zendesk_client_config(subdomain, api_key, email_address)endpoint_config = ZENDESK_ENDPOINTS.get(endpoint)if endpoint_config is not None and endpoint_config.fanout is not None:+ # The shared fan-out checkpoint lists every completed parent path and is re-serialized on+ # each page. A fan-out over every ticket makes that cost grow with the square of the ticket+ # count, so this path does not checkpoint. `ZendeskSource` marks the run as not resumable.return zendesk_fanout_source(client_config,endpoint_config,@@ -637,7 +726,30 @@ def zendesk_source("resources": [get_resource(endpoint, should_use_incremental_field, incremental_field_name)],}- return rest_api_resource(config, team_id, job_id, db_incremental_field_last_value)+ initial_paginator_state = _initial_paginator_state(resumable_source_manager)+ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=_resume_hook(resumable_source_manager) if resumable_source_manager is not None else None,+ initial_paginator_state=initial_paginator_state,+ )+ if initial_paginator_state is None or resumable_source_manager is None:+ return resource++ def iter_resource():+ try:+ yield from resource+ except HTTPError as exc:+ if _is_invalid_resume_cursor(exc):+ # Do not replay a vendor-rejected checkpoint on every activity attempt. Raise a+ # retryable error even when the expired URL returned the otherwise non-retryable 404.+ resumable_source_manager.clear_state()+ raise RuntimeError("Zendesk rejected the saved pagination cursor; retrying from the watermark") from exc+ raise++ return Resource(iter_resource, name=resource.name, hints=resource._hints)def validate_credentials(subdomain: str, api_key: str, email_address: str) -> bool: