Skip to content

: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.

fix(data-warehouse): stop sparing runs a full refresh is about to overwrite (#106863)

Tom Owers3dd4b537acce
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.py
index 504b1df7222b..c17f540519ed 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
@@ -1219,6 +1219,7 @@ class BatchQueue:
job_id: str,
current_run_uuid: str,
progress_stale_seconds: int = TAKEOVER_STALE_THRESHOLD_SECONDS,
+ spare_runs_with_progress: bool = True,
) -> int:
"""Mark non-terminal batches from *stalled* older runs of the same job as superseded.
@@ -1238,11 +1239,19 @@ class BatchQueue:
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.
+
+ ``spare_runs_with_progress=False`` drops the sparing rule. Pass it when the
+ incoming run overwrites the table regardless, which is a fresh non-resume
+ ``full_refresh``: its batch 0 writes with ``mode="overwrite"`` (``should_overwrite_table``
+ in ``load/processor.py``, applied in the full_refresh branch of ``core/delta/writer.py``),
+ so every row an older attempt loaded is discarded the moment this run starts. Sparing
+ those runs protects nothing, and leaves their batches to drain through the serial
+ per-(team, schema) gate — holding the queue head for hours to write data that has
+ already been thrown away. Incremental and CDC keep the sparing rule, because their
+ partially merged work survives into the new run.
"""
- cursor = conn.execute(
- _bulk_fail_dual_write_sql(
- f"""b.job_id = %(job_id)s AND b.run_uuid != %(current_run_uuid)s
- AND NOT EXISTS (
+ progress_guard = (
+ f"""AND NOT EXISTS (
SELECT 1
FROM {BATCH_TABLE} b_live
WHERE b_live.run_uuid = b.run_uuid
@@ -1250,6 +1259,13 @@ class BatchQueue:
AND b_live.latest_state IN ('executing', 'succeeded', 'waiting_retry')
AND b_live.state_changed_at > now() - make_interval(secs => %(progress_stale)s)
)"""
+ if spare_runs_with_progress
+ else ""
+ )
+ cursor = conn.execute(
+ _bulk_fail_dual_write_sql(
+ f"""b.job_id = %(job_id)s AND b.run_uuid != %(current_run_uuid)s
+ {progress_guard}"""
),
{
"job_id": job_id,
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.py
index a055986e7171..b6622cf43e1b 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
@@ -155,9 +155,16 @@ class PostgresProducer:
# 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.
+ #
+ # A full_refresh is the exception: this run's batch 0 overwrites the table, so
+ # an older attempt's loaded rows are gone either way and sparing it only leaves
+ # its batches clogging the serial per-(team, schema) gate.
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_uuid
+ self._conn,
+ job_id=self._job_id,
+ current_run_uuid=self._run_uuid,
+ spare_runs_with_progress=self._sync_type != "full_refresh",
)
if superseded > 0:
self._logger.info("superseded_old_run_batches", count=superseded)
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.py
index 5b53572cd333..541d734c47f1 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
@@ -1466,6 +1466,25 @@ class TestStateDualWrite:
assert (await _batch_state(conn, sibling))[0] == "failed"
assert (await _batch_state(conn, current))[0] == "pending"
+ @pytest.mark.parametrize("spare,expected_state", [(True, "pending"), (False, "failed")])
+ @pytest.mark.asyncio
+ async def test_supersede_can_drop_the_progress_guard(self, conn, sync_conn, spare, expected_state):
+ # A fresh full_refresh overwrites the table on its batch 0, so an older run's loaded rows
+ # are discarded no matter what. Sparing it there only leaves its batches draining through
+ # the serial per-(team, schema) gate to write data that is already gone.
+ 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="succeeded", age_seconds=60)
+
+ superseded = BatchQueue.supersede_other_runs(
+ sync_conn, job_id="job-dw", current_run_uuid="run-new", spare_runs_with_progress=spare
+ )
+
+ assert (superseded == 0) is spare
+ assert (await _batch_state(conn, sibling))[0] == expected_state
+ 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.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py
index 8f511edefd64..616fca2e742e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py
@@ -173,7 +173,31 @@ class TestPostgresProducerSupersede:
) as mock_supersede:
producer.send_batch_notification(batch_result)
- mock_supersede.assert_called_once_with(producer._conn, job_id="job-1", current_run_uuid="run-1")
+ mock_supersede.assert_called_once_with(
+ producer._conn,
+ job_id="job-1",
+ current_run_uuid="run-1",
+ spare_runs_with_progress=False,
+ )
+
+ @pytest.mark.parametrize(
+ "sync_type,spare",
+ [("full_refresh", False), ("incremental", True), ("append", True), ("cdc", True)],
+ )
+ def test_only_full_refresh_supersedes_a_run_that_is_still_loading(self, sync_type: str, spare: bool) -> None:
+ """A fresh full_refresh overwrites the table on batch 0, so an older attempt's loaded rows
+ are discarded either way and its queued batches are dead weight on the serial per-schema
+ gate. Every other sync type keeps the sparing rule, because partially merged work survives."""
+ producer = _make_producer(is_resume=False, sync_type=sync_type)
+ batch_result = _make_batch_result(batch_index=0)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer.BatchQueue.supersede_other_runs",
+ return_value=0,
+ ) as mock_supersede:
+ producer.send_batch_notification(batch_result)
+
+ assert mock_supersede.call_args.kwargs["spare_runs_with_progress"] is spare
def test_does_not_supersede_on_non_zero_batch(self) -> None:
producer = _make_producer(is_resume=False)