: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(warehouse-sources): make the fan-out drift signals countable per schema (#83322)
Daniel RC75bad1c639f7
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 3cfc68ffe3c6..bb0bccb54e04 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@@ -300,7 +300,7 @@ def create_resources(request_timeout=client_config.get("request_timeout"),)- hooks = create_response_hooks(endpoint_config.get("response_actions"))+ hooks = create_response_hooks(endpoint_config.get("response_actions"), resource_name=resource_name)resource_kwargs = exclude_keys(endpoint_resource, {"endpoint", "include_from_parent", "data_map", "data_iterator"}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/config_setup.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/config_setup.pyindex 8d3d34d19e93..58311923db9f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/config_setup.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/config_setup.py@@ -1,11 +1,11 @@import string-import loggingimport graphlib # type: ignore[import,unused-ignore]import warningsfrom collections.abc import Callablefrom copy import copyfrom typing import Any, NamedTuple, Optional, cast+import structlogfrom requests import Responsefrom .auth import APIKeyAuth, AuthConfigBase, BearerTokenAuth, HttpBasicAuth, OAuth2Auth@@ -36,7 +36,7 @@ from .typing import ()from .utils import exclude_keys-logger = logging.getLogger(__name__)+logger = structlog.get_logger(__name__)PAGINATOR_MAP: dict[PaginatorType, type[BasePaginator] | None] = {"json_response": JSONResponsePaginator,@@ -386,15 +386,22 @@ def _handle_response_actions(response: Response, actions: list[ResponseAction])def _create_response_actions_hook(response_actions: list[ResponseAction],+ resource_name: str | None = None,) -> Callable[[Response, Any, Any], None]:def response_actions_hook(response: Response, *args: Any, **kwargs: Any) -> None:matched = _handle_response_actions(response, response_actions)action_type = matched.get("action") if matched else Noneif action_type == "ignore":+ # Carries the resource so ignores are countable per schema.# Use response.text, not response.json(): an ignored response (e.g. a 404) often has an# empty or non-JSON body, and parsing it here would raise before the ignore takes effect.- logger.info(f"Ignoring response with code {response.status_code} and content '{response.text[:500]}'.")+ logger.info(+ "data_imports.response_action_ignored",+ resource=resource_name,+ status_code=response.status_code,+ content=response.text[:500],+ )raise IgnoreResponseException# Re-issue the request. This is how a source classifies an HTTP-200 body-level error@@ -418,9 +425,10 @@ def _create_response_actions_hook(def create_response_hooks(response_actions: Optional[list[ResponseAction]],+ resource_name: Optional[str] = None,) -> Optional[dict[str, Any]]:if response_actions:- return {"response": [_create_response_actions_hook(response_actions)]}+ return {"response": [_create_response_actions_hook(response_actions, resource_name)]}return Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.pyindex 08344fbfdea3..e56602bf2451 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py@@ -162,6 +162,7 @@ def build_dependent_resource(parent_name=fanout.parent_name,columns=parent_columns,page_size=parent_config.page_size,+ schema_name=child_endpoint,)child_path = child_config.pathdiff --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 8ab552d36418..d25fae75a326 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@@ -505,6 +505,9 @@ def test_warehouse_parent_builds_data_iterator_and_404_ignore(parent_name="parents",columns=["id"],page_size=3,+ # Without this the reader's rows-streamed log has no schema, so snapshot drift can't+ # be attributed to a child.+ schema_name="children",)assert child_resource["endpoint"]["response_actions"] == [{"status_code": 404, "action": "ignore"}]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_response_action_classification.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_response_action_classification.pyindex f229b11d15d8..1765a45f9bca 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_response_action_classification.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_response_action_classification.py@@ -19,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res)MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client"+CONFIG_SETUP_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup"def _make_response(body: Any, status_code: int = 200, reason: str = "OK") -> Response:@@ -98,15 +99,21 @@ class TestResponseActionClassification:resp._content = b""resp.url = "https://api.example.com/items"mock_session.send.return_value = resp- hooks = create_response_hooks([{"status_code": 404, "action": "ignore"}])+ hooks = create_response_hooks([{"status_code": 404, "action": "ignore"}], resource_name="issue_hashes")client = RESTClient(base_url="https://api.example.com", max_retry_attempts=1)- pages = list(- client.paginate(path="/items", data_selector="results", paginator=SinglePagePaginator(), hooks=hooks)- )+ with patch(f"{CONFIG_SETUP_MODULE}.logger") as mock_logger:+ pages = list(+ client.paginate(path="/items", data_selector="results", paginator=SinglePagePaginator(), hooks=hooks)+ )assert pages == []assert mock_session.send.call_count == 1+ # A stale fan-out parent is dropped here, so the ignore has to be countable per schema.+ logged = mock_logger.info.call_args+ assert logged.args[0] == "data_imports.response_action_ignored"+ assert logged.kwargs["resource"] == "issue_hashes"+ assert logged.kwargs["status_code"] == 404@patch("tenacity.nap.time.sleep")@patch(f"{MODULE}.make_tracked_session")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_warehouse_parent.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_warehouse_parent.pyindex aec03a5514ce..704baf765d7b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_warehouse_parent.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_warehouse_parent.py@@ -38,7 +38,9 @@ def _write_parent_table(tmp_path: Path) -> str:def _patched_reader(uri: str, version: int | None = None, **kwargs):ref = ParentTableRef(uri=uri, version=deltalake.DeltaTable(uri).version() if version is None else version)with patch.object(warehouse_parent, "delta_storage_options", return_value={}):- return list(iter_parent_pages_from_warehouse(table=ref, parent_name="issues", **kwargs))+ return list(+ iter_parent_pages_from_warehouse(table=ref, parent_name="issues", schema_name="issue_tag_values", **kwargs)+ )def _patched_resolve(uri: str, snapshot_timestamp=None):@@ -108,6 +110,43 @@ def test_reader_pages_and_rekeys_to_api_field_names(tmp_path: Path) -> None:assert all(set(row) == {"id", "lastSeen"} for row in rows)+ "ending,expected_rows,expected_outcome",+ [("drained", 3, "completed"), ("closed", 1, "stopped"), ("raised", 1, "failed")],+)+def test_reader_logs_the_row_count_and_how_the_scan_ended(+ tmp_path: Path, ending: str, expected_rows: int, expected_outcome: str+) -> None:+ # A resumable child checkpoints mid-fan-out and the pipeline closes the generator, so a+ # count logged after the loop would be lost for exactly the runs worth measuring. Only a+ # drained scan carries a full count, and a crash must not read as a clean early stop.+ uri = _write_parent_table(tmp_path)+ ref = ParentTableRef(uri=uri, version=deltalake.DeltaTable(uri).version())++ with (+ patch.object(warehouse_parent, "delta_storage_options", return_value={}),+ patch.object(warehouse_parent, "logger") as mock_logger,+ ):+ pages = warehouse_parent.iter_parent_pages_from_warehouse(+ table=ref, parent_name="issues", columns=["id"], page_size=1, schema_name="issue_hashes"+ )+ if ending == "drained":+ list(pages)+ else:+ next(pages)+ if ending == "closed":+ pages.close()+ else:+ with pytest.raises(RuntimeError):+ pages.throw(RuntimeError("consumer blew up"))++ logged = mock_logger.info.call_args+ assert logged.args[0] == "data_imports.fanout_parent_rows_streamed"+ assert logged.kwargs["schema"] == "issue_hashes"+ assert logged.kwargs["rows"] == expected_rows+ assert logged.kwargs["outcome"] == expected_outcome++def test_resolve_raises_when_parent_has_no_synced_table(tmp_path: Path) -> None:with pytest.raises(WarehouseParentTableNotFoundError, match="no synced table"):_patched_resolve(str(tmp_path / "does_not_exist"))@@ -219,7 +258,11 @@ def test_reader_stays_on_the_pinned_version_when_the_parent_re_syncs(tmp_path: P)with patch.object(warehouse_parent, "delta_storage_options", return_value={}):- pages = list(iter_parent_pages_from_warehouse(table=pinned, parent_name="issues", columns=["id"], page_size=10))+ pages = list(+ iter_parent_pages_from_warehouse(+ table=pinned, parent_name="issues", columns=["id"], page_size=10, schema_name="issue_tag_values"+ )+ )assert sorted(row["id"] for page in pages for row in page) == ["1", "2", "3"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/warehouse_parent.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/warehouse_parent.pyindex 7ebe7c32ec08..21624286cc80 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/warehouse_parent.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/warehouse_parent.py@@ -1,6 +1,6 @@import uuidimport datetime as dt-from collections.abc import Iterator+from collections.abc import Generatorfrom dataclasses import dataclassfrom typing import Any@@ -227,8 +227,8 @@ def iter_parent_pages_from_warehouse(parent_name: str,columns: list[str],page_size: int,- schema_name: str | None = None,-) -> Iterator[list[dict[str, Any]]]:+ schema_name: str,+) -> Generator[list[dict[str, Any]]]:"""Yield fan-out parent rows from the parent schema's already-synced Delta table.Pages are shaped like the REST parent pages the dependent-resource machinery consumes@@ -262,25 +262,38 @@ def iter_parent_pages_from_warehouse(dataset = delta_table.to_pyarrow_dataset()rows_streamed = 0- page: list[dict[str, Any]] = []- for batch in dataset.to_batches(columns=projected, batch_size=page_size):- for row in batch.to_pylist():- page.append({api_name: row.get(physical) for api_name, physical in physical_by_api_name.items()})- rows_streamed += 1- if len(page) >= page_size:- yield page- page = []- if page:- yield page-- # The snapshot only grows for an incremental parent, while the vendor's own listing drops- # rows past its retention. This count against the child's stale-parent skips is how we tell- # whether the fan-out set has drifted above what the API would return — see the reuse- # follow-up in the plan.- logger.info(- "data_imports.fanout_parent_rows_streamed",- schema=schema_name,- parent=parent_name,- rows=rows_streamed,- version=table.version,- )+ outcome = "failed"+ try:+ page: list[dict[str, Any]] = []+ for batch in dataset.to_batches(columns=projected, batch_size=page_size):+ for row in batch.to_pylist():+ page.append({api_name: row.get(physical) for api_name, physical in physical_by_api_name.items()})+ rows_streamed += 1+ if len(page) >= page_size:+ yield page+ page = []+ if page:+ yield page+ outcome = "completed"+ except GeneratorExit:+ outcome = "stopped"+ raise+ finally:+ # In a `finally` because a consumer can stop early: a resumable child checkpoints+ # mid-fan-out, and the pipeline's iterator cleanup closes this generator, which raises+ # GeneratorExit at the `yield` above. Logging after the loop would lose those runs+ # entirely. Only `completed` carries a full row count; a `stopped` or `failed` scan must+ # not be read as a shrinking snapshot.+ #+ # The snapshot only grows for an incremental parent, while the vendor's own listing+ # drops rows past its retention. This count against the child's ignored stale-parent+ # responses is how we tell whether the fan-out set has drifted above what the API+ # would return — see the reuse follow-up in the plan.+ logger.info(+ "data_imports.fanout_parent_rows_streamed",+ schema=schema_name,+ parent=parent_name,+ rows=rows_streamed,+ version=table.version,+ outcome=outcome,+ )