: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 failed runs without per-batch status probes (#83022)
estefania27f1ce9dda06
diff --git a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txtindex 6b21ef812ab4..ac92e62898dc 100644--- a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt+++ b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt@@ -17,3 +17,6 @@ tasks.0079_backfill_task_repositoriesreplay_vision.0073_rebackfill_usage_scanner_idreplay_vision.0070_backfill_usage_scanner_idtasks.0088_backfill_task_search_documents+# Does run CONCURRENTLY, one index per sourcebatch partition, but from RunPython+# (the partition list is only known at runtime), which the type-based check can't see.+warehouse_sources_queue.0008_sourcebatch_supersededdiff --git a/products/warehouse_sources/backend/management/commands/backfill_warehouse_queue_state.py b/products/warehouse_sources/backend/management/commands/backfill_warehouse_queue_state.pyindex 2755a049a622..d8c93bb5896e 100644--- a/products/warehouse_sources/backend/management/commands/backfill_warehouse_queue_state.py+++ b/products/warehouse_sources/backend/management/commands/backfill_warehouse_queue_state.py@@ -28,13 +28,17 @@ DEFAULT_BATCH_SIZE = 5000# Truth per batch: its latest status row, or 'pending' when none exists. For# never-claimed rows state_changed_at is set to the batch's own created_at so# the NULL "never visited" marker clears and retry-backoff math stays sane.+# superseded mirrors the failed status payload's flag; get_failed_runs refuses+# to reconcile until this backfill has cleared pre-flag failed rows._TRUTH_SELECT = f"""SELECTb.id,b.created_at,COALESCE(s.job_state, 'pending') AS expected_state,COALESCE(s.attempt, 0)::smallint AS expected_attempt,- COALESCE(s.created_at, b.created_at) AS expected_changed_at+ COALESCE(s.created_at, b.created_at) AS expected_changed_at,+ (COALESCE(s.job_state, 'pending') = 'failed'+ AND COALESCE((s.error_response->>'superseded')::boolean, false)) AS expected_supersededFROM {BATCH_TABLE} b{latest_status_lateral("b", "s")}WHERE b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'@@ -49,7 +53,8 @@ FILL_MISSING_SQL = f"""UPDATE {BATCH_TABLE} bSET latest_state = t.expected_state,latest_attempt = t.expected_attempt,- state_changed_at = t.expected_changed_at+ state_changed_at = t.expected_changed_at,+ superseded = t.expected_supersededFROM truth tWHERE b.id = t.idAND b.created_at = t.created_at@@ -59,18 +64,25 @@ FILL_MISSING_SQL = f"""RECONCILE_SQL = f"""WITH truth AS ({_TRUTH_SELECT}- AND (b.latest_state, b.latest_attempt)- IS DISTINCT FROM (COALESCE(s.job_state, 'pending'), COALESCE(s.attempt, 0))+ AND (b.latest_state, b.latest_attempt, b.superseded)+ IS DISTINCT FROM (+ COALESCE(s.job_state, 'pending'),+ COALESCE(s.attempt, 0),+ COALESCE(s.job_state, 'pending') = 'failed'+ AND COALESCE((s.error_response->>'superseded')::boolean, false)+ )LIMIT %(batch_size)s)UPDATE {BATCH_TABLE} bSET latest_state = t.expected_state,latest_attempt = t.expected_attempt,- state_changed_at = t.expected_changed_at+ state_changed_at = t.expected_changed_at,+ superseded = t.expected_supersededFROM truth tWHERE b.id = t.idAND b.created_at = t.created_at- AND (b.latest_state, b.latest_attempt) IS DISTINCT FROM (t.expected_state, t.expected_attempt)+ AND (b.latest_state, b.latest_attempt, b.superseded)+ IS DISTINCT FROM (t.expected_state, t.expected_attempt, t.expected_superseded)AND (b.state_changed_at IS NULL OR b.state_changed_at <= t.expected_changed_at)"""@@ -82,8 +94,13 @@ AUDIT_SQL = f"""FROM {BATCH_TABLE} b{latest_status_lateral("b", "s")}WHERE b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND (b.latest_state, b.latest_attempt)- IS DISTINCT FROM (COALESCE(s.job_state, 'pending'), COALESCE(s.attempt, 0))+ AND (b.latest_state, b.latest_attempt, b.superseded)+ IS DISTINCT FROM (+ COALESCE(s.job_state, 'pending'),+ COALESCE(s.attempt, 0),+ COALESCE(s.job_state, 'pending') = 'failed'+ AND COALESCE((s.error_response->>'superseded')::boolean, false)+ )GROUP BY 1, 2ORDER BY 3 DESC"""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 aae4e3d2e802..d0da7e3328f8 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@@ -173,10 +173,12 @@ def build_status_dual_write_sql(*, with_batch_created_at: bool) -> str:WITH ins AS (INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)VALUES (%(batch_id)s, %(job_state)s, %(attempt)s, now(), %(error_response)s, now())- RETURNING batch_id, job_state, attempt, created_at+ RETURNING batch_id, job_state, attempt, created_at, error_response)UPDATE {BATCH_TABLE} b- SET latest_state = ins.job_state, latest_attempt = ins.attempt, state_changed_at = ins.created_at+ SET latest_state = ins.job_state, latest_attempt = ins.attempt, state_changed_at = ins.created_at,+ superseded = (ins.job_state = 'failed'+ AND COALESCE((ins.error_response->>'superseded')::boolean, false))FROM insWHERE b.id = ins.batch_idAND {created_at_predicate}@@ -231,11 +233,13 @@ def build_status_dual_write_unless_failed_sql(INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)SELECT t.id, %(job_state)s, %(attempt)s, now(), %(error_response)s, now()FROM target t- RETURNING batch_id, job_state, attempt, created_at+ RETURNING batch_id, job_state, attempt, created_at, error_response),upd AS (UPDATE {BATCH_TABLE} b- SET latest_state = ins.job_state, latest_attempt = ins.attempt, state_changed_at = ins.created_at+ SET latest_state = ins.job_state, latest_attempt = ins.attempt, state_changed_at = ins.created_at,+ superseded = (ins.job_state = 'failed'+ AND COALESCE((ins.error_response->>'superseded')::boolean, false))FROM insWHERE b.id = ins.batch_idAND {created_at_predicate}@@ -272,7 +276,8 @@ def _bulk_fail_dual_write_sql(where_sql: str) -> str:RETURNING batch_id, created_at)UPDATE {BATCH_TABLE} b- SET latest_state = 'failed', latest_attempt = 0, state_changed_at = ins.created_at+ SET latest_state = 'failed', latest_attempt = 0, state_changed_at = ins.created_at,+ superseded = COALESCE((%(error_response)s::jsonb->>'superseded')::boolean, false)FROM insJOIN targets t ON t.id = ins.batch_idWHERE b.id = t.id@@ -1121,45 +1126,64 @@ class BatchQueue:"""Return one ref per run with a ``failed`` batch older than ``grace_seconds``, within ``lookback_seconds``.Ordered by latest failure first so fresh failures still land in the window when- already-reconciled runs outnumber ``limit`` within the lookback. The- denormalized-column pre-filter keeps the lateral (still needed for the- failure timestamp and error payload) probing only failed batches.+ already-reconciled runs outnumber ``limit`` within the lookback.++ Candidacy, the per-run pick, and the LIMIT run entirely off the+ denormalized batch columns: ``state_changed_at`` equals the failed+ status row's ``created_at`` (the dual-write CTEs guarantee it), and+ ``superseded`` mirrors the status payload's flag. The per-batch+ latest-status lateral this replaces was the sweep's melt-down under+ failure storms: each probe is a Merge Append across every status+ partition, and it ran once per failed batch in the window — 1.36M+ during the 2026-08 storm, minutes per sweep. The lateral now runs only+ for the ``LIMIT`` winners' error payloads.++ The post-LIMIT superseded re-check is the deploy-transition fence:+ failed rows written before the flag existed read ``superseded = false``+ until ``backfill_warehouse_queue_state reconcile`` has run, and+ reconciling such a run would fail an ExternalDataJob whose newer run is+ live. Until the backfill lands, those rows can occupy winner slots (the+ sweep returns fewer than ``limit`` refs), which only delays other+ reconciles to a later sweep.++ ``state_changed_at`` is nullable, and the NULL arm is exempt from the+ lookback only: batch ``created_at`` predates the failure, so a lookback+ measured on it would age such a row out while the run is still stranded+ (the stranded sweep skips runs that have a failed batch). Grace does+ apply to them, through that same ``created_at`` fallback, which also+ orders them. Every writer of ``latest_state = 'failed'`` also sets+ ``state_changed_at``, so the NULL arm matches only legacy rows."""async with conn.cursor(row_factory=dict_row) as cur:await cur.execute(f"""- SELECT run_uuid, job_id, team_id, schema_id, metadata, error_response- FROM (- SELECT DISTINCT ON (b.run_uuid)- b.run_uuid, b.job_id, b.team_id, b.schema_id, b.metadata, s.error_response,- s.created_at AS failed_at- FROM {BATCH_TABLE} b- {latest_status_lateral("b", "s", join="INNER")}- WHERE- b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND b.latest_state = 'failed'- -- Implied by the s.created_at lower bound (the denormalizing- -- status CTEs set state_changed_at to exactly the terminal- -- status row's created_at), so it changes no semantics: it- -- exists purely to prune the outer scan BEFORE the DISTINCT ON- -- sort and the per-row lateral probes. Without it the sort- -- input is every failed batch in the pruning window — 1.36M- -- rows during the 2026-08 failure storm, a minutes-long disk- -- spill at work_mem=4MB that, run by every pod concurrently,- -- starved the claim path (the 2026-08-09 loader stall).- -- state_changed_at is nullable; NULL rows must stay visible or a- -- failed run could strand until the retention prune (the stranded- -- sweep skips runs that have a failed batch).- AND (b.state_changed_at IS NULL- OR b.state_changed_at >= now() - make_interval(secs => %(lookback)s))- AND s.job_state = 'failed'- AND s.created_at <= now() - make_interval(secs => %(grace)s)- AND s.created_at >= now() - make_interval(secs => %(lookback)s)- AND COALESCE((s.error_response->>'superseded')::boolean, false) = false- ORDER BY b.run_uuid, s.created_at DESC- ) failed_runs- ORDER BY failed_at DESC- LIMIT %(limit)s+ WITH winners AS MATERIALIZED (+ SELECT run_uuid, batch_id, batch_created_at, failed_at+ FROM (+ SELECT DISTINCT ON (b.run_uuid)+ b.run_uuid, b.id AS batch_id, b.created_at AS batch_created_at,+ COALESCE(b.state_changed_at, b.created_at) AS failed_at+ FROM {BATCH_TABLE} b+ WHERE+ b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND b.latest_state = 'failed'+ AND NOT b.superseded+ AND (b.state_changed_at IS NULL+ OR b.state_changed_at >= now() - make_interval(secs => %(lookback)s))+ AND COALESCE(b.state_changed_at, b.created_at)+ <= now() - make_interval(secs => %(grace)s)+ ORDER BY b.run_uuid, COALESCE(b.state_changed_at, b.created_at) DESC+ ) ranked+ ORDER BY failed_at DESC+ LIMIT %(limit)s+ )+ SELECT b.run_uuid, b.job_id, b.team_id, b.schema_id, b.metadata, s.error_response+ FROM winners w+ JOIN {BATCH_TABLE} b ON b.id = w.batch_id AND b.created_at = w.batch_created_at+ {latest_status_lateral("b", "s", join="INNER")}+ WHERE s.job_state = 'failed'+ AND COALESCE((s.error_response->>'superseded')::boolean, false) = false+ ORDER BY w.failed_at DESC""",{"grace": grace_seconds, "lookback": lookback_seconds, "limit": limit},)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 689c81c26612..ed71a5b248d5 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@@ -75,6 +75,7 @@ def _ensure_tables(conn: psycopg.Connection[Any]) -> None:latest_state VARCHAR(32) NOT NULL DEFAULT 'pending',latest_attempt SMALLINT NOT NULL DEFAULT 0,state_changed_at TIMESTAMPTZ,+ superseded BOOLEAN NOT NULL DEFAULT FALSE,created_at TIMESTAMPTZ NOT NULL DEFAULT now())""")@@ -83,7 +84,8 @@ def _ensure_tables(conn: psycopg.Connection[Any]) -> None:ALTER TABLE {BATCH_TABLE}ADD COLUMN IF NOT EXISTS latest_state VARCHAR(32) NOT NULL DEFAULT 'pending',ADD COLUMN IF NOT EXISTS latest_attempt SMALLINT NOT NULL DEFAULT 0,- ADD COLUMN IF NOT EXISTS state_changed_at TIMESTAMPTZ+ ADD COLUMN IF NOT EXISTS state_changed_at TIMESTAMPTZ,+ ADD COLUMN IF NOT EXISTS superseded BOOLEAN NOT NULL DEFAULT FALSE""")conn.execute(f"""CREATE INDEX IF NOT EXISTS sb_claimable_idx ON {BATCH_TABLE} (team_id, created_at, batch_index)@@ -97,6 +99,10 @@ def _ensure_tables(conn: psycopg.Connection[Any]) -> None:CREATE INDEX IF NOT EXISTS sb_schema_busy_idx ON {BATCH_TABLE} (team_id, schema_id)WHERE latest_state = 'executing'""")+ conn.execute(f"""+ CREATE INDEX IF NOT EXISTS sb_failed_changed_idx ON {BATCH_TABLE} (state_changed_at)+ WHERE latest_state = 'failed'+ """)conn.execute(f"""CREATE TABLE IF NOT EXISTS {STATUS_TABLE} (id UUID PRIMARY KEY DEFAULT gen_random_uuid(),@@ -1641,3 +1647,106 @@ class TestRecoverySweepVsLiveOwner:cur = await conn.execute(f"SELECT latest_state FROM {BATCH_TABLE} WHERE id = %s", (bid,))row = await cur.fetchone()assert row is not None and row[0] == "succeeded", "the sweep must not re-queue a batch its owner finished"++[email protected]_db(transaction=True)+class TestGetFailedRuns:+ """The reconcile sweep judges candidacy from the denormalized batch columns+ alone; these guard the candidacy rules and the dual-write derivation of the+ superseded flag they depend on."""++ async def _backdate_run_failure(self, conn: psycopg.AsyncConnection[Any], run_uuid: str, age_seconds: int) -> None:+ await conn.execute(+ f"UPDATE {STATUS_TABLE} SET created_at = created_at - make_interval(secs => %s) "+ f"WHERE batch_id IN (SELECT id FROM {BATCH_TABLE} WHERE run_uuid = %s)",+ [age_seconds, run_uuid],+ )+ await conn.execute(+ f"UPDATE {BATCH_TABLE} SET state_changed_at = state_changed_at - make_interval(secs => %s) "+ f"WHERE run_uuid = %s",+ [age_seconds, run_uuid],+ )++ @pytest.mark.parametrize(+ "grace_seconds,failure_age_seconds,expect_returned",+ [+ (0, 0, True),+ (3600, 0, False), # too fresh: a fail_run may still be in flight+ (0, 90_000, False), # older than the lookback window+ ],+ )+ @pytest.mark.asyncio+ async def test_failed_run_surfaces_between_grace_and_lookback(+ self, conn, grace_seconds, failure_age_seconds, expect_returned+ ):+ await _insert_batch(conn, run_uuid="run-f", job_id="job-f", metadata={"workflow_run_id": "wf-1"})+ await BatchQueue.fail_run(conn, run_uuid="run-f", team_id=1, schema_id="schema-1", reason="boom")+ if failure_age_seconds:+ await self._backdate_run_failure(conn, "run-f", failure_age_seconds)++ refs = await BatchQueue.get_failed_runs(conn, grace_seconds=grace_seconds, lookback_seconds=86_400, limit=10)++ if expect_returned:+ assert [(r.run_uuid, r.job_id, r.team_id, r.schema_id, r.reason) for r in refs] == [+ ("run-f", "job-f", 1, "schema-1", "boom")+ ]+ assert refs[0].workflow_run_id == "wf-1"+ else:+ assert refs == []++ @pytest.mark.parametrize(+ "batch_age_seconds,grace_seconds,expect_returned",+ [+ (3 * 86_400, 0, True), # older than the lookback, but must not strand+ (0, 3600, False), # grace applies too, measured on the fallback+ ],+ )+ @pytest.mark.asyncio+ async def test_legacy_rows_without_a_failure_timestamp(+ self, conn, batch_age_seconds, grace_seconds, expect_returned+ ):+ # Pre-dual-write rows are 'failed' with no state_changed_at, so batch+ # created_at stands in. It predates the failure, so measuring the lookback+ # on it would age the row out while its run is still stranded.+ await _insert_batch(conn, run_uuid="run-legacy", job_id="job-f")+ await BatchQueue.fail_run(conn, run_uuid="run-legacy", team_id=1, schema_id="schema-1", reason="boom")+ await conn.execute(+ f"UPDATE {BATCH_TABLE} SET state_changed_at = NULL, created_at = now() - make_interval(secs => %s) "+ f"WHERE run_uuid = 'run-legacy'",+ [batch_age_seconds],+ )++ refs = await BatchQueue.get_failed_runs(conn, grace_seconds=grace_seconds, lookback_seconds=86_400, limit=10)++ assert [r.run_uuid for r in refs] == (["run-legacy"] if expect_returned else [])++ @pytest.mark.asyncio+ async def test_superseded_runs_are_not_reconciled(self, conn, sync_conn):+ await _insert_batch(conn, run_uuid="run-old", job_id="job-f")+ await _insert_batch(conn, run_uuid="run-new", job_id="job-f")+ BatchQueue.supersede_other_runs(sync_conn, job_id="job-f", current_run_uuid="run-new")+ await _insert_batch(conn, run_uuid="run-failed", job_id="job-g", schema_id="schema-2")+ await BatchQueue.fail_run(conn, run_uuid="run-failed", team_id=1, schema_id="schema-2", reason="boom")++ refs = await BatchQueue.get_failed_runs(conn, grace_seconds=0, lookback_seconds=86_400, limit=10)++ assert [r.run_uuid for r in refs] == ["run-failed"]+ # The flag itself must be set: the post-LIMIT status re-check would also+ # hide run-old from this query, silently masking a broken derivation.+ cur = await conn.execute(f"SELECT bool_and(superseded) FROM {BATCH_TABLE} WHERE run_uuid = 'run-old'")+ row = await cur.fetchone()+ assert row is not None and row[0] is True++ @pytest.mark.asyncio+ async def test_pre_backfill_superseded_rows_stay_excluded(self, conn, sync_conn):+ # A failed row written before the superseded column existed reads false+ # until the backfill command runs; the status payload must still veto+ # reconciling it, or a job with a live newer run gets failed.+ await _insert_batch(conn, run_uuid="run-old", job_id="job-f")+ await _insert_batch(conn, run_uuid="run-new", job_id="job-f")+ BatchQueue.supersede_other_runs(sync_conn, job_id="job-f", current_run_uuid="run-new")+ await conn.execute(f"UPDATE {BATCH_TABLE} SET superseded = false WHERE run_uuid = 'run-old'")++ refs = await BatchQueue.get_failed_runs(conn, grace_seconds=0, lookback_seconds=86_400, limit=10)++ assert refs == []diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.pyindex 083ff31fccc0..cc051d768484 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py@@ -9,6 +9,7 @@ from unittest import mockfrom django.conf import settingsfrom django.test import override_settings+import psycopgimport pymysqlimport aioboto3import pytest_asyncio@@ -35,7 +36,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (BATCH_TABLE,STATUS_TABLE,- STATUS_VIEW,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.test_jobs_db import (+ _ensure_tables,+ _get_test_database_url,)from products.warehouse_sources.backend.temporal.data_imports.post_import_job import PostImportWorkflowfrom products.warehouse_sources.backend.temporal.data_imports.settings import ACTIVITIES@@ -61,65 +65,13 @@ def _ensure_sourcebatch_tables(django_db_setup, django_db_blocker):The v3 pipeline tests patch WAREHOUSE_SOURCES_DATABASE_URL to point atthe Django test database, but the product migration only runs on the- dedicated warehouse_sources_queue DB. This fixture bridges the gap by- creating non-partitioned copies of the tables in the test DB.+ dedicated warehouse_sources_queue DB. This fixture bridges the gap with the+ queue suite's own DDL, so a column jobs_db starts writing can't reach these+ tests as a missing-column failure in an unrelated product suite."""with django_db_blocker.unblock():- from django.db import connection-- with connection.cursor() as cur:- cur.execute(f"""- CREATE TABLE IF NOT EXISTS {BATCH_TABLE} (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- team_id BIGINT NOT NULL,- schema_id VARCHAR(200) NOT NULL,- source_id VARCHAR(200) NOT NULL,- job_id VARCHAR(200) NOT NULL,- run_uuid VARCHAR(200) NOT NULL,- batch_index INT NOT NULL,- s3_path TEXT NOT NULL,- row_count INT NOT NULL,- byte_size BIGINT NOT NULL,- is_final_batch BOOLEAN NOT NULL,- total_batches INT,- total_rows BIGINT,- sync_type VARCHAR(32) NOT NULL,- cumulative_row_count BIGINT NOT NULL DEFAULT 0,- resource_name VARCHAR(400) NOT NULL,- is_resume BOOLEAN NOT NULL DEFAULT FALSE,- is_first_ever_sync BOOLEAN NOT NULL DEFAULT FALSE,- metadata JSONB NOT NULL DEFAULT '{{}}'::jsonb,- latest_state VARCHAR(32) NOT NULL DEFAULT 'pending',- latest_attempt SMALLINT NOT NULL DEFAULT 0,- state_changed_at TIMESTAMPTZ,- created_at TIMESTAMPTZ NOT NULL DEFAULT now()- )- """)- # Self-heal pre-existing test DBs where CREATE TABLE IF NOT EXISTS is a no-op.- cur.execute(f"""- ALTER TABLE {BATCH_TABLE}- ADD COLUMN IF NOT EXISTS latest_state VARCHAR(32) NOT NULL DEFAULT 'pending',- ADD COLUMN IF NOT EXISTS latest_attempt SMALLINT NOT NULL DEFAULT 0,- ADD COLUMN IF NOT EXISTS state_changed_at TIMESTAMPTZ- """)- cur.execute(f"""- CREATE TABLE IF NOT EXISTS {STATUS_TABLE} (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- batch_id UUID NOT NULL REFERENCES {BATCH_TABLE}(id) ON DELETE CASCADE,- job_state VARCHAR(32) NOT NULL,- attempt SMALLINT NOT NULL DEFAULT 0,- exec_time TIMESTAMPTZ,- error_response JSONB,- created_at TIMESTAMPTZ NOT NULL DEFAULT now()- )- """)- cur.execute(f"DROP VIEW IF EXISTS {STATUS_VIEW}")- cur.execute(f"""- CREATE VIEW {STATUS_VIEW} AS- SELECT DISTINCT ON (batch_id) *- FROM {STATUS_TABLE}- ORDER BY batch_id ASC, created_at DESC, id DESC- """)+ with psycopg.connect(_get_test_database_url(), autocommit=True) as conn:+ _ensure_tables(conn)@pytest.fixturediff --git a/products/warehouse_sources/backend/tests/management/test_backfill_warehouse_queue_state.py b/products/warehouse_sources/backend/tests/management/test_backfill_warehouse_queue_state.pyindex 1b4529e92604..e409029ff7f6 100644--- a/products/warehouse_sources/backend/tests/management/test_backfill_warehouse_queue_state.py+++ b/products/warehouse_sources/backend/tests/management/test_backfill_warehouse_queue_state.py@@ -136,3 +136,27 @@ class TestBackfillWarehouseQueueState:assert "Mismatched rows: 1" in outassert _columns(queue_conn, bid)[0] == "pending"++ def test_reconcile_backfills_superseded_flag_on_pre_flag_failed_rows(self, queue_conn):+ # The deploy plan depends on this: rows failed before the superseded+ # column existed read false, and get_failed_runs holds them back via a+ # per-row status re-check until reconcile stamps the flag.+ pre_flag = _insert_batch(queue_conn, batch_index=0)+ queue_conn.execute(+ f"INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, error_response, created_at) "+ "VALUES (%s, 'failed', 0, %s, now())",+ (pre_flag, '{"error": "superseded by newer attempt", "superseded": true}'),+ )+ # Pre-flag dual-writes set state_changed_at to exactly the status row's+ # created_at; a newer clock would (correctly) fail the monotonic guard.+ queue_conn.execute(+ f"UPDATE {BATCH_TABLE} SET latest_state = 'failed', "+ f"state_changed_at = (SELECT created_at FROM {STATUS_TABLE} WHERE batch_id = {BATCH_TABLE}.id) "+ "WHERE id = %s",+ (pre_flag,),+ )++ _run("reconcile", "--live-run")++ row = queue_conn.execute(f"SELECT superseded FROM {BATCH_TABLE} WHERE id = %s", (pre_flag,)).fetchone()+ assert row is not None and row[0] is Truediff --git a/products/warehouse_sources_queue/backend/migrations/0008_sourcebatch_superseded.py b/products/warehouse_sources_queue/backend/migrations/0008_sourcebatch_superseded.pynew file mode 100644index 000000000000..31190e3e445f--- /dev/null+++ b/products/warehouse_sources_queue/backend/migrations/0008_sourcebatch_superseded.py@@ -0,0 +1,161 @@+from django.db import migrations, models++import structlog++logger = structlog.get_logger(__name__)++INDEX_NAME = "sb_failed_changed_idx"+_INDEX_COLUMNS = "(state_changed_at)"+_INDEX_PREDICATE = "latest_state = 'failed'"++# Guarded with to_regclass so the migration no-ops on DBs without the sourcebatch+# table, following 0006. ADD COLUMN ... DEFAULT false is metadata-only on PG11+,+# but still takes a brief ACCESS EXCLUSIVE lock on the parent and every child —+# lock_timeout keeps a blocked attempt from queueing behind long claim queries+# (bin/migrate retries). The raw DEFAULT is load-bearing: producer INSERTs list+# their columns explicitly and never mention superseded.+#+# ON ONLY creates the parent index as metadata alone, leaving it invalid until+# every partition has a matching index attached. Building those per partition+# with CONCURRENTLY is the only way to add this index without locking writes out+# of the batch table for the length of the build: CONCURRENTLY is not supported+# on a partitioned parent, and a plain build there recurses into every partition+# under a lock that blocks the claim path this PR exists to protect.+_ADD_COLUMN_SQL = f"""+DO $$+BEGIN+ IF to_regclass('public.sourcebatch') IS NOT NULL THEN+ SET LOCAL lock_timeout = '5s';+ ALTER TABLE sourcebatch ADD COLUMN IF NOT EXISTS superseded boolean NOT NULL DEFAULT false;+ CREATE INDEX IF NOT EXISTS {INDEX_NAME}+ ON ONLY sourcebatch {_INDEX_COLUMNS}+ WHERE {_INDEX_PREDICATE};+ END IF;+END+$$;+"""++_DROP_COLUMN_SQL = """+DO $$+BEGIN+ IF to_regclass('public.sourcebatch') IS NOT NULL THEN+ SET LOCAL lock_timeout = '5s';+ ALTER TABLE sourcebatch DROP COLUMN IF EXISTS superseded;+ END IF;+END+$$;+"""++_PARTITIONS_SQL = """+ SELECT c.relname+ FROM pg_inherits i+ JOIN pg_class c ON c.oid = i.inhrelid+ WHERE i.inhparent = 'public.sourcebatch'::regclass+ ORDER BY c.relname+"""++# indisvalid is false while a CONCURRENTLY build is unfinished or was cancelled;+# the pg_inherits probe says whether the child index is already attached to the+# parent, which is what makes the whole loop re-runnable under bin/migrate retries.+_INDEX_STATE_SQL = """+ SELECT i.indisvalid, EXISTS (SELECT 1 FROM pg_inherits pi WHERE pi.inhrelid = c.oid)+ FROM pg_class c+ JOIN pg_index i ON i.indexrelid = c.oid+ WHERE c.relname = %s+"""+++def _sourcebatch_exists(schema_editor) -> bool:+ with schema_editor.connection.cursor() as cursor:+ cursor.execute("SELECT to_regclass('public.sourcebatch') IS NOT NULL")+ row = cursor.fetchone()+ return bool(row and row[0])+++def _partitions(schema_editor) -> list[str]:+ with schema_editor.connection.cursor() as cursor:+ cursor.execute(_PARTITIONS_SQL)+ return [row[0] for row in cursor.fetchall()]+++def _index_state(schema_editor, index_name: str) -> tuple[bool, bool]:+ """(exists_and_valid, attached_to_parent) for a per-partition index."""+ with schema_editor.connection.cursor() as cursor:+ cursor.execute(_INDEX_STATE_SQL, [index_name])+ row = cursor.fetchone()+ if row is None:+ return False, False+ return bool(row[0]), bool(row[1])+++def _disable_timeouts(schema_editor) -> None:+ # A cancelled CONCURRENTLY build leaves an invalid index that IF NOT EXISTS+ # would skip past on every retry, so these builds must not be interruptible.+ schema_editor.execute("SET lock_timeout = 0")+ schema_editor.execute("SET statement_timeout = 0")+++def _forward(apps, schema_editor):+ schema_editor.execute(_ADD_COLUMN_SQL)+ if not _sourcebatch_exists(schema_editor):+ return++ _disable_timeouts(schema_editor)+ for partition in _partitions(schema_editor):+ index_name = f"{partition}_{INDEX_NAME}"+ valid, attached = _index_state(schema_editor, index_name)+ if attached:+ continue+ if not valid:+ # Either absent, or an invalid leftover from an interrupted build.+ schema_editor.execute(f'DROP INDEX CONCURRENTLY IF EXISTS "{index_name}"')+ logger.info("sourcebatch_partition_index_build", partition=partition, index_name=index_name)+ schema_editor.execute(+ f'CREATE INDEX CONCURRENTLY IF NOT EXISTS "{index_name}" '+ f'ON "{partition}" {_INDEX_COLUMNS} WHERE {_INDEX_PREDICATE}'+ )+ # Attaching the last partition is what flips the parent index to valid.+ schema_editor.execute(f'ALTER INDEX {INDEX_NAME} ATTACH PARTITION "{index_name}"')+++def _reverse(apps, schema_editor):+ if _sourcebatch_exists(schema_editor):+ _disable_timeouts(schema_editor)+ # Dropping the parent takes every attached child with it; the loop then+ # clears children a partial forward run created but never attached.+ schema_editor.execute(f"DROP INDEX IF EXISTS {INDEX_NAME}")+ for partition in _partitions(schema_editor):+ schema_editor.execute(f'DROP INDEX CONCURRENTLY IF EXISTS "{partition}_{INDEX_NAME}"')+ schema_editor.execute(_DROP_COLUMN_SQL)+++class Migration(migrations.Migration):+ # CREATE INDEX CONCURRENTLY cannot run inside a transaction block.+ atomic = False++ dependencies = [+ ("warehouse_sources_queue", "0007_remove_duckgres_batch_sink_models"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AddField(+ model_name="sourcebatch",+ name="superseded",+ field=models.BooleanField(db_default=False, default=False),+ ),+ migrations.AddIndex(+ model_name="sourcebatch",+ index=models.Index(+ condition=models.Q(("latest_state", "failed")),+ fields=["state_changed_at"],+ name="sb_failed_changed_idx",+ ),+ ),+ ],+ database_operations=[+ migrations.RunPython(_forward, _reverse),+ ],+ ),+ ]diff --git a/products/warehouse_sources_queue/backend/migrations/max_migration.txt b/products/warehouse_sources_queue/backend/migrations/max_migration.txtindex d5830aa2f289..27a9b040337f 100644--- a/products/warehouse_sources_queue/backend/migrations/max_migration.txt+++ b/products/warehouse_sources_queue/backend/migrations/max_migration.txt@@ -1 +1 @@-0007_remove_duckgres_batch_sink_models+0008_sourcebatch_supersededdiff --git a/products/warehouse_sources_queue/backend/models.py b/products/warehouse_sources_queue/backend/models.pyindex d16276afca7c..021e9d11412c 100644--- a/products/warehouse_sources_queue/backend/models.py+++ b/products/warehouse_sources_queue/backend/models.py@@ -55,6 +55,11 @@ class SourceBatch(UUIDModel):latest_attempt = models.SmallIntegerField(default=0, db_default=0)# NULL means "never dual-written" — the backfill command's target marker.state_changed_at = models.DateTimeField(null=True, blank=True)+ # Denormalized from the failed status row's error payload ({"superseded": true},+ # written only by supersede_other_runs). Lets the reconcile sweep judge+ # candidacy from this table alone instead of a per-batch status lateral,+ # whose cost melted down under failure storms.+ superseded = models.BooleanField(default=False, db_default=False)created_at = models.DateTimeField(auto_now_add=True)@@ -81,6 +86,11 @@ class SourceBatch(UUIDModel):name="sb_schema_busy_idx",condition=models.Q(latest_state="executing"),),+ models.Index(+ fields=["state_changed_at"],+ name="sb_failed_changed_idx",+ condition=models.Q(latest_state="failed"),+ ),]