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.

feat(data-warehouse): split loader queue age into slot-wait and serialized ages (#123872)

Tom Owers891a056a305e
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 7ce4308a5a6f..0c52ff0e8951 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
@@ -96,6 +96,7 @@ from products.warehouse_sources_queue.backend.core.metrics import (
DEPTH_PROBE_TIMEOUTS_TOTAL,
DEPTH_SAMPLE_AGE_SECONDS,
DRAINED_AFTER_FAILURE_TOTAL,
+ OLDEST_SERIALIZED_BATCH_SECONDS,
OLDEST_UNCLAIMED_BATCH_SECONDS,
ORPHANED_BATCHES_DRAINED_TOTAL,
RUNS_FAILED_AGED_OUT_TOTAL,
@@ -931,8 +932,8 @@ class DeltaBatchConsumerAdapter:
that value as if it were fresh.
Each probe statement has a server-side timeout. Past it, the freshness
- probe skips its sample and its gauges stay NaN, except that the age gauge
- saturates on any timeout, because a queue DB too degraded to measure
+ probe skips its sample and its gauges stay NaN, except that the slot-wait
+ age gauge saturates on any timeout, because a queue DB too degraded to measure
freshness must read as stale. The depth gauges behave differently: the
queue is deepest exactly when the depth probe is slowest, so NaN would
read as an empty queue on a panel. The slot holder repeats its last good
@@ -985,7 +986,8 @@ class DeltaBatchConsumerAdapter:
return
# 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(freshness.oldest_age_seconds or 0.0)
+ OLDEST_UNCLAIMED_BATCH_SECONDS.set(freshness.slot_wait_age_seconds or 0.0)
+ OLDEST_SERIALIZED_BATCH_SECONDS.set(freshness.serialized_age_seconds or 0.0)
BLOCKED_BATCHES.set(freshness.blocked_batches)
BACKLOGGED_GROUPS.set(freshness.backlogged_groups)
# Depth rides the same slot and timeout: age says how stale the head of
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 607df3eacc52..6e6b26e0db39 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
@@ -84,6 +84,7 @@ from products.warehouse_sources_queue.backend.core.metrics import (
DEPTH_SAMPLE_AGE_SECONDS,
HEARTBEAT_RECONNECT_FAILURES_TOTAL,
HEARTBEAT_RECONNECTS_TOTAL,
+ OLDEST_SERIALIZED_BATCH_SECONDS,
OLDEST_UNCLAIMED_BATCH_SECONDS,
ORPHANED_BATCHES_DRAINED_TOTAL,
QUEUE_SAMPLE_GAUGES,
@@ -98,10 +99,15 @@ from products.warehouse_sources_queue.backend.models import SourceBatchStatus
def _freshness(
- oldest_age_seconds: float | None, *, blocked_batches: int = 0, backlogged_groups: int = 0
+ slot_wait_age_seconds: float | None,
+ *,
+ serialized_age_seconds: float | None = None,
+ blocked_batches: int = 0,
+ backlogged_groups: int = 0,
) -> QueueFreshness:
return QueueFreshness(
- oldest_age_seconds=oldest_age_seconds,
+ slot_wait_age_seconds=slot_wait_age_seconds,
+ serialized_age_seconds=serialized_age_seconds,
blocked_batches=blocked_batches,
backlogged_groups=backlogged_groups,
)
@@ -2666,7 +2672,7 @@ class TestReconcileFailedRuns:
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_queue_freshness",
new_callable=AsyncMock,
- return_value=_freshness(1234.5, blocked_batches=7, backlogged_groups=3),
+ return_value=_freshness(1234.5, serialized_age_seconds=5678.0, 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_queue_depth",
@@ -2682,6 +2688,7 @@ class TestReconcileFailedRuns:
):
await consumer._reconcile_failed_runs()
assert OLDEST_UNCLAIMED_BATCH_SECONDS._value.get() == 1234.5
+ assert OLDEST_SERIALIZED_BATCH_SECONDS._value.get() == 5678.0
assert CLAIMABLE_BATCHES._value.get() == 321
assert BLOCKED_BATCHES._value.get() == 7
assert BACKLOGGED_GROUPS._value.get() == 3
@@ -2709,6 +2716,7 @@ class TestReconcileFailedRuns:
):
await consumer._reconcile_failed_runs()
assert OLDEST_UNCLAIMED_BATCH_SECONDS._value.get() == 0.0
+ assert OLDEST_SERIALIZED_BATCH_SECONDS._value.get() == 0.0
assert CLAIMABLE_BATCHES._value.get() == 0
assert CLAIMABLE_GROUPS._value.get() == 0
assert TOP_GROUPS_CLAIMABLE_SHARE._value.get() == 0.0
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 d5c7daf101ab..14f6c31715ab 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
@@ -75,6 +75,32 @@ async def _insert_batch(conn: psycopg.AsyncConnection[Any], **overrides: Any) ->
return await BatchQueue.insert(conn, **params)
+async def _seed_gate_probe_population(conn: psycopg.AsyncConnection[Any]) -> None:
+ # Seed each probe's population and analyze, so the index pins are
+ # deterministic. With one row the planner rates the partial indexes that
+ # cover each probe on empty statistics, and the failed-run probe can pick
+ # sb_failed_changed_idx instead. Failed batches spread across many runs is
+ # the shape sb_run_gate_idx exists for, and executing batches spread across
+ # many groups is the shape sb_schema_busy_idx exists for. Keep the
+ # claimable set small: with many claimable runs the planner hashes every
+ # failed batch once, which is a correct plan for that shape.
+ await conn.execute(f"""
+ INSERT INTO {BATCH_TABLE} (
+ team_id, schema_id, source_id, job_id, run_uuid, batch_index,
+ s3_path, row_count, byte_size, is_final_batch, sync_type,
+ resource_name, latest_state, state_changed_at
+ )
+ SELECT 1, 'seed-schema-' || (g % 200), 'source-1', 'job-1', 'seed-run-' || (g % 500), g,
+ 's3://bucket/path', 100, 1024, false, 'full_refresh', 'test_resource',
+ CASE WHEN g <= 2500 THEN 'failed' ELSE 'executing' END,
+ now() - (g || ' seconds')::interval
+ FROM generate_series(1, 3000) g
+ """)
+ for n in range(3):
+ await _insert_batch(conn, schema_id=f"schema-{n}", run_uuid=f"run-{n}")
+ await conn.execute(f"ANALYZE {BATCH_TABLE}")
+
+
@pytest.fixture(scope="session")
def _db_url() -> str:
return _get_test_database_url()
@@ -774,14 +800,16 @@ class TestQueueFreshnessProbe:
@pytest.mark.asyncio
async def test_reports_only_batches_never_picked_up(self, conn):
- assert (await self._freshness(conn)).oldest_age_seconds is None
+ empty = await self._freshness(conn)
+ assert (empty.slot_wait_age_seconds, empty.serialized_age_seconds) == (None, None)
bid = await _insert_batch(conn)
- assert (await self._freshness(conn)).oldest_age_seconds is not None
+ assert (await self._freshness(conn)).slot_wait_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 self._freshness(conn)).oldest_age_seconds is None
+ picked_up = await self._freshness(conn)
+ assert (picked_up.slot_wait_age_seconds, picked_up.serialized_age_seconds) == (None, None)
@pytest.mark.asyncio
async def test_batch_blocked_behind_failed_sibling_is_not_queue_lag(self, conn):
@@ -794,7 +822,7 @@ class TestQueueFreshnessProbe:
freshness = await self._freshness(conn)
- assert freshness.oldest_age_seconds is None
+ assert freshness.slot_wait_age_seconds is None
assert freshness.blocked_batches == 1
@pytest.mark.asyncio
@@ -806,9 +834,44 @@ class TestQueueFreshnessProbe:
freshness = await self._freshness(conn)
- assert freshness.oldest_age_seconds is not None
+ assert freshness.slot_wait_age_seconds is not None
assert freshness.blocked_batches == 1
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "siblings,expected_lane",
+ [
+ ([("run-1", "executing")], "serialized"),
+ # The busy check is per group, not per run, matching the claim query's schema-busy gate.
+ ([("run-2", "executing")], "serialized"),
+ ([("run-1", "succeeded")], "slot_wait"),
+ ([("run-1", "waiting")], "slot_wait"),
+ ([("run-2", "failed")], "slot_wait"),
+ # A blocked run stays out of both ages, also when its group is busy.
+ ([("run-1", "failed"), ("run-2", "executing")], "blocked"),
+ ],
+ )
+ async def test_an_executing_batch_in_the_group_moves_the_pending_age_to_the_serialized_lane(
+ self, conn, siblings, expected_lane
+ ):
+ for run_uuid, state in siblings:
+ sibling = await _insert_batch(conn, run_uuid=run_uuid, batch_index=0)
+ await BatchQueue.update_status(conn, batch_id=sibling, job_state=state, attempt=1)
+ await _insert_batch(conn, run_uuid="run-1", batch_index=1)
+
+ freshness = await self._freshness(conn, backlog_threshold_seconds=0)
+
+ assert (
+ freshness.slot_wait_age_seconds is not None,
+ freshness.serialized_age_seconds is not None,
+ freshness.backlogged_groups,
+ freshness.blocked_batches,
+ ) == {
+ "slot_wait": (True, False, 1, 0),
+ "serialized": (False, True, 0, 0),
+ "blocked": (False, False, 0, 1),
+ }[expected_lane]
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
"threshold_seconds,expected_groups",
@@ -840,10 +903,10 @@ class TestQueueFreshnessProbe:
assert freshness.backlogged_groups == 0
@pytest.mark.asyncio
- async def test_probe_uses_the_partial_indexes_and_probes_each_run_once(self, conn):
- # An inlined CTE copies the failed-run EXISTS into each FILTER that reads it,
- # which ran the probe up to three times per pending batch in production.
- await _insert_batch(conn)
+ async def test_probe_uses_the_partial_indexes_and_probes_each_run_and_group_once(self, conn):
+ # An inlined CTE copies each EXISTS into every FILTER that reads it,
+ # which ran the failed-run probe up to three times per pending batch in production.
+ await _seed_gate_probe_population(conn)
await conn.execute("SET enable_seqscan = off")
try:
cur = await conn.execute("EXPLAIN (FORMAT TEXT) " + _queue_freshness_sql(), {"backlog_threshold": 900})
@@ -853,7 +916,8 @@ class TestQueueFreshnessProbe:
assert "sb_claimable_idx" in plan
assert "sb_run_gate_idx" in plan
- assert plan.count("SubPlan") == 1
+ assert "sb_schema_busy_idx" in plan
+ assert plan.count("SubPlan") == 2
@pytest.mark.asyncio
@pytest.mark.parametrize("probe", ["freshness", "depth"])
@@ -2864,29 +2928,7 @@ class TestGetQueueDepth:
# probes; a predicate edit that widens either falls back to scanning
# every retained partition on every pod, every reconcile interval.
#
- # Seed each probe's population and analyze, so the index pins are
- # deterministic. With one row the planner rates the partial indexes that
- # cover each probe on empty statistics, and the failed-run probe can pick
- # sb_failed_changed_idx instead. Failed batches spread across many runs is
- # the shape sb_run_gate_idx exists for, and executing batches spread across
- # many groups is the shape sb_schema_busy_idx exists for. Keep the
- # claimable set small: with many claimable runs the planner hashes every
- # failed batch once, which is a correct plan for that shape.
- await conn.execute(f"""
- INSERT INTO {BATCH_TABLE} (
- team_id, schema_id, source_id, job_id, run_uuid, batch_index,
- s3_path, row_count, byte_size, is_final_batch, sync_type,
- resource_name, latest_state, state_changed_at
- )
- SELECT 1, 'seed-schema-' || (g % 200), 'source-1', 'job-1', 'seed-run-' || (g % 500), g,
- 's3://bucket/path', 100, 1024, false, 'full_refresh', 'test_resource',
- CASE WHEN g <= 2500 THEN 'failed' ELSE 'executing' END,
- now() - (g || ' seconds')::interval
- FROM generate_series(1, 3000) g
- """)
- for n in range(3):
- await _insert_batch(conn, schema_id=f"schema-{n}", run_uuid=f"run-{n}")
- await conn.execute(f"ANALYZE {BATCH_TABLE}")
+ await _seed_gate_probe_population(conn)
await conn.execute("SET enable_seqscan = off")
try:
cur = await conn.execute("EXPLAIN (FORMAT TEXT) " + _queue_depth_sql(), {"top_groups": 5})
diff --git a/products/warehouse_sources_queue/backend/README.md b/products/warehouse_sources_queue/backend/README.md
index 67b3e28cc136..8fc5f6ec5420 100644
--- a/products/warehouse_sources_queue/backend/README.md
+++ b/products/warehouse_sources_queue/backend/README.md
@@ -136,8 +136,12 @@ Other sinks get that nine-metric engine set under their own `{prefix}_pg_consume
Further counters exist only under the `warehouse_pg_consumer_*` prefix, incremented by the Delta consumer's reconcile sweep (`consumer.py`) rather than by the shared engine: `runs_reconciled_total`, `runs_terminalized_stale_total` and `runs_failed_aged_out_total`.
`recovery_sweeps_total` has three outcomes. `clean` means the sweep found no orphaned batch. `orphans_found_after_shutdown` means every orphan carried the shutdown marker of a graceful stop, such as a deploy. `orphans_found` means at least one orphan had no marker, so a consumer died without notice (an OOM kill or a crash) or lost its lease. Alerts read `orphans_found`.
-The headline health signal is `warehouse_pg_queue_oldest_unclaimed_batch_seconds`: the age of the oldest batch no consumer has picked up yet.
+The headline health signal is `warehouse_pg_queue_oldest_unclaimed_batch_seconds`: the age of the oldest batch no consumer has picked up yet that a free loader slot could claim now.
It is the loader's data-freshness signal and rises whenever loading stalls, regardless of cause, so its alert fires even when every other signal looks green.
+It excludes batches whose `(team_id, schema_id)` group already has a batch executing, because the loader claims one batch per group at a time.
+`warehouse_pg_queue_oldest_serialized_batch_seconds` reports the age of those batches.
+One slow batch or a long full refresh raises the serialized age for hours while slots stay idle, so it is a per-group signal, not a capacity signal.
+`warehouse_pg_queue_backlogged_groups` counts the groups with no batch executing whose oldest pending batch is past the backlog threshold, so it pairs with the slot-wait age.
Its depth companion `warehouse_pg_queue_claimable_batches` says how much work sits behind that head; a stall and a burst look identical on age alone.
Four concentration gauges ride the same depth probe and say where that depth sits.
The loader drains each `(team_id, schema_id)` group one batch at a time by design.
diff --git a/products/warehouse_sources_queue/backend/core/jobs_db.py b/products/warehouse_sources_queue/backend/core/jobs_db.py
index e5ce7d797109..9ac1bf8ddc07 100644
--- a/products/warehouse_sources_queue/backend/core/jobs_db.py
+++ b/products/warehouse_sources_queue/backend/core/jobs_db.py
@@ -716,17 +716,22 @@ def _orphaned_candidate_runs_sql() -> str:
def _queue_freshness_sql() -> str:
- """Age, blocked count, and backlogged groups of the pending set, in one scan.
+ """Two ages, blocked count, and backlogged groups of the pending set, in one scan.
The scan is ``latest_state = 'pending'`` inside ``FRESHNESS_WINDOW``, which
``sb_claimable_idx`` serves (its predicate covers 'pending'). The scan is
aggregated into runs before the failed-run probe, so the probe costs one
``sb_run_gate_idx`` descent per run, not one per batch. The result is the
- same, because a run is blocked or not as a whole.
+ same, because a run is blocked or not as a whole. The runs are then
+ aggregated into groups before the executing probe, so that probe costs one
+ ``sb_schema_busy_idx`` descent per group, the same as in
+ :func:`_queue_depth_sql`. A group with an executing batch is serialized: the
+ claim query holds all its other batches until that batch finishes.
- ``gated_runs`` is MATERIALIZED on purpose. The final SELECT reads ``blocked``
- in three FILTER clauses. An inlined CTE copies the EXISTS sub-plan into each
- of them, which runs the probe up to three times per row.
+ ``gated_runs`` and ``gated_groups`` are MATERIALIZED on purpose. The SELECT
+ after each one reads ``blocked`` or ``executing`` in more than one FILTER
+ clause. An inlined CTE copies the EXISTS sub-plan into each of them, which
+ runs the probe once per FILTER for each row.
Split out from its caller so the plan-shape test can EXPLAIN exactly what runs.
"""
@@ -757,15 +762,39 @@ def _queue_freshness_sql() -> str:
AND b_failed.latest_state = 'failed'
) AS blocked
FROM pending_runs r
+ ),
+ pending_groups AS (
+ SELECT
+ g.team_id,
+ g.schema_id,
+ min(g.oldest_created_at) FILTER (WHERE NOT g.blocked) AS oldest_created_at,
+ coalesce(sum(g.batches) FILTER (WHERE g.blocked), 0) AS blocked_batches
+ FROM gated_runs g
+ GROUP BY g.team_id, g.schema_id
+ ),
+ gated_groups AS MATERIALIZED (
+ SELECT
+ p.oldest_created_at,
+ p.blocked_batches,
+ EXISTS (
+ SELECT 1
+ FROM {BATCH_TABLE} b_busy
+ WHERE b_busy.team_id = p.team_id
+ AND b_busy.schema_id = p.schema_id
+ AND b_busy.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND b_busy.latest_state = 'executing'
+ ) AS executing
+ FROM pending_groups p
)
SELECT
- EXTRACT(EPOCH FROM (now() - min(oldest_created_at) FILTER (WHERE NOT blocked))),
- coalesce(sum(batches) FILTER (WHERE blocked), 0),
- count(DISTINCT (team_id, schema_id)) FILTER (
- WHERE NOT blocked
+ EXTRACT(EPOCH FROM (now() - min(oldest_created_at) FILTER (WHERE NOT executing))),
+ EXTRACT(EPOCH FROM (now() - min(oldest_created_at) FILTER (WHERE executing))),
+ coalesce(sum(blocked_batches), 0),
+ count(*) FILTER (
+ WHERE NOT executing
AND oldest_created_at <= now() - make_interval(secs => %(backlog_threshold)s)
)
- FROM gated_runs
+ FROM gated_groups
"""
@@ -1354,15 +1383,21 @@ class GroupLease:
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.
+ Four numbers rather than one because they fail differently: the slot-wait
+ age says how far the queue head has fallen behind for lack of a free slot,
+ the serialized age says how long work waits behind its own group, 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 one blended age cannot
+ tell one slow group from a fleet-wide stall.
"""
- # None when nothing claimable is waiting.
- oldest_age_seconds: float | None
+ # Oldest pending batch whose group has no batch executing, so a free slot can
+ # claim it now. None when no such batch is waiting.
+ slot_wait_age_seconds: float | None
+ # Oldest pending batch whose group already has a batch executing. The claim
+ # query holds it until that batch finishes, however many slots are free.
+ # None when no such batch is waiting.
+ serialized_age_seconds: float | None
blocked_batches: int
backlogged_groups: int
@@ -2676,24 +2711,36 @@ class BatchQueue:
backlog_threshold_seconds: int,
statement_timeout_ms: int = GAUGE_STATEMENT_TIMEOUT_MS,
) -> 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
+ """Four readings off one scan of the pending set, bounded to ``FRESHNESS_WINDOW``.
+
+ Both ages exclude 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.
+
+ The two ages split the remaining pending batches by their (team_id,
+ schema_id) group, with the same rule as the
+ ``slot_waiting_batches``/``serialized_batches`` split of
+ :meth:`get_queue_depth`. ``slot_wait_age_seconds`` covers groups with no
+ batch executing: a free slot can claim that work now, so its age is the
+ loader's lag. ``serialized_age_seconds`` covers groups with a batch
+ executing: the claim query loads a group one batch at a time, so one
+ slow batch or a long full refresh holds the rest of its group back while
+ slots stay idle. A single blended age read that one slow group as a
+ fleet-wide stall.
+
+ ``blocked_batches`` keeps the failed-run 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.
+ ``backlogged_groups`` is the breadth companion to the slot-wait age, so
+ it counts only groups with no batch executing whose oldest pending batch
+ is past the threshold. 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.
Raises ``psycopg.errors.QueryCanceled`` past ``statement_timeout_ms``.
"""
@@ -2701,11 +2748,14 @@ class BatchQueue:
await cur.execute(_queue_freshness_sql(), {"backlog_threshold": backlog_threshold_seconds})
row = await cur.fetchone()
if row is None:
- return QueueFreshness(oldest_age_seconds=None, blocked_batches=0, backlogged_groups=0)
+ return QueueFreshness(
+ slot_wait_age_seconds=None, serialized_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),
+ slot_wait_age_seconds=float(row[0]) if row[0] is not None else None,
+ serialized_age_seconds=float(row[1]) if row[1] is not None else None,
+ blocked_batches=int(row[2] or 0),
+ backlogged_groups=int(row[3] or 0),
)
@staticmethod
diff --git a/products/warehouse_sources_queue/backend/core/metrics.py b/products/warehouse_sources_queue/backend/core/metrics.py
index 62ab90033c13..972c65fcc320 100644
--- a/products/warehouse_sources_queue/backend/core/metrics.py
+++ b/products/warehouse_sources_queue/backend/core/metrics.py
@@ -128,13 +128,30 @@ RUNS_FAILED_AGED_OUT_TOTAL = Counter(
OLDEST_UNCLAIMED_BATCH_SECONDS = Gauge(
"warehouse_pg_queue_oldest_unclaimed_batch_seconds",
"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. "
+ "free loader slot could claim now (0 = none waiting). Batches whose (team_id, schema_id) "
+ "group already has a batch executing are excluded: they wait behind their own group, not "
+ "for a slot, and warehouse_pg_queue_oldest_serialized_batch_seconds reports them. Batches "
+ "whose run already holds a failed batch are excluded too: the claim query refuses those, so "
+ "their age is not queue lag, and warehouse_pg_queue_blocked_batches counts them. "
"Sampled on the reconcile cadence; saturates at the freshness probe window.",
multiprocess_mode="liveall",
)
+# The population the age gauge above excludes because its group is busy. The loader
+# claims one batch per (team, schema) group at a time, so one slow batch or a long
+# full refresh holds the rest of its group back while slots stay idle. This gauge
+# keeps that wait apart from the age gauge above, so one slow group does not read
+# as a fleet-wide stall.
+OLDEST_SERIALIZED_BATCH_SECONDS = Gauge(
+ "warehouse_pg_queue_oldest_serialized_batch_seconds",
+ "Age of the oldest queue batch no consumer has picked up yet whose (team_id, schema_id) "
+ "group already has a batch executing, so it waits for its own group and not for a slot "
+ "(0 = none waiting). Same blocked-batch exclusion as "
+ "warehouse_pg_queue_oldest_unclaimed_batch_seconds. Sampled on the reconcile cadence; "
+ "NaN when the freshness probe times out.",
+ multiprocess_mode="liveall",
+)
+
# 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
@@ -152,8 +169,8 @@ BLOCKED_BATCHES = Gauge(
# 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.",
+ "Distinct (team_id, schema_id) groups with no batch executing whose oldest claimable "
+ "batch is older than the backlog threshold. Sampled on the reconcile cadence.",
multiprocess_mode="liveall",
)
@@ -229,6 +246,7 @@ DEPTH_PROBE_TIMEOUTS_TOTAL = Counter(
QUEUE_SAMPLE_GAUGES: tuple[Gauge, ...] = (
OLDEST_UNCLAIMED_BATCH_SECONDS,
+ OLDEST_SERIALIZED_BATCH_SECONDS,
BLOCKED_BATCHES,
BACKLOGGED_GROUPS,
CLAIMABLE_BATCHES,