: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): reconcile CDC jobs stranded RUNNING after a dead run (#67704)
estefania48be88553716
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.pyindex f68e791e043f..bbc39e5e1eb9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py@@ -20,6 +20,7 @@ from collections.abc import Callablefrom django.db import close_old_connections+import psycopgimport pyarrow as paimport structlogimport posthoganalytics@@ -58,6 +59,9 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.errors importfrom products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEventfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import resolve_table_and_folder_namesfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.common import SyncTypeLiteral+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.pipelines.pipeline_v3.postgres_queue.producer import (PostgresProducer,)@@ -85,6 +89,20 @@ RETENTION_CAP_SAFETY_FACTOR = 0.8# attempt a failure won't be retried, so it's the last chance to record a visible failed-run row.CDC_MAX_EXTRACTION_ATTEMPTS = 3+# Shown as latest_error on prior-run jobs reconciled by _reconcile_orphaned_prior_jobs.+CDC_ORPHANED_JOB_MESSAGE = (+ "CDC run ended without finalizing this job (worker timeout or eviction). It was superseded by a "+ "later run; no data was lost — change capture resumes from the last confirmed replication position."+)+# Only reconcile prior RUNNING jobs older than this. A healthy run enqueues its first batch within+# seconds, so a no-batch job older than this is abandoned; the floor also keeps us clear of any+# concurrent manual/backfill run of the same source that has only just created its job row.+CDC_ORPHAN_JOB_MIN_AGE = dt.timedelta(minutes=30)+# Upper bound: batches are pruned from the queue after PARTITION_PRUNING_INTERVAL (14 days), so a+# "no batches" verdict is only trustworthy within that window. Never touch older rows — we cannot+# tell an abandoned run from one whose batches simply aged out.+CDC_ORPHAN_JOB_MAX_AGE = dt.timedelta(days=14)+# 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@@ -673,6 +691,13 @@ class CDCExtractActivity:returnself._mark_schemas_running()+ # Best-effort — must never break the extraction run, so guard the call+ # site: the method itself has unguarded lines (activity.info(),+ # conn.close()) and runs before the main try block below.+ try:+ self._reconcile_orphaned_prior_jobs()+ except Exception:+ self.log.warning("cdc_orphan_reconcile_unexpected_failed", exc_info=True)try:self.reader.connect()@@ -758,6 +783,69 @@ class CDCExtractActivity:schema.status = ExternalDataSchema.Status.RUNNINGschema.save(update_fields=["status", "updated_at"])+ def _reconcile_orphaned_prior_jobs(self) -> None:+ """Finalize this source's prior RUNNING jobs that were stranded mid-run.++ A CDC run creates an ExternalDataJob at its first WAL event (RUNNING) and only+ finalizes it on clean completion (the loader, for streaming) or in its own failure+ handler. If an activity attempt dies abruptly — a heartbeat/start-to-close timeout+ or worker eviction — that finalizer never runs and the row is stranded RUNNING; every+ later run leaks another. Nothing in-process can close it, so the next run does.++ The schedule's SKIP overlap policy means any prior run (a different workflow_run_id)+ has already ended, so its still-RUNNING rows are safe to close. We only fail rows that+ enqueued NO queue batches: with nothing queued the loader has no outstanding work, so+ failing cannot race a late load. Rows that did enqueue batches are left to the loader,+ which owns their completion. Best-effort — must never break the extraction run.+ """+ current_run_id = activity.info().workflow_run_id+ now = dt.datetime.now(tz=dt.UTC)+ try:+ orphans = list(+ ExternalDataJob.objects.filter(+ team_id=self.inputs.team_id,+ schema_id__in=[s.id for s in self.cdc_schemas],+ status=ExternalDataJob.Status.RUNNING,+ pipeline_version=ExternalDataJob.PipelineVersion.V3,+ created_at__gt=now - CDC_ORPHAN_JOB_MAX_AGE,+ created_at__lt=now - CDC_ORPHAN_JOB_MIN_AGE,+ )+ .exclude(workflow_run_id=current_run_id)+ .order_by("created_at")[:200]+ )+ except Exception:+ self.log.warning("cdc_orphan_reconcile_query_failed", exc_info=True)+ return++ if not orphans:+ return++ try:+ conn = psycopg.Connection.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True)+ except Exception:+ self.log.warning("cdc_orphan_reconcile_queue_connect_failed", exc_info=True)+ return++ reconciled = 0+ try:+ for job in orphans:+ try:+ if BatchQueue.count_batches_for_run(conn, job_id=str(job.id)) > 0:+ # The run enqueued batches; the loader owns their completion — leave it.+ continue+ job.status = ExternalDataJob.Status.FAILED+ job.latest_error = CDC_ORPHANED_JOB_MESSAGE+ job.finished_at = dt.datetime.now(tz=dt.UTC)+ job.save(update_fields=["status", "latest_error", "finished_at", "updated_at"])+ reconciled += 1+ except Exception:+ self.log.warning("cdc_orphan_reconcile_job_failed", job_id=str(job.id), exc_info=True)+ finally:+ conn.close()++ if reconciled:+ self.log.info("cdc_orphaned_jobs_reconciled", count=reconciled)+# ------------------------------------------------------------------# PK column loading# ------------------------------------------------------------------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 62b23e52c980..0d75ead95699 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@@ -1,6 +1,6 @@import uuidfrom contextlib import nullcontext-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import Literalimport pytest@@ -10,8 +10,13 @@ import pyarrow as paimport psycopg.errorsfrom parameterized import parameterized+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.temporal.data_imports.cdc.activities import (CDC_MAX_CHANGES_PER_READ,+ CDC_ORPHAN_JOB_MIN_AGE,+ CDC_ORPHANED_JOB_MESSAGE,SLOT_INVALIDATION_RECOVERY_MESSAGE,CDCExtractActivity,CDCExtractInput,@@ -2609,3 +2614,66 @@ class TestCDCBoundedReadLoop:assert reader.upto_nchanges_calls == [CDC_MAX_CHANGES_PER_READ, CDC_MAX_CHANGES_PER_READ * 2]assert reader.confirmed_positions == ["0/300"] # nothing to advance on pass 1; pass 2 drains+++class TestReconcileOrphanedPriorJobs:+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.psycopg.Connection.connect")+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.BatchQueue.count_batches_for_run")+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")+ def test_only_fails_stale_prior_runs_with_no_queued_batches(self, mock_activity, mock_count, mock_connect, team):+ mock_activity.info.return_value = MagicMock(workflow_run_id="current-run")++ source = ExternalDataSource.objects.create(+ team_id=team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ status="Completed",+ source_type="Postgres",+ )+ schema = ExternalDataSchema.objects.create(+ team_id=team.pk,+ source=source,+ name="users",+ sync_type=ExternalDataSchema.SyncType.CDC,+ sync_type_config={"cdc_mode": "streaming"},+ )++ def _job(workflow_run_id: str, age: timedelta) -> ExternalDataJob:+ job = ExternalDataJob.objects.create(+ team_id=team.pk,+ pipeline_id=source.pk,+ schema=schema,+ status=ExternalDataJob.Status.RUNNING,+ rows_synced=0,+ workflow_id="wf",+ workflow_run_id=workflow_run_id,+ pipeline_version=ExternalDataJob.PipelineVersion.V3,+ )+ # created_at is auto_now_add; backdate via update to control the reconcile window.+ ExternalDataJob.objects.filter(id=job.id).update(created_at=datetime.now(UTC) - age)+ return job++ old_no_batch = _job("old-1", timedelta(hours=2)) # stale, ended, empty -> FAILED+ old_with_batch = _job("old-2", timedelta(hours=2)) # stale but queued -> left alone+ current_run = _job("current-run", timedelta(hours=2)) # this run's own -> left alone+ too_recent = _job("recent-1", CDC_ORPHAN_JOB_MIN_AGE / 2) # inside floor -> left alone+ ancient = _job("ancient-1", timedelta(days=20)) # past batch retention -> left alone++ # Only old_with_batch reports queued batches; the rest have none.+ mock_count.side_effect = lambda conn, job_id: 3 if job_id == str(old_with_batch.id) else 0++ activity_obj = CDCExtractActivity(CDCExtractInput(team_id=team.pk, source_id=source.pk))+ activity_obj.log = MagicMock()+ activity_obj.cdc_schemas = [schema]++ activity_obj._reconcile_orphaned_prior_jobs()++ old_no_batch.refresh_from_db()+ assert old_no_batch.status == ExternalDataJob.Status.FAILED+ assert old_no_batch.latest_error == CDC_ORPHANED_JOB_MESSAGE+ assert old_no_batch.finished_at is not None++ for untouched in (old_with_batch, current_run, too_recent, ancient):+ untouched.refresh_from_db()+ assert untouched.status == ExternalDataJob.Status.RUNNINGdiff --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 39c6ecb2fe0e..d5bb5af48a01 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@@ -692,3 +692,32 @@ class BatchQueue:has_non_terminal=non_terminal_count > 0,is_stale=age_seconds > TAKEOVER_STALE_THRESHOLD_SECONDS,)++ @staticmethod+ def count_batches_for_run(+ conn: psycopg.Connection[Any],+ *,+ job_id: str,+ ) -> int:+ """Count queue batches enqueued for a job, regardless of status.++ Unlike ``get_run_activity_summary`` (which inner-joins the status view and so+ reports ``has_batches=False`` for batches the loader hasn't claimed yet), this+ counts raw batch rows. It lets a caller tell a run that enqueued *nothing* (safe+ to finalize) apart from one whose batches are merely unclaimed — where the loader+ still owns completion and failing the job would strand a late load. The pruning+ window bounds the scan to batches the queue still retains, so a ``0`` here is only+ trustworthy for jobs newer than ``PARTITION_PRUNING_INTERVAL``.+ """+ with conn.cursor(row_factory=dict_row) as cur:+ cur.execute(+ f"""+ SELECT COUNT(*) AS batch_count+ FROM {BATCH_TABLE} b+ WHERE b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND b.job_id = %(job_id)s+ """,+ {"job_id": job_id},+ )+ row = cur.fetchone()+ return int(row["batch_count"]) if row else 0diff --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 5448af3df61a..390cd91d4d77 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@@ -737,3 +737,21 @@ class TestClaimWindowSkipsForeignLeasedGroups:await conn.execute(f"UPDATE {LEASE_TABLE} SET expires_at = now() - interval '1 second'")got_a_after_expiry = await _claim(conn, owner=OWNER_A, limit=2)assert "schema-A" in {b.schema_id for b in got_a_after_expiry}++[email protected]_db(transaction=True)+class TestCountBatchesForRun:+ @pytest.mark.asyncio+ async def test_counts_unclaimed_batches_and_zero_when_none(self, conn, _db_url):+ # Freshly inserted batches have no status row until the loader claims them. The count+ # must still see them: it exists so the CDC orphan reconciler can tell a run that+ # enqueued nothing (safe to fail) from one whose batches are merely unclaimed (a+ # status-view JOIN would report the latter as zero and strand a late load).+ await _insert_batch(conn, job_id="job-A", batch_index=0)+ await _insert_batch(conn, job_id="job-A", batch_index=1)+ await _insert_batch(conn, job_id="job-B", batch_index=0)++ with psycopg.Connection.connect(_db_url, autocommit=True) as sync_conn:+ assert BatchQueue.count_batches_for_run(sync_conn, job_id="job-A") == 2+ assert BatchQueue.count_batches_for_run(sync_conn, job_id="job-B") == 1+ assert BatchQueue.count_batches_for_run(sync_conn, job_id="job-missing") == 0