: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): close rest_source gaps (item-transform + fan-out resume) (#71481)
Tom Owers7c4b8c8cb365
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 a3ef383dd6eb..76eca75ef5e6 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@@ -127,8 +127,28 @@ def _make_paginate_dependent_resource(incremental_param: Optional[IncrementalParam],incremental_cursor_transform: Optional[Callable[..., Any]],db_incremental_field_last_value: Optional[Any],+ resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = None,+ initial_state: Optional[dict[str, Any]] = None,+ data_selector_required: bool = False,) -> Callable[..., Iterator[list[Any]]]:- """Build the generator for a dependent (child) resource."""+ """Build the generator for a dependent (child) resource.++ When ``resume_hook`` is set the fan-out is resumable: each parent's child pagination is+ checkpointed under that parent's resolved child path, so a restart skips parents already fully+ synced and resumes the one that was in progress. Parent pagination itself is not resumed — the+ (usually small) parent list is re-fetched each run and already-completed parents are skipped by+ path. Resume state shape:+ ``{"completed": [child_path, ...], "current": child_path | None, "child_state": {...} | None}``.+ """+ # Closure state persists across parent-page invocations within a single run.+ seed: dict[str, Any] = dict(initial_state) if initial_state else {}+ completed: set[str] = set(seed.get("completed") or [])+ current_path: Optional[str] = seed.get("current")+ current_child_state: Optional[dict[str, Any]] = seed.get("child_state")++ def checkpoint(current: Optional[str], child_state: Optional[dict[str, Any]]) -> None:+ # resume_hook is non-None here (only called from the resumable path).+ resume_hook({"completed": sorted(completed), "current": current, "child_state": child_state}) # type: ignore[misc]def paginate_dependent_resource(items: list[dict[str, Any]],@@ -140,6 +160,7 @@ def _make_paginate_dependent_resource(hooks: Optional[dict[str, Any]],columns_config: Optional[Any] = None,) -> Iterator[list[Any]]:+ nonlocal current_path, current_child_stateeffective_columns_config = columns_config if columns_config is not None else default_columns_configif incremental_object:@@ -154,6 +175,20 @@ def _make_paginate_dependent_resource(for item in items:formatted_path, parent_record = process_parent_data_item(path, item, resolved_param, include_from_parent)+ if resume_hook is not None and formatted_path in completed:+ continue++ # Resume this parent's child cursor only if it's the one we were mid-way through.+ child_initial = (+ 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:+ nonlocal current_path, current_child_state+ current_path = _path+ current_child_state = paginator_state+ checkpoint(_path, paginator_state)+for child_page in client.paginate(method=method,path=formatted_path,@@ -161,6 +196,9 @@ 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,+ initial_paginator_state=child_initial,+ data_selector_required=data_selector_required,):if parent_record:for child_record in child_page:@@ -168,6 +206,12 @@ def _make_paginate_dependent_resource(yield list(convert_types(child_page, effective_columns_config))+ if resume_hook is not None:+ completed.add(formatted_path)+ current_path = None+ current_child_state = None+ checkpoint(None, None)+return paginate_dependent_resource@@ -184,6 +228,11 @@ def create_resources() -> dict[str, Resource]:resources: dict[str, Resource] = {}+ # Resume is routed to the dependent (child) resource in a fan-out; the parent list is re-fetched+ # each run (see _make_paginate_dependent_resource). So when any resource is dependent, the+ # non-dependent resources in the same config don't consume the resume hook.+ has_dependent_resource = any(rp is not None for rp in resolved_param_map.values())+for resource_name in dependency_graph.static_order():resource_name = cast(str, resource_name)endpoint_resource = endpoint_resource_map[resource_name]@@ -217,7 +266,7 @@ def create_resources(hooks = create_response_hooks(endpoint_config.get("response_actions"))- resource_kwargs = exclude_keys(endpoint_resource, {"endpoint", "include_from_parent"})+ resource_kwargs = exclude_keys(endpoint_resource, {"endpoint", "include_from_parent", "data_map"})columns_config = endpoint_resource.get("columns")@@ -250,8 +299,13 @@ 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]] = resume_hook,- initial_paginator_state: Optional[dict[str, Any]] = initial_paginator_state,+ resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = (+ None if has_dependent_resource else resume_hook+ ),+ initial_paginator_state: Optional[dict[str, Any]] = (+ None if has_dependent_resource else initial_paginator_state+ ),+ data_selector_required: bool = bool(endpoint_config.get("data_selector_required")),) -> Iterator[list[Any]]:if incremental_object:params = _set_incremental_params(@@ -272,6 +326,7 @@ def create_resources(hooks=hooks,resume_hook=resume_hook,initial_paginator_state=initial_paginator_state,+ data_selector_required=data_selector_required,):yield list(convert_types(page, columns_config))@@ -292,10 +347,6 @@ def create_resources()else:- if resume_hook is not None or initial_paginator_state is not None:- raise NotImplementedError(- f"Resume is not supported for dependent REST resources (resource={resource_name!r})"- )predecessor = resources[resolved_param.resolve_config["resource"]]base_params = exclude_keys(request_params, {resolved_param.param_name})@@ -309,6 +360,9 @@ 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=resume_hook,+ initial_state=initial_paginator_state,+ data_selector_required=bool(endpoint_config.get("data_selector_required")),)resources[resource_name] = Resource(@@ -329,6 +383,12 @@ def create_resources(data_from=predecessor,)+ # Declarative per-item transform (e.g. flatten JSON:API attributes), applied after+ # type coercion during iteration. dict -> dict; use data_selector for extraction first.+ data_map = endpoint_resource.get("data_map")+ if data_map is not None:+ resources[resource_name].add_map(data_map)+return resourcesdiff --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 7a3df8beffd7..804c2cbcde39 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@@ -136,6 +136,7 @@ class RESTClient:hooks: Optional[Hooks] = None,resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = None,initial_paginator_state: Optional[dict[str, Any]] = None,+ data_selector_required: bool = False,) -> Iterator[list[Any]]:paginator = copy.deepcopy(paginator) if paginator else copy.deepcopy(self.paginator)hooks = hooks or {}@@ -164,7 +165,7 @@ class RESTClient:except IgnoreResponseException:break- data = self._extract_response(body, data_selector)+ data = self._extract_response(body, data_selector, required=data_selector_required)if paginator is not None:paginator.update_state(response, data)@@ -222,9 +223,20 @@ class RESTClient:return response, body- def _extract_response(self, body: Any, data_selector: Optional[TJsonPath]) -> list[Any]:+ def _extract_response(self, body: Any, data_selector: Optional[TJsonPath], *, required: bool = False) -> list[Any]:if data_selector:- data: Any = find_values(data_selector, body)+ matches: Any = find_values(data_selector, body)+ # ``required`` distinguishes "the selector key is absent" (no matches -> the response+ # shape changed, fail loud) from "the key is present but the list is empty" (a legit+ # zero-row page, which yields one match whose value is []). Sources that treat a missing+ # data key as an error set data_selector_required=True instead of silently syncing 0 rows.+ if required and not matches:+ keys = sorted(body.keys())[:20] if isinstance(body, dict) else type(body).__name__+ raise ValueError(+ f"Required data_selector {data_selector!r} matched nothing in the response "+ f"(body keys: {keys}). The API response shape may have changed."+ )+ data: Any = matches# unwrap single-item list from jsonpathif isinstance(data, list) and len(data) == 1:data = data[0]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_data_map.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_data_map.pynew file mode 100644index 000000000000..d55808b352da--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_data_map.py@@ -0,0 +1,26 @@+from unittest.mock import patch++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.rest_client import RESTClient+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import RESTAPIConfig+++def test_data_map_reshapes_rows_declaratively() -> None:+ config: RESTAPIConfig = {+ "client": {"base_url": "https://api.example.com"},+ "resource_defaults": None,+ "resources": [+ {+ "name": "things",+ "endpoint": {"path": "/things"},+ # flatten a JSON:API-style ``attributes`` block into the row root+ "data_map": lambda row: {"id": row["id"], **row.get("attributes", {})},+ }+ ],+ }+ raw_page = [{"id": 1, "attributes": {"name": "x", "active": True}}]+ with patch.object(RESTClient, "paginate", return_value=iter([raw_page])):+ resource = rest_api_resource(config, team_id=1, job_id="j", db_incremental_field_last_value=None)+ rows = [row for page in resource for row in page]++ assert rows == [{"id": 1, "name": "x", "active": True}]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 ac00fccc0ae4..39da52c689fa 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@@ -223,3 +223,115 @@ def test_paginate_dependent_resource_does_not_leak_params_across_parents() -> Noassert params_snapshot["since"] == "2026-01-01"assert params_snapshot["until"] == "2026-03-01"assert "before" not in params_snapshot+++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.+ def __init__(self, pages_by_path: dict[str, list[list[dict[str, Any]]]]) -> None:+ self.pages_by_path = pages_by_path++ def paginate(+ self,+ *,+ method,+ path,+ params,+ paginator,+ data_selector,+ hooks,+ resume_hook=None,+ initial_paginator_state=None,+ data_selector_required=False,+ ):+ pages = self.pages_by_path[path]+ start = initial_paginator_state["page"] if initial_paginator_state else 0+ for i in range(start, len(pages)):+ yield pages[i]+ if resume_hook is not None:+ resume_hook({"page": i + 1} if i < len(pages) - 1 else None)+++_RESOLVED_PARAM = ResolvedParam(+ param_name="parent_id",+ resolve_config={"type": "resolve", "resource": "parents", "field": "id"},+)+++def _dependent_fn(client, resume_hook=None, initial_state=None):+ return _make_paginate_dependent_resource(+ client=client,+ resolved_param=_RESOLVED_PARAM,+ include_from_parent=[],+ default_columns_config=None,+ incremental_object=None,+ incremental_param=None,+ incremental_cursor_transform=None,+ db_incremental_field_last_value=None,+ resume_hook=resume_hook,+ initial_state=initial_state,+ )+++def _drive(paginate_fn) -> list[dict[str, Any]]:+ rows: list[dict[str, Any]] = []+ for page in paginate_fn(+ items=[{"id": "a"}, {"id": "b"}],+ method="get",+ path="/parents/{parent_id}/children",+ params={},+ paginator=None,+ data_selector=None,+ hooks=None,+ ):+ rows.extend(page)+ return rows+++def test_dependent_resume_checkpoints_completed_parents() -> None:+ client = _FakeResumableClient(+ {+ "/parents/a/children": [[{"id": "a1"}], [{"id": "a2"}]],+ "/parents/b/children": [[{"id": "b1"}]],+ }+ )+ checkpoints: list[Any] = []+ rows = _drive(_dependent_fn(client, resume_hook=checkpoints.append))++ assert [r["id"] for r in rows] == ["a1", "a2", "b1"]+ # Final checkpoint records both parents fully synced, nothing in progress.+ assert checkpoints[-1] == {+ "completed": ["/parents/a/children", "/parents/b/children"],+ "current": None,+ "child_state": None,+ }+++def test_dependent_resume_skips_completed_and_resumes_current() -> None:+ client = _FakeResumableClient(+ {+ "/parents/a/children": [[{"id": "a1"}], [{"id": "a2"}]],+ "/parents/b/children": [[{"id": "b1"}], [{"id": "b2"}]],+ }+ )+ # Parent a already fully synced; parent b was mid-way (its child cursor is at page index 1).+ initial_state = {+ "completed": ["/parents/a/children"],+ "current": "/parents/b/children",+ "child_state": {"page": 1},+ }+ rows = _drive(_dependent_fn(client, resume_hook=lambda _s: None, initial_state=initial_state))++ # a is skipped entirely (no re-yield); b resumes from page 1, so only b2 (b1 already synced).+ assert [r["id"] for r in rows] == ["b2"]+++def test_dependent_resume_disabled_without_hook_processes_all() -> None:+ client = _FakeResumableClient(+ {+ "/parents/a/children": [[{"id": "a1"}]],+ "/parents/b/children": [[{"id": "b1"}]],+ }+ )+ rows = _drive(_dependent_fn(client, resume_hook=None))+ assert [r["id"] for r in rows] == ["a1", "b1"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_required_selector.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_required_selector.pynew file mode 100644index 000000000000..02187534c817--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_required_selector.py@@ -0,0 +1,26 @@+import pytest+from unittest.mock import Mock++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient+++def _client() -> RESTClient:+ return RESTClient(base_url="https://api.example.com", session=Mock())+++class TestRequiredDataSelector:+ def test_absent_key_raises_when_required(self) -> None:+ # The selector key is missing entirely -> response shape changed -> fail loud.+ with pytest.raises(ValueError, match="matched nothing"):+ _client()._extract_response({"unexpected": "envelope"}, "data", required=True)++ def test_present_empty_list_is_valid_zero_rows_when_required(self) -> None:+ # Key present, list empty -> a legit zero-row page, NOT a shape change -> no raise.+ assert _client()._extract_response({"data": []}, "data", required=True) == []++ def test_present_with_rows_when_required(self) -> None:+ assert _client()._extract_response({"data": [{"id": 1}]}, "data", required=True) == [{"id": 1}]++ def test_absent_key_is_silent_when_not_required(self) -> None:+ # Backward compatible: without required, a missing key still silently yields nothing.+ assert _client()._extract_response({"unexpected": "envelope"}, "data", required=False) == []diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.pyindex 15670694907d..22a7feaf26b6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py@@ -221,6 +221,10 @@ class Endpoint(TypedDict, total=False):json: Optional[dict[str, Any]]paginator: Optional[PaginatorConfig]data_selector: Optional[TJsonPath]+ # When True, a response whose ``data_selector`` matches nothing (the key is absent) raises+ # instead of yielding an empty page — fail-loud on an unexpected/changed API response shape,+ # rather than silently syncing 0 rows. A present-but-empty list is still a valid 0-row page.+ data_selector_required: Optional[bool]response_actions: Optional[list[ResponseAction]]incremental: Optional[IncrementalConfig]@@ -242,6 +246,10 @@ class ResourceBase(TypedDict, total=False):class EndpointResourceBase(ResourceBase, total=False):endpoint: Optional[str | Endpoint]include_from_parent: Optional[list[str]]+ # Per-item transform applied after ``data_selector`` and before type coercion, for reshaping+ # a row the selector can't express (e.g. flattening JSON:API ``attributes`` into the row root).+ # Wired through to ``Resource.add_map``; must be dict -> dict (1:1).+ data_map: Optional[Callable[[dict[str, Any]], dict[str, Any]]]class EndpointResource(EndpointResourceBase, total=False):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 8b29b6e64f1d..4a00ab9069b1 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@@ -581,6 +581,7 @@ async def _execute_run(workflow_id: str, inputs: ExternalDataWorkflowInputs, mochooks: Optional[Any] = None,resume_hook: Optional[Any] = None,initial_paginator_state: Optional[dict[str, Any]] = None,+ data_selector_required: bool = False,):return iter(mock_data_response)@@ -596,6 +597,7 @@ async def _execute_run(workflow_id: str, inputs: ExternalDataWorkflowInputs, mochooks: Optional[Any] = None,resume_hook: Optional[Any] = None,initial_paginator_state: Optional[dict[str, Any]] = None,+ data_selector_required: bool = False,):# Yield each record as its own page so tests that probe chunking# by record size still see one call per record.