: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): report fan-out parent size on Stripe's sweep (#93529)
Daniel RCac651b2a9a7b
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.mdindex c0b8edebdcd4..fcfe370a0f57 100644--- a/.agents/skills/implementing-warehouse-sources/SKILL.md+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md@@ -653,6 +653,7 @@ Requirements and behavior:The effective bound is usually invisible in our code, so classify empirically: run the listing against a real account with and without explicit bounds, compare counts, and check whether items outside the suspected bound still serve their child endpoints.- **Windowed parents must stay windowed.** If the source currently bounds its parent walk by the child watermark (e.g. Github's `_fan_out_get_rows`), a full warehouse read would _increase_ child fan-out — filter the warehouse read to the same window instead.- **Non-REST sources** (e.g. Stripe's SDK loop) can call `iter_parent_pages_from_warehouse` directly; project any fields their skip-checks inspect (e.g. customer `balance`). Resolve the table with `resolve_parent_table_ref(..., required_columns=[...])` eagerly in `source_for_pipeline` (sync context) — it does an ORM read, and the pipeline's iterator executor threads are the wrong place for ad-hoc DB connections. It also pins the parent's Delta version, so a parent that re-syncs mid-fan-out can't shift the rows underneath the child; pass the returned ref to the reader instead of re-deriving a URI.+ Such a source also skips the shared fan-out's telemetry, so call `log_fanout_parent_rows_consumed` (`sources/common/fanout_telemetry.py`) when its parent sweep ends, with the `parent_source` the run actually read from. Without that line nothing can compare the warehouse fan-out size against the API path's, which is the only detector for a parent that is missing rows the listing still returns.- **Catch `WarehouseParentTableNotFoundError` around that resolve call and take the API path.** A schema row can claim a completed sync while its table is unreadable (purged, renamed, or missing the fan-out columns), and the reader is a generator, so anything it validated lazily would raise deep inside the pipeline where no fallback is left. That is why `required_columns` is validated eagerly during resolution. When falling back, also turn off any behavior that only makes sense for a warehouse snapshot (the child's stale-parent `404 → ignore`, and resume checkpoints the warehouse scan skips), so the run matches the feature-off path exactly.## OAuth configurationdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/fanout_telemetry.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/fanout_telemetry.pynew file mode 100644index 000000000000..665a1088d87d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/fanout_telemetry.py@@ -0,0 +1,40 @@+from typing import Literal++from structlog.types import FilteringBoundLogger++FanoutParentSource = Literal["api", "warehouse"]++FANOUT_PARENT_ROWS_CONSUMED = "data_imports.fanout_parent_rows_consumed"+++def log_fanout_parent_rows_consumed(+ logger: FilteringBoundLogger,+ *,+ parent_source: FanoutParentSource,+ rows_total: int,+ resumed: bool,+ page_rows: int | None = None,+) -> None:+ """Report how many parent rows a fan-out sweep consumed, and which source served them.++ Comparing that count across the two parent sources for one schema is how a warehouse parent+ that is missing rows gets found, because a webhook-maintained parent holds only what its+ drains delivered.++ `rows_total` counts the current attempt, so an attempt that resumed reports fewer rows than+ the sweep covers. `resumed` marks those lines, because a partial count and a genuinely short+ parent listing otherwise look the same.++ Emit often enough that the last line of an attempt carries its running total. A caller that+ emits once per parent page also sets `page_rows`.++ Lives in a leaf module (no deltalake or pyarrow) so that any source can import it.+ """+ per_page_fields: dict[str, int] = {} if page_rows is None else {"page_rows": page_rows}+ logger.info(+ FANOUT_PARENT_ROWS_CONSUMED,+ parent_source=parent_source,+ rows_total=rows_total,+ resumed=resumed,+ **per_page_fields,+ )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 8bda69699624..18f7af96761e 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@@ -7,6 +7,11 @@ from typing import Any, Optional, castimport structlogfrom dateutil import parser+from products.warehouse_sources.backend.temporal.data_imports.sources.common.fanout_telemetry import (+ FanoutParentSource,+ log_fanout_parent_rows_consumed,+)+from .config_setup import (Incremental,IncrementalParam,@@ -142,6 +147,7 @@ def _make_paginate_dependent_resource(data_selector_required: bool = False,data_selector_empty_ok: bool = False,on_parent_error: Optional[Callable[[str, Exception], None]] = None,+ parent_source: FanoutParentSource = "api",) -> Callable[..., Iterator[list[Any]]]:"""Build the generator for a dependent (child) resource.@@ -158,6 +164,7 @@ def _make_paginate_dependent_resource(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")+ resumed = bool(completed or current_path)def checkpoint(current: Optional[str], child_state: Optional[dict[str, Any]]) -> None:# resume_hook is non-None here (only called from the resumable path).@@ -249,10 +256,12 @@ def _make_paginate_dependent_resource(# Counted after the page so parents a resume skips don't inflate it. A running total,# since there's no end-of-parent signal: the last line of a run carries the fan-out's# size, for either parent kind, which the API path never surfaced anywhere.- logger.info(- "data_imports.fanout_parent_rows_consumed",- page_rows=page_rows,+ log_fanout_parent_rows_consumed(+ logger,+ parent_source=parent_source,rows_total=parent_rows_consumed,+ resumed=resumed,+ page_rows=page_rows,)return paginate_dependent_resource@@ -421,7 +430,13 @@ def create_resources()else:- predecessor = resources[resolved_params[0].resolve_config["resource"]]+ parent_name = resolved_params[0].resolve_config["resource"]+ predecessor = resources[parent_name]++ # Set by `build_dependent_resource` only once the warehouse table resolves, so an+ # unresolvable table leaves this "api" and the telemetry names the parent the run+ # actually read.+ parent_source: FanoutParentSource = endpoint_resource_map[parent_name].get("parent_source") or "api"base_params = exclude_keys(request_params, {rp.param_name for rp in resolved_params})@@ -439,6 +454,7 @@ def create_resources(data_selector_required=bool(endpoint_config.get("data_selector_required")),data_selector_empty_ok=bool(endpoint_config.get("data_selector_empty_ok")),on_parent_error=on_parent_error,+ parent_source=parent_source,)resources[resource_name] = Resource(diff --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 09eb797bba56..9b2e2008d825 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@@ -167,6 +167,7 @@ def build_dependent_resource(# below, so the child syncs exactly the way it does without this feature.warehouse_parent = Falseelse:+ parent_resource["parent_source"] = "warehouse"parent_resource["data_iterator"] = lambda: iter_parent_pages_from_warehouse(table=parent_table,parent_name=fanout.parent_name,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 e358986e6a58..638456278f37 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@@ -1,10 +1,15 @@+from collections.abc import Callable, Iteratorfrom dataclasses import dataclass, replacefrom datetime import timedelta-from typing import Any+from typing import Any, castimport pytestfrom unittest.mock import Mock, patch+from products.warehouse_sources.backend.temporal.data_imports.sources.common import rest_source+from products.warehouse_sources.backend.temporal.data_imports.sources.common.fanout_telemetry import (+ FANOUT_PARENT_ROWS_CONSUMED,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (_make_paginate_dependent_resource,)@@ -14,9 +19,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resrequired_parents_from_endpoint_configs,)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.rest_client import RESTClientfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (ParentRowFilter,ResolvedParam,+ RESTAPIConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import (ParentTableRef,@@ -375,6 +382,68 @@ def test_paginate_dependent_resource_does_not_leak_params_across_parents() -> Noassert "before" not in params_snapshot+def _pages_by_path(+ pages: dict[str, list[dict[str, Any]]],+) -> Callable[..., Iterator[list[dict[str, Any]]]]:+ def paginate(self: Any, *, path: str = "", **kwargs: Any) -> Iterator[list[dict[str, Any]]]:+ yield pages[path]++ return paginate+++ "warehouse_parent,expected_parent_source",+ [(False, "api"), (True, "warehouse")],+)+def test_dependent_resource_reports_which_parent_source_served_its_rows(+ warehouse_parent: bool, expected_parent_source: str+) -> None:+ # The fan-out size only detects a warehouse parent that is missing rows when the same line+ # says which source produced it.+ parent_resource: dict[str, Any] = {"name": "parents", "endpoint": {"path": "/parents"}}+ if warehouse_parent:+ parent_resource["parent_source"] = "warehouse"+ parent_resource["data_iterator"] = lambda: iter([[{"id": "p1"}, {"id": "p2"}]])++ config: dict[str, Any] = {+ "client": {"base_url": "https://api.example.com"},+ "resources": [+ parent_resource,+ {+ "name": "children",+ "endpoint": {+ "path": "/parents/{parent_id}/children",+ "params": {"parent_id": {"type": "resolve", "resource": "parents", "field": "id"}},+ },+ },+ ],+ }+ pages = {+ "/parents": [{"id": "p1"}, {"id": "p2"}],+ "/parents/p1/children": [{"id": "c1"}],+ "/parents/p2/children": [{"id": "c2"}],+ }++ with (+ patch.object(RESTClient, "paginate", _pages_by_path(pages)),+ patch.object(rest_source, "logger") as logger,+ ):+ resources = rest_source.rest_api_resources(+ cast(RESTAPIConfig, config), team_id=1, job_id="j", db_incremental_field_last_value=None+ )+ children = next(r for r in resources if r.name == "children")+ rows = [row for page in children for row in page]++ assert [row["id"] for row in rows] == ["c1", "c2"]+ logger.info.assert_called_once_with(+ FANOUT_PARENT_ROWS_CONSUMED,+ parent_source=expected_parent_source,+ rows_total=2,+ resumed=False,+ page_rows=2,+ )++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.@@ -551,6 +620,7 @@ def test_warehouse_parent_builds_data_iterator_and_404_ignore(row_filter=row_filter,)assert child_resource["endpoint"]["response_actions"] == [{"status_code": 404, "action": "ignore"}]+ assert parent_resource["parent_source"] == "warehouse"@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")@@ -573,6 +643,7 @@ def test_warehouse_parent_config_stays_on_api_path_when_not_enabled(mock_rest_apparent_resource = config["resources"][0]child_resource = config["resources"][1]assert "data_iterator" not in parent_resource+ assert "parent_source" not in parent_resourceassert parent_resource["endpoint"]["params"]["limit"] == 3assert "response_actions" not in child_resource["endpoint"]@@ -606,6 +677,8 @@ def test_unreadable_parent_table_falls_back_to_the_api_path(mock_rest_api_resourconfig = mock_rest_api_resources.call_args.args[0]parent_resource = config["resources"][0]assert "data_iterator" not in parent_resource+ # Left unset so the telemetry reports the parent this run read, not the one it asked for.+ assert "parent_source" not in parent_resourceassert parent_resource["endpoint"]["params"]["limit"] == 3# The snapshot-only 404 handling goes with it: a fresh API parent doesn't list stale rows.assert "response_actions" not in config["resources"][1]["endpoint"]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 a1d7513388ba..856501d8a959 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@@ -7,6 +7,8 @@ from requests import Sessionfrom posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.common.fanout_telemetry import FanoutParentSource+from .auth import (APIKeyAuth,AuthConfigBase,@@ -348,6 +350,10 @@ class EndpointResourceBase(ResourceBase, total=False):# ``endpoint`` is kept only for dependency-graph bookkeeping. Used to drive a fan-out# child from an already-synced warehouse parent table.data_iterator: Optional[Callable[[], Iterator[list[dict[str, Any]]]]]+ # Which source served this resource's rows, for fan-out telemetry. Set by+ # ``build_dependent_resource`` only after the warehouse table resolves, so it names the parent+ # the run actually read rather than the one its config asked for.+ parent_source: Optional[FanoutParentSource]class EndpointResource(EndpointResourceBase, total=False):diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.pyindex 4fb833ec8b5f..91f947eda87c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py@@ -31,6 +31,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.basWebhookDeletionResult,WebhookSyncResult,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.fanout_telemetry import (+ log_fanout_parent_rows_consumed,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -916,6 +919,7 @@ def get_rows(# method's actual signature so both shapes get the parent id where Stripe expects it.parent_param_is_kwarg = resource.nested_parent_param in inspect.signature(resource.method).parametersskipped_parents = 0+ parents_consumed = 0parents_since_checkpoint = 0# Seeded from where this run started, so an interruption before any parent finishes# checkpoints there rather than back at the first parent.@@ -924,6 +928,22 @@ def get_rows(nested_resume = _trusted_nested_resume(resume_config, warehouse_start, from_warehouse=warehouse_parent is not None)+ sweep_resumed = bool(resume_params) or warehouse_start is not None++ # Counts every parent row the listing handed over, including the ones+ # `parent_has_nested` ruled out, so that the number means the same thing on both+ # parent sources. Reported at every checkpoint and not only after the loop, because+ # the pipeline raises `WorkerShuttingDownError` inside this loop for a resumable+ # source: a line emitted only after the loop would be lost on every deploy that lands+ # mid-sweep, which is when the longest sweeps are running.+ def report_parent_rows_consumed() -> None:+ log_fanout_parent_rows_consumed(+ logger,+ parent_source="warehouse" if warehouse_parent is not None else "api",+ rows_total=parents_consumed,+ resumed=sweep_resumed,+ )+for obj in parent_rows:# Checkpoint the sweep's position through the parent list every so often. The only# other checkpoint fires when a chunk fills, which for a sparse nested resource@@ -937,8 +957,10 @@ def get_rows(yield batcher.get_table()resumable_source_manager.save_state(_resume_state(last_finished_position, last_finished_parent))parents_since_checkpoint = 0+ report_parent_rows_consumed()parent_obj_id = obj[resource.parent_id]+ parents_consumed += 1parents_since_checkpoint += 1nested_resume_params: dict[str, Any] = {}if nested_resume is not None and parent_obj_id == nested_resume.nested_parent_id:@@ -1000,6 +1022,7 @@ def get_rows(# this parent contributes nothing further, so the sweep may resume after it.last_finished_parent = parent_obj_idlast_finished_position = parent_pages.position_after_current if parent_pages else None+ report_parent_rows_consumed()if skipped_parents:logger.debug(f"Stripe: skipped {skipped_parents} {resource.nested_parent_param}(s) with no nested data, saving that many API calls"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.pyindex 83f8811b50bb..32973d9e95e8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py@@ -15,9 +15,13 @@ import pyarrow as paimport deltalakefrom parameterized import parameterizedfrom stripe import ListObject+from structlog.types import FilteringBoundLoggerfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_listfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches+from products.warehouse_sources.backend.temporal.data_imports.sources.common.fanout_telemetry import (+ FANOUT_PARENT_ROWS_CONSUMED,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import (ParentTableRef,)@@ -462,6 +466,7 @@ def _run_nested_get_rows(warehouse_parent=None,parent_method=None,can_resume=False,+ logger: FilteringBoundLogger | None = None,):if parent_objects is None:parent_objects = [{"id": "cus_ok1"}, {"id": "cus_gone"}, {"id": "cus_ok2"}]@@ -494,7 +499,7 @@ def _run_nested_get_rows(account_id=None,db_incremental_field_last_value=None,db_incremental_field_earliest_value=None,- logger=MagicMock(),+ logger=logger or MagicMock(),resumable_source_manager=resumable_source_manager,api_version=STRIPE_API_VERSION_ACACIA,warehouse_parent=warehouse_parent,@@ -587,16 +592,21 @@ class TestStripeNestedResourceGetRows:return _list_object([])manager = MagicMock()+ logger = MagicMock()with patch.object(stripe_module, "NESTED_SWEEP_CHECKPOINT_PARENTS", 3):rows = _run_nested_get_rows(nested_method,parent_objects=[{"id": f"cus_{i}"} for i in range(8)],resumable_source_manager=manager,+ logger=logger,)assert rows == []# Checkpointed after the 3rd and 6th parent; the 7th and 8th are still in flight.assert [call.args[0].starting_after for call in manager.save_state.call_args_list] == ["cus_2", "cus_5"]+ # The pipeline kills this loop mid-sweep on a worker shutdown, so every checkpoint carries+ # the running fan-out size instead of leaving the attempt's only line until after the loop.+ assert [call.kwargs["rows_total"] for call in logger.info.call_args_list] == [3, 6, 8]def test_query_param_service_receives_parent_in_params(self):# Flat Stripe services with a required filter (e.g. entitlements.active_entitlements.list)@@ -1561,6 +1571,41 @@ class TestStripeWarehouseParentFanout:assert warehouse_rows == api_rowsassert [row["customer"] for row in warehouse_rows] == ["cus_1", "cus_2"]+ def test_both_parent_paths_report_the_fan_out_size_and_where_it_came_from(self, tmp_path):+ # A webhook-maintained parent holds only what its drains delivered, so it can be missing+ # customers the API listing still returns. Comparing the fan-out size across the two parent+ # sources for one schema is the only signal for that, and it needs both a count and the+ # label naming which source produced it. `cus_zero` is ruled out by the skip predicate and+ # still counts, because the number has to mean the same thing on both sources.+ customers = [{"id": "cus_zero", "balance": 0}, {"id": "cus_credit", "balance": -500}]+ uri = _write_customer_parent_table(tmp_path, customers)+ api_logger = MagicMock()+ warehouse_logger = MagicMock()++ api_method, api_probed = _recording_nested_method()+ warehouse_method, warehouse_probed = _recording_nested_method()++ _run_nested_get_rows(+ api_method,+ parent_objects=customers,+ parent_has_nested=stripe_module._customer_might_have_balance_transactions,+ logger=api_logger,+ )+ _run_nested_get_rows(+ warehouse_method,+ parent_has_nested=stripe_module._customer_might_have_balance_transactions,+ warehouse_parent=ParentTableRef(uri=uri, version=deltalake.DeltaTable(uri).version()),+ logger=warehouse_logger,+ )++ assert api_probed == warehouse_probed == ["cus_credit"]+ api_logger.info.assert_called_once_with(+ FANOUT_PARENT_ROWS_CONSUMED, parent_source="api", rows_total=2, resumed=False+ )+ warehouse_logger.info.assert_called_once_with(+ FANOUT_PARENT_ROWS_CONSUMED, parent_source="warehouse", rows_total=2, resumed=False+ )+def test_the_skip_predicate_reads_the_balance_off_the_warehouse_row(self, tmp_path):# The projected `balance` column is what makes this conversion worth doing: without it# every customer would be probed, turning a listing-dominated run into one call each.@@ -1671,14 +1716,19 @@ class TestStripeWarehouseParentFanout:)nested_method, _ = _recording_nested_method()+ logger = MagicMock()rows = _run_nested_get_rows(nested_method,resumable_source_manager=manager,warehouse_parent=ParentTableRef(uri=uri, version=version),can_resume=True,+ logger=logger,)assert [row["id"] for row in rows] == ["cbt_cus_2", "cbt_cus_3"]+ # A resumed attempt counts only the parents it walked, so its fan-out size is partial. The+ # line has to say so, or it reads as a warehouse parent that is missing rows.+ assert logger.info.call_args.kwargs["resumed"] is True@parameterized.expand([