: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): stop repeating identical CDC failure rows (#77884)
Tom Owersf794c8ab672b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.pyindex bca700463f6d..0bff0975ae19 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py@@ -93,6 +93,18 @@ 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+# How long an unchanged failure suppresses further visibility rows for a schema. A source that stays+# unreachable re-fails on every tick, and the schedule retries each failed tick at the workflow level+# too (maximum_attempts on the schedule's action), so a 10-minute source would otherwise stamp the+# same row per schema several times an hour for as long as the outage lasts. The schema's own status+# and latest_error are refreshed every run regardless — these rows are sync history, and repeating an+# identical one says nothing new while burying the runs that do.+CDC_FAILURE_VISIBILITY_COOLDOWN = dt.timedelta(hours=1)++# Every extraction run carries the schedule's workflow id, which is built from this prefix (see+# _get_cdc_extraction_schedule_id). Scopes the cooldown lookup to change-capture runs.+CDC_EXTRACTION_WORKFLOW_ID_PREFIX = "cdc-extraction-"+# 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 "@@ -1491,13 +1503,17 @@ class CDCExtractActivity:Mirrors the running-job creation in _get_or_create_tracker (workflow ids, V3, snapshot) sothe Syncs tab renders these the same way as a job that failed after it started writing.- Schemas whose job already exists this run (failed by _fail_created_jobs) are skipped.+ Schemas whose job already exists this run (failed by _fail_created_jobs) are skipped, as are+ schemas still inside the cooldown for this same failure (see _schemas_in_failure_cooldown)."""now = dt.datetime.now(tz=dt.UTC)activity_info = activity.info()schema_ids_with_jobs = {job.schema_id for job in self.created_jobs}+ in_cooldown = self._schemas_in_failure_cooldown(friendly_error, now)+ if in_cooldown:+ self.log.info("cdc_failure_visibility_jobs_suppressed", schemas=len(in_cooldown))for schema in self.cdc_schemas:- if schema.id in schema_ids_with_jobs:+ if schema.id in schema_ids_with_jobs or schema.id in in_cooldown:continueExternalDataJob.objects.create(team_id=self.inputs.team_id,@@ -1513,6 +1529,43 @@ class CDCExtractActivity:schema_snapshot=_build_schema_snapshot(schema),)+ def _schemas_in_failure_cooldown(self, friendly_error: str, now: dt.datetime) -> set[uuid.UUID]:+ """Schemas whose most recent extraction job already reports this exact failure, within the+ cooldown.++ Only the newest extraction job in the window counts: anything that happened since — a+ successful run, a different error, a run that synced rows before failing — is news, so the+ schema falls out of the cooldown and gets its row. Rows from other workflows are ignored: a+ schema still snapshotting runs the regular per-schema pipeline alongside change capture, and+ those runs say nothing about whether this failure has already been reported. One query for+ the whole source; the window keeps it small.+ """+ recent_jobs = (+ ExternalDataJob.objects.filter(+ team_id=self.inputs.team_id,+ schema_id__in=[schema.id for schema in self.cdc_schemas],+ created_at__gt=now - CDC_FAILURE_VISIBILITY_COOLDOWN,+ workflow_id__startswith=CDC_EXTRACTION_WORKFLOW_ID_PREFIX,+ )+ .order_by("schema_id", "-created_at")+ .values("schema_id", "status", "latest_error", "rows_synced")+ )++ in_cooldown: set[uuid.UUID] = set()+ seen: set[uuid.UUID] = set()+ for job in recent_jobs:+ schema_id = job["schema_id"]+ if schema_id in seen:+ continue+ seen.add(schema_id)+ if (+ job["status"] == ExternalDataJob.Status.FAILED+ and job["latest_error"] == friendly_error+ and not job["rows_synced"]+ ):+ in_cooldown.add(schema_id)+ return in_cooldown+def _record_run_heartbeat(self, schema: ExternalDataSchema, run_at: dt.datetime) -> None:"""Persist a per-schema last-run heartbeat (cdc_last_run_at / cdc_last_run_event_count) so aquiet zero-event run still proves extraction is alive. Nothing reads these keys yet — andiff --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 b4f4ab4dba92..53dd4964984d 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@@ -2982,3 +2982,126 @@ class TestReconcileOrphanedPriorJobs:for untouched in (old_with_batch, current_run, too_recent, ancient):untouched.refresh_from_db()assert untouched.status == ExternalDataJob.Status.RUNNING+++class TestFailureVisibilityCooldown:+ """A source that stays unreachable re-fails on every tick, and the schedule retries each failed+ tick at the workflow level on top of that. Without a cooldown one outage stamps the same row per+ schema many times an hour, for days — burying the runs that actually differ."""++ CONNECTION_FAILED = cdc_error_info(CDCErrorCategory.CONNECTION_FAILED).friendly_message+ AUTH_FAILED = cdc_error_info(CDCErrorCategory.AUTH_FAILED).friendly_message++ @pytest.mark.parametrize(+ "previous_status,previous_error,previous_rows_synced,previous_age_minutes,snapshot_run_since,expect_new_row",+ [+ # Nothing has changed since the last extraction row said exactly this — no new row.+ pytest.param(+ ExternalDataJob.Status.FAILED,+ CONNECTION_FAILED,+ 0,+ 0,+ False,+ False,+ id="identical_failure_within_cooldown",+ ),+ # A schema still snapshotting keeps running the regular per-schema pipeline; those rows+ # say nothing about whether this failure has been reported, so they don't reopen it.+ pytest.param(+ ExternalDataJob.Status.FAILED,+ CONNECTION_FAILED,+ 0,+ 0,+ True,+ False,+ id="unrelated_snapshot_run_since",+ ),+ # Everything below is news, so the outage gets a fresh row.+ pytest.param(+ ExternalDataJob.Status.FAILED,+ CONNECTION_FAILED,+ 0,+ 90,+ False,+ True,+ id="identical_failure_past_cooldown",+ ),+ pytest.param(ExternalDataJob.Status.COMPLETED, None, 10, 0, False, True, id="extraction_succeeded_since"),+ pytest.param(ExternalDataJob.Status.FAILED, AUTH_FAILED, 0, 0, False, True, id="different_error_since"),+ pytest.param(+ ExternalDataJob.Status.FAILED,+ CONNECTION_FAILED,+ 10,+ 0,+ False,+ True,+ id="previous_run_synced_rows_first",+ ),+ ],+ )+ def test_repeat_failure_rows_collapse_until_something_changes(+ self,+ previous_status,+ previous_error,+ previous_rows_synced,+ previous_age_minutes,+ snapshot_run_since,+ expect_new_row,+ team,+ ):+ source = ExternalDataSource.objects.create(+ team_id=team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ status="Running",+ 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"},+ )++ previous = ExternalDataJob.objects.create(+ team_id=team.pk,+ pipeline_id=source.pk,+ schema=schema,+ status=previous_status,+ rows_synced=previous_rows_synced,+ latest_error=previous_error,+ workflow_id=f"cdc-extraction-{source.pk}-2026-08-04T18:15:00Z",+ workflow_run_id="run-1",+ pipeline_version=ExternalDataJob.PipelineVersion.V3,+ )+ # created_at is auto_now_add; backdate via update to control the cooldown window.+ ExternalDataJob.objects.filter(id=previous.id).update(+ created_at=datetime.now(UTC) - timedelta(minutes=previous_age_minutes)+ )++ if snapshot_run_since:+ ExternalDataJob.objects.create(+ team_id=team.pk,+ pipeline_id=source.pk,+ schema=schema,+ status=ExternalDataJob.Status.COMPLETED,+ rows_synced=0,+ workflow_id=f"{schema.pk}-2026-08-04T18:20:00Z",+ workflow_run_id="run-snapshot",+ pipeline_version=ExternalDataJob.PipelineVersion.V3,+ )++ activity_obj = CDCExtractActivity(CDCExtractInput(team_id=team.pk, source_id=source.pk))+ activity_obj.log = MagicMock()+ activity_obj.cdc_schemas = [schema]++ with patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity") as mock_activity:+ mock_activity.info.return_value = MagicMock(+ workflow_id=f"cdc-extraction-{source.pk}-2026-08-04T18:25:00Z", workflow_run_id="run-2"+ )+ activity_obj._create_failure_visibility_jobs(self.CONNECTION_FAILED)++ rows_this_run = ExternalDataJob.objects.filter(schema=schema, workflow_run_id="run-2").count()+ assert rows_this_run == (1 if expect_new_row else 0)