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): keep the queue depth gauge honest during a backlog (#112702)

Tom Owers7076cee6a867
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 1c5720bb0828..0b040c4c6aa8 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
@@ -7,6 +7,7 @@ polling, retry, and recovery mechanics to the v3 batch consumer engine.
from __future__ import annotations
+import math
import time
import asyncio
from collections.abc import Callable, Coroutine
@@ -72,6 +73,7 @@ from products.warehouse_sources_queue.backend.core.jobs_db import (
BatchQueue,
FailedRunRef,
PendingBatch,
+ QueueDepth,
_Unset,
queue_gauges_slot_key,
)
@@ -80,6 +82,8 @@ from products.warehouse_sources_queue.backend.core.metrics import (
BLOCKED_BATCHES,
CLAIMABLE_BATCHES,
CLAIMABLE_GROUPS,
+ DEPTH_PROBE_TIMEOUTS_TOTAL,
+ DEPTH_SAMPLE_AGE_SECONDS,
DRAINED_AFTER_FAILURE_TOTAL,
OLDEST_UNCLAIMED_BATCH_SECONDS,
ORPHANED_BATCHES_DRAINED_TOTAL,
@@ -241,6 +245,10 @@ class DeltaBatchConsumerAdapter:
self._gauge_slot_key = queue_gauges_slot_key(
sync_types=claim_sync_types, exclude_sync_types=claim_exclude_sync_types
)
+ # Last full depth sample and when it was taken (time.monotonic()). Only the gauge
+ # slot holder keeps one; it is re-exported while the depth probe times out.
+ self._depth_sample: QueueDepth | None = None
+ self._depth_sampled_at = 0.0
# job_id -> (is_dead, checked_at via time.monotonic())
self._job_dead_cache: dict[str, tuple[bool, float]] = {}
# job_id -> (status, latest_error) for dead jobs only, so the drain decision in
@@ -767,19 +775,27 @@ class DeltaBatchConsumerAdapter:
slot, so a pod that sampled in an earlier round can never keep exporting
that value as if it were fresh.
- Each probe statement has a server-side timeout. Past it, the probe skips
- its sample and the gauges stay NaN, with one exception: the age gauge
+ 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
- freshness must read as stale. The whole probe also has a client timeout,
+ 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
+ depth sample instead, and ``warehouse_pg_queue_depth_sample_age_seconds``
+ says how old it is. A pod that does not hold the slot drops its sample
+ and exports NaN. The whole probe also has a client timeout,
so it cannot eat the reconcile sweep's budget. Other failures are
swallowed-with-capture so a broken probe can't take the sweep down.
"""
clear_queue_sample_gauges()
+ holds_slot = False
try:
async with asyncio.timeout(FRESHNESS_PROBE_TIMEOUT_SECONDS):
- if not await BatchQueue.try_acquire_queue_gauges_slot(
+ holds_slot = await BatchQueue.try_acquire_queue_gauges_slot(
conn, owner_token=self._gauge_owner_token, slot_key=self._gauge_slot_key
- ):
+ )
+ if not holds_slot:
+ self._depth_sample = None
logger.debug("queue_gauges_slot_held_elsewhere")
return
await self._sample_queue_gauges(conn)
@@ -789,6 +805,8 @@ class DeltaBatchConsumerAdapter:
timeout_seconds=FRESHNESS_PROBE_TIMEOUT_SECONDS,
)
OLDEST_UNCLAIMED_BATCH_SECONDS.set(FRESHNESS_WINDOW_SECONDS)
+ if holds_slot:
+ self._export_last_depth_sample()
return
except Exception as e:
logger.exception("queue_freshness_probe_failed")
@@ -805,6 +823,7 @@ class DeltaBatchConsumerAdapter:
logger.info("queue_freshness_probe_statement_timed_out", timeout_ms=GAUGE_STATEMENT_TIMEOUT_MS)
OLDEST_UNCLAIMED_BATCH_SECONDS.set(FRESHNESS_WINDOW_SECONDS)
# The depth probe reads a larger set than this one, so it would time out too.
+ self._export_last_depth_sample()
return
# Set immediately, so a failure in the depth probe below can never
# blind the age gauge this alert hangs off.
@@ -818,13 +837,44 @@ class DeltaBatchConsumerAdapter:
with observe_queue_query("claimable_depth_probe"):
depth = await BatchQueue.get_queue_depth(conn)
except psycopg.errors.QueryCanceled:
+ DEPTH_PROBE_TIMEOUTS_TOTAL.labels(stage="count").inc()
logger.info("queue_depth_probe_statement_timed_out", timeout_ms=GAUGE_STATEMENT_TIMEOUT_MS)
+ self._export_last_depth_sample()
+ return
+ now = time.monotonic()
+ previous = self._depth_sample
+ if depth.claimable_groups is None:
+ DEPTH_PROBE_TIMEOUTS_TOTAL.labels(stage="breakdown").inc()
+ logger.info("queue_depth_breakdown_statement_timed_out", timeout_ms=GAUGE_STATEMENT_TIMEOUT_MS)
+ # The fresh count still lands. The split keeps its last good value and its age.
+ self._depth_sample = QueueDepth(
+ claimable_batches=depth.claimable_batches,
+ claimable_groups=previous.claimable_groups if previous else None,
+ top_groups_claimable_share=previous.top_groups_claimable_share if previous else None,
+ slot_waiting_batches=previous.slot_waiting_batches if previous else None,
+ serialized_batches=previous.serialized_batches if previous else None,
+ )
+ else:
+ self._depth_sample = depth
+ self._depth_sampled_at = now
+ self._export_last_depth_sample()
+
+ def _export_last_depth_sample(self) -> None:
+ """Set the depth gauges from the last sample; leave NaN for any field never sampled."""
+ sample = self._depth_sample
+ if sample is None:
return
- CLAIMABLE_BATCHES.set(depth.claimable_batches)
- CLAIMABLE_GROUPS.set(depth.claimable_groups)
- TOP_GROUPS_CLAIMABLE_SHARE.set(depth.top_groups_claimable_share)
- SLOT_WAITING_BATCHES.set(depth.slot_waiting_batches)
- SERIALIZED_BATCHES.set(depth.serialized_batches)
+ CLAIMABLE_BATCHES.set(sample.claimable_batches)
+ for gauge, value in (
+ (CLAIMABLE_GROUPS, sample.claimable_groups),
+ (TOP_GROUPS_CLAIMABLE_SHARE, sample.top_groups_claimable_share),
+ (SLOT_WAITING_BATCHES, sample.slot_waiting_batches),
+ (SERIALIZED_BATCHES, sample.serialized_batches),
+ ):
+ if value is not None:
+ gauge.set(value)
+ has_breakdown = sample.claimable_groups is not None
+ DEPTH_SAMPLE_AGE_SECONDS.set(time.monotonic() - self._depth_sampled_at if has_breakdown else math.nan)
async def should_process_batch(
self,
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 4db79ade45ec..5f670ab05cf3 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
@@ -64,6 +64,8 @@ from products.warehouse_sources_queue.backend.core.metrics import (
BLOCKED_BATCHES,
CLAIMABLE_BATCHES,
CLAIMABLE_GROUPS,
+ DEPTH_PROBE_TIMEOUTS_TOTAL,
+ DEPTH_SAMPLE_AGE_SECONDS,
OLDEST_UNCLAIMED_BATCH_SECONDS,
ORPHANED_BATCHES_DRAINED_TOTAL,
QUEUE_SAMPLE_GAUGES,
@@ -2403,6 +2405,95 @@ class TestReconcileFailedRuns:
assert mock_depth.await_count == int(depth_awaited)
mock_failed_runs.assert_awaited_once()
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "second_round_failure",
+ ["depth_count_timeout", "depth_breakdown_timeout", "freshness_timeout"],
+ )
+ async def test_depth_gauges_keep_the_last_good_sample_when_a_probe_times_out(self, second_round_failure):
+ consumer = _make_consumer()
+ canceled = psycopg.errors.QueryCanceled("canceling statement due to statement timeout")
+ good = _depth(
+ 12_000,
+ claimable_groups=9,
+ top_groups_claimable_share=0.5,
+ slot_waiting_batches=10_000,
+ serialized_batches=2_000,
+ )
+ no_breakdown = QueueDepth(
+ claimable_batches=13_000,
+ claimable_groups=None,
+ top_groups_claimable_share=None,
+ slot_waiting_batches=None,
+ serialized_batches=None,
+ )
+ with (
+ patch.object(
+ consumer_module.BatchQueue,
+ "get_queue_freshness",
+ new_callable=AsyncMock,
+ side_effect=[
+ _freshness(42.0),
+ canceled if second_round_failure == "freshness_timeout" else _freshness(43.0),
+ ],
+ ),
+ patch.object(
+ consumer_module.BatchQueue,
+ "get_queue_depth",
+ new_callable=AsyncMock,
+ side_effect=[
+ good,
+ canceled if second_round_failure == "depth_count_timeout" else no_breakdown,
+ ],
+ ),
+ patch.object(consumer_module.BatchQueue, "get_failed_runs", new_callable=AsyncMock, return_value=[]),
+ ):
+ await consumer._reconcile_failed_runs()
+ assert DEPTH_SAMPLE_AGE_SECONDS._value.get() < 1
+ timeouts_before = DEPTH_PROBE_TIMEOUTS_TOTAL.labels(stage="count")._value.get()
+ await consumer._reconcile_failed_runs()
+
+ expected_batches = 13_000 if second_round_failure == "depth_breakdown_timeout" else 12_000
+ assert CLAIMABLE_BATCHES._value.get() == expected_batches
+ assert CLAIMABLE_GROUPS._value.get() == 9
+ assert SLOT_WAITING_BATCHES._value.get() == 10_000
+ assert SERIALIZED_BATCHES._value.get() == 2_000
+ assert TOP_GROUPS_CLAIMABLE_SHARE._value.get() == 0.5
+ assert DEPTH_SAMPLE_AGE_SECONDS._value.get() >= 0
+ counted = DEPTH_PROBE_TIMEOUTS_TOTAL.labels(stage="count")._value.get() - timeouts_before
+ assert counted == (1 if second_round_failure == "depth_count_timeout" else 0)
+
+ @pytest.mark.asyncio
+ async def test_a_pod_that_lost_the_gauge_slot_never_exports_a_depth_sample_or_zero(self):
+ consumer = _make_consumer()
+ canceled = psycopg.errors.QueryCanceled("canceling statement due to statement timeout")
+ with (
+ patch.object(
+ consumer_module.BatchQueue,
+ "try_acquire_queue_gauges_slot",
+ new_callable=AsyncMock,
+ side_effect=[True, False, True],
+ ),
+ patch.object(
+ consumer_module.BatchQueue, "get_queue_freshness", new_callable=AsyncMock, return_value=_freshness(1.0)
+ ),
+ patch.object(
+ consumer_module.BatchQueue,
+ "get_queue_depth",
+ new_callable=AsyncMock,
+ side_effect=[_depth(12_000, claimable_groups=3), canceled],
+ ),
+ patch.object(consumer_module.BatchQueue, "get_failed_runs", new_callable=AsyncMock, return_value=[]),
+ ):
+ await consumer._reconcile_failed_runs()
+ await consumer._reconcile_failed_runs()
+ assert all(math.isnan(gauge._value.get()) for gauge in QUEUE_SAMPLE_GAUGES)
+ await consumer._reconcile_failed_runs()
+
+ # Re-acquired after a gap: the old sample is gone, so a timeout leaves NaN rather than a stale value.
+ assert math.isnan(CLAIMABLE_BATCHES._value.get())
+ assert math.isnan(DEPTH_SAMPLE_AGE_SECONDS._value.get())
+
@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
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 d6c5ace9f3a0..7e6689aae3ca 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
@@ -28,6 +28,7 @@ from products.warehouse_sources_queue.backend.core.jobs_db import (
BatchQueue,
PendingBatch,
QueueDepth,
+ _claimable_count_sql,
_orphaned_candidate_runs_sql,
_queue_depth_sql,
_queue_freshness_sql,
@@ -2028,6 +2029,8 @@ class TestGetQueueDepth:
slot_waiting_batches=1,
serialized_batches=0,
)
+ assert depth.slot_waiting_batches is not None
+ assert depth.serialized_batches is not None
assert depth.claimable_batches - freshness.blocked_batches == (
depth.slot_waiting_batches + depth.serialized_batches
)
@@ -2050,6 +2053,42 @@ class TestGetQueueDepth:
assert "sb_run_gate_idx" in plan
assert "sb_schema_busy_idx" in plan
+ @pytest.mark.asyncio
+ async def test_headline_count_is_an_index_only_walk_of_the_claimable_index(self, conn):
+ # The count must stay free of the per-run and per-group probes: it is the
+ # statement that has to finish when a backlog defeats the breakdown.
+ await _insert_batch(conn)
+ await conn.execute("SET enable_seqscan = off")
+ try:
+ cur = await conn.execute("EXPLAIN (FORMAT TEXT) " + _claimable_count_sql())
+ 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
+ assert "sb_run_gate_idx" not in plan
+ assert "sb_schema_busy_idx" not in plan
+ assert "SubPlan" not in plan
+
+ @pytest.mark.asyncio
+ async def test_breakdown_timeout_keeps_the_count_and_blanks_the_split(self, conn):
+ await _insert_batch(conn, batch_index=0, run_uuid="r-a")
+ await _insert_batch(conn, batch_index=1, run_uuid="r-a")
+
+ with patch(
+ "products.warehouse_sources_queue.backend.core.jobs_db._queue_depth_sql",
+ return_value="SELECT pg_sleep(2), 0, 0, 0, 0",
+ ):
+ depth = await BatchQueue.get_queue_depth(conn, statement_timeout_ms=200)
+
+ assert depth == QueueDepth(
+ claimable_batches=2,
+ claimable_groups=None,
+ top_groups_claimable_share=None,
+ slot_waiting_batches=None,
+ serialized_batches=None,
+ )
+
@pytest.mark.django_db(transaction=True)
class TestClaimEligibilityWindow:
diff --git a/products/warehouse_sources_queue/backend/README.md b/products/warehouse_sources_queue/backend/README.md
index 7976e289f058..dda240589245 100644
--- a/products/warehouse_sources_queue/backend/README.md
+++ b/products/warehouse_sources_queue/backend/README.md
@@ -126,7 +126,16 @@ These gauges are queue-wide, so one pod per fleet samples them on the reconcile
The other pods export NaN, which `max()` skips, so aggregate all of these gauges with `max()`; `sum()` and `avg()` return NaN.
In multiprocess pods each process is exported separately with a `pid` label, and the same `max()` must aggregate over that label too, so one process's NaN cannot hide the elected process's sample during a restart.
A pod clears its gauges to NaN before each round, so a value from an earlier round never looks fresh.
-Each gauge statement runs with a 5-second server-side `statement_timeout`; a probe that times out skips its sample, except that the age gauge saturates at the probe window.
+Each gauge statement runs with a 5-second server-side `statement_timeout`; a freshness probe that times out skips its sample, except that the age gauge saturates at the probe window.
+The depth gauges do not go blank on a timeout, because a deep queue is exactly when the probe is slowest and a gap or a 0 reads as "the queue cleared".
+The depth probe runs two statements.
+The first counts the claimable set with an index-only walk of `sb_claimable_idx` and sets `warehouse_pg_queue_claimable_batches`.
+The second splits that set per run and per group (failed-run and executing probes) and sets the four concentration gauges.
+If a statement times out, the sampling pod repeats its last good value for the gauges it could not measure.
+`warehouse_pg_queue_depth_sample_age_seconds` is the seconds since the depth gauges were last measured in full; 0 means this round, and it rises while the probe times out.
+It is NaN when the pod has no sample yet.
+`warehouse_pg_queue_depth_probe_timeouts_total{stage="count"|"breakdown"}` counts the timeouts.
+A pod that does not hold the gauge slot drops its sample and exports NaN, never 0, so panels should aggregate with `max()` and not turn NaN into 0 (for example with `or vector(0)`).
Failed polls record their elapsed time in `poll_duration_seconds`, so degraded polls stay visible in the latency percentiles; `poll_failures_total` carries the reason label and is the alertable poll-health counter.
The maintenance queries (sweeps, reconcile passes, probes) report through `warehouse_pg_queue_query_duration_seconds` (labeled per query, observed on failure and timeout too) and `warehouse_pg_queue_query_failures_total`; the August 2026 stall came from a query with no latency signal at all.
diff --git a/products/warehouse_sources_queue/backend/core/jobs_db.py b/products/warehouse_sources_queue/backend/core/jobs_db.py
index 959c6d521c7d..fd2a9c126b25 100644
--- a/products/warehouse_sources_queue/backend/core/jobs_db.py
+++ b/products/warehouse_sources_queue/backend/core/jobs_db.py
@@ -586,8 +586,23 @@ def _queue_freshness_sql() -> str:
"""
+def _claimable_count_sql() -> str:
+ """Count the claimable set alone: an index-only walk of ``sb_claimable_idx``.
+
+ ``created_at`` is a key column of that partial index, so the count needs no
+ heap fetch, no per-run probe and no per-group probe. That is why it still
+ finishes on a backlog where :func:`_queue_depth_sql` times out.
+ """
+ return f"""
+ SELECT count(*)
+ FROM {BATCH_TABLE} b
+ WHERE b.created_at > now() - interval '{CLAIM_ELIGIBILITY_INTERVAL}'
+ AND b.latest_state IN ('pending', 'waiting_retry')
+ """
+
+
def _queue_depth_sql() -> str:
- """Queue depth and how it is spread over (team_id, schema_id) groups, in one scan.
+ """How the claimable set is spread over (team_id, schema_id) groups, in one scan.
The claimable set is the same as ``sb_claimable_idx`` covers: 'pending' or
'waiting_retry' inside ``CLAIM_ELIGIBILITY_INTERVAL``. The per-run and
@@ -598,12 +613,11 @@ def _queue_depth_sql() -> str:
``PARTITION_PRUNING_INTERVAL`` because they must see every row that still
exists, the same as the claim query's gates.
- ``batches`` per group keeps every claimable row, so the depth total stays
- what the claim query could scan. ``live_batches`` drops the runs that hold a
- failed batch: the claim query refuses those, so they are neither waiting for
- a slot nor waiting behind their group. Without that split a leaked run reads
- as capacity demand forever, which is the same distortion that made the age
- gauge exclude them.
+ ``live_batches`` drops the runs that hold a failed batch: the claim query
+ refuses those, so they are neither waiting for a slot nor waiting behind
+ their group. Without that split a leaked run reads as capacity demand
+ forever, which is the same distortion that made the age gauge exclude them.
+ The headline count comes from :func:`_claimable_count_sql`, not from here.
Split out from its caller so the plan-shape test can EXPLAIN exactly what
runs, the way :func:`_state_claim_candidates_sql` is pinned.
@@ -634,14 +648,12 @@ def _queue_depth_sql() -> str:
SELECT
g.team_id,
g.schema_id,
- sum(g.batches) AS batches,
coalesce(sum(g.batches) FILTER (WHERE NOT g.blocked), 0) AS live_batches
FROM gated_runs g
GROUP BY g.team_id, g.schema_id
),
ranked AS (
SELECT
- g.batches,
g.live_batches,
EXISTS (
SELECT 1
@@ -655,7 +667,6 @@ def _queue_depth_sql() -> str:
FROM groups g
)
SELECT
- coalesce(sum(batches), 0) AS claimable_batches,
count(*) FILTER (WHERE live_batches > 0) AS claimable_groups,
coalesce(sum(live_batches), 0) AS live_batches,
coalesce(sum(live_batches) FILTER (WHERE depth_rank <= %(top_groups)s), 0) AS top_groups_batches,
@@ -952,13 +963,16 @@ class QueueDepth:
"""
claimable_batches: int
- claimable_groups: int
+ # The fields below are None when the breakdown statement timed out: the count
+ # statement is much cheaper, so it can still land while a deep queue defeats
+ # the per-run and per-group probes.
+ claimable_groups: int | None
# 0..1 share of those batches held by the DEPTH_TOP_GROUPS deepest groups; 0 when empty.
- top_groups_claimable_share: float
+ top_groups_claimable_share: float | None
# Batches whose group has nothing executing: they start as soon as a slot frees.
- slot_waiting_batches: int
+ slot_waiting_batches: int | None
# Batches whose group already has a batch executing: they wait for their own group.
- serialized_batches: int
+ serialized_batches: int | None
# Idle sync connections kept per queue DB for the worker-thread lease checks. Sized to the loader's
@@ -1961,7 +1975,7 @@ class BatchQueue:
The depth companion to :meth:`get_queue_freshness`. ``claimable_batches``
applies none of the claim's per-run, schema-busy, or lease gates (those
- need per-row probes, and this must stay one partial-index scan), nor the
+ need per-row probes, and this must stay one index-only count), nor the
retry-backoff gate (it needs the fleet's backoff config, and this probe
stays parameter-free), so the count reads slightly high. Bounded by
``CLAIM_ELIGIBILITY_INTERVAL`` to match what the claim query can see.
@@ -1971,26 +1985,41 @@ class BatchQueue:
so ``slot_waiting_batches + serialized_batches`` is the depth minus those.
See :func:`_queue_depth_sql` for why.
- Raises ``psycopg.errors.QueryCanceled`` past ``statement_timeout_ms``.
+ Two statements, each with its own ``statement_timeout_ms``. A timeout in
+ the count raises ``psycopg.errors.QueryCanceled``. A timeout in the
+ breakdown returns the count with the four other fields set to None.
"""
async with _gauge_cursor(conn, statement_timeout_ms=statement_timeout_ms) as cur:
- await cur.execute(_queue_depth_sql(), {"top_groups": DEPTH_TOP_GROUPS})
- row = await cur.fetchone()
+ await cur.execute(_claimable_count_sql())
+ count_row = await cur.fetchone()
+ claimable_batches = int(count_row[0]) if count_row else 0
+ try:
+ async with _gauge_cursor(conn, statement_timeout_ms=statement_timeout_ms) as cur:
+ await cur.execute(_queue_depth_sql(), {"top_groups": DEPTH_TOP_GROUPS})
+ row = await cur.fetchone()
+ except psycopg.errors.QueryCanceled:
+ return QueueDepth(
+ claimable_batches=claimable_batches,
+ claimable_groups=None,
+ top_groups_claimable_share=None,
+ slot_waiting_batches=None,
+ serialized_batches=None,
+ )
if row is None:
return QueueDepth(
- claimable_batches=0,
+ claimable_batches=claimable_batches,
claimable_groups=0,
top_groups_claimable_share=0.0,
slot_waiting_batches=0,
serialized_batches=0,
)
- live_batches = int(row[2])
+ live_batches = int(row[1])
return QueueDepth(
- claimable_batches=int(row[0]),
- claimable_groups=int(row[1]),
- top_groups_claimable_share=int(row[3]) / live_batches if live_batches else 0.0,
- slot_waiting_batches=int(row[4]),
- serialized_batches=int(row[5]),
+ claimable_batches=claimable_batches,
+ claimable_groups=int(row[0]),
+ top_groups_claimable_share=int(row[2]) / live_batches if live_batches else 0.0,
+ slot_waiting_batches=int(row[3]),
+ serialized_batches=int(row[4]),
)
@staticmethod
diff --git a/products/warehouse_sources_queue/backend/core/metrics.py b/products/warehouse_sources_queue/backend/core/metrics.py
index db02cdc30b69..24f25e64863a 100644
--- a/products/warehouse_sources_queue/backend/core/metrics.py
+++ b/products/warehouse_sources_queue/backend/core/metrics.py
@@ -187,6 +187,24 @@ SERIALIZED_BATCHES = Gauge(
multiprocess_mode="liveall",
)
+# A depth statement that times out must not read as an empty queue. The sampling pod
+# re-exports its last good depth sample and says how old it is here, so a panel can
+# tell a fresh 47k from a 47k that was last measured minutes ago.
+DEPTH_SAMPLE_AGE_SECONDS = Gauge(
+ "warehouse_pg_queue_depth_sample_age_seconds",
+ "Seconds since the depth gauges were last measured in full (0 = measured this round). "
+ "Rises while the depth probe times out and the gauges repeat their last good sample. "
+ "NaN when no sample exists. Aggregate with max().",
+ multiprocess_mode="liveall",
+)
+
+DEPTH_PROBE_TIMEOUTS_TOTAL = Counter(
+ "warehouse_pg_queue_depth_probe_timeouts_total",
+ "Depth probe statements that hit the statement timeout, by stage: count (the headline "
+ "claimable batch count) or breakdown (the group and slot split).",
+ labelnames=["stage"],
+)
+
QUEUE_SAMPLE_GAUGES: tuple[Gauge, ...] = (
OLDEST_UNCLAIMED_BATCH_SECONDS,
BLOCKED_BATCHES,
@@ -196,6 +214,7 @@ QUEUE_SAMPLE_GAUGES: tuple[Gauge, ...] = (
TOP_GROUPS_CLAIMABLE_SHARE,
SLOT_WAITING_BATCHES,
SERIALIZED_BATCHES,
+ DEPTH_SAMPLE_AGE_SECONDS,
)