: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): only supersede v3 runs with no recent loader progress (#80568)
estefania93f1cb45cd7f
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 bb1e6c704ceb..d639b06e7174 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@@ -1049,13 +1049,43 @@ class BatchQueue:*,job_id: str,current_run_uuid: str,+ progress_stale_seconds: int = TAKEOVER_STALE_THRESHOLD_SECONDS,) -> int:- """Mark non-terminal batches from older runs of the same job as superseded."""+ """Mark non-terminal batches from *stalled* older runs of the same job as superseded.++ A run the loader is still working through is spared: any batch whose latest+ state is 'executing', 'succeeded', or 'waiting_retry' with ``state_changed_at``+ within ``progress_stale_seconds`` counts as loader progress. Superseding such a+ run destroys partially loaded work and, repeated on a timer, can re-enqueue a+ large table from zero forever while flooding the queue with failed rows. A run+ with no such write is genuinely stalled and still gets superseded, so dead runs+ recover here on the same clock as the stranded-run reconcile sweep.++ Progress is judged on active-state transitions only: 'pending'/'waiting' rows+ are producer output the loader never touched (superseding an unstarted backlog+ loses nothing, since this run re-enqueues equivalent data), and 'failed' is+ terminal. Heartbeats refresh only the status log, not ``state_changed_at``, so+ a wedged-but-heartbeating loader cannot keep a run unsupersedable forever.++ A spared run that stalls later is not re-checked here (this fires once, at the+ new run's first batch); the reconcile sweep's stranded-run pass owns that case.+ """cursor = conn.execute(- _bulk_fail_dual_write_sql("b.job_id = %(job_id)s AND b.run_uuid != %(current_run_uuid)s"),+ _bulk_fail_dual_write_sql(+ f"""b.job_id = %(job_id)s AND b.run_uuid != %(current_run_uuid)s+ AND NOT EXISTS (+ SELECT 1+ FROM {BATCH_TABLE} b_live+ WHERE b_live.run_uuid = b.run_uuid+ AND b_live.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND b_live.latest_state IN ('executing', 'succeeded', 'waiting_retry')+ AND b_live.state_changed_at > now() - make_interval(secs => %(progress_stale)s)+ )"""+ ),{"job_id": job_id,"current_run_uuid": current_run_uuid,+ "progress_stale": progress_stale_seconds,"error_response": json.dumps({"error": "superseded by newer attempt", "superseded": True}),},)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.pyindex ebc745ef3a89..f80b990869a0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py@@ -149,6 +149,10 @@ class PostgresProducer:metadata["workflow_run_id"] = self._workflow_run_idmetadata["timestamp_ns"] = batch_result.timestamp_ns+ # One-shot, at the start of a fresh (non-resume) run: stalled sibling runs of+ # this job go terminal so their batches can't double-load. Runs the loader is+ # still draining are spared (see supersede_other_runs); a spared run that+ # stalls later is recovered by the reconcile sweep's stranded-run pass.if batch_result.batch_index == 0 and not self._is_resume:superseded = BatchQueue.supersede_other_runs(self._conn, job_id=self._job_id, current_run_uuid=self._run_uuiddiff --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 07e86fb0f1d8..689c81c26612 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@@ -22,6 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineLEASE_TABLE,STATUS_TABLE,STATUS_VIEW,+ TAKEOVER_STALE_THRESHOLD_SECONDS,BatchQueue,PendingBatch,build_status_dual_write_sql,@@ -423,12 +424,12 @@ async def _lease_count(conn: psycopg.AsyncConnection[Any], *, team_id: int = 1,return int(row[0]) if row else 0-async def _insert_backdated_executing(- conn: psycopg.AsyncConnection[Any], *, batch_id: str, age_seconds: int = 120, attempt: int = 1+async def _write_backdated_status(+ conn: psycopg.AsyncConnection[Any], *, batch_id: str, job_state: str, age_seconds: int, attempt: int = 1) -> None:# Seed through the dual-write, then backdate both clocks, so the log and# the state columns stay consistent like they do under real writers.- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="executing", attempt=attempt)+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state=job_state, attempt=attempt)await conn.execute(f"UPDATE {STATUS_TABLE} SET created_at = created_at - make_interval(secs => %s) WHERE batch_id = %s",[age_seconds, batch_id],@@ -439,6 +440,14 @@ async def _insert_backdated_executing()+async def _insert_backdated_executing(+ conn: psycopg.AsyncConnection[Any], *, batch_id: str, age_seconds: int = 120, attempt: int = 1+) -> None:+ await _write_backdated_status(+ conn, batch_id=batch_id, job_state="executing", age_seconds=age_seconds, attempt=attempt+ )++async def _wait_until_a_backend_blocks_on_lock(probe: psycopg.AsyncConnection[Any], *, timeout: float = 5.0) -> None:"""Poll until some backend is parked waiting on a lock (the isolated test DBhas no other traffic, so this is the requeue blocking behind the owner)."""@@ -1191,6 +1200,7 @@ class TestStateDualWrite:@pytest.mark.asyncioasync def test_supersede_fails_columns_of_older_runs(self, conn, sync_conn):+ # The old run was never claimed, so superseding it loses no load progress.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")@@ -1200,6 +1210,51 @@ class TestStateDualWrite:assert (await _batch_state(conn, old))[0] == "failed"assert (await _batch_state(conn, current))[0] == "pending"+ @pytest.mark.parametrize(+ "job_state,age_seconds,expect_spared",+ [+ ("executing", 60, True),+ ("succeeded", 60, True),+ ("waiting_retry", 60, True),+ ("executing", TAKEOVER_STALE_THRESHOLD_SECONDS + 60, False),+ ("failed", 60, False),+ ],+ )+ @pytest.mark.asyncio+ async def test_supersede_spares_runs_with_recent_loader_progress(+ self, conn, sync_conn, job_state, age_seconds, expect_spared+ ):+ # Regression guard for the timer-fired supersede storm: a run the loader is+ # actively draining must not be failed by a newer attempt's first batch.+ signal = await _insert_batch(conn, batch_index=0, run_uuid="run-old", job_id="job-dw")+ sibling = await _insert_batch(conn, batch_index=1, run_uuid="run-old", job_id="job-dw")+ current = await _insert_batch(conn, batch_index=0, run_uuid="run-new", job_id="job-dw")+ await _write_backdated_status(conn, batch_id=signal, job_state=job_state, age_seconds=age_seconds)++ superseded = BatchQueue.supersede_other_runs(sync_conn, job_id="job-dw", current_run_uuid="run-new")++ if expect_spared:+ assert superseded == 0+ assert (await _batch_state(conn, sibling))[0] == "pending"+ else:+ assert superseded > 0+ assert (await _batch_state(conn, sibling))[0] == "failed"+ assert (await _batch_state(conn, current))[0] == "pending"++ @pytest.mark.asyncio+ async def test_supersede_judges_progress_per_run(self, conn, sync_conn):+ # One live run must not shield a stalled sibling run of the same job.+ live = await _insert_batch(conn, batch_index=0, run_uuid="run-live", job_id="job-dw")+ stalled = await _insert_batch(conn, batch_index=0, run_uuid="run-stalled", job_id="job-dw")+ await _insert_batch(conn, batch_index=0, run_uuid="run-new", job_id="job-dw")+ await _write_backdated_status(conn, batch_id=live, job_state="executing", age_seconds=60)++ superseded = BatchQueue.supersede_other_runs(sync_conn, job_id="job-dw", current_run_uuid="run-new")++ assert superseded == 1+ assert (await _batch_state(conn, live))[0] == "executing"+ assert (await _batch_state(conn, stalled))[0] == "failed"+@pytest.mark.asyncioasync 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