: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): make stripe backfill resilient to heartbeat timeouts (#67648)
estefaniaf76b703fbd13
diff --git a/posthog/temporal/common/shutdown.py b/posthog/temporal/common/shutdown.pyindex f7b27cad3a7f..8b22636ea8f6 100644--- a/posthog/temporal/common/shutdown.py+++ b/posthog/temporal/common/shutdown.py@@ -189,5 +189,3 @@ class ShutdownMonitor:if self.is_worker_shutdown():self.logger.debug("Worker is shutting down.")raise WorkerShuttingDownError.from_activity_context()-- self.logger.debug("Worker is not shutting down.")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 d9e3f22e3098..c7887ae28448 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@@ -65,6 +65,9 @@ DEFAULT_LIMIT = 100# genuinely transient cuts.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+_JSON_WHITESPACE = frozenset(b" \t\n\r\f\v")_OPEN_BRACE = ord("{")_CLOSE_BRACE = ord("}")@@ -266,6 +269,27 @@ class StripeResumeConfig:starting_after: str+def _batch_and_yield(+ objects: Any,+ batcher: Batcher,+ incremental_field_name: Optional[str] = None,+ stop_at_or_before: Optional[int] = None,+):+ """Batch raw Stripe objects into pa.Tables and yield them, stopping early once we reach an object+ we already have (`stop_at_or_before`). Yielding in small batches lets the pipeline write and+ persist the incremental watermark frequently, so progress survives a heartbeat timeout or redeploy."""+ for obj in objects:+ if stop_at_or_before is not None and incremental_field_name is not None:+ if obj[incremental_field_name] <= stop_at_or_before:+ break+ batcher.batch(obj)+ while batcher.should_yield():+ yield batcher.get_table()++ while batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()++def _build_resources(client: StripeClient, logger: Optional[FilteringBoundLogger] = None) -> dict[str, Union[StripeResource, StripeNestedResource]]:@@ -352,7 +376,7 @@ def get_rows(default_params = {"limit": DEFAULT_LIMIT}resources = _build_resources(client, logger=logger)- batcher = Batcher(logger=logger)+ batcher = Batcher(logger=logger, chunk_size=STRIPE_CHUNK_SIZE)if endpoint in WEBHOOK_ONLY_ENDPOINTS:# Webhook-only resources (e.g. Discount) have no Stripe list endpoint — Discount@@ -474,7 +498,7 @@ def get_rows(f"created[lt]": db_incremental_field_earliest_value,},)- yield from stripe_objects.auto_paging_iter()+ yield from _batch_and_yield(stripe_objects.auto_paging_iter(), batcher)# check for any objects more than the maximum object we already haveif db_incremental_field_last_value is not None:@@ -488,12 +512,12 @@ def get_rows(f"created[gt]": db_incremental_field_last_value,},)- last_value_cursor = _coerce_incremental_cursor(db_incremental_field_last_value)- for obj in stripe_objects.auto_paging_iter():- if last_value_cursor is not None and obj[incremental_field_name] <= last_value_cursor:- break-- yield obj+ yield from _batch_and_yield(+ stripe_objects.auto_paging_iter(),+ batcher,+ incremental_field_name=incremental_field_name,+ stop_at_or_before=_coerce_incremental_cursor(db_incremental_field_last_value),+ )def _webhook_table_transformer(table: pa.Table) -> pa.Table: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 368f6f5d73f9..383b934f39ed 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@@ -93,7 +93,7 @@ class TestStripeGetRowsIncrementalCursor:"products.warehouse_sources.backend.temporal.data_imports.sources.stripe.stripe._build_resources",return_value={"charge": resource},):- rows = list(+ tables = list(get_rows(api_key="sk_test_123",endpoint="charge",@@ -106,7 +106,39 @@ class TestStripeGetRowsIncrementalCursor:))- assert [obj["id"] for obj in rows] == ["ch_2"]+ rows = [row for table in tables for row in table.to_pylist()]+ assert [row["id"] for row in rows] == ["ch_2"]++ def test_backfill_branch_yields_all_earlier_objects_in_bounded_chunks(self):+ # The created[lt] backfill must yield every earlier object AND batch them into bounded chunks:+ # each yielded chunk is what makes the pipeline persist the `earliest` watermark, so a large+ # backfill checkpoints progress mid-attempt instead of restarting the whole scan on a+ # heartbeat timeout. A single giant batch (the previous behaviour) never checkpoints.+ objects = [{"id": f"ch_{i}", "created": 1700000000 - i} for i in range(5)]+ resource = StripeResource(method=lambda params: cast(ListObject[Any], _FakeStripeList(objects)))+ resumable_source_manager = mock.MagicMock()+ resumable_source_manager.can_resume.return_value = False++ with (+ mock.patch.object(stripe_module, "STRIPE_CHUNK_SIZE", 2),+ mock.patch.object(stripe_module, "_build_resources", return_value={"charge": resource}),+ ):+ tables = list(+ get_rows(+ api_key="sk_test_123",+ endpoint="charge",+ account_id=None,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=1700000100,+ logger=mock.MagicMock(),+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=True,+ )+ )++ rows = [row for table in tables for row in table.to_pylist()]+ assert [row["id"] for row in rows] == [f"ch_{i}" for i in range(5)]+ assert len(tables) > 1class TestStripeSource:@@ -361,12 +393,11 @@ class TestStripeBatcherDrainsSplitChunks:resumable_source_manager.can_resume.return_value = False# Tiny caps force every 2-row buffer flush to split into single-row chunks.- splitting_batcher = functools.partial(- stripe_module.Batcher, chunk_size=2, max_table_bytes=1, max_column_offset_bytes=1- )+ splitting_batcher = functools.partial(stripe_module.Batcher, max_table_bytes=1, max_column_offset_bytes=1)with (patch.object(stripe_module, "StripeClient"),+ patch.object(stripe_module, "STRIPE_CHUNK_SIZE", 2),patch.object(stripe_module, "Batcher", splitting_batcher),patch.object(stripe_module, "_build_resources", return_value={"charge": resource}),):@@ -390,11 +421,12 @@ class TestStripeBatcherDrainsSplitChunks:def nested_method(customer=None, params=None):return _list_object(nested_objects)- splitting_batcher = functools.partial(- stripe_module.Batcher, chunk_size=2, max_table_bytes=1, max_column_offset_bytes=1- )+ splitting_batcher = functools.partial(stripe_module.Batcher, max_table_bytes=1, max_column_offset_bytes=1)- with patch.object(stripe_module, "Batcher", splitting_batcher):+ with (+ patch.object(stripe_module, "STRIPE_CHUNK_SIZE", 2),+ patch.object(stripe_module, "Batcher", splitting_batcher),+ ):rows = _run_nested_get_rows(nested_method, parent_objects=[{"id": "cus_1"}])assert [row["id"] for row in rows] == [f"cbt_{i}" for i in range(6)]@@ -409,12 +441,11 @@ class TestStripeBatcherDrainsSplitChunks:resumable_source_manager = MagicMock()resumable_source_manager.can_resume.return_value = False- splitting_batcher = functools.partial(- stripe_module.Batcher, chunk_size=100, max_table_bytes=1, max_column_offset_bytes=1- )+ splitting_batcher = functools.partial(stripe_module.Batcher, max_table_bytes=1, max_column_offset_bytes=1)with (patch.object(stripe_module, "StripeClient"),+ patch.object(stripe_module, "STRIPE_CHUNK_SIZE", 100),patch.object(stripe_module, "Batcher", splitting_batcher),patch.object(stripe_module, "_build_resources", return_value={"charge": resource}),):