: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): unblock tables that never finish a first sync (#82517)
Tom Owers0441919bf655
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.pyindex a33b18f31762..5723a46877c1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.py@@ -68,6 +68,7 @@ class Batcher:_table_buffer_rows: int_table_buffer_bytes: int_table_buffer_schema: Optional[pa.Schema]+ _ready_bytes: int_coalesce_tables: bool_ready: deque[pa.Table]_logger: FilteringBoundLogger@@ -117,6 +118,7 @@ class Batcher:self._table_buffer_bytes = 0self._table_buffer_schema = Noneself._ready = deque()+ self._ready_bytes = 0def _set_ready(self, table: pa.Table) -> None:"""Split `table` so no yielded chunk overflows a 32-bit offset column or exceeds@@ -130,6 +132,8 @@ class Batcher:# would be misreported as a merge death, biasing the exact distribution this signal exists# to measure.report_phase("extract")+ # Held until `get_table` drains every chunk, so it stays part of what this activity occupies.+ self._ready_bytes = payload_bytesreport_buffer_bytes(payload_bytes)if self._source_type is not None:# The materialised table is the true in-memory peak (an unbounded source yields one giant@@ -247,6 +251,16 @@ class Batcher:return sys.getsizeof(obj)def batch(self, item: list[Any] | dict | pa.Table) -> None:+ self._batch(item)+ # Report after every item, not only when a chunk completes. `_set_ready` fires once a chunk+ # is materialised, so an activity accumulating toward one reported whatever the *previous*+ # chunk measured — a long accumulation looked like it held nothing, and a death inside it+ # was attributed to a co-tenant. The phase is re-declared for the same reason `_set_ready`+ # does it: without it a death mid-accumulation reads as a merge death.+ report_phase("extract")+ report_buffer_bytes(self._ready_bytes + self._table_buffer_bytes + self._buffer_size_bytes)++ def _batch(self, item: list[Any] | dict | pa.Table) -> None:if self._ready:raise Exception("Batcher already has a table ready to yield. Call get_table() before batching more items.")@@ -321,6 +335,9 @@ class Batcher:self._flush_table_buffer()if self._ready:- return self._ready.popleft()+ chunk = self._ready.popleft()+ if not self._ready:+ self._ready_bytes = 0+ return chunkraise Exception("No chunks available to yield")diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/table_stats.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/table_stats.pyindex 0542b621825c..9da4e4de5fc5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/table_stats.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/table_stats.py@@ -13,7 +13,7 @@ over-count there."""import os-from typing import Any, Optional+from typing import Any, Optional, castimport pyarrow as paimport pyarrow.compute as pc@@ -39,6 +39,21 @@ def _pod_name() -> Optional[str]:return os.environ.get("HOSTNAME")+def _is_list_like(col_type: pa.DataType) -> bool:+ """True for any type whose payload lives in a child values array reachable via `list_flatten`."""+ return (+ pa.types.is_list(col_type)+ or pa.types.is_large_list(col_type)+ or pa.types.is_fixed_size_list(col_type)+ or pa.types.is_map(col_type)+ )+++def _list_offset_width(col_type: pa.DataType) -> int:+ """Bytes per offset entry: large lists carry 64-bit offsets, everything else 32-bit."""+ return 8 if pa.types.is_large_list(col_type) else 4++def _column_payload_bytes(col: pa.ChunkedArray) -> int:"""Slice-accurate in-memory payload bytes: value bytes + offset buffer (string/binary/list)or col_length * byte_width (fixed-width); nested/other types return 0. Avoids `.nbytes` (wrong for slices)."""@@ -50,9 +65,23 @@ def _column_payload_bytes(col: pa.ChunkedArray) -> int:if pa.types.is_large_string(col_type) or pa.types.is_large_binary(col_type):payload = int(pc.sum(pc.binary_length(col)).as_py() or 0)return payload + col_length * 8- if pa.types.is_list(col_type):- elements = int(pc.sum(pc.list_value_length(col)).as_py() or 0)- return elements + col_length * 4+ if _is_list_like(col_type):+ # Recurse into the child values. `list_value_length` counts elements, not their size, so a+ # `list<string>` of JSON blobs measured a few bytes per row instead of kilobytes — sources+ # that map repeated fields to lists (Google Ads serializes repeated protobuf messages to+ # JSON strings) undercounted by orders of magnitude, which silently defeats the byte-based+ # chunk flush in `Batcher` and the recursive split in `_split_table`.+ offsets = 0 if pa.types.is_fixed_size_list(col_type) else col_length * _list_offset_width(col_type)+ try:+ # `list_flatten` has no map kernel, so a map is viewed as its equivalent list of+ # key/value structs first — a zero-copy cast, since that is the layout already.+ if pa.types.is_map(col_type):+ col = col.cast(pa.list_(pa.struct([("key", col_type.key_type), ("value", col_type.item_type)])))+ # `list_flatten` preserves chunking, so a column in yields a column out; the stubs+ # describe the bare-`Array` overload only.+ return _column_payload_bytes(cast(pa.ChunkedArray, pc.list_flatten(col))) + offsets+ except Exception:+ return offsetsif pa.types.is_struct(col_type):# Recurse into child fields so a nested struct (e.g. a Mongo document under `data`) is counted# instead of undercounting to 0. A flatten failure degrades to 0 rather than breaking accounting.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_batcher.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_batcher.pyindex 8d184e77f932..9f8cb11a63b6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_batcher.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_batcher.py@@ -204,8 +204,24 @@ def test_batcher_splits_buffered_list_items():# value bytes + 64-bit offset buffer (n * 8): 4 + 16 = 20("large_string_counted", pa.array(["aa", "bb"], type=pa.large_string()), 20),("large_binary_counted", pa.array([b"aa", b"bb"], type=pa.large_binary()), 20),- # child element count + 32-bit offset buffer (n * 4): 3 + 8 = 11- ("list", pa.array([[1, 2], [3]], type=pa.list_(pa.int64())), 11),+ # Lists recurse into their child values + 32-bit offset buffer (n * 4). Counting the child+ # *element count* instead (the old behaviour) undercounts a list of blobs by orders of+ # magnitude, which silently disables the byte-driven split for every source that maps a+ # repeated field to a list (e.g. Google Ads repeated protobuf messages -> JSON strings).+ # child 3 * int64 = 24; offsets 2 * 4 = 8+ ("list_of_int64", pa.array([[1, 2], [3]], type=pa.list_(pa.int64())), 32),+ # child strings 4+2+1 value bytes + 3 * 4 offsets = 19; list offsets 2 * 4 = 8+ ("list_of_string_counts_child_bytes", pa.array([["aaaa", "bb"], ["c"]], type=pa.list_(pa.string())), 27),+ # child "aa" = 2 + 1 * 4 = 6; large-list offsets 1 * 8 = 8+ ("large_list_uses_64_bit_offsets", pa.array([["aa"]], type=pa.large_list(pa.string())), 14),+ # child 4 * int64 = 32; fixed-size lists carry no offset buffer+ ("fixed_size_list_has_no_offsets", pa.array([[1, 2], [3, 4]], type=pa.list_(pa.int64(), 2)), 32),+ # struct child: "k" = 1 + 4 = 5, "vv" = 2 + 4 = 6; list offsets 1 * 4 = 4+ ("map_counted_via_key_value_struct", pa.array([[("k", "vv")]], type=pa.map_(pa.string(), pa.string())), 15),+ # struct child "aa" = 2 + 1 * 4 = 6; list offsets 1 * 4 = 4+ ("list_of_struct", pa.array([[{"s": "aa"}]], type=pa.list_(pa.struct([("s", pa.string())]))), 10),+ # No child values to measure, but the offset buffer is still resident+ ("all_null_list_counts_offsets_only", pa.array([None, None], type=pa.list_(pa.string())), 8),("int64", pa.array([1, 2, 3], type=pa.int64()), 24),("bool_subbyte_is_zero", pa.array([True, False, True], type=pa.bool_()), 0),("nulls_counted_as_zero_payload", pa.array([None, "abc"], type=pa.string()), 3 + 8),@@ -258,6 +274,22 @@ def test_split_table_byte_cap_sums_across_columns():assert pa.concat_tables(result).equals(table)+def test_split_table_splits_a_list_column_on_its_child_bytes():+ # The shape that used to slip through: four rows holding ~4 KiB of strings inside a list column.+ # Measured by child element count the table scored 12 bytes and never split, so a chunk of these+ # grew to the row limit regardless of its real size and became the loader's merge memory.+ table = pa.table(+ {"val": pa.array([["x" * 1000], ["y" * 1000], ["z" * 1000], ["w" * 1000]], type=pa.list_(pa.string()))}+ )++ result = _split_table(table, offset_limit=1_000_000, bytes_limit=2048)++ assert len(result) > 1+ for slice_table in result:+ assert table_payload_bytes(slice_table) <= 2048 or slice_table.num_rows <= 1+ assert pa.concat_tables(result).equals(table)++def test_split_table_single_oversized_row_terminates():table = pa.table({"val": ["a-very-long-value"]})diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_table_stats.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_table_stats.pyindex 851911d8245b..ea0337a3cd90 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_table_stats.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_table_stats.py@@ -15,7 +15,9 @@ _MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.co_STATS = f"{_MODULE}.record_table_stats"_CAPTURE = f"{_MODULE}.posthoganalytics.capture"_POD = f"{_MODULE}._pod_name"-_BATCHER_STATS = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher.record_table_stats"+_BATCHER_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher"+_BATCHER_STATS = f"{_BATCHER_MODULE}.record_table_stats"+_BATCHER_BUFFER_REPORT = f"{_BATCHER_MODULE}.report_buffer_bytes"class TestRecordTableStats:@@ -121,6 +123,20 @@ class TestBatcherStatsEmission:assert kwargs["num_rows"] == 3assert kwargs["payload_bytes"] is not None+ def test_buffer_report_grows_while_accumulating_toward_a_chunk(self):+ # The self-report only fired when a chunk was materialised, so an activity buffering toward+ # one reported whatever the previous chunk measured — extract-phase deaths came back with+ # "held ~0 bytes" and got blamed on a co-tenant. Every batched item must move the number.+ with mock.patch(_BATCHER_BUFFER_REPORT) as reported:+ batcher = Batcher(logger=mock.MagicMock(), chunk_size=1_000_000, chunk_size_bytes=1024 * 1024 * 1024)+ for _ in range(3):+ batcher.batch({"val": "x" * 500})++ sizes = [call.args[0] for call in reported.call_args_list]+ assert len(sizes) == 3+ assert sizes == sorted(sizes)+ assert sizes[0] < sizes[-1]+def test_silent_when_source_type_absent(self):# Source-internal batchers leave source_type None; their output is measured when it reaches# the pipeline's own batcher, so this must not double-count.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.pyindex 70c1c28568fe..350e74339c2f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py@@ -73,6 +73,14 @@ GOOGLE_ADS_HOST = "googleads.googleapis.com"GOOGLE_ADS_INCREMENTAL_WINDOW_DAYS = 7GOOGLE_ADS_MAX_DATA_WINDOWS_PER_RUN = 5+# How far back a *first* sync starts its windowed drain. A first sync has no cursor to start from,+# and the drain cannot begin at the 1970 incremental sentinel: empty windows are cheap but not free+# (one request each), so stepping from 1970 would spend the whole run on requests that return+# nothing. This bound only decides where the walk begins — every window from here forward is+# imported, and once the cursor exists the drain continues from it. It is not an API limit: Google+# serves older rows than this, so raising it costs first-sync catch-up time rather than correctness.+GOOGLE_ADS_INITIAL_BACKFILL_DAYS = 2 * 365+# The Google Ads SDK hardcodes `grpc.max_receive_message_length` to 64 MiB. A single# `GoogleAdsService.Search` page can carry up to 10,000 rows, and wide resources routinely# serialize past 64 MiB — when that happens the gRPC client aborts the call with a@@ -558,15 +566,18 @@ def google_ads_source(if incremental_field is None or incremental_field_type is None:raise ValueError("incremental_field and incremental_field_type can't be None")- # Bounded windowed drain: only date-partitioned report tables (`requires_filter`) with an- # established cursor. A first sync (sentinel value) keeps the open-ended scan below so it- # doesn't crawl a window at a time from the 1970 initial value.- if (- table.requires_filter- and incremental_field_type == IncrementalFieldType.Date- and db_incremental_field_last_value is not None- ):- start = _incremental_value_as_date(db_incremental_field_last_value)+ # Bounded windowed drain for date-partitioned report tables (`requires_filter`), including+ # the first sync. Excluding first syncs is what stranded them: with no cursor they ran a+ # single open-ended 1970..2100 scan over the whole account history, and a run that never+ # finishes never lands a chunk, so the cursor stays empty and the next run repeats the same+ # unbounded scan — the very death spiral the windows exist to break, except nothing could+ # escape it. A first sync instead starts a bounded backfill window behind today.+ if table.requires_filter and incremental_field_type == IncrementalFieldType.Date:+ start = (+ _incremental_value_as_date(db_incremental_field_last_value)+ if db_incremental_field_last_value is not None+ else dt.date.today() - dt.timedelta(days=GOOGLE_ADS_INITIAL_BACKFILL_DAYS)+ )# Exclusive upper bound of today+1 keeps today in range, matching the open-ended scan.end = dt.date.today() + dt.timedelta(days=1)windows_with_data = 0@@ -595,7 +606,8 @@ def google_ads_source(resumable_source_manager.clear_state()return- # First-ever sync (initial sentinel) or a non-date cursor: single open-ended ascending scan.+ # Not a date-partitioned report table, or a non-date cursor: single open-ended ascending+ # scan. These have no date windows to walk, so there is nothing to bound them by.if db_incremental_field_last_value is None:last_value: int | dt.datetime | dt.date | str = incremental_type_to_initial_value(incremental_field_type)else:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.pyindex 42d03d561a35..fafd2254bc41 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py@@ -1484,9 +1484,12 @@ class TestGoogleAdsQueryConstruction:assert all("2100-01-01" not in q for q in queries)assert response.sort_mode == "asc"- def test_first_sync_uses_open_ended_scan_not_windows(self):- # A first sync carries the 1970 sentinel cursor; windowing it would crawl 7 days at a time- # from 1970 and never catch up, so first syncs must stay a single open-ended ascending scan.+ def test_first_sync_drains_in_windows_from_a_bounded_backfill_start(self):+ # A first sync has no cursor. Running it as the open-ended `1970 .. 2100` scan meant one run+ # had to extract the whole account history before anything landed durably; it never+ # finished, so the cursor never advanced and the next run repeated the same scan — report+ # tables that had never synced could never start. It must window like any other run,+ # beginning a bounded backfill behind today.with freeze_time("2026-07-17"):_response, queries = self._run_source(self._stats_table(),@@ -1496,11 +1499,13 @@ class TestGoogleAdsQueryConstruction:incremental_field_type=IncrementalFieldType.Date,)- assert queries == [+ assert queries[0] == ("SELECT campaign.id,segments.date FROM campaign_stats "- "WHERE segments.date >= '1970-01-01' AND segments.date < '2100-01-01' "+ "WHERE segments.date >= '2024-07-17' AND segments.date < '2024-07-24' ""ORDER BY segments.date ASC"- ]+ )+ assert all("2100-01-01" not in q for q in queries)+ assert all("1970-01-01" not in q for q in queries)def test_run_stops_after_max_data_windows(self):# Every window has data; the run must stop after GOOGLE_ADS_MAX_DATA_WINDOWS_PER_RUNdiff --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 5995f76738e2..5c75a9636c98 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@@ -108,6 +108,14 @@ SUBSCRIPTION_PAGE_LIMIT = 20# Small write batch so each chunk (and its durable `earliest` watermark) commits well inside the heartbeat window, letting a large backfill make progress every attempt.STRIPE_CHUNK_SIZE = 1000+# How many parents a nested sweep may walk before it records its position, independent of whether+# any rows were produced. `STRIPE_CHUNK_SIZE` already checkpoints a sweep that is finding data, but+# it measures rows, not parents: a sparse nested resource (CustomerPaymentMethod over a customer+# base where few have a stored payment method) spends one API call per parent and produces almost+# nothing, so thousands of parents can pass between chunks — and every pod death throws that walk+# away. Counting parents bounds the work a restart repeats no matter how sparse the data is.+NESTED_SWEEP_CHECKPOINT_PARENTS = 5000+_JSON_WHITESPACE = frozenset(b" \t\n\r\f\v")_OPEN_BRACE = ord("{")_CLOSE_BRACE = ord("}")@@ -708,12 +716,29 @@ 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_since_checkpoint = 0+ last_finished_parent: Optional[str] = Nonefor obj in stripe_parent_objects.auto_paging_iter():+ # 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+ # (most customers have no payment methods) can take the entire customer base — so a+ # sweep could walk hundreds of thousands of parents, one API call each, without ever+ # recording progress, and a pod death restarted it from the first parent forever.+ # Flushing first is what makes the position safe to save: every row up to+ # `last_finished_parent` has been yielded by the time `starting_after` names it.+ if parents_since_checkpoint >= NESTED_SWEEP_CHECKPOINT_PARENTS and last_finished_parent is not None:+ while batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+ resumable_source_manager.save_state(StripeResumeConfig(starting_after=last_finished_parent))+ parents_since_checkpoint = 0+parent_obj_id = obj[resource.parent_id]+ parents_since_checkpoint += 1# Skip parents that a cheap signal on the parent object rules out — avoids one empty# nested call per parent (the bulk of Stripe API volume for these resources).if resource.parent_has_nested is not None and not resource.parent_has_nested(obj):skipped_parents += 1+ last_finished_parent = parent_obj_idcontinueparent_params = resource.nested_params_from_parent(obj) if resource.nested_params_from_parent else {}nested_params = {**default_params, **resource.params, **parent_params}@@ -753,6 +778,9 @@ def get_rows(if not _is_stripe_resource_missing_error(e):raiselogger.debug(f"Stripe: skipping {resource.nested_parent_param}={parent_obj_id}, no longer exists")+ # Reached whether the nested call succeeded or the parent had vanished: either way+ # this parent contributes nothing further, so the sweep may resume after it.+ last_finished_parent = parent_obj_idif 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 2d0f4eff53ab..d51710a15eba 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@@ -413,7 +413,7 @@ class TestStripeSource:assert client._last_request_method == "get"-def _run_nested_get_rows(nested_method, parent_objects=None, parent_has_nested=None):+def _run_nested_get_rows(nested_method, parent_objects=None, parent_has_nested=None, resumable_source_manager=None):if parent_objects is None:parent_objects = [{"id": "cus_ok1"}, {"id": "cus_gone"}, {"id": "cus_ok2"}]parent = StripeResource(method=lambda **kwargs: _list_object(parent_objects))@@ -426,7 +426,8 @@ def _run_nested_get_rows(nested_method, parent_objects=None, parent_has_nested=Nparent_has_nested=parent_has_nested,)- resumable_source_manager = MagicMock()+ if resumable_source_manager is None:+ resumable_source_manager = MagicMock()resumable_source_manager.can_resume.return_value = Falsewith (@@ -527,6 +528,26 @@ class TestStripeNestedResourceGetRows:assert called_for == ["cus_credit", "cus_owed"]assert {row["customer"] for row in rows} == {"cus_credit", "cus_owed"}+ def test_sparse_sweep_checkpoints_by_parent_count(self):+ # A nested resource where no parent has data (CustomerPaymentMethod over customers with no+ # stored payment method) never fills a chunk, so the row-driven checkpoint never fires and+ # a killed run restarted the whole customer walk. Position must be recorded by parents+ # walked, regardless of how few rows come back.+ def nested_method(customer=None, params=None):+ return _list_object([])++ manager = 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,+ )++ 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"]+def test_query_param_service_receives_parent_in_params(self):# Flat Stripe services with a required filter (e.g. entitlements.active_entitlements.list)# expose the parent only inside `params`, not as a method keyword — passing it as a kwarg