: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): skip cdc extraction tick while previous batches load (#70226)
estefania4c4346959604
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.pyindex 38a30c8156dd..7c34a55e9352 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py@@ -104,6 +104,12 @@ CDC_ORPHAN_JOB_MIN_AGE = dt.timedelta(minutes=30)# tell an abandoned run from one whose batches simply aged out.CDC_ORPHAN_JOB_MAX_AGE = dt.timedelta(days=14)+# Backpressure guard: past this age a skipped tick is a stuck load, not a slow one — well beyond+# the loader's recovery-sweep grace (300s) and retry backoffs, so it only trips when a run needs+# operator attention. Skips past it log at error level; the tick is still skipped (see+# _previous_load_still_pending for why we never auto-fail the pending run).+CDC_BACKPRESSURE_STUCK_AGE = dt.timedelta(hours=2)+# Per-peek bound on WAL changes. A large backlog is drained over several passes (and, if needed,# several scheduled runs) instead of one unbounded read that risks the 2h activity timeout and# re-decodes from the slot start on every retry. The slot advances after each pass, so the next@@ -691,6 +697,9 @@ class CDCExtractActivity:if not self._setup():return+ if self._previous_load_still_pending():+ return+self._mark_schemas_running()# Best-effort — must never break the extraction run, so guard the call# site: the method itself has unguarded lines (activity.info(),@@ -778,6 +787,52 @@ class CDCExtractActivity:except Exception:self.log.exception("failed_to_delete_own_schedule")+ def _previous_load_still_pending(self) -> bool:+ """Backpressure guard: skip this tick while a previous run's batches are still loading.++ CDC ticks don't hold the per-schema pipeline lock the way external-data-job runs do,+ so without this check every tick enqueues a fresh run regardless of whether the+ previous one landed. Coexisting runs of one schema can then be claimed out of order+ by the loader (its head-of-line gate is run-scoped), and an incremental merge applied+ out of order silently overwrites newer rows with older ones. Skipping keeps at most+ one active run per schema; nothing has been peeked and the slot is untouched, so WAL+ accumulates and the next tick catches up.++ Per-source, not per-schema: the slot is read once for all tables, so one table's+ pending load must hold back the whole source's tick.++ Deliberately no auto-remediation past CDC_BACKPRESSURE_STUCK_AGE: the slot already+ advanced past the pending runs' events, so failing their batches would leave a+ permanent gap in the table. The queue-freshness alert fires well before the+ threshold, and if nobody intervenes the engine eventually invalidates the slot,+ which triggers the existing full re-sync recovery. Fail-open on probe errors — the+ producer writes to the same DB, so a run that can't be probed can't enqueue either.+ """+ schema_ids = [str(s.id) for s in self.cdc_schemas]+ try:+ conn = psycopg.Connection.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True)+ except Exception:+ self.log.warning("cdc_backpressure_probe_connect_failed", exc_info=True)+ return False+ try:+ age = BatchQueue.get_oldest_non_terminal_batch_age_seconds(+ conn, team_id=self.inputs.team_id, schema_ids=schema_ids+ )+ except Exception:+ self.log.warning("cdc_backpressure_probe_failed", exc_info=True)+ return False+ finally:+ conn.close()++ if age is None:+ return False++ stuck = age >= CDC_BACKPRESSURE_STUCK_AGE.total_seconds()+ log = self.log.error if stuck else self.log.info+ log("cdc_tick_skipped_pending_load", oldest_pending_age_seconds=round(age, 1), stuck=stuck)+ metrics.get_tick_skipped_metric(self.inputs.team_id, str(self.inputs.source_id), stuck).add(1)+ return True+def _mark_schemas_running(self) -> None:"""Mark CDC schemas as Running at the start."""for schema in self.cdc_schemas:diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/metrics.pyindex 543e8fdd02cd..e66bac021b73 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/metrics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/metrics.py@@ -51,6 +51,17 @@ def get_extraction_duration_metric(team_id: int, source_id: str, status: str) ->)+def get_tick_skipped_metric(team_id: int, source_id: str, stuck: bool) -> MetricCounter:+ return (+ _meter()+ .with_additional_attributes({"team_id": str(team_id), "source_id": source_id, "stuck": str(stuck).lower()})+ .create_counter(+ "cdc_ticks_skipped_pending_load_total",+ "Total extraction ticks skipped because a previous run's batches are still loading",+ )+ )++def get_slot_advance_metric(team_id: int, source_id: str) -> MetricCounter:return _source_meter(team_id, source_id).create_counter("cdc_slot_advance_total", "Total replication slot advances")diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.pyindex 0d75ead95699..486646c1b949 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.models.external_data_job import Externalfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.temporal.data_imports.cdc.activities import (+ CDC_BACKPRESSURE_STUCK_AGE,CDC_MAX_CHANGES_PER_READ,CDC_ORPHAN_JOB_MIN_AGE,CDC_ORPHANED_JOB_MESSAGE,@@ -25,6 +26,9 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.activities imp)from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import CDCErrorCategory, cdc_error_infofrom products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (+ BatchQueue,+)from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter import PostgresCDCAdapterfrom products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableException@@ -312,6 +316,57 @@ def _make_extract_activity(source, log=None) -> CDCExtractActivity:return activity_obj+class TestBackpressureGuard:+ def _activity(self) -> CDCExtractActivity:+ source = _make_source()+ act = _make_extract_activity(source)+ act.cdc_schemas = [_make_schema("users", source=source)]+ return act++ @pytest.mark.parametrize(+ "age_seconds,expect_skip,expect_stuck",+ [+ (None, False, None),+ (30.0, True, False),+ (CDC_BACKPRESSURE_STUCK_AGE.total_seconds() + 1, True, True),+ ],+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.metrics.get_tick_skipped_metric")+ @patch("psycopg.Connection.connect")+ def test_skips_only_while_previous_batches_pend(+ self, mock_connect, mock_metric, age_seconds, expect_skip, expect_stuck+ ):+ act = self._activity()++ with patch.object(BatchQueue, "get_oldest_non_terminal_batch_age_seconds", return_value=age_seconds):+ assert act._previous_load_still_pending() is expect_skip++ if expect_skip:+ mock_metric.assert_called_once_with(act.inputs.team_id, str(act.inputs.source_id), expect_stuck)+ else:+ mock_metric.assert_not_called()++ def test_fails_open_when_queue_db_unreachable(self):+ act = self._activity()++ with patch("psycopg.Connection.connect", side_effect=Exception("queue db down")):+ assert act._previous_load_still_pending() is False++ @patch("psycopg.Connection.connect")+ def test_run_skips_tick_without_touching_schemas_or_reader(self, mock_connect):+ act = self._activity()++ with (+ patch.object(act, "_setup", return_value=True),+ patch.object(act, "_mark_schemas_running") as mark_running,+ patch.object(BatchQueue, "get_oldest_non_terminal_batch_age_seconds", return_value=42.0),+ ):+ act.run()++ mark_running.assert_not_called()+ assert act.reader is None++class TestFlushDeferredRuns:@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")def test_sends_kafka_messages_for_deferred_runs(self, MockProducer):diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.pyindex 63287c093bab..259cc8c0ba6b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py@@ -144,7 +144,9 @@ class DeltaBatchConsumerAdapter:Each step is isolated so a failure can't crash the consumer."""try:- await BatchQueue.fail_run(conn, run_uuid=batch.run_uuid, reason=reason)+ await BatchQueue.fail_run(+ conn, run_uuid=batch.run_uuid, team_id=batch.team_id, schema_id=batch.schema_id, reason=reason+ )except Exception as e:logger.exception("fail_run_queue_update_failed", batch_id=batch.id, run_uuid=batch.run_uuid)capture_exception(e)@@ -237,6 +239,32 @@ class DeltaBatchConsumerAdapter:limit=limit,)for ref in refs:+ # A producer can enqueue a batch into a run after fail_run swept it (the+ # extraction is still in flight when a sibling batch exhausts retries).+ # Such stragglers stay 'pending' forever — unclaimable, but counted by the+ # freshness gauge and the CDC backpressure probe — so re-sweep the run here.+ # No-op (one indexed statement) when the run has no non-terminal batches.+ try:+ stragglers = await BatchQueue.fail_run(+ conn,+ run_uuid=ref.run_uuid,+ team_id=ref.team_id,+ schema_id=ref.schema_id,+ reason="enqueued into an already-failed run (reconcile sweep)",+ )+ except Exception as e:+ logger.exception("reconcile_straggler_sweep_failed", run_uuid=ref.run_uuid)+ capture_exception(e)+ else:+ if stragglers:+ logger.warning(+ "reconcile_swept_straggler_batches",+ run_uuid=ref.run_uuid,+ team_id=ref.team_id,+ external_data_schema_id=ref.schema_id,+ batch_count=stragglers,+ )+try:reconciled = await sync_to_async(mark_job_failed_if_not_terminal)(job_id=ref.job_id,diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.pyindex db2e4c5172bb..eb8c20f1ff44 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py@@ -162,9 +162,16 @@ def _bulk_fail_dual_write_sql(where_sql: str) -> str:"""-# Shared between the async consumer path and the sync ops command so both agree-# on what counts as a pending (fail-able) batch.+# Both fail-run variants share _bulk_fail_dual_write_sql so the async consumer+# path and the sync ops command agree on what counts as a pending (fail-able)+# batch. The ops command targets by run_uuid alone (human-driven); consumer+# paths always know the run's group, so they scope by it too — guards against+# cross-group writes on a run_uuid collision and keeps the scan on the+# team/schema indexes.FAIL_RUN_SQL = _bulk_fail_dual_write_sql("b.run_uuid = %(run_uuid)s")+FAIL_RUN_SCOPED_SQL = _bulk_fail_dual_write_sql(+ "b.run_uuid = %(run_uuid)s AND b.team_id = %(team_id)s AND b.schema_id = %(schema_id)s"+)def _state_claim_candidates_sql() -> str:@@ -708,13 +715,17 @@ class BatchQueue:conn: psycopg.AsyncConnection[Any],*,run_uuid: str,+ team_id: int,+ schema_id: str,reason: str,) -> int:"""Mark every pending batch in a run as failed. Returns the count of batches failed."""cursor = await conn.execute(- FAIL_RUN_SQL,+ FAIL_RUN_SCOPED_SQL,{"run_uuid": run_uuid,+ "team_id": team_id,+ "schema_id": schema_id,"error_response": json.dumps({"error": reason}),},)@@ -856,6 +867,51 @@ class BatchQueue:return Nonereturn float(row[0])+ @staticmethod+ def get_oldest_non_terminal_batch_age_seconds(+ conn: psycopg.Connection[Any],+ *,+ team_id: int,+ schema_ids: list[str],+ ) -> float | None:+ """Age in seconds of the oldest batch still working through the queue for these schemas, or None.++ Non-terminal means unclaimed ('pending', 'waiting') or claimed but unfinished+ ('executing', 'waiting_retry'), read from the denormalized state columns.+ Runs containing a 'failed' batch are excluded, mirroring the loader's claim+ gate: their remaining batches can never be claimed (a batch enqueued into a+ run after ``fail_run`` swept it stays 'pending' forever — seen in production),+ so counting them would hold the backpressure guard down for the whole pruning+ window. Sync because its caller is the CDC producer's backpressure guard,+ which runs in synchronous activity code. Bounded to the pruning window —+ older batches are gone anyway.+ """+ with conn.cursor() as cur:+ cur.execute(+ f"""+ SELECT EXTRACT(EPOCH FROM (now() - min(b.created_at)))+ FROM {BATCH_TABLE} b+ WHERE b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND b.team_id = %(team_id)s+ AND b.schema_id = ANY(%(schema_ids)s)+ AND b.latest_state IN ('pending', 'waiting', 'waiting_retry', 'executing')+ AND NOT EXISTS (+ SELECT 1+ FROM {BATCH_TABLE} b_failed+ WHERE b_failed.run_uuid = b.run_uuid+ AND b_failed.team_id = b.team_id+ AND b_failed.schema_id = b.schema_id+ AND b_failed.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND b_failed.latest_state = 'failed'+ )+ """,+ {"team_id": team_id, "schema_ids": schema_ids},+ )+ row = cur.fetchone()+ if row is None or row[0] is None:+ return None+ return float(row[0])+@staticmethodasync def unlock_for_batches(conn: psycopg.AsyncConnection[Any],diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.pyindex 895cd2612cee..5c583e14fe0d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py@@ -823,6 +823,41 @@ class TestReconcileFailedRuns:mock_mark.assert_called_once_with(job_id=ref.job_id, team_id=ref.team_id, error=ref.reason)mock_release.assert_called_once_with(team_id=ref.team_id, schema_id=ref.schema_id, token=ref.workflow_run_id)+ @pytest.mark.asyncio+ async def test_sweeps_stragglers_even_for_already_terminal_run(self):+ # A batch enqueued into a run after fail_run swept it stays 'pending' forever+ # (unclaimable, but it pins the freshness gauge and holds the CDC backpressure+ # guard down) unless the reconcile sweep re-fails the run — seen in production.+ # The sweep must run before the already-terminal gate, not behind it.+ consumer = _make_consumer()+ ref = _make_failed_run_ref()++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_failed_runs",+ new_callable=AsyncMock,+ return_value=[ref],+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.fail_run",+ new_callable=AsyncMock,+ return_value=1,+ ) as mock_fail_run,+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.mark_job_failed_if_not_terminal",+ return_value=False,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.release_v3_pipeline_lock",+ ),+ ):+ await consumer._reconcile_failed_runs()++ mock_fail_run.assert_called_once()+ assert mock_fail_run.call_args.kwargs["run_uuid"] == ref.run_uuid+ assert mock_fail_run.call_args.kwargs["team_id"] == ref.team_id+ assert mock_fail_run.call_args.kwargs["schema_id"] == ref.schema_id+@pytest.mark.asyncioasync def test_skips_already_terminal_run(self):consumer = _make_consumer()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.pyindex 8f1d636a6bb6..f32c4218002a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py@@ -338,7 +338,9 @@ class TestBatchQueueFailRun:await _insert_batch(conn, batch_index=2, run_uuid="run-x")await BatchQueue.update_status(conn, batch_id=bid1, job_state="succeeded", attempt=1)- count = await BatchQueue.fail_run(conn, run_uuid="run-x", reason="test failure")+ count = await BatchQueue.fail_run(+ conn, run_uuid="run-x", team_id=1, schema_id="schema-1", reason="test failure"+ )assert count == 2@@ -558,6 +560,70 @@ class TestQueueFreshnessProbe:assert await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn) is None[email protected]_db(transaction=True)+class TestOldestNonTerminalBatchAge:+ @pytest.mark.parametrize(+ "job_state,expect_pending",+ [+ (None, True), # never claimed+ ("executing", True),+ ("waiting_retry", True),+ ("succeeded", False),+ ("failed", False),+ ],+ )+ @pytest.mark.asyncio+ async def test_counts_only_non_terminal_states(self, conn, sync_conn, job_state, expect_pending):+ bid = await _insert_batch(conn)+ if job_state is not None:+ await BatchQueue.update_status(conn, batch_id=bid, job_state=job_state, attempt=1)++ age = BatchQueue.get_oldest_non_terminal_batch_age_seconds(sync_conn, team_id=1, schema_ids=["schema-1"])++ if expect_pending:+ assert age is not None and age >= 0+ else:+ assert age is None++ @pytest.mark.asyncio+ async def test_scoped_to_team_and_schemas(self, conn, sync_conn):+ await _insert_batch(conn)++ assert (+ BatchQueue.get_oldest_non_terminal_batch_age_seconds(sync_conn, team_id=1, schema_ids=["other-schema"])+ is None+ )+ assert (+ BatchQueue.get_oldest_non_terminal_batch_age_seconds(sync_conn, team_id=2, schema_ids=["schema-1"]) is None+ )+ assert (+ BatchQueue.get_oldest_non_terminal_batch_age_seconds(+ sync_conn, team_id=1, schema_ids=["schema-1", "other-schema"]+ )+ is not None+ )++ @pytest.mark.asyncio+ async def test_dead_run_remnants_do_not_count(self, conn, sync_conn):+ # A batch enqueued into a run after fail_run swept it stays 'pending' but can+ # never be claimed; counting it would hold the CDC backpressure guard down for+ # the whole pruning window (a full extraction stop for the source).+ failed = await _insert_batch(conn, run_uuid="dead-run", batch_index=0)+ await BatchQueue.update_status(conn, batch_id=failed, job_state="failed", attempt=1)+ await _insert_batch(conn, run_uuid="dead-run", batch_index=1)++ assert (+ BatchQueue.get_oldest_non_terminal_batch_age_seconds(sync_conn, team_id=1, schema_ids=["schema-1"]) is None+ )++ await _insert_batch(conn, run_uuid="live-run", batch_index=0)++ assert (+ BatchQueue.get_oldest_non_terminal_batch_age_seconds(sync_conn, team_id=1, schema_ids=["schema-1"])+ is not None+ )++@pytest.mark.django_db(transaction=True)class TestGroupLeaseRecovery:@pytest.mark.asyncio@@ -946,7 +1012,7 @@ class TestStateDualWrite:done = await _insert_batch(conn, batch_index=1, run_uuid="run-dw")await BatchQueue.update_status(conn, batch_id=done, job_state="succeeded", attempt=1)- failed = await BatchQueue.fail_run(conn, run_uuid="run-dw", reason="boom")+ failed = await BatchQueue.fail_run(conn, run_uuid="run-dw", team_id=1, schema_id="schema-1", reason="boom")assert failed == 1assert (await _batch_state(conn, pending))[0] == "failed"