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): add queue concentration gauges to the batch queue (#107908)

Tom Owers29c75e9198f0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/README.md b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/README.md
index 15a61886d5a6..b817dc6ca9dd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/README.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/README.md
@@ -103,7 +103,15 @@ Two further counters exist only under the `warehouse_pg_consumer_*` prefix, incr
The headline health signal is `warehouse_pg_queue_oldest_unclaimed_batch_seconds`: the age of the oldest batch no consumer has picked up yet.
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.
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.
-Every pod reports the same queue-wide values on the reconcile cadence; aggregate both gauges with `max()`.
+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.
+A deep queue held by a few groups is therefore serial by construction, while a deep queue spread over idle groups is a capacity problem; depth alone reads the same either way.
+`warehouse_pg_queue_claimable_groups` counts the distinct groups with claimable work.
+`warehouse_pg_queue_top_groups_claimable_share` is the 0..1 share of claimable batches held by the five deepest groups.
+`warehouse_pg_queue_slot_waiting_batches` counts claimable batches whose group has nothing executing; they start as soon as a slot frees.
+`warehouse_pg_queue_serialized_batches` counts claimable batches waiting behind an executing batch of their own group.
+All four exclude batches whose run already holds a failed batch, the population `warehouse_pg_queue_blocked_batches` reports and the age gauge excludes, so `slot_waiting + serialized` is the depth minus the blocked batches.
+Every pod reports the same queue-wide values on the reconcile cadence; aggregate all of these gauges with `max()`.
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/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 d0519225c486..99ca27325f84 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
@@ -64,11 +64,15 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
BACKLOGGED_GROUPS,
BLOCKED_BATCHES,
CLAIMABLE_BATCHES,
+ CLAIMABLE_GROUPS,
DRAINED_AFTER_FAILURE_TOTAL,
OLDEST_UNCLAIMED_BATCH_SECONDS,
ORPHANED_BATCHES_DRAINED_TOTAL,
RUNS_RECONCILED_TOTAL,
RUNS_TERMINALIZED_STALE_TOTAL,
+ SERIALIZED_BATCHES,
+ SLOT_WAITING_BATCHES,
+ TOP_GROUPS_CLAIMABLE_SHARE,
observe_queue_query,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (
@@ -748,8 +752,12 @@ class DeltaBatchConsumerAdapter:
# of the queue is, depth says how much sits behind it — a stall and a
# burst are indistinguishable on age alone.
with observe_queue_query("claimable_depth_probe"):
- depth = await BatchQueue.get_claimable_batch_count(conn)
- CLAIMABLE_BATCHES.set(depth)
+ depth = await BatchQueue.get_queue_depth(conn)
+ 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)
except TimeoutError:
logger.error( # noqa: TRY400 — designed degraded path, traceback is noise
"queue_freshness_probe_timed_out",
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 cc2548b0fa9a..efd16bd8b4e5 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
@@ -89,6 +89,11 @@ TAKEOVER_STALE_THRESHOLD_SECONDS = 6 * 60 * 60
FRESHNESS_WINDOW_SECONDS = 48 * 60 * 60
FRESHNESS_WINDOW = f"{FRESHNESS_WINDOW_SECONDS} seconds"
+# How many of the deepest (team_id, schema_id) groups the depth probe's
+# concentration share covers. Small enough that a near-1 share means a handful
+# of tenants own the queue, large enough that one bursty tenant does not.
+DEPTH_TOP_GROUPS = 5
+
class _Unset:
"""Sentinel for ``update_status_unless_failed(expected_state_changed_at=...)``.
@@ -424,6 +429,85 @@ def _orphaned_candidate_runs_sql() -> str:
"""
+def _queue_depth_sql() -> str:
+ """Queue depth and how it 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
+ per-group gates below are not filters on that scan. The scan is aggregated
+ into runs first, so the failed-run probe costs one ``sb_run_gate_idx``
+ descent per run, and then into groups, so the executing probe costs one
+ ``sb_schema_busy_idx`` descent per group. Both probes keep
+ ``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.
+
+ Split out from its caller so the plan-shape test can EXPLAIN exactly what
+ runs, the way :func:`_state_claim_candidates_sql` is pinned.
+ """
+ return f"""
+ WITH claimable_runs AS (
+ SELECT b.team_id, b.schema_id, b.run_uuid, count(*) AS batches
+ FROM {BATCH_TABLE} b
+ WHERE b.created_at > now() - interval '{CLAIM_ELIGIBILITY_INTERVAL}'
+ AND b.latest_state IN ('pending', 'waiting_retry')
+ GROUP BY b.team_id, b.schema_id, b.run_uuid
+ ),
+ gated_runs AS (
+ SELECT
+ r.team_id,
+ r.schema_id,
+ r.batches,
+ EXISTS (
+ SELECT 1
+ FROM {BATCH_TABLE} b_failed
+ WHERE b_failed.run_uuid = r.run_uuid
+ AND b_failed.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND b_failed.latest_state = 'failed'
+ ) AS blocked
+ FROM claimable_runs r
+ ),
+ groups AS (
+ 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
+ FROM {BATCH_TABLE} b_busy
+ WHERE b_busy.team_id = g.team_id
+ AND b_busy.schema_id = g.schema_id
+ AND b_busy.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND b_busy.latest_state = 'executing'
+ ) AS executing,
+ row_number() OVER (ORDER BY g.live_batches DESC) AS depth_rank
+ 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,
+ coalesce(sum(live_batches) FILTER (WHERE NOT executing), 0) AS slot_waiting_batches,
+ coalesce(sum(live_batches) FILTER (WHERE executing), 0) AS serialized_batches
+ FROM ranked
+ """
+
+
def _stranded_candidate_runs_sql() -> str:
"""Candidate selection for the stranded-run sweep: aggregate first, then gate per run.
@@ -698,6 +782,27 @@ class QueueFreshness:
backlogged_groups: int
+@dataclass(frozen=True, slots=True)
+class QueueDepth:
+ """What one depth probe reads off the claimable set.
+
+ The total alone cannot tell a few (team_id, schema_id) groups draining one
+ batch at a time from a fleet that has run out of loader slots: the loader
+ serializes each group by design, so a deep queue with idle slots is normal
+ when the depth sits in a handful of groups. The other four numbers separate
+ those two readings.
+ """
+
+ claimable_batches: int
+ claimable_groups: int
+ # 0..1 share of those batches held by the DEPTH_TOP_GROUPS deepest groups; 0 when empty.
+ top_groups_claimable_share: float
+ # Batches whose group has nothing executing: they start as soon as a slot frees.
+ slot_waiting_batches: int
+ # Batches whose group already has a batch executing: they wait for their own group.
+ serialized_batches: int
+
+
class BatchQueue:
"""
Async interface to the Postgres batch queue tables. Each method runs
@@ -1569,28 +1674,40 @@ class BatchQueue:
)
@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_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
- 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.
+ async def get_queue_depth(conn: psycopg.AsyncConnection[Any]) -> QueueDepth:
+ """How many batches are state-eligible for claiming right now, and where they sit.
+
+ 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
+ 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.
+
+ The other four fields exclude batches whose run holds a failed batch, the
+ same population :meth:`get_queue_freshness` reports as ``blocked_batches``,
+ so ``slot_waiting_batches + serialized_batches`` is the depth minus those.
+ See :func:`_queue_depth_sql` for why.
"""
async with conn.cursor() as cur:
- await cur.execute(
- f"""
- SELECT count(*)
- FROM {BATCH_TABLE} b
- WHERE b.created_at > now() - interval '{CLAIM_ELIGIBILITY_INTERVAL}'
- AND b.latest_state IN ('pending', 'waiting_retry')
- """
- )
+ await cur.execute(_queue_depth_sql(), {"top_groups": DEPTH_TOP_GROUPS})
row = await cur.fetchone()
- return int(row[0]) if row else 0
+ if row is None:
+ return QueueDepth(
+ claimable_batches=0,
+ claimable_groups=0,
+ top_groups_claimable_share=0.0,
+ slot_waiting_batches=0,
+ serialized_batches=0,
+ )
+ live_batches = int(row[2])
+ 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]),
+ )
@staticmethod
def get_oldest_non_terminal_batch_age_seconds(
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 8db3122ec0f6..f68a10f51a38 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
@@ -145,6 +145,47 @@ CLAIMABLE_BATCHES = Gauge(
multiprocess_mode="livemax",
)
+# Concentration companions to the depth gauge. The loader drains each (team,
+# schema) group one batch at a time by design, so a deep queue held by a few
+# groups is serial by construction and loader slots sit idle; a deep queue spread
+# over many groups with nothing executing is a capacity problem. Depth alone
+# reads the same either way. Same probe, same cadence, same aggregation (max
+# across pods).
+CLAIMABLE_GROUPS = Gauge(
+ "warehouse_pg_queue_claimable_groups",
+ "Distinct (team_id, schema_id) groups holding at least one claimable batch. Excludes "
+ "batches whose run already holds a failed batch, as warehouse_pg_queue_oldest_unclaimed_"
+ "batch_seconds does. Sampled on the reconcile cadence.",
+ multiprocess_mode="livemax",
+)
+
+TOP_GROUPS_CLAIMABLE_SHARE = Gauge(
+ "warehouse_pg_queue_top_groups_claimable_share",
+ "Fraction (0..1) of claimable batches held by the 5 (team_id, schema_id) groups with the "
+ "most claimable batches; 0 when the queue is empty. Near 1 means a few groups own the "
+ "queue and drain serially by design. Same blocked-batch exclusion as "
+ "warehouse_pg_queue_claimable_groups. Sampled on the reconcile cadence.",
+ multiprocess_mode="livemax",
+)
+
+SLOT_WAITING_BATCHES = Gauge(
+ "warehouse_pg_queue_slot_waiting_batches",
+ "Claimable batches whose (team_id, schema_id) group has no batch executing: work that "
+ "starts as soon as a loader slot is free, so a high value with free slots means the "
+ "claim path is slow. Same blocked-batch exclusion as warehouse_pg_queue_claimable_groups; "
+ "with warehouse_pg_queue_serialized_batches it sums to the depth minus the blocked "
+ "batches. Sampled on the reconcile cadence.",
+ multiprocess_mode="livemax",
+)
+
+SERIALIZED_BATCHES = Gauge(
+ "warehouse_pg_queue_serialized_batches",
+ "Claimable batches whose (team_id, schema_id) group already has a batch executing: they "
+ "wait behind their own group, not for fleet capacity. Same blocked-batch exclusion as "
+ "warehouse_pg_queue_claimable_groups. Sampled on the reconcile cadence.",
+ multiprocess_mode="livemax",
+)
+
# The maintenance queries (sweeps, reconcile passes, probes) shaped like the claim
# poll: cost scales with queue state, and the 2026-08 stall came from one that had
# no latency signal at all. Same bucket ceiling rationale as POLL_DURATION_BUCKETS.
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 a2e739ed0c21..5e2cc4a8bdfb 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
@@ -47,6 +47,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
FailedRunRef,
OrphanedRunRef,
PendingBatch,
+ QueueDepth,
QueueFreshness,
StrandedRunRef,
)
@@ -54,9 +55,13 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
BACKLOGGED_GROUPS,
BLOCKED_BATCHES,
CLAIMABLE_BATCHES,
+ CLAIMABLE_GROUPS,
OLDEST_UNCLAIMED_BATCH_SECONDS,
ORPHANED_BATCHES_DRAINED_TOTAL,
RUNS_RECONCILED_TOTAL,
+ SERIALIZED_BATCHES,
+ SLOT_WAITING_BATCHES,
+ TOP_GROUPS_CLAIMABLE_SHARE,
)
from products.warehouse_sources_queue.backend.models import SourceBatchStatus
@@ -71,6 +76,23 @@ def _freshness(
)
+def _depth(
+ claimable_batches: int,
+ *,
+ claimable_groups: int = 0,
+ top_groups_claimable_share: float = 0.0,
+ slot_waiting_batches: int = 0,
+ serialized_batches: int = 0,
+) -> QueueDepth:
+ return QueueDepth(
+ claimable_batches=claimable_batches,
+ claimable_groups=claimable_groups,
+ top_groups_claimable_share=top_groups_claimable_share,
+ slot_waiting_batches=slot_waiting_batches,
+ serialized_batches=serialized_batches,
+ )
+
+
def _make_batch(**overrides: Any) -> PendingBatch:
defaults: dict[str, Any] = {
"id": "00000000-0000-0000-0000-000000000001",
@@ -2009,9 +2031,9 @@ class TestReconcileFailedRuns:
return_value=_freshness(42.0),
),
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_claimable_batch_count",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_queue_depth",
new_callable=AsyncMock,
- return_value=7,
+ return_value=_depth(7),
),
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_failed_runs",
@@ -2041,9 +2063,15 @@ class TestReconcileFailedRuns:
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",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_queue_depth",
new_callable=AsyncMock,
- return_value=321,
+ return_value=_depth(
+ 321,
+ claimable_groups=12,
+ top_groups_claimable_share=0.75,
+ slot_waiting_batches=20,
+ serialized_batches=300,
+ ),
) as mock_depth,
):
await consumer._reconcile_failed_runs()
@@ -2051,8 +2079,13 @@ class TestReconcileFailedRuns:
assert CLAIMABLE_BATCHES._value.get() == 321
assert BLOCKED_BATCHES._value.get() == 7
assert BACKLOGGED_GROUPS._value.get() == 3
+ assert CLAIMABLE_GROUPS._value.get() == 12
+ assert TOP_GROUPS_CLAIMABLE_SHARE._value.get() == 0.75
+ assert SLOT_WAITING_BATCHES._value.get() == 20
+ assert SERIALIZED_BATCHES._value.get() == 300
mock_probe.return_value = _freshness(None) # empty queue -> gauge resets to 0
+ mock_depth.return_value = _depth(0)
with patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_failed_runs",
new_callable=AsyncMock,
@@ -2064,12 +2097,17 @@ class TestReconcileFailedRuns:
mock_probe,
),
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_claimable_batch_count",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_queue_depth",
mock_depth,
),
):
await consumer._reconcile_failed_runs()
assert OLDEST_UNCLAIMED_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
+ assert SLOT_WAITING_BATCHES._value.get() == 0
+ assert SERIALIZED_BATCHES._value.get() == 0
@pytest.mark.asyncio
async def test_orphan_drain_retires_leftovers_the_newest_first_pass_never_reached(self):
@@ -2090,9 +2128,9 @@ class TestReconcileFailedRuns:
return_value=_freshness(0.0),
),
patch(
- f"{consumer_module.__name__}.BatchQueue.get_claimable_batch_count",
+ f"{consumer_module.__name__}.BatchQueue.get_queue_depth",
new_callable=AsyncMock,
- return_value=0,
+ return_value=_depth(0),
),
patch(
f"{consumer_module.__name__}.BatchQueue.get_failed_runs",
@@ -2162,9 +2200,9 @@ class TestReconcileFailedRuns:
return_value=_freshness(0.0),
),
patch(
- f"{consumer_module.__name__}.BatchQueue.get_claimable_batch_count",
+ f"{consumer_module.__name__}.BatchQueue.get_queue_depth",
new_callable=AsyncMock,
- return_value=0,
+ return_value=_depth(0),
),
patch(
f"{consumer_module.__name__}.BatchQueue.get_failed_runs",
@@ -2383,9 +2421,9 @@ class TestReconcileFailedRuns:
return_value=_freshness(0.0),
),
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_claimable_batch_count",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_queue_depth",
new_callable=AsyncMock,
- return_value=0,
+ return_value=_depth(0),
),
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_failed_runs",
@@ -2446,9 +2484,9 @@ class TestReconcileFailedRuns:
return_value=_freshness(0.0),
),
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_claimable_batch_count",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_queue_depth",
new_callable=AsyncMock,
- return_value=0,
+ return_value=_depth(0),
),
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_failed_runs",
@@ -2525,9 +2563,9 @@ class TestReconcileFailedRuns:
return_value=_freshness(0.0),
),
patch(
- f"{consumer_module.__name__}.BatchQueue.get_claimable_batch_count",
+ f"{consumer_module.__name__}.BatchQueue.get_queue_depth",
new_callable=AsyncMock,
- return_value=0,
+ return_value=_depth(0),
),
patch(
f"{consumer_module.__name__}.BatchQueue.get_failed_runs",
@@ -2590,9 +2628,9 @@ class TestReconcileFailedRuns:
return_value=_freshness(0.0),
),
patch(
- f"{consumer_module.__name__}.BatchQueue.get_claimable_batch_count",
+ f"{consumer_module.__name__}.BatchQueue.get_queue_depth",
new_callable=AsyncMock,
- return_value=0,
+ return_value=_depth(0),
),
patch(
f"{consumer_module.__name__}.BatchQueue.get_failed_runs",
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 a7692e1ba839..ad7f0c739110 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
@@ -26,7 +26,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
TAKEOVER_STALE_THRESHOLD_SECONDS,
BatchQueue,
PendingBatch,
+ QueueDepth,
_orphaned_candidate_runs_sql,
+ _queue_depth_sql,
build_status_dual_write_sql,
)
@@ -1833,7 +1835,19 @@ class TestClaimGates:
@pytest.mark.django_db(transaction=True)
-class TestGetClaimableBatchCount:
+class TestGetQueueDepth:
+ @pytest.mark.asyncio
+ async def test_empty_queue_reads_all_zero(self, conn):
+ # Every aggregate is NULL over no rows; the share must come back as 0,
+ # not as a division by zero or a NULL the gauge cannot take.
+ assert await BatchQueue.get_queue_depth(conn) == QueueDepth(
+ claimable_batches=0,
+ claimable_groups=0,
+ top_groups_claimable_share=0.0,
+ slot_waiting_batches=0,
+ serialized_batches=0,
+ )
+
@pytest.mark.asyncio
async def test_counts_claimable_states_within_eligibility_window(self, conn):
# Feeds the queue-depth gauge; dropping a state or the window bound here
@@ -1846,7 +1860,104 @@ class TestGetClaimableBatchCount:
expired = await _insert_batch(conn, batch_index=0, run_uuid="r-old")
await conn.execute(f"UPDATE {BATCH_TABLE} SET created_at = now() - interval '7 days' WHERE id = %s", (expired,))
- assert await BatchQueue.get_claimable_batch_count(conn) == 2
+ assert await BatchQueue.get_queue_depth(conn) == QueueDepth(
+ claimable_batches=2,
+ claimable_groups=1,
+ top_groups_claimable_share=1.0,
+ slot_waiting_batches=2,
+ serialized_batches=0,
+ )
+
+ @pytest.mark.asyncio
+ async def test_one_deep_group_among_shallow_ones_reads_as_concentrated(self, conn):
+ executing = await _insert_batch(conn, schema_id="deep", run_uuid="run-deep", batch_index=0)
+ await BatchQueue.update_status(conn, batch_id=executing, job_state="executing", attempt=1)
+ for batch_index in range(1, 11):
+ await _insert_batch(conn, schema_id="deep", run_uuid="run-deep", batch_index=batch_index)
+ for n in range(1, 7):
+ await _insert_batch(conn, schema_id=f"shallow-{n}", run_uuid=f"run-shallow-{n}", batch_index=1)
+ busy_shallow = await _insert_batch(conn, schema_id="shallow-1", run_uuid="run-shallow-1", batch_index=0)
+ await BatchQueue.update_status(conn, batch_id=busy_shallow, job_state="executing", attempt=1)
+
+ depth = await BatchQueue.get_queue_depth(conn)
+
+ # Top 5 by depth: the deep group (10) plus four shallow ones (1 each) of 16.
+ assert depth == QueueDepth(
+ claimable_batches=16,
+ claimable_groups=7,
+ top_groups_claimable_share=14 / 16,
+ slot_waiting_batches=5,
+ serialized_batches=11,
+ )
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "sibling_state,sibling_run,expected_slot_waiting,expected_serialized",
+ [
+ ("executing", "run-1", 0, 1),
+ # The busy check is per group, not per run, matching the claim query's schema-busy gate.
+ ("executing", "run-2", 0, 1),
+ ("succeeded", "run-1", 1, 0),
+ ("waiting", "run-1", 1, 0),
+ # A failure in another run of the same group blocks nothing here.
+ ("failed", "run-2", 1, 0),
+ ],
+ )
+ async def test_only_an_executing_batch_in_the_group_serializes_its_waiting_work(
+ self, conn, sibling_state, sibling_run, expected_slot_waiting, expected_serialized
+ ):
+ sibling = await _insert_batch(conn, run_uuid=sibling_run, batch_index=0)
+ await BatchQueue.update_status(conn, batch_id=sibling, job_state=sibling_state, attempt=1)
+ await _insert_batch(conn, run_uuid="run-1", batch_index=1)
+
+ depth = await BatchQueue.get_queue_depth(conn)
+
+ assert depth.claimable_batches == 1
+ assert (depth.slot_waiting_batches, depth.serialized_batches) == (expected_slot_waiting, expected_serialized)
+
+ @pytest.mark.asyncio
+ async def test_blocked_batches_stay_in_the_depth_but_leave_the_split(self, conn):
+ # A run holding a failed batch can never be claimed. Its leftovers must keep
+ # the depth gauge's meaning (the claim query could scan them), but counting
+ # them as waiting work would report capacity demand that no slot can serve,
+ # the distortion that made the age gauge exclude them.
+ failed = await _insert_batch(conn, schema_id="dead", run_uuid="run-dead", batch_index=0)
+ await BatchQueue.update_status(conn, batch_id=failed, job_state="failed", attempt=1)
+ await _insert_batch(conn, schema_id="dead", run_uuid="run-dead", batch_index=1)
+ await _insert_batch(conn, schema_id="dead", run_uuid="run-dead", batch_index=2)
+ await _insert_batch(conn, schema_id="live", run_uuid="run-live", batch_index=0)
+
+ depth = await BatchQueue.get_queue_depth(conn)
+ freshness = await BatchQueue.get_queue_freshness(conn, backlog_threshold_seconds=0)
+
+ assert depth == QueueDepth(
+ claimable_batches=3,
+ claimable_groups=1,
+ top_groups_claimable_share=1.0,
+ slot_waiting_batches=1,
+ serialized_batches=0,
+ )
+ assert depth.claimable_batches - freshness.blocked_batches == (
+ depth.slot_waiting_batches + depth.serialized_batches
+ )
+
+ @pytest.mark.asyncio
+ async def test_probe_uses_the_partial_indexes(self, conn):
+ # Every pod runs this probe on its own timer. The scan must stay on
+ # sb_claimable_idx, and the per-run and per-group gates must stay index
+ # probes; a predicate edit that widens either falls back to scanning
+ # every retained partition on every pod, every reconcile interval.
+ await _insert_batch(conn)
+ await conn.execute("SET enable_seqscan = off")
+ try:
+ cur = await conn.execute("EXPLAIN (FORMAT TEXT) " + _queue_depth_sql(), {"top_groups": 5})
+ 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" in plan
+ assert "sb_schema_busy_idx" in plan
@pytest.mark.django_db(transaction=True)