: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-imports): treat empty envelope body as zero rows for required selectors (#73662)
Tom Owers56d27a98285b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/cohere.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/cohere.pyindex 8af8dab67690..8a8af1941885 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/cohere.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/cohere.py@@ -75,10 +75,13 @@ def cohere_source("path": config.path,"params": params,"data_selector": config.data_key,- # A successful response that omits the envelope key is a shape mismatch, not empty- # data. Every Cohere schema is full-refresh-only, so silently treating a missing- # key as an empty page would clear the existing warehouse table; fail loud instead.+ # A response that carries other keys but omits the envelope key is a shape mismatch,+ # not empty data. Every Cohere schema is full-refresh-only, so silently treating that+ # as an empty page would clear the existing warehouse table; fail loud instead."data_selector_required": True,+ # Cohere returns a bare ``{}`` for an empty collection (e.g. an account with no+ # datasets) rather than ``{"datasets": []}``, so an empty body is a valid 0-row page.+ "data_selector_empty_ok": True,},}],diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/tests/test_cohere.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/tests/test_cohere.pyindex d83faedd2dbe..639ed4047b17 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/tests/test_cohere.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/tests/test_cohere.py@@ -154,6 +154,16 @@ class TestFailLoud:with pytest.raises(ValueError, match="matched nothing"):_rows(cohere_source("key", "datasets", team_id=1, job_id="j"))+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_empty_body_yields_nothing(self, MockSession) -> None:+ session = MockSession.return_value+ # Cohere returns a bare {} for an empty collection (an account with no datasets) rather than+ # {"datasets": []}; that empty body is a valid 0-row page, not a shape change.+ _wire(session, [_response(None, None)])++ assert _rows(cohere_source("key", "datasets", team_id=1, job_id="j")) == []+ assert session.send.call_count == 1+class TestRetry:@mock.patch(CLIENT_SESSION_PATCH)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 2d15eda3e413..c7973c808002 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@@ -130,6 +130,7 @@ def _make_paginate_dependent_resource(resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = None,initial_state: Optional[dict[str, Any]] = None,data_selector_required: bool = False,+ data_selector_empty_ok: bool = False,) -> Callable[..., Iterator[list[Any]]]:"""Build the generator for a dependent (child) resource.@@ -199,6 +200,7 @@ def _make_paginate_dependent_resource(resume_hook=child_resume_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,):if parent_record:for child_record in child_page:@@ -315,6 +317,7 @@ def create_resources(None if has_dependent_resource else initial_paginator_state),data_selector_required: bool = bool(endpoint_config.get("data_selector_required")),+ data_selector_empty_ok: bool = bool(endpoint_config.get("data_selector_empty_ok")),data_selector_malformed_retryable: bool = bool(endpoint_config.get("data_selector_malformed_retryable")),@@ -339,6 +342,7 @@ def create_resources(resume_hook=resume_hook,initial_paginator_state=initial_paginator_state,data_selector_required=data_selector_required,+ data_selector_empty_ok=data_selector_empty_ok,data_selector_malformed_retryable=data_selector_malformed_retryable,):yield list(convert_types(page, columns_config))@@ -376,6 +380,7 @@ def create_resources(resume_hook=dependent_resume_hook,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")),)resources[resource_name] = Resource(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 2ed05a7c39c3..e5f92e28f622 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@@ -286,6 +286,7 @@ class RESTClient:resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = None,initial_paginator_state: Optional[dict[str, Any]] = None,data_selector_required: bool = False,+ data_selector_empty_ok: bool = False,data_selector_malformed_retryable: bool = False,) -> Iterator[list[Any]]:paginator = copy.deepcopy(paginator) if paginator else copy.deepcopy(self.paginator)@@ -326,7 +327,9 @@ class RESTClient:except IgnoreResponseException:break- data = self._extract_response(body, data_selector, required=data_selector_required)+ data = self._extract_response(+ body, data_selector, required=data_selector_required, empty_body_ok=data_selector_empty_ok+ )if paginator is not None:paginator.update_state(response, data)@@ -449,7 +452,9 @@ class RESTClient:return response, body- def _extract_response(self, body: Any, data_selector: Optional[TJsonPath], *, required: bool = False) -> list[Any]:+ def _extract_response(+ self, body: Any, data_selector: Optional[TJsonPath], *, required: bool = False, empty_body_ok: bool = False+ ) -> list[Any]:if data_selector:matches: Any = find_values(data_selector, body)# ``required`` distinguishes "the selector key is absent" (no matches -> the response@@ -457,6 +462,13 @@ class RESTClient:# 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:+ # An empty container omits the key but carries no rows and no alternative shape.+ # Sources whose API drops the envelope key for an empty collection (rather than+ # returning an empty list) opt into treating it as a 0-row page via ``empty_body_ok``;+ # by default it stays a fail-loud shape mismatch, since a body with other keys is a+ # genuine shape change.+ if empty_body_ok and isinstance(body, dict | list) and not body:+ return []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 "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 fc6632251143..6b49eb0c3320 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@@ -274,6 +274,7 @@ class _FakeResumableClient:resume_hook=None,initial_paginator_state=None,data_selector_required=False,+ data_selector_empty_ok=False,):pages = self.pages_by_path[path]start = initial_paginator_state["page"] if initial_paginator_state else 0diff --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.pyindex 4ab387a96c97..bbf0d4252ad1 100644--- 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.py@@ -1,6 +1,8 @@import pytestfrom unittest.mock import Mock+from parameterized import parameterized+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient@@ -25,6 +27,23 @@ class TestRequiredDataSelector:# Backward compatible: without required, a missing key still silently yields nothing.assert _client()._extract_response({"unexpected": "envelope"}, "data", required=False) == []+ @parameterized.expand([("empty_object", {}), ("empty_array", [])])+ def test_empty_body_raises_by_default_when_required(self, _name: str, body: object) -> None:+ # Without the opt-in, an empty container missing the key stays a fail-loud shape mismatch.+ with pytest.raises(ValueError, match="matched nothing"):+ _client()._extract_response(body, "data", required=True)++ @parameterized.expand([("empty_object", {}), ("empty_array", [])])+ def test_empty_body_is_zero_rows_when_empty_ok(self, _name: str, body: object) -> None:+ # With empty_body_ok, an empty container is a legit zero-row page -> for sources whose API+ # drops the envelope key for an empty collection (e.g. Cohere returns {} for no datasets).+ assert _client()._extract_response(body, "data", required=True, empty_body_ok=True) == []++ def test_non_empty_body_missing_key_still_raises_when_empty_ok(self) -> None:+ # empty_body_ok only relaxes empty containers; a body with other keys is still a shape change.+ with pytest.raises(ValueError, match="matched nothing"):+ _client()._extract_response({"unexpected": "envelope"}, "data", required=True, empty_body_ok=True)+class TestRequiredListBody:def test_non_list_body_raises_when_required_and_no_selector(self) -> None: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 2feadcad7446..7fc58c9a78d2 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@@ -253,6 +253,11 @@ class Endpoint(TypedDict, total=False):# 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]+ # Relaxes ``data_selector_required`` for empty-container bodies: when True, a 200 whose body is an+ # empty ``{}`` or ``[]`` is treated as a valid 0-row page instead of a shape mismatch. For sources+ # whose API drops the envelope key entirely for an empty collection. A body carrying other keys is+ # still a shape change and still fails loud. No effect unless ``data_selector_required`` is set.+ data_selector_empty_ok: Optional[bool]# When True, a 200 whose parsed body isn't the expected list shape (selector matches nothing, or# the matched value / selector-less body isn't a list) raises a RETRYABLE error and the request is# reissued — for sources that defensively treat an unexpected 200-body shape as transient. This isdiff --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 e3d644165c03..415a96427ebd 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@@ -551,6 +551,7 @@ async def _execute_run(workflow_id: str, inputs: ExternalDataWorkflowInputs, mocresume_hook: Optional[Any] = None,initial_paginator_state: Optional[dict[str, Any]] = None,data_selector_required: bool = False,+ data_selector_empty_ok: bool = False,data_selector_malformed_retryable: bool = False,):return iter(mock_data_response)@@ -568,6 +569,7 @@ async def _execute_run(workflow_id: str, inputs: ExternalDataWorkflowInputs, mocresume_hook: Optional[Any] = None,initial_paginator_state: Optional[dict[str, Any]] = None,data_selector_required: bool = False,+ data_selector_empty_ok: bool = False,data_selector_malformed_retryable: bool = False,):# Yield each record as its own page so tests that probe chunking