: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
feat(data-warehouse): denormalize v3 batch state onto sourcebatch (A1: schema + dual-writes + backfill) (#69010)
estefaniae8b887e2464d
diff --git a/products/warehouse_sources/backend/management/commands/backfill_warehouse_queue_state.py b/products/warehouse_sources/backend/management/commands/backfill_warehouse_queue_state.pynew file mode 100644index 000000000000..2755a049a622--- /dev/null+++ b/products/warehouse_sources/backend/management/commands/backfill_warehouse_queue_state.py@@ -0,0 +1,167 @@+"""Backfill and verify the denormalized state columns on sourcebatch.++The dual-write CTEs in jobs_db keep latest_state/latest_attempt/state_changed_at+in step with sourcebatchstatus for new writes; this command brings pre-existing+rows up to date (fill-missing), repairs drift (reconcile), and measures it+(audit). sourcebatchstatus is the source of truth throughout.+"""++from typing import Any++from django.core.management.base import BaseCommand, CommandError++import psycopg+import structlog++from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (+ BATCH_TABLE,+ PARTITION_PRUNING_INTERVAL,+ latest_status_lateral,+)++logger = structlog.get_logger(__name__)++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.+_TRUTH_SELECT = f"""+ SELECT+ b.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+ FROM {BATCH_TABLE} b+ {latest_status_lateral("b", "s")}+ WHERE b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+"""++FILL_MISSING_SQL = f"""+ WITH truth AS (+ {_TRUTH_SELECT}+ AND b.state_changed_at IS NULL+ LIMIT %(batch_size)s+ )+ UPDATE {BATCH_TABLE} b+ SET latest_state = t.expected_state,+ latest_attempt = t.expected_attempt,+ state_changed_at = t.expected_changed_at+ FROM truth t+ WHERE b.id = t.id+ AND b.created_at = t.created_at+ AND b.state_changed_at IS NULL+"""++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))+ LIMIT %(batch_size)s+ )+ UPDATE {BATCH_TABLE} b+ SET latest_state = t.expected_state,+ latest_attempt = t.expected_attempt,+ state_changed_at = t.expected_changed_at+ FROM truth t+ WHERE b.id = t.id+ AND b.created_at = t.created_at+ AND (b.latest_state, b.latest_attempt) IS DISTINCT FROM (t.expected_state, t.expected_attempt)+ AND (b.state_changed_at IS NULL OR b.state_changed_at <= t.expected_changed_at)+"""++AUDIT_SQL = f"""+ SELECT+ COALESCE(s.job_state, 'pending') AS expected_state,+ b.latest_state AS actual_state,+ count(*) AS mismatches+ 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))+ GROUP BY 1, 2+ ORDER BY 3 DESC+"""++COUNT_MISSING_SQL = f"""+ SELECT count(*) FROM {BATCH_TABLE} b+ WHERE b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND b.state_changed_at IS NULL+"""+++class Command(BaseCommand):+ help = (+ "Backfill (fill-missing), repair (reconcile), or measure (audit) the denormalized "+ "sourcebatch state columns against the sourcebatchstatus log. Writes need --live-run."+ )++ def add_arguments(self, parser):+ parser.add_argument("mode", choices=["fill-missing", "reconcile", "audit"])+ parser.add_argument("--live-run", action="store_true", help="Apply changes (default reports only)")+ parser.add_argument("--batch-size", type=int, default=DEFAULT_BATCH_SIZE)+ parser.add_argument(+ "--max-batches", type=int, default=0, help="Stop after N update batches (0 = run to completion)"+ )++ def handle(self, *args: Any, **options: Any) -> None:+ mode: str = options["mode"]+ with psycopg.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True) as conn:+ if mode == "audit":+ self._audit(conn)+ return+ if not options["live_run"]:+ self._dry_run_report(conn, mode)+ return+ self._run_updates(+ conn,+ mode=mode,+ sql=FILL_MISSING_SQL if mode == "fill-missing" else RECONCILE_SQL,+ batch_size=options["batch_size"],+ max_batches=options["max_batches"],+ )++ def _audit(self, conn: psycopg.Connection[Any]) -> None:+ rows = conn.execute(AUDIT_SQL).fetchall()+ total = sum(r[2] for r in rows)+ for expected, actual, count in rows:+ self.stdout.write(f" expected={expected} actual={actual}: {count}")+ missing = conn.execute(COUNT_MISSING_SQL).fetchone()+ self.stdout.write(+ f"Mismatched rows: {total}. Never dual-written (state_changed_at IS NULL): {missing[0] if missing else 0}."+ )++ def _dry_run_report(self, conn: psycopg.Connection[Any], mode: str) -> None:+ if mode == "fill-missing":+ row = conn.execute(COUNT_MISSING_SQL).fetchone()+ self.stdout.write(f"Would fill {row[0] if row else 0} row(s). Re-run with --live-run to apply.")+ return+ self._audit(conn)+ self.stdout.write("Re-run with --live-run to repair the mismatches above.")++ def _run_updates(+ self,+ conn: psycopg.Connection[Any],+ *,+ mode: str,+ sql: str,+ batch_size: int,+ max_batches: int,+ ) -> None:+ if batch_size <= 0:+ raise CommandError("--batch-size must be positive")+ total = 0+ batches = 0+ while True:+ updated = conn.execute(sql, {"batch_size": batch_size}).rowcount or 0+ total += updated+ batches += 1+ logger.info("backfill_warehouse_queue_state_batch", mode=mode, batch=batches, updated=updated)+ if updated < batch_size or (max_batches and batches >= max_batches):+ break+ self.stdout.write(self.style.SUCCESS(f"{mode}: updated {total} row(s) in {batches} batch(es)."))diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.pyindex 773e4adbdf04..8bc6a5d0bec5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py@@ -7,6 +7,7 @@ import asynciofrom collections import defaultdictfrom collections.abc import Callable, Coroutinefrom dataclasses import dataclass+from datetime import datetimefrom typing import Any, Protocolfrom uuid import uuid4@@ -155,6 +156,7 @@ class BatchConsumerAdapter(Protocol):job_state: str,attempt: int,error_response: dict[str, Any] | None = None,+ batch_created_at: datetime | None = None,) -> None: ...async def fail_run(@@ -636,6 +638,7 @@ class BatchConsumer:batch_id=batch.id,job_state=self._adapter.executing_state,attempt=attempt,+ batch_created_at=batch.created_at,)except Exception:return@@ -735,6 +738,7 @@ class BatchConsumer:batch_id=batch.id,job_state=self._adapter.executing_state,attempt=attempt,+ batch_created_at=batch.created_at,)if should_process:@@ -766,6 +770,7 @@ class BatchConsumer:batch_id=batch.id,job_state=self._adapter.succeeded_state,attempt=attempt,+ batch_created_at=batch.created_at,)self._metrics.batches_processed_total.labels(team_id=team_id, schema_id=schema_id, status="success").inc()logger.info(@@ -836,6 +841,7 @@ class BatchConsumer:job_state=self._adapter.waiting_retry_state,attempt=attempt,error_response={"error": str(err)[:1000]},+ batch_created_at=batch.created_at,)async def _fail_run(@@ -1034,6 +1040,7 @@ class BatchConsumer:job_state=self._adapter.waiting_retry_state,attempt=batch.latest_attempt,error_response={"error": "executing timed out - pod restart or OOM"},+ batch_created_at=batch.created_at,)finally:structlog.contextvars.unbind_contextvars(*recovery_bound_keys)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_queue.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_queue.pyindex 6fc67103de36..89a5d67ab9aa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_queue.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_queue.py@@ -167,12 +167,14 @@ def enqueue_chunks(id, team_id, schema_id, source_id, job_id, run_uuid,batch_index, s3_path, row_count, byte_size, is_final_batch,total_batches, total_rows, sync_type, cumulative_row_count,- resource_name, is_resume, is_first_ever_sync, metadata+ resource_name, is_resume, is_first_ever_sync, metadata,+ latest_state, latest_attempt, state_changed_at) VALUES (%(id)s, %(team_id)s, %(schema_id)s, %(source_id)s, %(job_id)s, %(run_uuid)s,%(batch_index)s, %(s3_path)s, %(row_count)s, %(byte_size)s, false,%(total_batches)s, NULL, 'full_refresh', 0,- %(resource_name)s, true, false, %(metadata)s+ %(resource_name)s, true, false, %(metadata)s,+ 'succeeded', 1, now())""",{diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.pyindex e57dfdfb9a0d..c0b4d9548747 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport timefrom collections.abc import Callable+from datetime import datetimefrom typing import Anyimport psycopg@@ -255,6 +256,7 @@ class DuckgresBatchConsumerAdapter:job_state: str,attempt: int,error_response: dict[str, Any] | None = None,+ batch_created_at: datetime | None = None, # delta-sink denormalization only; unused here) -> None:# Invariant: never write ANY status over a terminal 'failed' — statuses# are latest-row-wins, so an unconditional write would un-retire a batchdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.pyindex 889965a45ebd..532e729cdce7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py@@ -51,9 +51,19 @@ def _ensure_tables(conn: psycopg.Connection[Any]) -> None: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.+ conn.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+ """)conn.execute(f"""CREATE TABLE IF NOT EXISTS {STATUS_TABLE} (id UUID PRIMARY KEY DEFAULT gen_random_uuid(),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 6ccfcdc49ec2..7d0c4ea6e908 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@@ -9,6 +9,7 @@ from __future__ import annotationsimport asynciofrom collections.abc import Callable+from datetime import datetimefrom typing import Anyfrom django.db import close_old_connections@@ -114,22 +115,15 @@ class DeltaBatchConsumerAdapter:job_state: str,attempt: int,error_response: dict[str, Any] | None = None,+ batch_created_at: datetime | None = None,) -> None:- if error_response is None:- await BatchQueue.update_status(- conn,- batch_id=batch_id,- job_state=job_state,- attempt=attempt,- )- return-await BatchQueue.update_status(conn,batch_id=batch_id,job_state=job_state,attempt=attempt,error_response=error_response,+ batch_created_at=batch_created_at,)async def fail_run(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 829a622a76f1..2121a416b79d 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@@ -96,18 +96,75 @@ def pending_batch_predicate(status_alias: str) -> str:return f"({status_alias}.batch_id IS NULL OR {status_alias}.job_state IN ('waiting', 'waiting_retry', 'executing'))"+def build_status_dual_write_sql(*, with_batch_created_at: bool) -> str:+ """Single-statement status INSERT + denormalized-state UPDATE (atomic under autocommit).++ The UPDATE guards: exact ``created_at`` match prunes to one partition when the+ caller knows it (PendingBatch always does; the window fallback keeps ad-hoc+ callers bounded); the ``IS DISTINCT FROM`` check makes heartbeat re-inserts a+ 0-row no-op so they never churn the batch heap; the monotonic+ ``state_changed_at`` check makes cross-connection races converge to the status+ row with the greatest ``created_at`` — the same answer the latest-status+ lateral gives.+ """+ created_at_predicate = (+ "b.created_at = %(batch_created_at)s"+ if with_batch_created_at+ else f"b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'"+ )+ return f"""+ 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+ )+ UPDATE {BATCH_TABLE} b+ SET latest_state = ins.job_state, latest_attempt = ins.attempt, state_changed_at = ins.created_at+ FROM ins+ WHERE b.id = ins.batch_id+ AND {created_at_predicate}+ AND ((b.latest_state, b.latest_attempt) IS DISTINCT FROM (ins.job_state, ins.attempt)+ OR b.state_changed_at IS NULL)+ AND (b.state_changed_at IS NULL OR b.state_changed_at <= ins.created_at)+ """+++def _bulk_fail_dual_write_sql(where_sql: str) -> str:+ """Bulk 'failed' status inserts plus the denormalized-state UPDATE, one statement.++ ``targets`` carries ``(id, created_at)`` so the UPDATE join prunes partitions+ exactly; rowcount reports updated batches (== inserted statuses, minus any a+ concurrent newer write already superseded via the monotonic guard).+ """+ return f"""+ WITH targets AS (+ SELECT b.id, b.created_at+ FROM {BATCH_TABLE} b+ {latest_status_lateral("b", "s")}+ WHERE+ b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND {where_sql}+ AND {pending_batch_predicate("s")}+ ),+ ins AS (+ INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)+ SELECT t.id, 'failed', 0, now(), %(error_response)s, now()+ FROM targets t+ RETURNING batch_id, created_at+ )+ UPDATE {BATCH_TABLE} b+ SET latest_state = 'failed', latest_attempt = 0, state_changed_at = ins.created_at+ FROM ins+ JOIN targets t ON t.id = ins.batch_id+ WHERE b.id = t.id+ AND b.created_at = t.created_at+ AND (b.state_changed_at IS NULL OR b.state_changed_at <= ins.created_at)+ """++# Shared between the async consumer path and the sync ops command so both agree# on what counts as a pending (fail-able) batch.-FAIL_RUN_SQL = f"""- INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)- SELECT b.id, 'failed', 0, now(), %(error_response)s, now()- FROM {BATCH_TABLE} b- {latest_status_lateral("b", "s")}- WHERE- b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND b.run_uuid = %(run_uuid)s- AND {pending_batch_predicate("s")}-"""+FAIL_RUN_SQL = _bulk_fail_dual_write_sql("b.run_uuid = %(run_uuid)s")def _stale_executing_sql(scope_sql: str = "") -> str:@@ -495,19 +552,24 @@ class BatchQueue:job_state: str,attempt: int = 0,error_response: dict[str, Any] | None = None,+ batch_created_at: datetime | None = None,) -> None:- """Append a status row for a batch (executing, succeeded, waiting_retry, failed)."""+ """Append a status row and mirror it into the batch's denormalized state columns.++ ``batch_created_at`` (from PendingBatch) prunes the state UPDATE to one+ partition; without it the update falls back to the retention-window scan.+ """+ params: dict[str, Any] = {+ "batch_id": batch_id,+ "job_state": job_state,+ "attempt": attempt,+ "error_response": json.dumps(error_response) if error_response else None,+ }+ if batch_created_at is not None:+ params["batch_created_at"] = batch_created_atawait conn.execute(- f"""- 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())- """,- {- "batch_id": batch_id,- "job_state": job_state,- "attempt": attempt,- "error_response": json.dumps(error_response) if error_response else None,- },+ build_status_dual_write_sql(with_batch_created_at=batch_created_at is not None),+ params,)@staticmethod@@ -634,16 +696,7 @@ class BatchQueue:newer data or flip the FAILED job back to COMPLETED via the final batch."""cursor = conn.execute(- f"""- INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)- SELECT b.id, 'failed', 0, now(), %(error_response)s, now()- FROM {BATCH_TABLE} b- {latest_status_lateral("b", "s")}- WHERE- b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND b.job_id = %(job_id)s- AND (s.batch_id IS NULL OR s.job_state IN ('waiting', 'waiting_retry', 'executing'))- """,+ _bulk_fail_dual_write_sql("b.job_id = %(job_id)s"),{"job_id": job_id,"error_response": json.dumps({"error": reason}),@@ -660,17 +713,7 @@ class BatchQueue:) -> int:"""Mark non-terminal batches from older runs of the same job as superseded."""cursor = conn.execute(- f"""- INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)- SELECT b.id, 'failed', 0, now(), %(error_response)s, now()- FROM {BATCH_TABLE} b- {latest_status_lateral("b", "s")}- WHERE- b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND b.job_id = %(job_id)s- AND b.run_uuid != %(current_run_uuid)s- AND (s.batch_id IS NULL OR s.job_state IN ('waiting', 'waiting_retry', 'executing'))- """,+ _bulk_fail_dual_write_sql("b.job_id = %(job_id)s AND b.run_uuid != %(current_run_uuid)s"),{"job_id": job_id,"current_run_uuid": current_run_uuid,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 1381d7b6ff34..0e9137d350ac 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@@ -107,7 +107,7 @@ class TestProcessSingle:batch = _make_batch(latest_attempt=0)states: list[str] = []- async def track_status(conn, *, batch_id, job_state, attempt, error_response=None):+ async def track_status(conn, *, batch_id, job_state, attempt, error_response=None, batch_created_at=None):states.append(job_state)consumer._process_batch = AsyncMock()@@ -125,7 +125,7 @@ class TestProcessSingle:batch = _make_batch(latest_attempt=0)states: list[str] = []- async def track_status(conn, *, batch_id, job_state, attempt, error_response=None):+ async def track_status(conn, *, batch_id, job_state, attempt, error_response=None, batch_created_at=None):states.append(job_state)consumer._process_batch = AsyncMock(side_effect=ValueError("boom"))@@ -379,6 +379,7 @@ class TestRecoverySweep:job_state=SourceBatchStatus.State.WAITING_RETRY,attempt=1,error_response={"error": "executing timed out - pod restart or OOM"},+ batch_created_at=stale_batch.created_at,)mock_unlock.assert_called_once_with(consumer._recovery_conn, batches=[stale_batch], owner_token=consumer._owner_tokendiff --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 c1038d92337b..114882fcaca4 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@@ -58,9 +58,31 @@ def _ensure_tables(conn: psycopg.Connection[Any]) -> None: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.+ conn.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+ """)+ conn.execute(f"""+ CREATE INDEX IF NOT EXISTS sb_claimable_idx ON {BATCH_TABLE} (team_id, created_at, batch_index)+ WHERE latest_state IN ('pending', 'waiting_retry')+ """)+ conn.execute(f"""+ CREATE INDEX IF NOT EXISTS sb_run_gate_idx ON {BATCH_TABLE} (run_uuid, latest_state, batch_index)+ WHERE latest_state IN ('executing', 'waiting_retry', 'failed')+ """)+ conn.execute(f"""+ CREATE INDEX IF NOT EXISTS sb_schema_busy_idx ON {BATCH_TABLE} (team_id, schema_id)+ WHERE latest_state = 'executing'+ """)conn.execute(f"""CREATE TABLE IF NOT EXISTS {STATUS_TABLE} (id UUID PRIMARY KEY DEFAULT gen_random_uuid(),@@ -818,3 +840,104 @@ class TestCountBatchesForRun:assert BatchQueue.count_batches_for_run(sync_conn, job_id="job-A") == 2assert BatchQueue.count_batches_for_run(sync_conn, job_id="job-B") == 1assert BatchQueue.count_batches_for_run(sync_conn, job_id="job-missing") == 0+++async def _batch_state(conn: psycopg.AsyncConnection[Any], batch_id: str) -> tuple[str, int, Any]:+ cur = await conn.execute(+ f"SELECT latest_state, latest_attempt, state_changed_at FROM {BATCH_TABLE} WHERE id = %s",+ (batch_id,),+ )+ row = await cur.fetchone()+ assert row is not None+ return row[0], row[1], row[2]++[email protected]_db(transaction=True)+class TestStateDualWrite:+ """The denormalized columns must always mirror the latest status row — the+ A2 claim path reads only the columns, so silent drift breaks claiming."""++ @pytest.mark.parametrize(+ "sequence,expected_state,expected_attempt",+ [+ ([("executing", 1)], "executing", 1),+ ([("executing", 1), ("succeeded", 1)], "succeeded", 1),+ ([("executing", 1), ("waiting_retry", 1), ("executing", 2), ("failed", 2)], "failed", 2),+ ],+ )+ @pytest.mark.asyncio+ async def test_update_status_mirrors_latest_into_columns(self, conn, sequence, expected_state, expected_attempt):+ bid = await _insert_batch(conn)+ state, attempt, changed = await _batch_state(conn, bid)+ assert (state, attempt, changed) == ("pending", 0, None)++ for job_state, attempt_n in sequence:+ await BatchQueue.update_status(conn, batch_id=bid, job_state=job_state, attempt=attempt_n)++ state, attempt, changed = await _batch_state(conn, bid)+ assert (state, attempt) == (expected_state, expected_attempt)+ assert changed is not None++ @pytest.mark.asyncio+ async def test_update_status_with_batch_created_at_matches_row(self, conn):+ bid = await _insert_batch(conn)+ cur = await conn.execute(f"SELECT created_at FROM {BATCH_TABLE} WHERE id = %s", (bid,))+ row = await cur.fetchone()+ assert row is not None++ await BatchQueue.update_status(conn, batch_id=bid, job_state="executing", attempt=1, batch_created_at=row[0])++ state, attempt, _ = await _batch_state(conn, bid)+ assert (state, attempt) == ("executing", 1)++ @pytest.mark.asyncio+ async def test_heartbeat_reinsert_does_not_touch_the_columns(self, conn):+ # Heartbeats re-insert 'executing' every ~100s; if they updated the batch+ # heap the columns would churn/bloat exactly when the fleet is busiest.+ bid = await _insert_batch(conn)+ await BatchQueue.update_status(conn, batch_id=bid, job_state="executing", attempt=1)+ _, _, first_changed = await _batch_state(conn, bid)++ await BatchQueue.update_status(conn, batch_id=bid, job_state="executing", attempt=1)++ _, _, second_changed = await _batch_state(conn, bid)+ assert second_changed == first_changed+ cur = await conn.execute(f"SELECT count(*) FROM {STATUS_TABLE} WHERE batch_id = %s", (bid,))+ row = await cur.fetchone()+ assert row is not None and row[0] == 2 # the log still grows++ @pytest.mark.asyncio+ async def test_fail_run_fails_columns_of_pending_batches_only(self, conn):+ pending = await _insert_batch(conn, batch_index=0, run_uuid="run-dw")+ 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")++ assert failed == 1+ assert (await _batch_state(conn, pending))[0] == "failed"+ assert (await _batch_state(conn, done))[0] == "succeeded"++ @pytest.mark.asyncio+ async def test_supersede_fails_columns_of_older_runs(self, conn, sync_conn):+ old = await _insert_batch(conn, run_uuid="run-old", job_id="job-dw")+ current = await _insert_batch(conn, run_uuid="run-new", job_id="job-dw")++ superseded = BatchQueue.supersede_other_runs(sync_conn, job_id="job-dw", current_run_uuid="run-new")++ assert superseded == 1+ assert (await _batch_state(conn, old))[0] == "failed"+ assert (await _batch_state(conn, current))[0] == "pending"++ @pytest.mark.asyncio+ async def test_fail_batches_for_job_fails_columns_across_runs(self, conn, sync_conn):+ # The takeover path writes through this site; drift here leaves stale+ # claimable columns exactly when a job was force-failed.+ first = await _insert_batch(conn, batch_index=0, run_uuid="run-tk1", job_id="job-tk")+ second = await _insert_batch(conn, batch_index=1, run_uuid="run-tk2", job_id="job-tk")++ failed = BatchQueue.fail_batches_for_job_sync(sync_conn, job_id="job-tk", reason="takeover")++ assert failed == 2+ assert (await _batch_state(conn, first))[0] == "failed"+ assert (await _batch_state(conn, second))[0] == "failed"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 fe2c0d42e666..df1326838074 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@@ -80,9 +80,19 @@ def _ensure_sourcebatch_tables(django_db_setup, django_db_blocker):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(),diff --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.pynew file mode 100644index 000000000000..1b4529e92604--- /dev/null+++ b/products/warehouse_sources/backend/tests/management/test_backfill_warehouse_queue_state.py@@ -0,0 +1,138 @@+from collections.abc import Generator+from io import StringIO+from typing import Any++import pytest+from unittest.mock import patch++from django.core.management import call_command++import psycopg++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (+ BATCH_TABLE,+ STATUS_TABLE,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.test_jobs_db import (+ _BATCH_DEFAULTS,+ _ensure_tables,+ _get_test_database_url,+ _truncate_tables,+)++pytestmark = [pytest.mark.django_db]++COMMAND_MODULE = "products.warehouse_sources.backend.management.commands.backfill_warehouse_queue_state"+++def queue_conn() -> Generator[psycopg.Connection[Any]]:+ url = _get_test_database_url()+ with psycopg.connect(url, autocommit=True) as conn:+ _ensure_tables(conn)+ _truncate_tables(conn)+ with patch(f"{COMMAND_MODULE}.WAREHOUSE_SOURCES_DATABASE_URL", url):+ yield conn+++def _insert_batch(conn: psycopg.Connection[Any], **overrides: Any) -> str:+ import json++ params = {**_BATCH_DEFAULTS, **overrides}+ params["metadata"] = json.dumps(params["metadata"])+ row = conn.execute(+ f"""+ INSERT INTO {BATCH_TABLE} (+ id, team_id, schema_id, source_id, job_id, run_uuid, batch_index, s3_path,+ row_count, byte_size, is_final_batch, total_batches, total_rows, sync_type,+ cumulative_row_count, resource_name, is_resume, is_first_ever_sync, metadata, created_at+ ) VALUES (+ gen_random_uuid(), %(team_id)s, %(schema_id)s, %(source_id)s, %(job_id)s, %(run_uuid)s,+ %(batch_index)s, %(s3_path)s, %(row_count)s, %(byte_size)s, %(is_final_batch)s,+ %(total_batches)s, %(total_rows)s, %(sync_type)s, %(cumulative_row_count)s,+ %(resource_name)s, %(is_resume)s, %(is_first_ever_sync)s, %(metadata)s, now()+ ) RETURNING id+ """,+ params,+ ).fetchone()+ assert row is not None+ return str(row[0])+++def _insert_raw_status(conn: psycopg.Connection[Any], batch_id: str, state: str, attempt: int = 1) -> None:+ # Deliberately NOT the dual-write: simulates a pre-dual-write pod appending+ # status rows the columns don't reflect.+ conn.execute(+ f"INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, created_at) VALUES (%s, %s, %s, now())",+ (batch_id, state, attempt),+ )+++def _columns(conn: psycopg.Connection[Any], batch_id: str) -> tuple[str, int, Any]:+ row = conn.execute(+ f"SELECT latest_state, latest_attempt, state_changed_at FROM {BATCH_TABLE} WHERE id = %s",+ (batch_id,),+ ).fetchone()+ assert row is not None+ return row[0], row[1], row[2]+++def _run(mode: str, *args: str) -> str:+ out = StringIO()+ call_command("backfill_warehouse_queue_state", mode, *args, stdout=out)+ return out.getvalue()+++class TestBackfillWarehouseQueueState:+ def test_fill_missing_derives_columns_from_status_log(self, queue_conn):+ drifted = _insert_batch(queue_conn, batch_index=0)+ _insert_raw_status(queue_conn, drifted, "succeeded")+ never_claimed = _insert_batch(queue_conn, batch_index=1)++ _run("fill-missing", "--live-run")++ state, attempt, changed = _columns(queue_conn, drifted)+ assert (state, attempt) == ("succeeded", 1)+ assert changed is not None+ state, _, changed = _columns(queue_conn, never_claimed)+ assert state == "pending"+ assert changed is not None # visited marker set so the row leaves the backlog++ def test_fill_missing_dry_run_writes_nothing(self, queue_conn):+ bid = _insert_batch(queue_conn)+ _insert_raw_status(queue_conn, bid, "failed")++ out = _run("fill-missing")++ assert "Would fill 1" in out+ assert _columns(queue_conn, bid)[0] == "pending"++ def test_reconcile_fixes_drift_but_respects_newer_dual_writes(self, queue_conn):+ # Drifted: columns stale relative to the log.+ drifted = _insert_batch(queue_conn, batch_index=0)+ _insert_raw_status(queue_conn, drifted, "failed")+ queue_conn.execute(+ f"UPDATE {BATCH_TABLE} SET latest_state = 'executing', state_changed_at = now() - interval '1 hour' WHERE id = %s",+ (drifted,),+ )+ # Newer-than-log columns (a dual-write that raced ahead) must not regress.+ ahead = _insert_batch(queue_conn, batch_index=1)+ _insert_raw_status(queue_conn, ahead, "executing")+ queue_conn.execute(+ f"UPDATE {BATCH_TABLE} SET latest_state = 'succeeded', latest_attempt = 1, state_changed_at = now() + interval '1 minute' WHERE id = %s",+ (ahead,),+ )++ _run("reconcile", "--live-run")++ assert _columns(queue_conn, drifted)[0] == "failed"+ assert _columns(queue_conn, ahead)[0] == "succeeded"++ def test_audit_counts_mismatches_without_writing(self, queue_conn):+ bid = _insert_batch(queue_conn)+ _insert_raw_status(queue_conn, bid, "succeeded")++ out = _run("audit")++ assert "Mismatched rows: 1" in out+ assert _columns(queue_conn, bid)[0] == "pending"diff --git a/products/warehouse_sources_queue/backend/migrations/0006_sourcebatch_latest_state.py b/products/warehouse_sources_queue/backend/migrations/0006_sourcebatch_latest_state.pynew file mode 100644index 000000000000..f052542e7aa1--- /dev/null+++ b/products/warehouse_sources_queue/backend/migrations/0006_sourcebatch_latest_state.py@@ -0,0 +1,131 @@+from django.db import migrations, models++# Guarded with to_regclass so the migration no-ops on DBs without the sourcebatch+# table. ADD COLUMN ... DEFAULT is metadata-only on PG11+, but it 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).+# Partial indexes on the parent propagate to all children; plain (non-concurrent)+# creation follows this app's 0002 precedent and the queue's current low volume.+# The per-child autovacuum tuning keeps the partial indexes from bloating once the+# dual-writes turn state flips into in-place updates.+_FORWARD_SQL = """+DO $$+DECLARE+ part text;+BEGIN+ IF to_regclass('public.sourcebatch') IS NOT NULL THEN+ SET LOCAL lock_timeout = '5s';+ ALTER TABLE sourcebatch ADD COLUMN IF NOT EXISTS latest_state varchar(32) NOT NULL DEFAULT 'pending';+ ALTER TABLE sourcebatch ADD COLUMN IF NOT EXISTS latest_attempt smallint NOT NULL DEFAULT 0;+ ALTER TABLE sourcebatch ADD COLUMN IF NOT EXISTS state_changed_at timestamptz NULL;+ CREATE INDEX IF NOT EXISTS sb_claimable_idx+ ON sourcebatch (team_id, created_at, batch_index)+ WHERE latest_state IN ('pending', 'waiting_retry');+ CREATE INDEX IF NOT EXISTS sb_run_gate_idx+ ON sourcebatch (run_uuid, latest_state, batch_index)+ WHERE latest_state IN ('executing', 'waiting_retry', 'failed');+ CREATE INDEX IF NOT EXISTS sb_schema_busy_idx+ ON sourcebatch (team_id, schema_id)+ WHERE latest_state = 'executing';+ FOR part IN+ SELECT inhrelid::regclass::text FROM pg_inherits WHERE inhparent = 'sourcebatch'::regclass+ LOOP+ -- Concatenation, not format(): psycopg scans this whole script for+ -- placeholders, so no percent sign may appear anywhere in it.+ EXECUTE 'ALTER TABLE ' || part+ || ' SET (autovacuum_vacuum_scale_factor = 0.02, autovacuum_analyze_scale_factor = 0.02)';+ END LOOP;+ END IF;+END+$$;+"""++_REVERSE_SQL = """+DO $$+BEGIN+ IF to_regclass('public.sourcebatch') IS NOT NULL THEN+ DROP INDEX IF EXISTS sb_claimable_idx;+ DROP INDEX IF EXISTS sb_run_gate_idx;+ DROP INDEX IF EXISTS sb_schema_busy_idx;+ ALTER TABLE sourcebatch DROP COLUMN IF EXISTS latest_state;+ ALTER TABLE sourcebatch DROP COLUMN IF EXISTS latest_attempt;+ ALTER TABLE sourcebatch DROP COLUMN IF EXISTS state_changed_at;+ END IF;+END+$$;+"""+++def _forward(apps, schema_editor):+ schema_editor.execute(_FORWARD_SQL)+++def _reverse(apps, schema_editor):+ schema_editor.execute(_REVERSE_SQL)+++class Migration(migrations.Migration):+ dependencies = [+ ("warehouse_sources_queue", "0005_duckgres_group_lease"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AddField(+ model_name="sourcebatch",+ name="latest_state",+ field=models.CharField(+ choices=[+ ("pending", "pending"),+ ("waiting", "waiting"),+ ("executing", "executing"),+ ("succeeded", "succeeded"),+ ("waiting_retry", "waiting_retry"),+ ("failed", "failed"),+ ],+ db_default="pending",+ default="pending",+ max_length=32,+ ),+ ),+ migrations.AddField(+ model_name="sourcebatch",+ name="latest_attempt",+ field=models.SmallIntegerField(db_default=0, default=0),+ ),+ migrations.AddField(+ model_name="sourcebatch",+ name="state_changed_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ migrations.AddIndex(+ model_name="sourcebatch",+ index=models.Index(+ condition=models.Q(("latest_state__in", ["pending", "waiting_retry"])),+ fields=["team_id", "created_at", "batch_index"],+ name="sb_claimable_idx",+ ),+ ),+ migrations.AddIndex(+ model_name="sourcebatch",+ index=models.Index(+ condition=models.Q(("latest_state__in", ["executing", "waiting_retry", "failed"])),+ fields=["run_uuid", "latest_state", "batch_index"],+ name="sb_run_gate_idx",+ ),+ ),+ migrations.AddIndex(+ model_name="sourcebatch",+ index=models.Index(+ condition=models.Q(("latest_state", "executing")),+ fields=["team_id", "schema_id"],+ name="sb_schema_busy_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 0daddc644d82..0568b7205b5c 100644--- a/products/warehouse_sources_queue/backend/migrations/max_migration.txt+++ b/products/warehouse_sources_queue/backend/migrations/max_migration.txt@@ -1 +1 @@-0005_duckgres_group_lease+0006_sourcebatch_latest_statediff --git a/products/warehouse_sources_queue/backend/models.py b/products/warehouse_sources_queue/backend/models.pyindex 24815cab944a..9d471d4ee4fb 100644--- a/products/warehouse_sources_queue/backend/models.py+++ b/products/warehouse_sources_queue/backend/models.py@@ -11,6 +11,16 @@ class SourceBatch(UUIDModel):APPEND = "append", "append"CDC = "cdc", "cdc"+ class LatestState(models.TextChoices):+ # 'pending' means "no status row yet" — deliberately distinct from+ # SourceBatchStatus.State.WAITING, which claim semantics treat differently.+ PENDING = "pending", "pending"+ WAITING = "waiting", "waiting"+ EXECUTING = "executing", "executing"+ SUCCEEDED = "succeeded", "succeeded"+ WAITING_RETRY = "waiting_retry", "waiting_retry"+ FAILED = "failed", "failed"+team_id = models.BigIntegerField()schema_id = models.CharField(max_length=200)source_id = models.CharField(max_length=200)@@ -37,6 +47,16 @@ class SourceBatch(UUIDModel):help_text="Stores partitioning config, CDC mode, primary keys, schema path, data folder, etc.",)+ # Denormalized mirror of the latest sourcebatchstatus row, maintained by the+ # dual-write CTEs in jobs_db so hot readers don't re-derive state from the+ # append-only log. sourcebatchstatus remains the source of truth.+ latest_state = models.CharField(+ max_length=32, choices=LatestState.choices, default=LatestState.PENDING, db_default="pending"+ )+ 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)+created_at = models.DateTimeField(auto_now_add=True)__repr__ = sane_repr("id", "team_id", "schema_id", "batch_index")@@ -47,6 +67,21 @@ class SourceBatch(UUIDModel):models.Index(fields=["team_id", "schema_id"], name="sb_team_schema_idx"),models.Index(fields=["run_uuid"], name="sb_run_uuid_idx"),models.Index(fields=["run_uuid", "batch_index"], name="sb_run_uuid_bi_idx"),+ models.Index(+ fields=["team_id", "created_at", "batch_index"],+ name="sb_claimable_idx",+ condition=models.Q(latest_state__in=["pending", "waiting_retry"]),+ ),+ models.Index(+ fields=["run_uuid", "latest_state", "batch_index"],+ name="sb_run_gate_idx",+ condition=models.Q(latest_state__in=["executing", "waiting_retry", "failed"]),+ ),+ models.Index(+ fields=["team_id", "schema_id"],+ name="sb_schema_busy_idx",+ condition=models.Q(latest_state="executing"),+ ),]