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): make the v3 queue freshness gauge report real lag (#103952)

Tom Owersbc0544e4d237
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 cb54c0ff256a..f6b078975b66 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
@@ -53,8 +53,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
_Unset,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.metrics import (
+ BACKLOGGED_GROUPS,
+ BLOCKED_BATCHES,
CLAIMABLE_BATCHES,
OLDEST_UNCLAIMED_BATCH_SECONDS,
+ ORPHANED_BATCHES_DRAINED_TOTAL,
RUNS_RECONCILED_TOTAL,
RUNS_TERMINALIZED_STALE_TOTAL,
observe_queue_query,
@@ -77,6 +80,13 @@ 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
+# A group whose oldest claimable batch is older than this counts as backlogged.
+# Set above the reconcile cadence that samples it (300s) so a group cannot be
+# counted purely because it was enqueued between two probes, and well below the
+# lease TTL, so a group that is merely waiting its turn behind a sibling run
+# does not register while the loader is still working the group normally.
+BACKLOG_THRESHOLD_SECONDS = 900
+
# 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.
# Shown to the customer verbatim as latest_error, so keep it plain and reassuring rather than
@@ -86,6 +96,10 @@ STRANDED_RUN_ERROR = (
"The next scheduled sync retries automatically. No action is needed."
)
+# Stamped on batches retired by the orphan drain. Their run already failed and the customer has
+# already seen that failure on the job, so this text only has to explain the batch rows themselves.
+ORPHANED_BATCH_ERROR = "left over from a run that had already failed (orphan drain)"
+
# Permanent failures the customer can fix. These stop the schedule as well as the run: the loader
# fails outside the workflow, so the finalization activity that would otherwise disable the schema
@@ -430,6 +444,21 @@ class DeltaBatchConsumerAdapter:
)
await self._release_run_lock(ref)
+ # The pass above is newest-first inside a lookback, so a run whose failure ages out of the
+ # window keeps its leftover batches forever. Drain those oldest-first here, on the same
+ # cadence and connection. Isolated so its failure can't take the sweep down.
+ try:
+ await self._drain_orphaned_batches(conn, limit=limit)
+ except psycopg.OperationalError as e:
+ if conn.closed:
+ logger.warning("orphaned_batch_drain_closed_connection", error=str(e))
+ else:
+ logger.exception("orphaned_batch_drain_failed")
+ capture_exception(e)
+ except Exception as e:
+ logger.exception("orphaned_batch_drain_failed")
+ capture_exception(e)
+
# 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:
@@ -446,6 +475,39 @@ class DeltaBatchConsumerAdapter:
logger.exception("stranded_run_reconcile_sweep_failed")
capture_exception(e)
+ async def _drain_orphaned_batches(self, conn: psycopg.AsyncConnection[Any], *, limit: int) -> None:
+ """Terminalize the leftovers of runs the newest-first reconcile pass never reached.
+
+ Their job is already terminal, so there is nothing to reconcile in the
+ app DB and no lock left to release — only queue rows to retire. Returns
+ nothing to sweep in a healthy fleet.
+ """
+ orphaned = await BatchQueue.get_runs_with_orphaned_batches(conn, limit=limit)
+ for ref in orphaned:
+ try:
+ drained = await BatchQueue.fail_run(
+ conn,
+ run_uuid=ref.run_uuid,
+ team_id=ref.team_id,
+ schema_id=ref.schema_id,
+ reason=ORPHANED_BATCH_ERROR,
+ )
+ except Exception as e:
+ if _is_transient_queue_connection_drop(e, conn):
+ raise
+ logger.exception("orphaned_batch_drain_run_failed", run_uuid=ref.run_uuid)
+ capture_exception(e)
+ continue
+ if drained:
+ ORPHANED_BATCHES_DRAINED_TOTAL.inc(drained)
+ logger.warning(
+ "drained_orphaned_batches",
+ run_uuid=ref.run_uuid,
+ team_id=ref.team_id,
+ external_data_schema_id=ref.schema_id,
+ batch_count=drained,
+ )
+
async def _sweep_straggler_batches(self, conn: psycopg.AsyncConnection[Any], ref: FailedRunRef) -> None:
"""Terminalize batches enqueued into a run that ``fail_run`` had already swept.
@@ -638,10 +700,14 @@ class DeltaBatchConsumerAdapter:
try:
async with asyncio.timeout(FRESHNESS_PROBE_TIMEOUT_SECONDS):
with observe_queue_query("oldest_unclaimed_probe"):
- age = await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn)
+ freshness = await BatchQueue.get_queue_freshness(
+ conn, backlog_threshold_seconds=BACKLOG_THRESHOLD_SECONDS
+ )
# Set immediately, so a failure in the depth probe below can never
# blind the age gauge this alert hangs off.
- OLDEST_UNCLAIMED_BATCH_SECONDS.set(age or 0.0)
+ OLDEST_UNCLAIMED_BATCH_SECONDS.set(freshness.oldest_age_seconds or 0.0)
+ BLOCKED_BATCHES.set(freshness.blocked_batches)
+ BACKLOGGED_GROUPS.set(freshness.backlogged_groups)
# Depth rides the same probe and timeout: age says how stale the head
# of the queue is, depth says how much sits behind it — a stall and a
# burst are indistinguishable on age alone.
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 98aee2fc745e..504b1df7222b 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
@@ -373,6 +373,40 @@ def _state_claim_candidates_sql(sync_type_scope: str = "") -> str:
"""
+def _orphaned_candidate_runs_sql() -> str:
+ """Runs holding a ``failed`` batch that still have claimable batches behind it.
+
+ Split out from its caller so the plan-shape test can EXPLAIN exactly what runs,
+ the same way :func:`_state_claim_candidates_sql` is pinned.
+ """
+ return f"""
+ WITH stuck_runs AS (
+ SELECT
+ b.run_uuid,
+ b.team_id,
+ b.schema_id,
+ MIN(b.created_at) AS oldest_created_at,
+ count(*) AS non_terminal_batches
+ FROM {BATCH_TABLE} b
+ WHERE b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND b.latest_state IN ('pending', 'waiting_retry')
+ GROUP BY b.run_uuid, b.team_id, b.schema_id
+ )
+ SELECT r.run_uuid, r.team_id, r.schema_id, r.non_terminal_batches
+ FROM stuck_runs r
+ WHERE EXISTS (
+ SELECT 1
+ FROM {BATCH_TABLE} bf
+ WHERE bf.run_uuid = r.run_uuid
+ AND bf.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND bf.latest_state = 'failed'
+ OFFSET 0
+ )
+ ORDER BY r.oldest_created_at ASC
+ LIMIT %(limit)s
+ """
+
+
def _stranded_candidate_runs_sql() -> str:
"""Candidate selection for the stranded-run sweep: aggregate first, then gate per run.
@@ -576,6 +610,20 @@ class StrandedRunRef:
non_terminal_batches: int
+@dataclass(frozen=True, slots=True)
+class OrphanedRunRef:
+ """A run holding a ``failed`` batch that still has non-terminal batches behind it.
+
+ Carries no ``job_id``: the job is already terminal by the time a run reaches
+ this state, so the only work left is terminalizing the queue rows.
+ """
+
+ run_uuid: str
+ team_id: int
+ schema_id: str
+ 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."""
@@ -616,6 +664,23 @@ class GroupLease:
is_live: bool
+@dataclass(frozen=True, slots=True)
+class QueueFreshness:
+ """What one freshness probe reads off the pending set.
+
+ Three numbers rather than one because they fail differently: the age says
+ how far the queue head has fallen behind, the blocked count says how much
+ of the table can never move, and the group count says how widely the lag
+ is spread. An alert on the age alone cannot tell one wedged tenant from a
+ fleet-wide stall.
+ """
+
+ # None when nothing claimable is waiting.
+ oldest_age_seconds: float | None
+ blocked_batches: int
+ backlogged_groups: int
+
+
class BatchQueue:
"""
Async interface to the Postgres batch queue tables. Each method runs
@@ -1281,6 +1346,56 @@ class BatchQueue:
for row in rows
]
+ @staticmethod
+ async def get_runs_with_orphaned_batches(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ limit: int,
+ ) -> list[OrphanedRunRef]:
+ """Runs that hold a ``failed`` batch and still have non-terminal batches behind it.
+
+ Those batches are stuck in both directions: the claim query refuses any
+ run with a failed batch, and the stranded sweep excludes the same runs
+ because ``get_failed_runs`` is supposed to own them. It cannot reach all
+ of them. It is ``ORDER BY failed_at DESC LIMIT n`` inside a lookback,
+ with no gate for runs it has already swept, so every sweep re-picks the
+ same newest runs; once a failure ages past the lookback its leftovers
+ are unreachable until the retention prune, days later.
+
+ This pass closes that gap and cannot starve: oldest-first, and a run
+ leaves the set as soon as its batches go terminal. Normally it returns
+ nothing — the set is non-empty only when the newest-first pass has
+ fallen behind.
+
+ Shaped like :func:`_stranded_candidate_runs_sql`: aggregate the bounded
+ claimable scan into runs first, then one ``sb_run_gate_idx`` probe per
+ candidate run. Gating the raw batch rows instead turns the failed probe
+ into a hash anti-join whose hash side is every failed batch in the
+ window, which is exactly the shape that melted down under a failure
+ storm. The ``OFFSET 0`` fence is what holds the probe shape.
+
+ The candidate states are exactly ``sb_claimable_idx``'s, and must stay
+ that way. Widening them to every non-terminal state (adding 'waiting'
+ and 'executing') puts the scan outside that partial index, and the
+ planner answers it with a parallel sequential scan of every partition
+ instead — 12x the cost on the production queue, once every reconcile
+ interval. It also loses nothing: a blocked batch is one no consumer
+ could claim, and 'executing' rows belong to the stale-executing sweep.
+ """
+ async with conn.cursor(row_factory=dict_row) as cur:
+ await cur.execute(_orphaned_candidate_runs_sql(), {"limit": limit})
+ rows = await cur.fetchall()
+
+ return [
+ OrphanedRunRef(
+ run_uuid=row["run_uuid"],
+ team_id=row["team_id"],
+ schema_id=row["schema_id"],
+ non_terminal_batches=row["non_terminal_batches"],
+ )
+ for row in rows
+ ]
+
@staticmethod
async def get_stale_stranded_runs(
conn: psycopg.AsyncConnection[Any],
@@ -1350,36 +1465,74 @@ class BatchQueue:
]
@staticmethod
- async def get_oldest_unclaimed_batch_age_seconds(
+ async def get_queue_freshness(
conn: psycopg.AsyncConnection[Any],
- ) -> float | None:
- """Age in seconds of the oldest batch no consumer has ever picked up, or None when none are waiting.
-
- 'pending' means no status row yet — this is the queue's data-freshness
- signal, and it rises whenever loading stalls regardless of the cause.
- Answered from the claimable partial index; bounded to
- ``FRESHNESS_WINDOW`` so the reported age saturates instead of scanning
- unbounded history.
+ *,
+ backlog_threshold_seconds: int,
+ ) -> QueueFreshness:
+ """Three readings off one scan of the pending set, bounded to ``FRESHNESS_WINDOW``.
+
+ ``oldest_age_seconds`` excludes batches whose run already holds a
+ ``failed`` batch. The claim query refuses those (see
+ ``_state_claim_candidates_sql``) and the stranded sweep skips them too,
+ so nothing can ever pick them up: counting them made the gauge report
+ the age of an abandoned row rather than the queue's lag, and it grew at
+ exactly one second per second until retention pruned it.
+ ``get_oldest_non_terminal_batch_age_seconds`` already excludes them for
+ the same reason.
+
+ ``blocked_batches`` keeps that excluded population visible in its own
+ lane, so a leak still shows up somewhere instead of disappearing.
+
+ ``backlogged_groups`` is the breadth companion to the age: the age is a
+ fleet-wide max, so one wedged (team, schema) pins it and a fleet-wide
+ alert cannot tell one stuck tenant from a real stall. Counting the
+ groups past the threshold separates those.
"""
async with conn.cursor() as cur:
await cur.execute(
f"""
- SELECT EXTRACT(EPOCH FROM (now() - min(b.created_at)))
- FROM {BATCH_TABLE} b
- WHERE b.created_at > now() - interval '{FRESHNESS_WINDOW}'
- AND b.latest_state = 'pending'
- """
+ WITH pending AS (
+ SELECT
+ b.team_id,
+ b.schema_id,
+ b.created_at,
+ EXISTS (
+ SELECT 1
+ FROM {BATCH_TABLE} b_failed
+ WHERE b_failed.run_uuid = b.run_uuid
+ AND b_failed.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND b_failed.latest_state = 'failed'
+ ) AS blocked
+ FROM {BATCH_TABLE} b
+ WHERE b.created_at > now() - interval '{FRESHNESS_WINDOW}'
+ AND b.latest_state = 'pending'
+ )
+ SELECT
+ EXTRACT(EPOCH FROM (now() - min(created_at) FILTER (WHERE NOT blocked))),
+ count(*) FILTER (WHERE blocked),
+ count(DISTINCT (team_id, schema_id)) FILTER (
+ WHERE NOT blocked
+ AND created_at <= now() - make_interval(secs => %(backlog_threshold)s)
+ )
+ FROM pending
+ """,
+ {"backlog_threshold": backlog_threshold_seconds},
)
row = await cur.fetchone()
- if row is None or row[0] is None:
- return None
- return float(row[0])
+ if row is None:
+ return QueueFreshness(oldest_age_seconds=None, blocked_batches=0, backlogged_groups=0)
+ return QueueFreshness(
+ oldest_age_seconds=float(row[0]) if row[0] is not None else None,
+ blocked_batches=int(row[1] or 0),
+ backlogged_groups=int(row[2] or 0),
+ )
@staticmethod
async def get_claimable_batch_count(conn: psycopg.AsyncConnection[Any]) -> int:
"""How many batches are state-eligible for claiming right now (queue depth).
- The depth companion to :meth:`get_oldest_unclaimed_batch_age_seconds`:
+ The depth companion to :meth:`get_queue_freshness`:
the claim's per-run, schema-busy, and lease gates are deliberately not
applied (they need per-row probes; this must stay one cheap partial-index
scan), and neither is the retry-backoff gate (it needs the fleet's backoff
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 ded54b7c8c19..8c92cfeaf506 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
@@ -77,6 +77,13 @@ RUNS_RECONCILED_TOTAL = Counter(
"was reconciled to Failed by the reconcile sweep",
)
+ORPHANED_BATCHES_DRAINED_TOTAL = Counter(
+ "warehouse_pg_consumer_orphaned_batches_drained_total",
+ "Non-terminal batches retired because their run had already failed and the newest-first "
+ "reconcile pass never reached it. Pairs with warehouse_pg_queue_blocked_batches: that gauge "
+ "is the standing population, this counter is the drain rate.",
+)
+
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 "
@@ -90,11 +97,36 @@ RUNS_TERMINALIZED_STALE_TOTAL = Counter(
# briefly co-exist in one pod, where livesum would double the age.
OLDEST_UNCLAIMED_BATCH_SECONDS = Gauge(
"warehouse_pg_queue_oldest_unclaimed_batch_seconds",
- "Age of the oldest queue batch no consumer has picked up yet (0 = none waiting). "
+ "Age of the oldest queue batch no consumer has picked up yet, counting only batches a "
+ "consumer could still pick up (0 = none waiting). Batches whose run already holds a failed "
+ "batch are excluded — the claim query refuses those, so their age is not queue lag; they are "
+ "counted by warehouse_pg_queue_blocked_batches instead. "
"Sampled on the reconcile cadence; saturates at the freshness probe window.",
multiprocess_mode="livemax",
)
+# The population the age gauge above excludes. Split out rather than dropped: these
+# rows are a real leak (nothing claims them, and the stranded sweep skips runs with a
+# failed batch), they just are not latency. Folding them into the age made a fleet-wide
+# alert fire on one abandoned run and climb at one second per second until retention
+# pruned it.
+BLOCKED_BATCHES = Gauge(
+ "warehouse_pg_queue_blocked_batches",
+ "Pending batches no consumer can ever claim because their run already holds a failed "
+ "batch. Sampled on the reconcile cadence, within the freshness probe window.",
+ multiprocess_mode="livemax",
+)
+
+# Breadth companion to the age gauge. The age is a fleet-wide max, so a single wedged
+# (team, schema) group reads identically to every group falling behind. This separates
+# them: alert on groups, diagnose on age.
+BACKLOGGED_GROUPS = Gauge(
+ "warehouse_pg_queue_backlogged_groups",
+ "Distinct (team_id, schema_id) groups whose oldest claimable batch is older than the "
+ "backlog threshold. Sampled on the reconcile cadence.",
+ multiprocess_mode="livemax",
+)
+
# Depth companion to the age gauge above: age says how stale the head of the queue
# is, depth says how much work is behind it — a stall and a burst look identical on
# age alone. Same probe, same cadence, same aggregation (max across pods).
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.py
index f93ada95c609..bc86c7be1c87 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
@@ -37,17 +37,32 @@ 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 (
FRESHNESS_WINDOW_SECONDS,
FailedRunRef,
+ OrphanedRunRef,
PendingBatch,
+ QueueFreshness,
StrandedRunRef,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.metrics import (
+ BACKLOGGED_GROUPS,
+ BLOCKED_BATCHES,
CLAIMABLE_BATCHES,
OLDEST_UNCLAIMED_BATCH_SECONDS,
+ ORPHANED_BATCHES_DRAINED_TOTAL,
RUNS_RECONCILED_TOTAL,
)
from products.warehouse_sources_queue.backend.models import SourceBatchStatus
+def _freshness(
+ oldest_age_seconds: float | None, *, blocked_batches: int = 0, backlogged_groups: int = 0
+) -> QueueFreshness:
+ return QueueFreshness(
+ oldest_age_seconds=oldest_age_seconds,
+ blocked_batches=blocked_batches,
+ backlogged_groups=backlogged_groups,
+ )
+
+
def _make_batch(**overrides: Any) -> PendingBatch:
defaults: dict[str, Any] = {
"id": "00000000-0000-0000-0000-000000000001",
@@ -88,6 +103,17 @@ def _make_failed_run_ref(**overrides: Any) -> FailedRunRef:
return FailedRunRef(**defaults)
+def _make_orphaned_run_ref(**overrides: Any) -> OrphanedRunRef:
+ defaults: dict[str, Any] = {
+ "run_uuid": "run-1",
+ "team_id": 1,
+ "schema_id": "schema-1",
+ "non_terminal_batches": 3,
+ }
+ defaults.update(overrides)
+ return OrphanedRunRef(**defaults)
+
+
def _make_consumer(max_attempts: int = 3, **kwargs) -> BatchConsumer:
config = ConsumerConfig(
database_url="postgres://unused:unused@localhost/unused",
@@ -1824,9 +1850,9 @@ class TestReconcileFailedRuns:
return_value=False,
),
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_oldest_unclaimed_batch_age_seconds",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_queue_freshness",
new_callable=AsyncMock,
- return_value=42.0,
+ return_value=_freshness(42.0),
),
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_claimable_batch_count",
@@ -1856,9 +1882,9 @@ class TestReconcileFailedRuns:
return_value=[],
),
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_oldest_unclaimed_batch_age_seconds",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_queue_freshness",
new_callable=AsyncMock,
- return_value=1234.5,
+ return_value=_freshness(1234.5, blocked_batches=7, backlogged_groups=3),
) as mock_probe,
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_claimable_batch_count",
@@ -1869,8 +1895,10 @@ class TestReconcileFailedRuns:
await consumer._reconcile_failed_runs()
assert OLDEST_UNCLAIMED_BATCH_SECONDS._value.get() == 1234.5
assert CLAIMABLE_BATCHES._value.get() == 321
+ assert BLOCKED_BATCHES._value.get() == 7
+ assert BACKLOGGED_GROUPS._value.get() == 3
- mock_probe.return_value = None # empty queue -> gauge resets to 0
+ mock_probe.return_value = _freshness(None) # empty queue -> gauge resets to 0
with patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_failed_runs",
new_callable=AsyncMock,
@@ -1878,7 +1906,7 @@ class TestReconcileFailedRuns:
):
with (
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_oldest_unclaimed_batch_age_seconds",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_queue_freshness",
mock_probe,
),
patch(
@@ -1889,15 +1917,130 @@ class TestReconcileFailedRuns:
await consumer._reconcile_failed_runs()
assert OLDEST_UNCLAIMED_BATCH_SECONDS._value.get() == 0.0
+ @pytest.mark.asyncio
+ async def test_orphan_drain_retires_leftovers_the_newest_first_pass_never_reached(self):
+ # get_failed_runs is ORDER BY failed_at DESC LIMIT n inside a 24h lookback, so a run
+ # whose failure ages out keeps its non-terminal batches until the retention prune.
+ consumer = _make_consumer()
+ drained_before = ORPHANED_BATCHES_DRAINED_TOTAL._value.get()
+
+ with (
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.try_acquire_reconcile_sweep_slot",
+ new_callable=AsyncMock,
+ return_value=True,
+ ),
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.get_queue_freshness",
+ new_callable=AsyncMock,
+ return_value=_freshness(0.0),
+ ),
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.get_claimable_batch_count",
+ new_callable=AsyncMock,
+ return_value=0,
+ ),
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.get_failed_runs",
+ new_callable=AsyncMock,
+ return_value=[],
+ ),
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.get_stale_stranded_runs",
+ new_callable=AsyncMock,
+ return_value=[],
+ ),
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.get_runs_with_orphaned_batches",
+ new_callable=AsyncMock,
+ return_value=[_make_orphaned_run_ref(non_terminal_batches=4)],
+ ),
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.fail_run",
+ new_callable=AsyncMock,
+ return_value=4,
+ ) as mock_fail_run,
+ ):
+ await consumer._reconcile_failed_runs()
+
+ mock_fail_run.assert_awaited_once()
+ assert ORPHANED_BATCHES_DRAINED_TOTAL._value.get() == drained_before + 4
+
+ @pytest.mark.asyncio
+ async def test_orphan_drain_failure_does_not_starve_later_runs(self):
+ adapter = DeltaBatchConsumerAdapter()
+ conn = _make_healthy_conn()
+ refs = [_make_orphaned_run_ref(run_uuid="run-1"), _make_orphaned_run_ref(run_uuid="run-2")]
+ drained_before = ORPHANED_BATCHES_DRAINED_TOTAL._value.get()
+
+ with (
+ patch.object(
+ consumer_module.BatchQueue, "get_runs_with_orphaned_batches", new_callable=AsyncMock, return_value=refs
+ ),
+ patch.object(
+ consumer_module.BatchQueue,
+ "fail_run",
+ new_callable=AsyncMock,
+ side_effect=[RuntimeError("bad run"), 2],
+ ) as mock_fail_run,
+ patch(f"{consumer_module.__name__}.capture_exception") as mock_capture,
+ ):
+ await adapter._drain_orphaned_batches(conn, limit=2)
+
+ assert [call.kwargs["run_uuid"] for call in mock_fail_run.await_args_list] == ["run-1", "run-2"]
+ mock_capture.assert_called_once()
+ assert ORPHANED_BATCHES_DRAINED_TOTAL._value.get() == drained_before + 2
+
+ @pytest.mark.asyncio
+ async def test_orphan_drain_failure_does_not_stop_the_stranded_sweep(self):
+ # Each pass is isolated: the drain is best-effort cleanup, the sweeps are not.
+ consumer = _make_consumer()
+
+ with (
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.try_acquire_reconcile_sweep_slot",
+ new_callable=AsyncMock,
+ return_value=True,
+ ),
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.get_queue_freshness",
+ new_callable=AsyncMock,
+ return_value=_freshness(0.0),
+ ),
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.get_claimable_batch_count",
+ new_callable=AsyncMock,
+ return_value=0,
+ ),
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.get_failed_runs",
+ new_callable=AsyncMock,
+ return_value=[],
+ ),
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.get_runs_with_orphaned_batches",
+ new_callable=AsyncMock,
+ side_effect=RuntimeError("queue DB blew up"),
+ ),
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.get_stale_stranded_runs",
+ new_callable=AsyncMock,
+ return_value=[],
+ ) as mock_stranded,
+ ):
+ await consumer._reconcile_failed_runs()
+
+ mock_stranded.assert_awaited_once()
+
@pytest.mark.asyncio
async def test_hung_freshness_probe_saturates_gauge_and_reconcile_still_runs(self):
# A queue DB too degraded to measure freshness must read as stale, not
# pin the last good value — and the probe must not eat the sweep's budget.
consumer = _make_consumer()
- async def hung_probe(*args: Any, **kwargs: Any) -> float:
+ async def hung_probe(*args: Any, **kwargs: Any) -> QueueFreshness:
await asyncio.sleep(3600)
- return 0.0
+ return _freshness(0.0)
with (
patch(
@@ -1905,7 +2048,7 @@ class TestReconcileFailedRuns:
0.05,
),
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_oldest_unclaimed_batch_age_seconds",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_queue_freshness",
side_effect=hung_probe,
),
patch(
@@ -2071,9 +2214,9 @@ class TestReconcileFailedRuns:
with (
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_oldest_unclaimed_batch_age_seconds",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_queue_freshness",
new_callable=AsyncMock,
- return_value=0.0,
+ return_value=_freshness(0.0),
),
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_claimable_batch_count",
@@ -2085,6 +2228,11 @@ class TestReconcileFailedRuns:
new_callable=AsyncMock,
return_value=[ref],
),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_runs_with_orphaned_batches",
+ new_callable=AsyncMock,
+ return_value=[],
+ ),
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_stale_stranded_runs",
new_callable=AsyncMock,
@@ -2122,9 +2270,9 @@ class TestReconcileFailedRuns:
with (
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_oldest_unclaimed_batch_age_seconds",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_queue_freshness",
new_callable=AsyncMock,
- return_value=0.0,
+ return_value=_freshness(0.0),
),
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_claimable_batch_count",
@@ -2136,6 +2284,11 @@ class TestReconcileFailedRuns:
new_callable=AsyncMock,
return_value=[],
),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_runs_with_orphaned_batches",
+ new_callable=AsyncMock,
+ return_value=[],
+ ),
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_stale_stranded_runs",
new_callable=AsyncMock,
@@ -2184,9 +2337,9 @@ class TestReconcileFailedRuns:
with (
patch(
- f"{consumer_module.__name__}.BatchQueue.get_oldest_unclaimed_batch_age_seconds",
+ f"{consumer_module.__name__}.BatchQueue.get_queue_freshness",
new_callable=AsyncMock,
- return_value=0.0,
+ return_value=_freshness(0.0),
),
patch(
f"{consumer_module.__name__}.BatchQueue.get_claimable_batch_count",
@@ -2198,6 +2351,11 @@ class TestReconcileFailedRuns:
new_callable=AsyncMock,
return_value=[],
),
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.get_runs_with_orphaned_batches",
+ new_callable=AsyncMock,
+ return_value=[],
+ ),
patch(
f"{consumer_module.__name__}.BatchQueue.get_stale_stranded_runs",
new_callable=AsyncMock,
@@ -2231,9 +2389,9 @@ class TestReconcileFailedRuns:
with (
patch(
- f"{consumer_module.__name__}.BatchQueue.get_oldest_unclaimed_batch_age_seconds",
+ f"{consumer_module.__name__}.BatchQueue.get_queue_freshness",
new_callable=AsyncMock,
- return_value=0.0,
+ return_value=_freshness(0.0),
),
patch(
f"{consumer_module.__name__}.BatchQueue.get_claimable_batch_count",
@@ -2250,6 +2408,11 @@ class TestReconcileFailedRuns:
new_callable=AsyncMock,
side_effect=raise_with_maybe_closed_conn,
),
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.get_runs_with_orphaned_batches",
+ new_callable=AsyncMock,
+ return_value=[],
+ ),
patch(
f"{consumer_module.__name__}.BatchQueue.get_stale_stranded_runs",
new_callable=AsyncMock,
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 4d5fbddff2cf..5b53572cd333 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
@@ -25,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
TAKEOVER_STALE_THRESHOLD_SECONDS,
BatchQueue,
PendingBatch,
+ _orphaned_candidate_runs_sql,
build_status_dual_write_sql,
)
@@ -632,17 +633,76 @@ class TestVerifyGroupLeaseSync:
@pytest.mark.django_db(transaction=True)
class TestQueueFreshnessProbe:
+ @staticmethod
+ async def _freshness(conn, *, backlog_threshold_seconds: int = 900):
+ return await BatchQueue.get_queue_freshness(conn, backlog_threshold_seconds=backlog_threshold_seconds)
+
@pytest.mark.asyncio
async def test_reports_only_batches_never_picked_up(self, conn):
- assert await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn) is None
+ assert (await self._freshness(conn)).oldest_age_seconds is None
bid = await _insert_batch(conn)
- age = await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn)
- assert age is not None and age >= 0
+ assert (await self._freshness(conn)).oldest_age_seconds is not None
# Any status row means the batch was picked up — it must stop counting.
await BatchQueue.update_status(conn, batch_id=bid, job_state="executing", attempt=1)
- assert await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn) is None
+ assert (await self._freshness(conn)).oldest_age_seconds is None
+
+ @pytest.mark.asyncio
+ async def test_batch_blocked_behind_failed_sibling_is_not_queue_lag(self, conn):
+ # The claim query refuses a run that holds a failed batch, so its pending siblings
+ # can never be picked up. Counting their age made the gauge climb at one second
+ # per second until retention pruned them.
+ failed = await _insert_batch(conn, batch_index=0)
+ await BatchQueue.update_status(conn, batch_id=failed, job_state="failed", attempt=1)
+ await _insert_batch(conn, batch_index=1)
+
+ freshness = await self._freshness(conn)
+
+ assert freshness.oldest_age_seconds is None
+ assert freshness.blocked_batches == 1
+
+ @pytest.mark.asyncio
+ async def test_a_healthy_run_is_unaffected_by_another_runs_failure(self, conn):
+ failed = await _insert_batch(conn, run_uuid="run-dead", batch_index=0)
+ await BatchQueue.update_status(conn, batch_id=failed, job_state="failed", attempt=1)
+ await _insert_batch(conn, run_uuid="run-dead", batch_index=1)
+ await _insert_batch(conn, run_uuid="run-live", batch_index=0)
+
+ freshness = await self._freshness(conn)
+
+ assert freshness.oldest_age_seconds is not None
+ assert freshness.blocked_batches == 1
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "threshold_seconds,expected_groups",
+ [
+ (0, 2), # everything waiting is past a zero threshold
+ (900, 0), # nothing has waited 15 minutes in a fresh table
+ ],
+ )
+ async def test_backlogged_groups_counts_distinct_groups_past_the_threshold(
+ self, conn, threshold_seconds, expected_groups
+ ):
+ await _insert_batch(conn, team_id=1, schema_id="schema-a", run_uuid="run-a")
+ await _insert_batch(conn, team_id=1, schema_id="schema-b", run_uuid="run-b")
+ # Same group, second batch: breadth counts groups, not batches.
+ await _insert_batch(conn, team_id=1, schema_id="schema-b", run_uuid="run-b", batch_index=1)
+
+ freshness = await self._freshness(conn, backlog_threshold_seconds=threshold_seconds)
+
+ assert freshness.backlogged_groups == expected_groups
+
+ @pytest.mark.asyncio
+ async def test_blocked_batches_do_not_count_as_backlogged_groups(self, conn):
+ failed = await _insert_batch(conn, batch_index=0)
+ await BatchQueue.update_status(conn, batch_id=failed, job_state="failed", attempt=1)
+ await _insert_batch(conn, batch_index=1)
+
+ freshness = await self._freshness(conn, backlog_threshold_seconds=0)
+
+ assert freshness.backlogged_groups == 0
@pytest.mark.django_db(transaction=True)
@@ -981,6 +1041,97 @@ class TestGetRunActivitySummary:
assert summary.is_stale is False
[email protected]_db(transaction=True)
+class TestGetRunsWithOrphanedBatches:
+ """The orphan drain: runs holding a failed batch that still have non-terminal batches behind it."""
+
+ @pytest.mark.asyncio
+ async def test_returns_nothing_when_no_run_has_failed(self, conn):
+ await _insert_batch(conn, run_uuid="run-live", batch_index=0)
+
+ assert await BatchQueue.get_runs_with_orphaned_batches(conn, limit=10) == []
+
+ @pytest.mark.asyncio
+ async def test_returns_nothing_when_a_failed_run_has_no_leftovers(self, conn):
+ # fail_run already retired everything: there is nothing left to drain.
+ failed = await _insert_batch(conn, batch_index=0)
+ await BatchQueue.update_status(conn, batch_id=failed, job_state="failed", attempt=1)
+
+ assert await BatchQueue.get_runs_with_orphaned_batches(conn, limit=10) == []
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "leftover_state,expected",
+ [
+ ("pending", [("run-1", 1)]),
+ ("waiting_retry", [("run-1", 1)]),
+ # Deliberately not claimable, and outside sb_claimable_idx. Widening the
+ # candidate states to reach it costs a seq scan of every partition.
+ ("waiting", []),
+ # A consumer is working this one, or the stale-executing sweep owns it.
+ ("executing", []),
+ ],
+ )
+ async def test_finds_the_leftover_states_a_consumer_could_have_claimed(self, conn, leftover_state, expected):
+ failed = await _insert_batch(conn, batch_index=0)
+ await BatchQueue.update_status(conn, batch_id=failed, job_state="failed", attempt=1)
+ leftover = await _insert_batch(conn, batch_index=1)
+ await conn.execute(f"UPDATE {BATCH_TABLE} SET latest_state = %s WHERE id = %s", (leftover_state, leftover))
+
+ orphaned = await BatchQueue.get_runs_with_orphaned_batches(conn, limit=10)
+
+ assert [(r.run_uuid, r.non_terminal_batches) for r in orphaned] == expected
+
+ @pytest.mark.asyncio
+ async def test_candidate_scan_can_use_the_claimable_index(self, conn):
+ # The candidate states must stay exactly sb_claimable_idx's. Adding 'waiting' or
+ # 'executing' puts the scan outside the partial index and the planner falls back to
+ # a parallel seq scan of every partition — 12x the cost on the production queue,
+ # once per reconcile interval.
+ failed = await _insert_batch(conn, batch_index=0)
+ await BatchQueue.update_status(conn, batch_id=failed, job_state="failed", attempt=1)
+ await _insert_batch(conn, batch_index=1)
+ await conn.execute("SET enable_seqscan = off")
+ try:
+ cur = await conn.execute(
+ "EXPLAIN (FORMAT TEXT) " + _orphaned_candidate_runs_sql(),
+ {"limit": 100},
+ )
+ plan = "\n".join(row[0] for row in await cur.fetchall())
+ finally:
+ await conn.execute("SET enable_seqscan = on")
+
+ assert "sb_claimable_idx" in plan
+
+ @pytest.mark.asyncio
+ async def test_oldest_run_first_so_the_limit_cannot_starve_the_backlog(self, conn):
+ # get_failed_runs is newest-first inside a lookback, which is exactly how a run's
+ # leftovers become unreachable. This pass must walk the other way.
+ for run_uuid, age_hours in (("run-new", 1), ("run-old", 48), ("run-mid", 12)):
+ failed = await _insert_batch(conn, run_uuid=run_uuid, batch_index=0)
+ await BatchQueue.update_status(conn, batch_id=failed, job_state="failed", attempt=1)
+ leftover = await _insert_batch(conn, run_uuid=run_uuid, batch_index=1)
+ await conn.execute(
+ f"UPDATE {BATCH_TABLE} SET created_at = now() - make_interval(hours => %s) WHERE id = %s",
+ (age_hours, leftover),
+ )
+
+ orphaned = await BatchQueue.get_runs_with_orphaned_batches(conn, limit=2)
+
+ assert [r.run_uuid for r in orphaned] == ["run-old", "run-mid"]
+
+ @pytest.mark.asyncio
+ async def test_another_runs_failure_does_not_pull_in_a_healthy_run(self, conn):
+ failed = await _insert_batch(conn, run_uuid="run-dead", batch_index=0)
+ await BatchQueue.update_status(conn, batch_id=failed, job_state="failed", attempt=1)
+ await _insert_batch(conn, run_uuid="run-dead", batch_index=1)
+ await _insert_batch(conn, run_uuid="run-live", batch_index=0)
+
+ orphaned = await BatchQueue.get_runs_with_orphaned_batches(conn, limit=10)
+
+ assert [r.run_uuid for r in orphaned] == ["run-dead"]
+
+
@pytest.mark.django_db(transaction=True)
class TestGetStaleStrandedRuns:
"""The abandoned-run query: non-terminal batches, no live lease, no loader progress past the threshold."""