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): reconcile abandoned v3 runs before the retention prune (#73904)

estefaniaed60fbf419f5
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.py
index 51d1f6283da8..0778a8e22eca 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
@@ -42,6 +42,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
_UNSET,
FRESHNESS_WINDOW_SECONDS,
+ TAKEOVER_STALE_THRESHOLD_SECONDS,
BatchQueue,
PendingBatch,
_Unset,
@@ -49,6 +50,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.metrics import (
OLDEST_UNCLAIMED_BATCH_SECONDS,
RUNS_RECONCILED_TOTAL,
+ RUNS_TERMINALIZED_STALE_TOTAL,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (
release_v3_pipeline_lock,
@@ -68,6 +70,10 @@ DeltaProcessBatchFn = Callable[[PendingBatch, VerifyOwnership | None], Coroutine
# timeout so a degraded probe can't starve the reconcile sweep it rides on.
FRESHNESS_PROBE_TIMEOUT_SECONDS = 30.0
+# Stamped on a run the loader abandoned: its extraction ended without a final batch, so nothing
+# finalized it and there is no failed queue batch for the failed-run reconcile to key on.
+STRANDED_RUN_ERROR = "run abandoned before completion (no loader progress; reconciled from queue)"
+
# Errors that fail identically on every attempt. Substring-matched because they
# surface as generic exceptions; keep entries specific so transients can't match.
NON_RETRYABLE_ERROR_PATTERNS: tuple[str, ...] = (
@@ -385,6 +391,95 @@ class DeltaBatchConsumerAdapter:
external_data_schema_id=ref.schema_id,
)
+ # Runs the loader abandoned leave no 'failed' batch for get_failed_runs to key on, so sweep
+ # them on the same cadence and connection. Isolated so its failure can't take the sweep down.
+ try:
+ await self._reconcile_stale_stranded_runs(conn, stale_seconds=TAKEOVER_STALE_THRESHOLD_SECONDS, limit=limit)
+ except Exception as e:
+ logger.exception("stranded_run_reconcile_sweep_failed")
+ capture_exception(e)
+
+ async def _reconcile_stale_stranded_runs(
+ self,
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ stale_seconds: int,
+ limit: int,
+ ) -> None:
+ """Fail runs the loader abandoned: non-terminal batches, no live lease, no progress for ``stale_seconds``.
+
+ ``reconcile_failed_runs`` above only catches runs with a ``failed`` queue batch. When an
+ extraction workflow dies mid-run it leaves the batches non-terminal with no failed batch and the
+ ExternalDataJob stuck RUNNING, and lock takeover only fires on the next scheduled run — so
+ without this the batches strand until the retention prune (days later).
+
+ Ordering mirrors lock takeover, not the retention sweep: these batches are still within
+ ``CLAIM_ELIGIBILITY_INTERVAL`` and could still be claimed, so fail them FIRST — a straggler
+ claimed after the job is failed could load and flip a FAILED job back to COMPLETED via its final
+ batch. Failing batches first also self-heals a crash mid-sweep: the run then has a failed batch,
+ so ``reconcile_failed_runs`` finalizes the job next cycle.
+ """
+ refs = await BatchQueue.get_stale_stranded_runs(conn, stale_seconds=stale_seconds, limit=limit)
+ for ref in refs:
+ try:
+ failed_batches = await BatchQueue.fail_run(
+ conn,
+ run_uuid=ref.run_uuid,
+ team_id=ref.team_id,
+ schema_id=ref.schema_id,
+ reason=STRANDED_RUN_ERROR,
+ )
+ except Exception as e:
+ # Without the batches failed we'd fail the job while leaving claimable stragglers
+ # behind — the exact resurrection this ordering prevents. Skip the rest for this run.
+ logger.exception("stranded_run_batch_sweep_failed", run_uuid=ref.run_uuid)
+ capture_exception(e)
+ continue
+
+ try:
+ reconciled = await sync_to_async(mark_job_failed_if_not_terminal)(
+ job_id=ref.job_id,
+ team_id=ref.team_id,
+ error=STRANDED_RUN_ERROR,
+ )
+ except Exception as e:
+ logger.exception("stranded_run_job_status_update_failed", job_id=ref.job_id, run_uuid=ref.run_uuid)
+ capture_exception(e)
+ reconciled = False
+
+ # Count only fully terminalized runs: on a failed job write the failed-run
+ # reconcile finishes the job next cycle and counts it in RUNS_RECONCILED_TOTAL.
+ if reconciled:
+ RUNS_TERMINALIZED_STALE_TOTAL.inc()
+ logger.warning(
+ "stranded_run_terminalized",
+ job_id=ref.job_id,
+ run_uuid=ref.run_uuid,
+ team_id=ref.team_id,
+ external_data_schema_id=ref.schema_id,
+ non_terminal_batches=ref.non_terminal_batches,
+ failed_batches=failed_batches,
+ job_reconciled=reconciled,
+ )
+
+ # Best-effort, compare-and-deletes on the token: safe even if the lease already expired
+ # or another pod reclaimed the group.
+ if ref.workflow_run_id:
+ try:
+ await sync_to_async(release_v3_pipeline_lock)(
+ team_id=ref.team_id,
+ schema_id=ref.schema_id,
+ token=ref.workflow_run_id,
+ )
+ except Exception as e:
+ logger.error(
+ "failed_to_release_v3_pipeline_lock",
+ job_id=ref.job_id,
+ schema_id=ref.schema_id,
+ exc_info=True,
+ )
+ capture_exception(e)
+
async def _observe_queue_freshness(self, conn: psycopg.AsyncConnection[Any]) -> None:
"""Report the age of the oldest batch no consumer has picked up yet.
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 11bc231b412d..22dcf9a4ccdf 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
@@ -480,6 +480,23 @@ class FailedRunRef:
reason: str | None
+@dataclass(frozen=True, slots=True)
+class StrandedRunRef:
+ """Identity of a run the loader abandoned: non-terminal batches, no live lease, no recent progress.
+
+ Unlike ``FailedRunRef`` there is no ``failed`` queue batch — the extraction ended (workflow died
+ or errored out) before a final batch, so nothing finalizes the run and ``get_failed_runs`` never
+ sees it. The reconcile sweep fails these so they don't strand until the retention prune.
+ """
+
+ run_uuid: str
+ job_id: str
+ team_id: int
+ schema_id: str
+ workflow_run_id: str | None
+ non_terminal_batches: int
+
+
@dataclass(frozen=True, slots=True)
class RunActivitySummary:
"""Queue DB activity for a holder's run, used by the lock takeover decision matrix."""
@@ -1064,6 +1081,91 @@ class BatchQueue:
for row in rows
]
+ @staticmethod
+ async def get_stale_stranded_runs(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ stale_seconds: int,
+ limit: int,
+ ) -> list[StrandedRunRef]:
+ """Runs the loader abandoned: non-terminal batches, no live lease, no loader progress for ``stale_seconds``.
+
+ Complements ``get_failed_runs``, which only sees runs with a ``failed`` batch. When an
+ extraction workflow dies mid-run its batches are left non-terminal with no failed batch and
+ the ExternalDataJob stuck RUNNING; lock takeover only fires on the next scheduled run, so
+ without this the batches strand until the retention prune (days later).
+
+ Staleness is *loader progress only*: the newest status write across the run, or — when the
+ loader never claimed anything — the oldest batch's age. Batch inserts (producer activity)
+ deliberately do not reset the clock, mirroring ``get_run_activity_summary``, so a live producer
+ streaming into a dead loader still reads as stale. A live group lease means a pod is actively
+ working the group (making progress, or the recovery sweep reclaims it on lease expiry), so those
+ are excluded. Runs with a ``failed`` batch are excluded — ``get_failed_runs`` owns those.
+
+ Seeded from the cheap denormalized-state index (oldest-batch-first, so the bounded candidate
+ window always holds the longest-stranded runs rather than an arbitrary set), then the full-run
+ lateral confirms staleness, so a slow-but-live run (recent success, momentarily between lease
+ renewals) is not swept.
+ """
+ async with conn.cursor(row_factory=dict_row) as cur:
+ await cur.execute(
+ f"""
+ WITH candidates AS (
+ SELECT b.run_uuid, b.team_id, b.schema_id
+ FROM {BATCH_TABLE} b
+ WHERE b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND b.created_at <= now() - make_interval(secs => %(stale)s)
+ AND b.latest_state IN ('pending', 'waiting', 'waiting_retry', 'executing')
+ AND NOT EXISTS (
+ SELECT 1 FROM {LEASE_TABLE} l
+ WHERE l.team_id = b.team_id AND l.schema_id = b.schema_id
+ AND l.expires_at > now()
+ )
+ AND NOT EXISTS (
+ SELECT 1 FROM {BATCH_TABLE} bf
+ WHERE bf.run_uuid = b.run_uuid
+ AND bf.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND bf.latest_state = 'failed'
+ )
+ -- Oldest-batch-first, so the window can't be starved by an arbitrary set of
+ -- not-yet-stale runs the outer HAVING later rejects: the longest-stranded runs
+ -- always land in it, and successive sweeps make deterministic forward progress.
+ GROUP BY b.run_uuid, b.team_id, b.schema_id
+ ORDER BY MIN(b.created_at) ASC
+ LIMIT %(limit)s
+ )
+ SELECT
+ b.run_uuid,
+ b.team_id,
+ b.schema_id,
+ MAX(b.job_id) AS job_id,
+ MAX(b.metadata->>'workflow_run_id') AS workflow_run_id,
+ COUNT(*) FILTER (WHERE {pending_batch_predicate("s")}) AS non_terminal_batches
+ FROM {BATCH_TABLE} b
+ JOIN candidates c
+ ON c.run_uuid = b.run_uuid AND c.team_id = b.team_id AND c.schema_id = b.schema_id
+ {latest_status_lateral("b", "s")}
+ WHERE b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ GROUP BY b.run_uuid, b.team_id, b.schema_id
+ HAVING COALESCE(MAX(s.created_at), MIN(b.created_at)) <= now() - make_interval(secs => %(stale)s)
+ ORDER BY MIN(b.created_at) ASC
+ """,
+ {"stale": stale_seconds, "limit": limit},
+ )
+ rows = await cur.fetchall()
+
+ return [
+ StrandedRunRef(
+ run_uuid=row["run_uuid"],
+ job_id=row["job_id"],
+ team_id=row["team_id"],
+ schema_id=row["schema_id"],
+ workflow_run_id=row["workflow_run_id"],
+ non_terminal_batches=row["non_terminal_batches"],
+ )
+ for row in rows
+ ]
+
@staticmethod
async def get_oldest_unclaimed_batch_age_seconds(
conn: psycopg.AsyncConnection[Any],
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py
index 38fccff5b40d..228e8008b061 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py
@@ -70,6 +70,12 @@ RUNS_RECONCILED_TOTAL = Counter(
"was reconciled to Failed by the reconcile sweep",
)
+RUNS_TERMINALIZED_STALE_TOTAL = Counter(
+ "warehouse_pg_consumer_runs_terminalized_stale_total",
+ "Runs the loader abandoned (non-terminal batches, no live lease, no progress past the "
+ "staleness threshold) that the reconcile sweep failed before the retention prune would",
+)
+
# The loader's data-freshness signal: it rises whenever loading stalls,
# regardless of why (wedged consumers, claim-query degradation, crashloops).
# Every pod reports the same queue-wide value, so aggregate with max().
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 05924f1f77ec..743edbc7cd40 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
@@ -946,6 +946,110 @@ class TestGetRunActivitySummary:
assert summary.is_stale is False
[email protected]_db(transaction=True)
+class TestGetStaleStrandedRuns:
+ """The abandoned-run query: non-terminal batches, no live lease, no loader progress past the threshold."""
+
+ STALE = 3600 # seconds; batches are backdated well past this to read as stale
+
+ async def _stale_pending(self, conn: psycopg.AsyncConnection[Any], **overrides: Any) -> str:
+ bid = await _insert_batch(conn, **overrides)
+ await conn.execute(f"UPDATE {BATCH_TABLE} SET created_at = now() - interval '2 hours' WHERE id = %s", (bid,))
+ return bid
+
+ async def _run(self, conn: psycopg.AsyncConnection[Any]):
+ return await BatchQueue.get_stale_stranded_runs(conn, stale_seconds=self.STALE, limit=100)
+
+ @pytest.mark.asyncio
+ async def test_returns_abandoned_run(self, conn):
+ await self._stale_pending(
+ conn, batch_index=0, run_uuid="strand", job_id="job-s", metadata={"workflow_run_id": "wf-s"}
+ )
+ await self._stale_pending(
+ conn, batch_index=1, run_uuid="strand", job_id="job-s", metadata={"workflow_run_id": "wf-s"}
+ )
+
+ refs = await self._run(conn)
+
+ assert len(refs) == 1
+ ref = refs[0]
+ assert (ref.run_uuid, ref.job_id, ref.team_id, ref.schema_id) == ("strand", "job-s", 1, "schema-1")
+ assert ref.workflow_run_id == "wf-s"
+ assert ref.non_terminal_batches == 2
+
+ @pytest.mark.asyncio
+ async def test_excludes_group_with_live_lease(self, conn):
+ # A live lease means a pod is actively working the group — failing it would kill an in-flight load.
+ await self._stale_pending(conn, run_uuid="leased")
+ await _insert_lease(conn, expires_in_seconds=300)
+
+ assert await self._run(conn) == []
+
+ @pytest.mark.asyncio
+ async def test_excludes_run_with_recent_loader_progress(self, conn):
+ # Oldest batch is old, but the loader just succeeded one: slow-but-live, not abandoned. Guards
+ # against the staleness clock counting batch age instead of loader progress.
+ await self._stale_pending(conn, batch_index=0, run_uuid="live")
+ done = await self._stale_pending(conn, batch_index=1, run_uuid="live")
+ await BatchQueue.update_status(conn, batch_id=done, job_state="succeeded", attempt=1)
+
+ assert await self._run(conn) == []
+
+ @pytest.mark.asyncio
+ async def test_excludes_run_with_failed_batch(self, conn):
+ # A failed batch is the failed-run reconcile's job; this sweep must not double-handle it.
+ failed = await self._stale_pending(conn, batch_index=0, run_uuid="had-failure")
+ await BatchQueue.update_status(conn, batch_id=failed, job_state="failed", attempt=1)
+ await self._stale_pending(conn, batch_index=1, run_uuid="had-failure")
+
+ assert await self._run(conn) == []
+
+ @pytest.mark.asyncio
+ async def test_excludes_fresh_run_within_threshold(self, conn):
+ # Normal backlog waiting to be claimed — younger than the threshold, not abandoned.
+ await _insert_batch(conn, run_uuid="fresh")
+
+ assert await self._run(conn) == []
+
+
[email protected]_db(transaction=True)
+class TestReconcileAbandonedRuns:
+ CONSUMER_MOD = (
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer"
+ )
+
+ @pytest.mark.asyncio
+ async def test_reconcile_fails_abandoned_run_and_finalizes(self, conn):
+ # End-to-end through the public reconcile: an abandoned run (pending batches, no failed batch,
+ # no live lease, no loader progress past the staleness threshold) gets its queue batches failed,
+ # its job finalized, and its lock released. Guards the wiring and the fail-batches-first ordering.
+ for i in range(2):
+ bid = await _insert_batch(
+ conn, batch_index=i, run_uuid="abandoned", job_id="job-ab", metadata={"workflow_run_id": "wf-ab"}
+ )
+ await conn.execute(
+ f"UPDATE {BATCH_TABLE} SET created_at = now() - interval '7 hours' WHERE id = %s", (bid,)
+ )
+
+ adapter = DeltaBatchConsumerAdapter()
+ with (
+ patch(f"{self.CONSUMER_MOD}.mark_job_failed_if_not_terminal", return_value=True) as mock_fail_job,
+ patch(f"{self.CONSUMER_MOD}.release_v3_pipeline_lock", return_value=True) as mock_release,
+ ):
+ await adapter.reconcile_failed_runs(conn, grace_seconds=120, lookback_seconds=86400, limit=100)
+
+ rows = await (
+ await conn.execute(
+ f"SELECT latest_state FROM {BATCH_TABLE} WHERE run_uuid = 'abandoned' ORDER BY batch_index"
+ )
+ ).fetchall()
+ assert [r[0] for r in rows] == ["failed", "failed"]
+ mock_fail_job.assert_called_once()
+ assert mock_fail_job.call_args.kwargs["job_id"] == "job-ab"
+ mock_release.assert_called_once()
+ assert mock_release.call_args.kwargs["token"] == "wf-ab"
+
+
@pytest.mark.django_db(transaction=True)
class TestClaimWindowSkipsForeignLeasedGroups:
@pytest.mark.asyncio