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): pin duckgres backfill promotions to their run generation (#69101)

Eric Duong5e47e5792115
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py
index 2f33204fb1dd..922d01144c41 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py
@@ -247,11 +247,16 @@ def sink_eligible_schema_ids(team_ids: list[int]) -> list[str]:
return eligible
-def mark_primed(schema_id: str, *, chunks_applied: int | None = None) -> None:
+def mark_primed(schema_id: str, *, run_uuid: str, chunks_applied: int | None = None) -> None:
"""Fast path called by the processor right after the swap commits.
CAS from BACKFILLING only — the reconciler is the authoritative healer,
- and a late call must never clobber a state that has since moved on.
+ and a late call must never clobber a state that has since moved on. The
+ CAS is also pinned to the run generation: a replan can retire run R1 and
+ plan R2 while R1's final chunk is still mid-swap (its duckgres transaction
+ cannot be cancelled), and R1's late mark_primed must not flip R2's row —
+ that would unblock live batches over a table R2's own swap later replaces,
+ silently dropping them.
"""
updates: dict[str, Any] = {
"state": DuckgresSinkSchemaState.State.PRIMED,
@@ -261,9 +266,11 @@ def mark_primed(schema_id: str, *, chunks_applied: int | None = None) -> None:
}
if chunks_applied is not None:
updates["chunks_applied"] = chunks_applied
- DuckgresSinkSchemaState.objects.filter(schema_id=schema_id, state=DuckgresSinkSchemaState.State.BACKFILLING).update(
- **updates
- )
+ DuckgresSinkSchemaState.objects.filter(
+ schema_id=schema_id,
+ state=DuckgresSinkSchemaState.State.BACKFILLING,
+ backfill_run_uuid=run_uuid,
+ ).update(**updates)
def replan_backfill(schema_id: str) -> None:
@@ -504,6 +511,59 @@ def _revert_to_pending(state_id: Any, error: str | None = None, *, record_failur
).update(**updates)
+def _has_inflight_replace_run(conn: psycopg.Connection[Any], *, team_id: int, schema_id: str) -> bool:
+ """A replace-head live run that Delta accepted but duckgres has not finished.
+
+ Batch 0 replace-shaped and delta-succeeded, with no terminal Delta failure,
+ duckgres-succeeded final marker (completion), or duckgres-failed batch for
+ the run. Planning must wait these out: the snapshot would cover the run's
+ head and orphan its tail (see the guard in _plan_one).
+ """
+ row = conn.execute(
+ f"""
+ SELECT 1
+ FROM {BATCH_TABLE} h
+ JOIN v_latest_source_batch_status hds ON hds.batch_id = h.id
+ WHERE h.team_id = %(team_id)s
+ AND h.schema_id = %(schema_id)s
+ AND h.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND h.batch_index = 0
+ AND h.is_final_batch = false
+ AND h.is_resume = false
+ AND (h.sync_type = 'full_refresh' OR (h.sync_type = 'incremental' AND h.is_first_ever_sync))
+ AND hds.job_state = 'succeeded'
+ AND NOT EXISTS (
+ SELECT 1
+ FROM {BATCH_TABLE} x
+ JOIN v_latest_source_batch_status xds ON xds.batch_id = x.id
+ WHERE x.run_uuid = h.run_uuid
+ AND x.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND xds.job_state = 'failed'
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM {BATCH_TABLE} f
+ JOIN v_latest_source_batch_duckgres_status fdgs ON fdgs.batch_id = f.id
+ WHERE f.run_uuid = h.run_uuid
+ AND f.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND f.is_final_batch = true
+ AND fdgs.job_state = 'succeeded'
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM {BATCH_TABLE} x
+ JOIN v_latest_source_batch_duckgres_status xdgs ON xdgs.batch_id = x.id
+ WHERE x.run_uuid = h.run_uuid
+ AND x.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND xdgs.job_state = 'failed'
+ )
+ LIMIT 1
+ """,
+ {"team_id": team_id, "schema_id": schema_id},
+ ).fetchone()
+ return row is not None
+
+
def _plan_one(state: DuckgresSinkSchemaState) -> None:
"""Runs only on the pod that won the lease claim.
@@ -535,6 +595,19 @@ def _plan_one(state: DuckgresSinkSchemaState) -> None:
keepalives_interval=15,
keepalives_count=4,
) as conn:
+ if _has_inflight_replace_run(conn, team_id=schema.team_id, schema_id=str(state.schema_id)):
+ # Planning now would pin a snapshot mid-run and pre-apply the
+ # replace run's head: its post-snapshot tail would then apply into
+ # the doomed pre-swap table (the replace-head gate bypass admits
+ # it), and the swap would silently drop those rows while their
+ # apply markers prevent any re-apply. Defer until the run reaches
+ # a terminal duckgres state; the planner retries every tick.
+ logger.info(
+ "duckgres_backfill_plan_deferred_for_inflight_replace",
+ schema_id=str(state.schema_id),
+ team_id=schema.team_id,
+ )
+ return
plan = resolve_snapshot_plan(schema)
snapshot_version = plan.snapshot_version
chunks = plan.chunks
@@ -692,8 +765,14 @@ def _reconcile_one(conn: psycopg.Connection[Any], state: DuckgresSinkSchemaState
if state.chunk_count and applied >= state.chunk_count:
# Full application proves the swap committed (the last chunk's apply
# marker shares the swap's transaction). CAS so a stale pass can never
- # resurrect a state another pod already advanced.
- DuckgresSinkSchemaState.objects.filter(id=state.id, state=DuckgresSinkSchemaState.State.BACKFILLING).update(
+ # resurrect a state another pod already advanced — pinned to the run
+ # the applied-count evidence was gathered for, so a replan that swapped
+ # generations mid-pass cannot be promoted on the old run's counts.
+ DuckgresSinkSchemaState.objects.filter(
+ id=state.id,
+ state=DuckgresSinkSchemaState.State.BACKFILLING,
+ backfill_run_uuid=run_uuid,
+ ).update(
state=DuckgresSinkSchemaState.State.PRIMED,
chunks_applied=applied,
last_error=None,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py
index 7d32f1441cc3..443185b555bf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py
@@ -353,7 +353,7 @@ def _process_backfill_batch(
mark_primed,
)
- mark_primed(batch.schema_id, chunks_applied=chunk_count)
+ mark_primed(batch.schema_id, run_uuid=batch.run_uuid, chunks_applied=chunk_count)
return
chunk_paths = _backfill_chunk_paths(batch)
@@ -422,7 +422,7 @@ def _process_backfill_batch(
mark_primed,
)
- mark_primed(batch.schema_id, chunks_applied=chunk_count)
+ mark_primed(batch.schema_id, run_uuid=batch.run_uuid, chunks_applied=chunk_count)
logger.info(
"duckgres_backfill_swapped",
team_id=batch.team_id,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py
index 7ece400d4ca3..d75068a8ccdf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py
@@ -472,6 +472,78 @@ class TestFailingSchemaClassification:
assert str(row.schema_id) not in backfill_module.failing_schema_ids(None)
+class TestGenerationPinnedPromotions:
+ def _team(self) -> Team:
+ return Team.objects.create(organization=Organization.objects.create(name="org"), name="t")
+
+ def _backfilling_state(self, run_uuid: str | None, chunk_count: int = 2) -> DuckgresSinkSchemaState:
+ return DuckgresSinkSchemaState.objects.create(
+ team=self._team(),
+ schema_id=uuid.uuid4(),
+ state=DuckgresSinkSchemaState.State.BACKFILLING,
+ backfill_run_uuid=run_uuid,
+ chunk_count=chunk_count,
+ chunks_applied=0,
+ )
+
+ def test_mark_primed_ignores_stale_generation(self):
+ # A replan can retire run R1 and plan R2 while R1's final swap is still
+ # committing; R1's late mark_primed must not promote R2's row.
+ row = self._backfilling_state("run-r2")
+
+ backfill_module.mark_primed(str(row.schema_id), run_uuid="run-r1", chunks_applied=2)
+ row.refresh_from_db()
+ assert row.state == DuckgresSinkSchemaState.State.BACKFILLING
+
+ backfill_module.mark_primed(str(row.schema_id), run_uuid="run-r2", chunks_applied=2)
+ row.refresh_from_db()
+ assert row.state == DuckgresSinkSchemaState.State.PRIMED
+ assert row.chunks_applied == 2
+
+ def test_reconcile_promotion_ignores_stale_generation(self):
+ # The reconciler's applied-count evidence belongs to the run it read at
+ # the top of the pass; a replan swapping generations mid-pass must not
+ # be promoted on the old run's counts.
+ row = self._backfilling_state("run-r1")
+ stale_snapshot = DuckgresSinkSchemaState.objects.get(id=row.id)
+ DuckgresSinkSchemaState.objects.filter(id=row.id).update(backfill_run_uuid="run-r2")
+
+ conn = MagicMock()
+ conn.execute.return_value.fetchone.return_value = (stale_snapshot.chunk_count,)
+ backfill_module._reconcile_one(conn, stale_snapshot)
+
+ row.refresh_from_db()
+ assert row.state == DuckgresSinkSchemaState.State.BACKFILLING
+ assert row.backfill_run_uuid == "run-r2"
+
+ def test_plan_one_defers_while_replace_run_inflight(self):
+ team = self._team()
+ source = ExternalDataSource.objects.create(
+ team=team, source_id="s", connection_id="c", source_type="Stripe", status="Running"
+ )
+ schema = ExternalDataSchema.objects.create(team=team, source=source, name="customers")
+ row = DuckgresSinkSchemaState.objects.create(
+ team=team,
+ schema_id=schema.id,
+ state=DuckgresSinkSchemaState.State.BACKFILLING,
+ backfill_run_uuid=None,
+ )
+
+ with (
+ patch.object(backfill_module, "_has_inflight_replace_run", return_value=True),
+ patch.object(backfill_module, "resolve_snapshot_plan") as resolve,
+ patch.object(backfill_module.psycopg, "connect") as connect,
+ ):
+ connect.return_value.__enter__.return_value = MagicMock()
+ backfill_module._plan_one(row)
+
+ resolve.assert_not_called()
+ row.refresh_from_db()
+ assert row.backfill_run_uuid is None
+ assert row.state == DuckgresSinkSchemaState.State.BACKFILLING
+
+
@pytest.mark.django_db
class TestDeletedSchemaPurge:
def _fixture(self, deleted: bool, run_uuid: str | None = "run-1"):
diff --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.py
index 27885f4a258d..35244e269a0e 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
@@ -4,6 +4,9 @@ import pytest
import psycopg
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill import (
+ _has_inflight_replace_run,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.jobs_db import (
DUCKGRES_APPLY_TABLE,
DUCKGRES_LEASE_TABLE,
@@ -198,6 +201,27 @@ async def conn(_db_url: str):
@pytest.mark.django_db(transaction=True)
class TestDuckgresBatchQueueEligibility:
+ @pytest.mark.asyncio
+ async def test_failed_delta_replace_run_is_not_inflight(
+ self, conn: psycopg.AsyncConnection[Any], _db_url: str
+ ) -> None:
+ run_uuid = "failed-replace-run"
+ head_id = await _insert_batch(
+ conn,
+ run_uuid=run_uuid,
+ batch_index=0,
+ sync_type="full_refresh",
+ is_final_batch=False,
+ is_resume=False,
+ )
+ await BatchQueue.update_status(conn, batch_id=head_id, job_state="succeeded", attempt=1)
+
+ tail_id = await _insert_batch(conn, run_uuid=run_uuid, batch_index=1)
+ await BatchQueue.update_status(conn, batch_id=tail_id, job_state="failed", attempt=1)
+
+ with psycopg.Connection.connect(_db_url, autocommit=True) as sync_conn:
+ assert not _has_inflight_replace_run(sync_conn, team_id=1, schema_id="schema-1")
+
@pytest.mark.asyncio
async def test_ignores_batches_until_delta_succeeds(self, conn):
await _insert_batch(conn)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py
index 0eb6ef5c5c2e..425502c6a728 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py
@@ -534,7 +534,7 @@ class TestBackfillProcessing:
assert "Identifier('stripe_customers')" in executed
assert "RENAME TO" in executed
insert.assert_called_once()
- primed.assert_called_once_with("schema-1", chunks_applied=3)
+ primed.assert_called_once_with("schema-1", run_uuid="duckgres-backfill-schema-1-v7", chunks_applied=3)
def test_already_applied_chunk_is_a_noop(self) -> None:
conn = _make_conn()