: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
fix(data-warehouse): hand a rest page to the pipeline with its resume state (#112722)
Tom Owers4e10725d5ebc
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.mdindex d5c9f8ccef81..94f0f133f5ee 100644--- a/.agents/skills/implementing-warehouse-sources/SKILL.md+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md@@ -426,14 +426,16 @@ while True:url = next_url # advance before the next fetch, otherwise we loop on the same page```-Save state **before** yielding the batch it covers. `save_state` only stages the cursor; the pipeline commits it to Redis once that batch is written, so a crash resumes exactly after the last written batch. A source that saves after yielding still works, but a crash re-yields its last batch (merge dedupes on primary key, append does not). A source with nothing yielded yet, such as one persisting an export job id before polling it, stages inside `with manager.committing():`, which commits when the block ends.+Save state **before** yielding the batch it covers. `save_state` only stages the cursor; the pipeline commits it to Redis once that batch is written, so a crash resumes exactly after the last written batch. Do not save after the yield. On a worker shutdown the pipeline ends the attempt before control returns to the source, so state saved after the `yield` is lost for the last batch: the next attempt reads that batch again (merge dedupes on primary key, a resumed full refresh appends it twice), and an attempt that writes one batch or fewer keeps no progress. A source with nothing yielded yet, such as one persisting an export job id before polling it, stages inside `with manager.committing():`, which commits when the block ends.Call `manager.safe_point()` wherever the source can make many requests that return no rows: an empty delta page, a fan-out parent with no children, a page with no comments.The pipeline checks for a worker shutdown only when an item arrives, so a run of empty responses otherwise holds the worker for the whole graceful shutdown timeout, and its cursor never commits.At a safe point the pipeline can hand the run to another worker, and it commits the staged cursor when nothing is waiting to be written.Call it only where resuming from the staged cursor loses no rows: every row the cursor covers is already yielded, and none sits in a local buffer.References: `document_deltas` in `convex/convex.py`, the sparse-sweep checkpoint in `stripe/stripe.py`, `_page_fan_out` in `notion/notion.py`.-The `rest_source` framework reaches a safe point after each page on its own, but only when `SourceResponse.items` returns the framework's `Resource` directly. A source that wraps it gets no framework safe points, because the wrapper could buffer rows.+The `rest_source` framework reaches a safe point after each page and before each retry wait on its own, but only when `SourceResponse.items` returns the framework's `Resource` directly. A source that wraps it gets no framework safe points, because the wrapper could buffer rows.+The same condition decides when a `resume_hook` runs. When `items` returns the `Resource` directly, the hook runs before the page reaches the pipeline, so a page and its cursor commit together and a hand-off repeats no rows. When a source wraps the `Resource`, the hook runs when the wrapper asks for the next page, so a hand-off reads the last page again. Return the `Resource` directly when you can: use `data_map`, `add_map` and `add_filter` for row changes. A wrapper that hands each page on unchanged and holds no rows can keep the framework behavior by returning `Resource(wrapper, name=..., hints=resource._hints)` (see the usage report in `anthropic/anthropic.py`).+Do not call `safe_point()` or `commit()` in a `resume_hook`.### Webhook source patterndiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.pyindex 5724a2d45d8b..f7686b22126c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py@@ -25,6 +25,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinePostgresProducer,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3 import BatchWriteResult+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import rest_api_resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.tests.test_resume_checkpoints import (+ paged_config,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (OutputLane,@@ -858,6 +862,11 @@ class _Cursor:id: str+@dataclass(frozen=True)+class _PageCursor:+ page: int++def _manager() -> ResumableSourceManager[_Cursor]:inputs = cast(SourceInputs, SimpleNamespace(team_id=1, job_id="job-1", logger=MagicMock()))return ResumableSourceManager[_Cursor](inputs, _Cursor)@@ -965,6 +974,50 @@ class TestResumeCursorCommit:assert cast(AsyncMock, pipeline._process_batch).await_count == 2assert [json.loads(call.args[1])["id"] for call in redis.set.call_args_list] == expected_committed+ @pytest.mark.parametrize("wrapped", [False, True], ids=["rest_resource", "wrapped_rest_resource"])+ @pytest.mark.asyncio+ async def test_a_rest_source_handed_off_after_its_first_batch_resumes_without_losing_rows(+ self, wrapped: bool+ ) -> None:+ redis = MagicMock()+ inputs = cast(SourceInputs, SimpleNamespace(team_id=1, job_id="job-1", logger=MagicMock()))+ manager = ResumableSourceManager[_PageCursor](inputs, _PageCursor)+ pages = {"/items": [[{"id": 1}], [{"id": 2}], [{"id": 3}]]}++ def rest_items(state: dict | None):+ resource = rest_api_resource(+ paged_config(pages, ["items"]),+ 1,+ "job-1",+ None,+ resume_hook=lambda next_page: manager.save_state(_PageCursor(next_page["page"])) if next_page else None,+ initial_paginator_state=state,+ )+ return (lambda: (page for page in resource)) if wrapped else (lambda: resource)++ pipeline = _runnable_pipeline(cast(ResumableSourceManager[_Cursor], manager), rest_items(None))+ pipeline._batcher = Batcher(MagicMock(), chunk_size=1, primary_keys=["id"])+ cast(MagicMock, pipeline._shutdown_monitor).raise_if_is_worker_shutdown.side_effect = WorkerShuttingDownError(+ "id", "type", "queue", 1, "workflow", "workflow_type"+ )++ await _run_expecting(pipeline, redis, WorkerShuttingDownError)++ written = [+ row_id+ for call in cast(AsyncMock, pipeline._process_batch).await_args_list+ for row_id in call.kwargs["pa_table"]["id"].to_pylist()+ ]+ committed = [json.loads(call.args[1]) for call in redis.set.call_args_list]+ resumed = [row["id"] for page in rest_items(committed[-1] if committed else None)() for row in page]++ assert written == [1]+ if wrapped:+ assert set(written + resumed) == {1, 2, 3}+ else:+ assert committed == [{"page": 1}]+ assert written + resumed == [1, 2, 3]+@pytest.mark.asyncioasync def test_cursor_not_persisted_for_rows_the_batcher_still_holds(self) -> None:redis = MagicMock()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.pyindex 690f0f2c18e4..4cd3fafebbd0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py@@ -1,5 +1,5 @@import hashlib-from collections.abc import Callable, Iterator+from collections.abc import Callable, Iterable, Iteratorfrom datetime import UTC, date, datetime, timedeltafrom functools import partialfrom typing import Any, Optional@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resrest_api_resources,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (ApiKeyAuthConfig,ClientConfig,@@ -815,7 +816,7 @@ def anthropic_source(# schema and pauses its schedule instead of retrying a KeyError forever.raise ValueError(f"{ENDPOINT_RETIRED_ERROR}: {endpoint}")# Set only where the rows come from something other than iterating `resource` once.- items: Optional[Callable[[], Iterator[list[dict[str, Any]]]]] = None+ items: Optional[Callable[[], Iterable[list[dict[str, Any]]]]] = None# The report endpoints page the rate-limited Admin API; the entity lists do not. Give the reports# a wider retry budget so it can outlast the organization rate-limit window.@@ -1014,9 +1015,8 @@ def anthropic_source(initial_paginator_state = {"cursor": resume.cursor}def save_checkpoint(state: Optional[dict[str, Any]]) -> None:- # Persist only while a next page remains; the checkpoint is saved AFTER a page is- # yielded, pointing at the next page, so a crash resumes from a page whose predecessors- # were all yielded — the overlap merge dedupes on the primary key.+ # Persist only while a next page remains. The checkpoint points at the next page, so a+ # crash resumes from a page whose predecessors were all yielded.if state and state.get("cursor"):resumable_source_manager.save_state(AnthropicResumeConfig(cursor=state["cursor"]))@@ -1068,7 +1068,18 @@ def anthropic_source(if endpoint == "usage_report":resource = build_resource(USAGE_GROUP_BY_FALLBACKS[0], initial_paginator_state)- items = partial(_iter_narrowing_group_by, build_resource, USAGE_GROUP_BY_FALLBACKS, initial_paginator_state)+ # The fallback loop hands each page on unchanged and holds no rows. As a `Resource` it+ # keeps the framework's checkpoints, so a run that waits on a rate limit can hand off.+ narrowing = Resource(+ partial(_iter_narrowing_group_by, build_resource, USAGE_GROUP_BY_FALLBACKS, initial_paginator_state),+ name=endpoint,+ hints=resource._hints,+ )++ def narrowed_items() -> Iterable[list[dict[str, Any]]]:+ return narrowing++ items = narrowed_itemselse:resource = build_resource(config.group_by, initial_paginator_state)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.pyindex d0f6a2740cb5..5e2e55fa08fb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.py@@ -9,6 +9,9 @@ import requestsfrom parameterized import parameterizedfrom requests import Request, Response+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.safe_point import (+ source_items_are_framework_output,+)from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.anthropic import (ANALYTICS_ACCESS_MISSING,ANTHROPIC_VERSION,@@ -655,10 +658,14 @@ class TestUsageReportGroupByFallback:],)- rows = _rows(_source("usage_report", _make_manager()))+ source_response = _source("usage_report", _make_manager())+ rows = _rows(source_response)assert [r["workspace_id"] for r in rows] == ["wrkspc_1"]assert [p["params"]["group_by[]"] for p in params] == USAGE_GROUP_BY_FALLBACKS[:2]+ # The pipeline gives the framework's safe points only to a `Resource`. Without them a run+ # that waits on a rate limit cannot hand off.+ assert source_items_are_framework_output(source_response.items())@parameterized.expand([diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.pyindex 18f7af96761e..b9d061299b22 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py@@ -24,7 +24,7 @@ from .config_setup import ()from .jsonpath_utils import TJsonPathfrom .paginators import BasePaginator-from .resource import Resource+from .resource import PageCheckpoints, Resourcefrom .rest_client import DEFAULT_RETRY_ATTEMPTS, DEFAULT_RETRY_BACKOFF_MAX_SECONDS, RESTClient, RESTClientRetryableErrorfrom .typing import ClientConfig, Endpoint, EndpointResource, HTTPMethodBasic, ResolvedParam, RESTAPIConfigfrom .utils import exclude_keys # noqa: F401@@ -70,6 +70,11 @@ def rest_api_resource(``resume_hook`` and ``initial_paginator_state`` enable integration with``ResumableSourceManager``. They are only supported for non-dependentresources (no ``data_from`` parent/child fanout).++ ``resume_hook`` receives the state that fetches the page after the current one. When+ ``SourceResponse.items`` returns the resource itself, the hook runs before the page reaches the+ pipeline, so the pipeline commits a page and its state together. When a source wraps the+ resource, the hook runs when the wrapper asks for the next page."""resources = rest_api_resources(config,@@ -208,8 +213,19 @@ def _make_paginate_dependent_resource(current_child_state if (resume_hook is not None and current_path == formatted_path) else None)- def child_resume_hook(paginator_state: Optional[dict[str, Any]], _path: str = formatted_path) -> None:+ def child_page_state_hook(+ paginator_state: Optional[dict[str, Any]], has_next_page: bool, _path: str = formatted_path+ ) -> None:nonlocal current_path, current_child_state+ if not has_next_page:+ # The state of a parent's last page is staged before that page is handed on. An+ # in-progress checkpoint would make a resumed run read the whole parent again,+ # so the parent is recorded as complete here.+ completed.add(_path)+ current_path = None+ current_child_state = None+ checkpoint(None, None)+ returncurrent_path = _pathcurrent_child_state = paginator_statecheckpoint(_path, paginator_state)@@ -222,7 +238,7 @@ def _make_paginate_dependent_resource(paginator=paginator,data_selector=data_selector,hooks=hooks,- resume_hook=child_resume_hook if resume_hook is not None else None,+ page_state_hook=child_page_state_hook if resume_hook is not None else None,initial_paginator_state=child_initial,data_selector_required=data_selector_required,data_selector_empty_ok=data_selector_empty_ok,@@ -247,7 +263,8 @@ def _make_paginate_dependent_resource(checkpoint(None, None)continue- if resume_hook is not None:+ # A parent whose child endpoint answered nothing never reached the hook.+ if resume_hook is not None and formatted_path not in completed:completed.add(formatted_path)current_path = Nonecurrent_child_state = None@@ -330,6 +347,16 @@ def create_resources(hooks = create_response_hooks(endpoint_config.get("response_actions"), resource_name=resource_name)+ # The resource applies resume states itself, so that a page and its state reach the pipeline+ # together (see `Resource._iter_generator`).+ if resolved_params is not None:+ own_resume_hook = dependent_resume_hook+ elif has_dependent_resource:+ own_resume_hook = None+ else:+ own_resume_hook = resume_hook+ page_checkpoints = PageCheckpoints(own_resume_hook) if own_resume_hook is not None else None+resource_kwargs = exclude_keys(endpoint_resource, {"endpoint", "include_from_parent", "data_map", "data_iterator"})@@ -376,9 +403,7 @@ def create_resources(incremental_object: Optional[Incremental] = incremental_object,incremental_param: Optional[IncrementalParam] = incremental_param,incremental_cursor_transform: Optional[Callable[..., Any]] = incremental_cursor_transform,- resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = (- None if has_dependent_resource else resume_hook- ),+ page_checkpoints: Optional[PageCheckpoints] = page_checkpoints,initial_paginator_state: Optional[dict[str, Any]] = (None if has_dependent_resource else initial_paginator_state),@@ -405,7 +430,7 @@ def create_resources(paginator=paginator,data_selector=data_selector,hooks=hooks,- resume_hook=resume_hook,+ page_state_hook=page_checkpoints.defer_page_state if page_checkpoints is not None else None,initial_paginator_state=initial_paginator_state,data_selector_required=data_selector_required,data_selector_empty_ok=data_selector_empty_ok,@@ -427,6 +452,7 @@ def create_resources("hooks": hooks,"columns_config": columns_config,},+ page_checkpoints=page_checkpoints,)else:@@ -449,7 +475,7 @@ def create_resources(incremental_param=incremental_param,incremental_cursor_transform=incremental_cursor_transform,db_incremental_field_last_value=db_incremental_field_last_value,- resume_hook=dependent_resume_hook,+ resume_hook=page_checkpoints.defer if page_checkpoints is not None else None,initial_state=dependent_initial_state,data_selector_required=bool(endpoint_config.get("data_selector_required")),data_selector_empty_ok=bool(endpoint_config.get("data_selector_empty_ok")),@@ -473,6 +499,7 @@ def create_resources("columns_config": columns_config,},data_from=predecessor,+ page_checkpoints=page_checkpoints,)# Declarative per-item transform (e.g. flatten JSON:API attributes), applied afterdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/resource.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/resource.pyindex 6bac338f819b..f33f239118a6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/resource.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/resource.py@@ -1,6 +1,46 @@from collections.abc import Callable, Iteratorfrom typing import Any, Optional+from products.warehouse_sources.backend.temporal.data_imports.sources.common.safe_point import (+ framework_checkpoints_are_covered,+ hold_safe_points,+)++ResumeHook = Callable[[Optional[dict[str, Any]]], None]+++class PageCheckpoints:+ """Holds the resume states that pagination produces until the `Resource` hands the page on.++ Pagination knows a page's resume state before the page is converted and transformed. A state+ staged at that point would cover rows that a failing transform never hands on, and the pipeline+ commits staged state when a source raises. The `Resource` therefore applies the state itself,+ next to its own `yield`.+ """++ def __init__(self, resume_hook: ResumeHook) -> None:+ self._resume_hook = resume_hook+ self._pending: list[Optional[dict[str, Any]]] = []++ def defer(self, state: Optional[dict[str, Any]]) -> None:+ self._pending.append(state)++ def defer_page_state(self, state: Optional[dict[str, Any]], _has_next_page: bool) -> None:+ self.defer(state)++ def apply(self, *, page_is_handed_on: bool) -> None:+ pending, self._pending = self._pending, []+ if not pending:+ return+ if page_is_handed_on:+ for state in pending:+ self._resume_hook(state)+ return+ # The framework reaches its own safe point after the page is handed on, so nothing is lost.+ with hold_safe_points():+ for state in pending:+ self._resume_hook(state)+class Resource:"""Lightweight resource wrapper that replaces DltResource.@@ -29,6 +69,7 @@ class Resource:args: tuple[Any, ...] = (),kwargs: Optional[dict[str, Any]] = None,data_from: Optional["Resource"] = None,+ page_checkpoints: Optional[PageCheckpoints] = None,) -> None:self.name = nameself._hints = hints@@ -38,6 +79,7 @@ class Resource:self._args = argsself._kwargs = kwargs or {}self._data_from = data_from+ self._page_checkpoints = page_checkpoints@propertydef column_hints(self) -> Optional[dict[str, Any]]:@@ -94,10 +136,28 @@ class Resource:return resultdef _iter_generator(self, call_kwargs: dict[str, Any]) -> Iterator[list[dict[str, Any]]]:+ checkpoints = self._page_checkpointsfor page in self._generator_fn(*self._args, **call_kwargs):transformed = self._apply_transforms(page)+ if checkpoints is None:+ if transformed:+ yield transformed+ continue++ # When the pipeline iterates this resource directly, it must receive a page with its+ # resume state already staged. The pipeline commits staged state right after it writes a+ # batch, and it can end the attempt before control returns here. State staged after the+ # `yield` is then lost for the last page, and the next attempt reads that page again.+ # A source that wraps this resource can hold the page before it hands rows on, so its+ # state waits until the wrapper asks for the next page.+ if framework_checkpoints_are_covered():+ checkpoints.apply(page_is_handed_on=False)if transformed:yield transformed+ checkpoints.apply(page_is_handed_on=True)++ if checkpoints is not None:+ checkpoints.apply(page_is_handed_on=True)def __iter__(self) -> Iterator[list[dict[str, Any]]]:if self._data_from is None:diff --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 af2e8059c240..f7efcd07e02d 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@@ -285,6 +285,12 @@ def _retry_wait_seconds(state: RetryCallState) -> float:return float(fallback)+def _reach_safe_point_before_retry_wait(_state: RetryCallState) -> None:+ # A rate-limited endpoint can wait minutes per attempt, and the source yields nothing in that+ # time. Every page before the failed request has been handed on, so the run can stop here.+ reach_framework_safe_point()++Hooks = dict[str, list[Any]]@@ -432,7 +438,20 @@ class RESTClient:data_selector_required: bool = False,data_selector_empty_ok: bool = False,data_selector_malformed_retryable: bool = False,+ page_state_hook: Optional[Callable[[Optional[dict[str, Any]], bool], None]] = None,) -> Iterator[list[Any]]:+ """Yield each page of an endpoint.++ `resume_hook` receives the paginator state that fetches the page after the one this call+ yields, or `None` when no page follows. It runs after the `yield` returns, which is when the+ caller asks for the next page. A caller that does work between this `yield` and its own (a+ child request per row, a transform that can raise) needs that order: state staged earlier+ would cover rows the caller has not handed on.++ `page_state_hook` receives the same state and whether a page follows, before the `yield`.+ The caller then owns the state until the page reaches the pipeline. `Resource` does this, so+ the pipeline receives a page and its cursor together and can commit both in one step.+ """paginator = copy.deepcopy(paginator) if paginator else copy.deepcopy(self.paginator)hooks = hooks or {}@@ -479,16 +498,19 @@ class RESTClient:paginator.update_state(response, data)paginator.update_request(request)+ has_next_page = paginator is not None and paginator.has_next_page+ next_page_state = paginator.get_resume_state() if paginator is not None and has_next_page else None+ if page_state_hook is not None:+ page_state_hook(next_page_state, has_next_page)+yield dataif 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()+ resume_hook(next_page_state)# 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.- if resume_hook is None:- reach_framework_safe_point()+ reach_framework_safe_point()if paginator is None or not paginator.has_next_page:break@@ -497,6 +519,7 @@ class RESTClient:retry=retry_if_exception_type(RESTClientRetryableError),stop=_stop_after_client_attempts,wait=_retry_wait_seconds,+ before_sleep=_reach_safe_point_before_retry_wait,reraise=True,)def _send_request(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_fanout.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_fanout.pyindex f55ebcceaeb0..a731891e53ae 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_fanout.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_fanout.py@@ -449,7 +449,7 @@ def test_dependent_resource_reports_which_parent_source_served_its_rows(class _FakeResumableClient:# paginate() simulates page-by-page pagination with resume: it honors- # initial_paginator_state["page"] as the start index and calls resume_hook after each page.+ # initial_paginator_state["page"] as the start index and calls page_state_hook before each page.def __init__(self, pages_by_path: dict[str, list[list[dict[str, Any]]]]) -> None:self.pages_by_path = pages_by_path@@ -462,7 +462,7 @@ class _FakeResumableClient:paginator,data_selector,hooks,- resume_hook=None,+ page_state_hook=None,initial_paginator_state=None,data_selector_required=False,data_selector_empty_ok=False,@@ -470,9 +470,10 @@ class _FakeResumableClient:pages = self.pages_by_path[path]start = initial_paginator_state["page"] if initial_paginator_state else 0for i in range(start, len(pages)):+ has_next_page = i < len(pages) - 1+ if page_state_hook is not None:+ page_state_hook({"page": i + 1} if has_next_page else None, has_next_page)yield pages[i]- if resume_hook is not None:- resume_hook({"page": i + 1} if i < len(pages) - 1 else None)_RESOLVED_PARAM = ResolvedParam(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.pyindex 078a0d8b02fa..a1419c5c79d3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py@@ -197,10 +197,20 @@ class TestRESTClient:client = RESTClient(base_url="https://api.example.com")assert client._join_url("https://other.com/items") == "https://other.com/items"+ @parameterized.expand(+ [+ # Each checkpoint is followed by a safe point, never preceded by one, so the staged+ # cursor covers the page.+ ("after_the_page", False, ["page", {"page": 1}, "safe_point", "page", None, "safe_point"]),+ ("before_the_page", True, [{"page": 1}, "page", "safe_point", None, "page", "safe_point"]),+ ]+ )@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session")- def test_paginate_invokes_resume_hook_after_each_page(self, MockSession) -> None:+ def test_paginate_invokes_resume_hook_once_per_page(+ self, _name: str, before_yield: bool, expected: list[Any], MockSession+ ) -> None:mock_session = MockSession.return_valuemock_session.headers = {}mock_session.prepare_request.return_value = MagicMock()@@ -230,12 +240,16 @@ class TestRESTClient:client = RESTClient(base_url="https://api.example.com")with activate_safe_point(lambda: saved.append("safe_point"), covers_framework_checkpoints=True):- list(client.paginate(path="/items", paginator=TwoPagePaginator(), resume_hook=saved.append))+ for _page in client.paginate(+ path="/items",+ paginator=TwoPagePaginator(),+ resume_hook=None if before_yield else saved.append,+ page_state_hook=(lambda state, _has_next_page: saved.append(state)) if before_yield else None,+ ):+ saved.append("page")- # Called once between page 1 and page 2 with the next-page state, and- # once on the terminal page with None (no more pages to resume to). Each checkpoint is- # followed by a safe point, never preceded by one, so the staged cursor covers the page.- assert saved == [{"page": 1}, "safe_point", None, "safe_point"]+ # The hook gets the next-page state, then None on the terminal page (nothing to resume to).+ assert saved == expected@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"@@ -394,6 +408,35 @@ class TestRESTClient:# activity interceptor uses to keep it out of error tracking.assert isinstance(ctx.value, NonReportableError)+ @pytest.mark.parametrize(+ "covers_framework_checkpoints,expected_error,expected_sends",+ [(True, RuntimeError, 1), (False, RESTClientRetryableError, 5)],+ ids=["framework_output", "wrapped_output"],+ )+ @patch("tenacity.nap.time.sleep")+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ )+ def test_a_retry_wait_is_a_safe_point_only_for_unwrapped_framework_output(+ self, MockSession, mock_sleep, covers_framework_checkpoints, expected_error, expected_sends+ ) -> None:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.return_value = MagicMock()+ error = _make_response({"error": "rate limited"}, status_code=429)+ error.url = "https://api.example.com/items"+ mock_session.send.return_value = error++ def worker_is_shutting_down() -> None:+ raise RuntimeError("worker shutting down")++ client = RESTClient(base_url="https://api.example.com")+ with activate_safe_point(worker_is_shutting_down, covers_framework_checkpoints=covers_framework_checkpoints):+ with pytest.raises(expected_error):+ list(client.paginate(path="/items", paginator=SinglePagePaginator()))++ assert mock_session.send.call_count == expected_sends+@pytest.mark.parametrize("content",[diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_resume_checkpoints.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_resume_checkpoints.pynew file mode 100644index 000000000000..af02b04e0154--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_resume_checkpoints.py@@ -0,0 +1,197 @@+import json+from collections.abc import Callable, Iterator+from typing import Any, Optional, cast+from urllib.parse import parse_qs, urlsplit++import pytest++from requests import PreparedRequest, Request, Response, Session++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import rest_api_resources+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import RESTAPIConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.common.safe_point import (+ activate_safe_point,+ reach_safe_point,+)+++class PagedSession:+ def __init__(self, pages_by_path: dict[str, list[list[dict[str, Any]]]]) -> None:+ self.headers: dict[str, str] = {}+ self._pages_by_path = pages_by_path++ def prepare_request(self, request: Request) -> PreparedRequest:+ return Session().prepare_request(request)++ def send(self, prepared: PreparedRequest, **_kwargs: Any) -> Response:+ parts = urlsplit(cast(str, prepared.url))+ page = int(parse_qs(parts.query).get("page", ["0"])[0])+ pages = self._pages_by_path[parts.path]+ response = Response()+ response.status_code = 200+ response._content = json.dumps(pages[page] if page < len(pages) else []).encode()+ response.url = cast(str, prepared.url)+ return response+++def paged_config(+ pages_by_path: dict[str, list[list[dict[str, Any]]]], resources: list[Any], total_pages: Optional[int] = None+) -> RESTAPIConfig:+ return cast(+ RESTAPIConfig,+ {+ "client": {+ "base_url": "https://api.example.com",+ "session": PagedSession(pages_by_path),+ "paginator": {"type": "page_number", "base_page": 0, "total_path": None, "maximum_page": total_pages},+ },+ "resources": resources,+ },+ )+++def _resource(+ config: RESTAPIConfig, name: str, hook: Callable[[Optional[dict[str, Any]]], None], state: Any = None+) -> Resource:+ resources = rest_api_resources(config, 1, "job", None, resume_hook=hook, initial_paginator_state=state)+ return next(resource for resource in resources if resource.name == name)+++def _wrapped(resource: Resource) -> Iterator[list[dict[str, Any]]]:+ yield from resource+++ITEMS = {"/items": [[{"id": 1}], [{"id": 2}]]}+FANOUT = {+ "/parents": [[{"id": "a"}, {"id": "b"}]],+ "/parents/a/children": [[{"id": "a1"}], [{"id": "a2"}]],+ "/parents/b/children": [[{"id": "b1"}]],+}+FANOUT_RESOURCES: list[Any] = [+ "parents",+ {+ "name": "children",+ "endpoint": {+ "path": "/parents/{parent_id}/children",+ "params": {"parent_id": {"type": "resolve", "resource": "parents", "field": "id"}},+ },+ },+]+++def _events(items: Any, events: list[Any], *, covers_framework_checkpoints: bool) -> list[Any]:+ with activate_safe_point(+ lambda: events.append("safe_point"), covers_framework_checkpoints=covers_framework_checkpoints+ ):+ for page in items:+ events.append([row["id"] for row in page])+ return events+++ "wrapped,expected",+ [+ (False, [{"page": 1}, [1], "safe_point", None, [2], "safe_point"]),+ (True, [[1], {"page": 1}, [2], None]),+ ],+ ids=["pipeline_iterates_the_resource", "source_wraps_the_resource"],+)+def test_a_page_reaches_the_pipeline_with_its_resume_state_only_when_nothing_wraps_the_resource(+ wrapped: bool, expected: list[Any]+) -> None:+ events: list[Any] = []+ resource = _resource(paged_config(ITEMS, ["items"], total_pages=1), "items", events.append)++ _events(_wrapped(resource) if wrapped else resource, events, covers_framework_checkpoints=not wrapped)++ assert events == expected+++def test_a_safe_point_inside_the_hook_waits_until_the_page_is_handed_on() -> None:+ events: list[Any] = []++ def hook(state: Optional[dict[str, Any]]) -> None:+ events.append(state)+ reach_safe_point()++ resource = _resource(paged_config(ITEMS, ["items"], total_pages=1), "items", hook)++ _events(resource, events, covers_framework_checkpoints=True)++ assert events == [{"page": 1}, [1], "safe_point", None, [2], "safe_point"]+++def test_a_page_that_fails_its_transform_leaves_its_resume_state_unstaged() -> None:+ states: list[Any] = []+ resource = _resource(paged_config(ITEMS, ["items"], total_pages=1), "items", states.append)++ def fail_on_second_page(row: dict[str, Any]) -> dict[str, Any]:+ if row["id"] == 2:+ raise ValueError("bad row")+ return row++ resource.add_map(fail_on_second_page)++ with pytest.raises(ValueError, match="bad row"):+ _events(resource, [], covers_framework_checkpoints=True)++ assert states == [{"page": 1}]+++def test_the_last_page_of_a_parent_is_handed_on_with_the_parent_recorded_complete() -> None:+ events: list[Any] = []+ resource = _resource(paged_config(FANOUT, FANOUT_RESOURCES, total_pages=1), "children", events.append)++ _events(resource, events, covers_framework_checkpoints=True)++ states_before = {tuple(page): events[index - 1] for index, page in enumerate(events) if isinstance(page, list)}+ assert states_before[("a1",)] == {+ "completed": [],+ "current": "/parents/a/children",+ "child_state": {"page": 1},+ }+ assert states_before[("a2",)] == {"completed": ["/parents/a/children"], "current": None, "child_state": None}+ assert states_before[("b1",)]["current"] == "/parents/b/children"+++class _NoResumeStatePaginator(PageNumberPaginator):+ def get_resume_state(self) -> Optional[dict[str, Any]]:+ return None+++def test_a_parent_stays_in_progress_while_a_paginator_without_resume_state_has_more_pages() -> None:+ events: list[Any] = []+ children = {+ **FANOUT_RESOURCES[1],+ "endpoint": {**FANOUT_RESOURCES[1]["endpoint"], "paginator": _NoResumeStatePaginator()},+ }+ resource = _resource(paged_config(FANOUT, ["parents", children]), "children", events.append)++ _events(resource, events, covers_framework_checkpoints=True)++ assert events[events.index(["a1"]) - 1] == {+ "completed": [],+ "current": "/parents/a/children",+ "child_state": None,+ }++[email protected]("stop_after_pages", [1, 2, 3])+def test_a_fan_out_resumed_from_the_state_staged_with_a_page_reads_every_row_once(stop_after_pages: int) -> None:+ states: list[Any] = []+ first = _resource(paged_config(FANOUT, FANOUT_RESOURCES), "children", states.append)+ rows: list[str] = []+ with activate_safe_point(lambda: None, covers_framework_checkpoints=True):+ for index, page in enumerate(first, start=1):+ rows.extend(row["id"] for row in page)+ if index == stop_after_pages:+ break++ resumed = _resource(paged_config(FANOUT, FANOUT_RESOURCES), "children", lambda _state: None, states[-1])+ rows.extend(row["id"] for page in resumed for row in page)++ assert rows == ["a1", "a2", "b1"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/safe_point.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/safe_point.pyindex 8c6eb2a45678..b8ba0558504b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/safe_point.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/safe_point.py@@ -34,6 +34,7 @@ class _ActiveSafePoint:_active_safe_point: ContextVar[_ActiveSafePoint | None] = ContextVar("warehouse_source_safe_point", default=None)+_safe_points_held: ContextVar[bool] = ContextVar("warehouse_source_safe_points_held", default=False)@contextmanager@@ -48,15 +49,34 @@ def activate_safe_point(hook: SafePointHook, *, covers_framework_checkpoints: bo_active_safe_point.reset(token)+@contextmanager+def hold_safe_points() -> Iterator[None]:+ """Make safe points do nothing inside the block.++ The REST framework stages a page's cursor before it hands the page on. A resume hook that+ reaches a safe point would then let the pipeline commit a cursor for rows it does not have yet.+ """+ token = _safe_points_held.set(True)+ try:+ yield+ finally:+ _safe_points_held.reset(token)++def reach_safe_point() -> None:"""Tell the pipeline that the source is at a safe point. Does nothing outside an extraction."""active = _active_safe_point.get()- if active is not None:+ if active is not None and not _safe_points_held.get():active.hook()+def framework_checkpoints_are_covered() -> bool:+ """Whether the pipeline iterates the REST framework's own generator, with no source wrapper around it."""+ active = _active_safe_point.get()+ return active is not None and active.covers_framework_checkpoints++def reach_framework_safe_point() -> None:"""The REST framework's safe point, which applies only when nothing wraps the framework's output."""- active = _active_safe_point.get()- if active is not None and active.covers_framework_checkpoints:- active.hook()+ if framework_checkpoints_are_covered():+ reach_safe_point()diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.pyindex 53573531345b..5ce958e26c51 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py@@ -543,6 +543,7 @@ async def _execute_run(data_selector_required: bool = False,data_selector_empty_ok: bool = False,data_selector_malformed_retryable: bool = False,+ page_state_hook: Optional[Any] = None,):return iter(mock_data_response)@@ -561,6 +562,7 @@ async def _execute_run(data_selector_required: bool = False,data_selector_empty_ok: bool = False,data_selector_malformed_retryable: bool = False,+ page_state_hook: Optional[Any] = None,):# Yield each record as its own page so tests that probe chunking# by record size still see one call per record.