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.

perf(data-warehouse): stop the v3 queue gauges from loading the queue database (#110624)

Tom Owers672aa355f4c2
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 cf3b80dbcb15..fbaa116795e1 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,13 @@ from products.warehouse_sources_queue.backend.core.batch_consumer import (
from products.warehouse_sources_queue.backend.core.jobs_db import (
_UNSET,
FRESHNESS_WINDOW_SECONDS,
+ GAUGE_STATEMENT_TIMEOUT_MS,
TAKEOVER_STALE_THRESHOLD_SECONDS,
BatchQueue,
FailedRunRef,
PendingBatch,
_Unset,
+ queue_gauges_slot_key,
)
from products.warehouse_sources_queue.backend.core.metrics import (
BACKLOGGED_GROUPS,
@@ -83,6 +85,7 @@ from products.warehouse_sources_queue.backend.core.metrics import (
SERIALIZED_BATCHES,
SLOT_WAITING_BATCHES,
TOP_GROUPS_CLAIMABLE_SHARE,
+ clear_queue_sample_gauges,
observe_queue_query,
)
from products.warehouse_sources_queue.backend.models import SourceBatchStatus
@@ -225,6 +228,11 @@ class DeltaBatchConsumerAdapter:
# None/None (the default) means the whole queue — a single-fleet deployment.
self._claim_sync_types = claim_sync_types
self._claim_exclude_sync_types = claim_exclude_sync_types
+ # Stable for the life of the consumer, so the gauge-slot holder can renew its own slot.
+ self._gauge_owner_token = str(uuid4())
+ self._gauge_slot_key = queue_gauges_slot_key(
+ sync_types=claim_sync_types, exclude_sync_types=claim_exclude_sync_types
+ )
# 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
@@ -467,9 +475,8 @@ class DeltaBatchConsumerAdapter:
# which is exactly when concurrent copies on every pod can saturate the
# queue DB and starve the claim path (the 2026-08-09 loader stall: 36
# concurrent sweep queries, claim polls timing out fleet-wide). The
- # freshness probe above deliberately stays outside the slot: every pod
- # must keep its own gauge current, or max() across the fleet pins stale
- # values. The token is throwaway — the slot is never verified or
+ # freshness probe above has its own slot, so a long sweep cannot delay
+ # the gauges. The token is throwaway — the slot is never verified or
# released, it just expires into the next pod's hands.
if not await BatchQueue.try_acquire_reconcile_sweep_slot(conn, owner_token=str(uuid4())):
logger.debug("reconcile_sweep_slot_held_elsewhere")
@@ -738,37 +745,34 @@ class DeltaBatchConsumerAdapter:
capture_exception(e)
async def _observe_queue_freshness(self, conn: psycopg.AsyncConnection[Any]) -> None:
- """Report the age of the oldest batch no consumer has picked up yet.
+ """Report the age of the oldest batch no consumer has picked up yet, and the queue depth.
This is the loader's data-freshness signal: it rises whenever loading
stalls, no matter why — the alert on it fires even when every other
- health signal looks green. The probe has its own timeout so it cannot
- eat the reconcile sweep's budget; on timeout the gauge saturates, since
- a queue DB too degraded to measure freshness must read as stale. Other
- failures are swallowed-with-capture so a broken probe can't take the
- sweep down.
+ health signal looks green.
+
+ The gauges are queue-wide, so only the pod that holds this fleet's gauge
+ slot samples them. Every other pod exports NaN ("no sample"), which max()
+ across the fleet skips. Each pod blanks its gauges before it asks for the
+ 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
+ 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,
+ 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()
try:
async with asyncio.timeout(FRESHNESS_PROBE_TIMEOUT_SECONDS):
- with observe_queue_query("oldest_unclaimed_probe"):
- 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(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.
- with observe_queue_query("claimable_depth_probe"):
- 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)
+ if not await BatchQueue.try_acquire_queue_gauges_slot(
+ conn, owner_token=self._gauge_owner_token, slot_key=self._gauge_slot_key
+ ):
+ logger.debug("queue_gauges_slot_held_elsewhere")
+ return
+ await self._sample_queue_gauges(conn)
except TimeoutError:
logger.error( # noqa: TRY400 — designed degraded path, traceback is noise
"queue_freshness_probe_timed_out",
@@ -781,6 +785,37 @@ class DeltaBatchConsumerAdapter:
capture_exception(e)
return
+ async def _sample_queue_gauges(self, conn: psycopg.AsyncConnection[Any]) -> None:
+ try:
+ with observe_queue_query("oldest_unclaimed_probe"):
+ freshness = await BatchQueue.get_queue_freshness(
+ conn, backlog_threshold_seconds=BACKLOG_THRESHOLD_SECONDS
+ )
+ except psycopg.errors.QueryCanceled:
+ 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.
+ 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)
+ 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
+ # the queue is, depth says how much sits behind it — a stall and a burst
+ # are indistinguishable on age alone.
+ try:
+ with observe_queue_query("claimable_depth_probe"):
+ depth = await BatchQueue.get_queue_depth(conn)
+ except psycopg.errors.QueryCanceled:
+ logger.info("queue_depth_probe_statement_timed_out", timeout_ms=GAUGE_STATEMENT_TIMEOUT_MS)
+ 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)
+
async def should_process_batch(
self,
conn: psycopg.AsyncConnection[Any],
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 d15ef74ff5c4..f070acff859d 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
@@ -1,3 +1,4 @@
+import math
import asyncio
from datetime import UTC, datetime
from typing import Any, NamedTuple, cast
@@ -61,6 +62,7 @@ from products.warehouse_sources_queue.backend.core.metrics import (
CLAIMABLE_GROUPS,
OLDEST_UNCLAIMED_BATCH_SECONDS,
ORPHANED_BATCHES_DRAINED_TOTAL,
+ QUEUE_SAMPLE_GAUGES,
RUNS_RECONCILED_TOTAL,
SERIALIZED_BATCHES,
SLOT_WAITING_BATCHES,
@@ -180,6 +182,15 @@ def _lease_renewal_succeeds():
yield
[email protected](autouse=True)
+def _gauge_slot_granted():
+ # Grant the gauge-sampling slot by default; the real SQL can't run against mock connections.
+ with patch.object(
+ consumer_module.BatchQueue, "try_acquire_queue_gauges_slot", new_callable=AsyncMock, return_value=True
+ ):
+ yield
+
+
class TestProcessSingle:
@pytest.mark.asyncio
async def test_success_updates_status_to_executing_then_succeeded(self):
@@ -2084,8 +2095,8 @@ class TestReconcileFailedRuns:
@pytest.mark.asyncio
async def test_slot_held_elsewhere_skips_sweep_but_still_probes_freshness(self):
- # Single-flighting must never silence the freshness gauge: every pod
- # reports it, only the slot winner runs the sweep body.
+ # The sweep slot must never silence the freshness gauge: the gauges have
+ # their own slot, and only the sweep slot winner runs the sweep body.
consumer = _make_consumer()
with (
@@ -2293,6 +2304,87 @@ class TestReconcileFailedRuns:
mock_stranded.assert_awaited_once()
+ @pytest.mark.asyncio
+ async def test_only_the_gauge_slot_holder_samples_and_a_former_holder_stops_exporting(self):
+ # Every pod used to run both probes on every reconcile. A pod that loses the slot
+ # must not keep exporting its old sample: max() across the fleet would pin it.
+ consumer = _make_consumer()
+ with (
+ patch.object(
+ consumer_module.BatchQueue,
+ "try_acquire_queue_gauges_slot",
+ new_callable=AsyncMock,
+ side_effect=[True, False],
+ ),
+ patch.object(
+ consumer_module.BatchQueue,
+ "get_queue_freshness",
+ new_callable=AsyncMock,
+ return_value=_freshness(42.0, blocked_batches=1, backlogged_groups=2),
+ ) as mock_freshness,
+ patch.object(
+ consumer_module.BatchQueue, "get_queue_depth", new_callable=AsyncMock, return_value=_depth(7)
+ ) as mock_depth,
+ patch.object(consumer_module.BatchQueue, "get_failed_runs", new_callable=AsyncMock, return_value=[]),
+ ):
+ await consumer._reconcile_failed_runs()
+ assert OLDEST_UNCLAIMED_BATCH_SECONDS._value.get() == 42.0
+ assert CLAIMABLE_BATCHES._value.get() == 7
+
+ await consumer._reconcile_failed_runs()
+
+ assert mock_freshness.await_count == 1
+ assert mock_depth.await_count == 1
+ assert all(math.isnan(gauge._value.get()) for gauge in QUEUE_SAMPLE_GAUGES)
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "timed_out_probe,expected_age,expected_blocked,expected_claimable,depth_awaited",
+ [
+ # The age saturates, so a queue DB too slow to measure reads as stale.
+ ("get_queue_freshness", FRESHNESS_WINDOW_SECONDS, math.nan, math.nan, False),
+ ("get_queue_depth", 42.0, 1.0, math.nan, True),
+ ],
+ )
+ async def test_statement_timeout_skips_the_sample_and_the_sweep_still_runs(
+ self, timed_out_probe, expected_age, expected_blocked, expected_claimable, depth_awaited
+ ):
+ consumer = _make_consumer()
+ canceled = psycopg.errors.QueryCanceled("canceling statement due to statement timeout")
+ freshness = _freshness(42.0, blocked_batches=1)
+ with (
+ patch.object(
+ consumer_module.BatchQueue,
+ "get_queue_freshness",
+ new_callable=AsyncMock,
+ side_effect=canceled if timed_out_probe == "get_queue_freshness" else None,
+ return_value=freshness,
+ ),
+ patch.object(
+ consumer_module.BatchQueue,
+ "get_queue_depth",
+ new_callable=AsyncMock,
+ side_effect=canceled if timed_out_probe == "get_queue_depth" else None,
+ return_value=_depth(7),
+ ) as mock_depth,
+ patch.object(
+ consumer_module.BatchQueue, "get_failed_runs", new_callable=AsyncMock, return_value=[]
+ ) as mock_failed_runs,
+ patch(f"{consumer_module.__name__}.capture_exception") as mock_capture,
+ ):
+ await consumer._reconcile_failed_runs()
+
+ assert not any(isinstance(call.args[0], psycopg.errors.QueryCanceled) for call in mock_capture.call_args_list)
+
+ def _same(actual: float, expected: float) -> bool:
+ return math.isnan(actual) if math.isnan(expected) else actual == expected
+
+ assert _same(OLDEST_UNCLAIMED_BATCH_SECONDS._value.get(), expected_age)
+ assert _same(BLOCKED_BATCHES._value.get(), expected_blocked)
+ assert _same(CLAIMABLE_BATCHES._value.get(), expected_claimable)
+ assert mock_depth.await_count == int(depth_awaited)
+ mock_failed_runs.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
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 d68c874e4d2c..d6c5ace9f3a0 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
@@ -30,8 +30,10 @@ from products.warehouse_sources_queue.backend.core.jobs_db import (
QueueDepth,
_orphaned_candidate_runs_sql,
_queue_depth_sql,
+ _queue_freshness_sql,
_sync_connection_pool,
build_status_dual_write_sql,
+ queue_gauges_slot_key,
)
from products.warehouse_sources_queue.backend.testing import (
BATCH_DEFAULTS as _BATCH_DEFAULTS,
@@ -112,6 +114,51 @@ class TestReconcileSweepSlot:
assert await BatchQueue.try_acquire_reconcile_sweep_slot(conn_b, owner_token="pod-b") is True
+ "sync_types,exclude_sync_types,expected",
+ [
+ (None, None, "__queue-gauges__"),
+ (["cdc"], None, "__queue-gauges__:only:cdc"),
+ (None, ["cdc"], "__queue-gauges__:except:cdc"),
+ (["webhook", "cdc"], None, "__queue-gauges__:only:cdc,webhook"),
+ ],
+)
+def test_slot_key_is_per_fleet_partition(sync_types, exclude_sync_types, expected):
+ assert queue_gauges_slot_key(sync_types=sync_types, exclude_sync_types=exclude_sync_types) == expected
+
+
[email protected]_db(transaction=True)
+class TestQueueGaugesSlot:
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "first_ttl,second_owner,second_key,expected",
+ [
+ # The holder renews its own live slot, or no pod samples until the TTL runs out.
+ (240, "pod-a", None, True),
+ (240, "pod-b", None, False),
+ (0, "pod-b", None, True),
+ # Each fleet elects its own sampler, so every fleet keeps exporting the gauges.
+ (240, "pod-b", "__queue-gauges__:only:cdc", True),
+ ],
+ )
+ async def test_slot_election(self, conn, conn_b, first_ttl, second_owner, second_key, expected):
+ default_key = queue_gauges_slot_key()
+ assert await BatchQueue.try_acquire_queue_gauges_slot(
+ conn, owner_token="pod-a", slot_key=default_key, ttl_seconds=first_ttl
+ )
+
+ acquired = await BatchQueue.try_acquire_queue_gauges_slot(
+ conn_b, owner_token=second_owner, slot_key=second_key or default_key
+ )
+
+ assert acquired is expected
+
+ @pytest.mark.asyncio
+ async def test_gauge_slot_does_not_take_the_sweep_slot(self, conn, conn_b):
+ assert await BatchQueue.try_acquire_queue_gauges_slot(conn, owner_token="pod-a")
+ assert await BatchQueue.try_acquire_reconcile_sweep_slot(conn_b, owner_token="pod-b") is True
+
+
@pytest.mark.django_db(transaction=True)
class TestBatchQueueInsert:
@pytest.mark.asyncio
@@ -717,6 +764,38 @@ 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)
+ await conn.execute("SET enable_seqscan = off")
+ try:
+ cur = await conn.execute("EXPLAIN (FORMAT TEXT) " + _queue_freshness_sql(), {"backlog_threshold": 900})
+ 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 plan.count("SubPlan") == 1
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("probe", ["freshness", "depth"])
+ async def test_probe_gives_up_at_its_statement_timeout_without_changing_the_session(self, conn, conn_b, probe):
+ await conn.execute("SET statement_timeout = 0")
+ # A lock the probe must wait for stands in for a struggling queue DB.
+ async with conn_b.transaction():
+ await conn_b.execute(f"LOCK TABLE {BATCH_TABLE} IN ACCESS EXCLUSIVE MODE")
+ with pytest.raises(psycopg.errors.QueryCanceled):
+ if probe == "freshness":
+ await BatchQueue.get_queue_freshness(conn, backlog_threshold_seconds=900, statement_timeout_ms=50)
+ else:
+ await BatchQueue.get_queue_depth(conn, statement_timeout_ms=50)
+
+ cur = await conn.execute("SHOW statement_timeout")
+ assert (await cur.fetchone())[0] == "0"
+
@pytest.mark.django_db(transaction=True)
class TestOldestNonTerminalBatchAge:
diff --git a/products/warehouse_sources_queue/backend/README.md b/products/warehouse_sources_queue/backend/README.md
index 175e0ae8dbff..c67ca51212da 100644
--- a/products/warehouse_sources_queue/backend/README.md
+++ b/products/warehouse_sources_queue/backend/README.md
@@ -122,7 +122,11 @@ A deep queue held by a few groups is therefore serial by construction, while a d
`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()`.
+These gauges are queue-wide, so one pod per fleet samples them on the reconcile cadence: the pod that holds the fleet's gauge slot (a sentinel lease row, like the reconcile-sweep slot).
+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.
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 5b7731a61fd1..28840cadd713 100644
--- a/products/warehouse_sources_queue/backend/core/jobs_db.py
+++ b/products/warehouse_sources_queue/backend/core/jobs_db.py
@@ -18,8 +18,8 @@ from __future__ import annotations
import json
import time
import threading
-from collections.abc import Iterator
-from contextlib import contextmanager, suppress
+from collections.abc import AsyncIterator, Iterator
+from contextlib import asynccontextmanager, contextmanager, suppress
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
@@ -44,7 +44,7 @@ LEASE_TABLE = "sourcegrouplease"
# for while it waits. `renew_lease` can therefore be a link in a cycle it did not cause.
#
# Single-row statements (`renew_lease`, `delete_expired_lease`,
-# `try_acquire_reconcile_sweep_slot`) satisfy the order for free. Multi-row statements
+# `try_acquire_reconcile_sweep_slot`, `try_acquire_queue_gauges_slot`) satisfy the order for free. Multi-row statements
# have to force it, either with `ORDER BY team_id, schema_id` on the rows an upsert
# reads, or with an ordered `FOR UPDATE` sub-select that takes every lock before the
# delete runs.
@@ -66,6 +66,20 @@ RECONCILE_SWEEP_LEASE_TEAM_ID = 0
RECONCILE_SWEEP_LEASE_SCHEMA_ID = "__reconcile-sweep__"
RECONCILE_SWEEP_SLOT_TTL_SECONDS = 240
+# Sentinel lease row that elects the one pod that samples the queue-wide gauges
+# (freshness and depth). Every pod reads the same queue, so when each pod runs the
+# probes the queue DB does N times the work for the same numbers, in competition
+# with the claim path. Same TTL as the sweep slot: it sits under the 300s reconcile
+# interval, so the slot is free again when a pod's next timer fires. The key has a
+# per-fleet suffix (see ``queue_gauges_slot_key``), because each fleet exports the
+# gauges from its own pods.
+QUEUE_GAUGES_LEASE_SCHEMA_ID_PREFIX = "__queue-gauges__"
+QUEUE_GAUGES_SLOT_TTL_SECONDS = 240
+
+# Server-side ceiling for one gauge statement. On a struggling queue DB a gauge must
+# give up quickly and skip its sample, not compete with the claim path for seconds.
+GAUGE_STATEMENT_TIMEOUT_MS = 5_000
+
# Partition pruning hint: only scan partitions within this window.
# Set to 2x the retention period so the planner can skip dropped
# partitions. Not a correctness filter -- older partitions are already
@@ -181,6 +195,24 @@ def sync_type_scope_sql(
return "", {}
+def queue_gauges_slot_key(
+ *,
+ sync_types: list[str] | None = None,
+ exclude_sync_types: list[str] | None = None,
+) -> str:
+ """Lease key of the gauge-sampling slot for one fleet partition.
+
+ The gauges are queue-wide, but each fleet exports them from its own pods. One
+ slot shared by all fleets would let a pod of one fleet win every round, and
+ the other fleet's dashboards would go empty.
+ """
+ if sync_types:
+ return f"{QUEUE_GAUGES_LEASE_SCHEMA_ID_PREFIX}:only:{','.join(sorted(sync_types))}"
+ if exclude_sync_types:
+ return f"{QUEUE_GAUGES_LEASE_SCHEMA_ID_PREFIX}:except:{','.join(sorted(exclude_sync_types))}"
+ return QUEUE_GAUGES_LEASE_SCHEMA_ID_PREFIX
+
+
def build_status_dual_write_sql(*, with_batch_created_at: bool) -> str:
"""Single-statement status INSERT + denormalized-state UPDATE (atomic under autocommit).
@@ -500,6 +532,60 @@ def _orphaned_candidate_runs_sql() -> str:
"""
+def _queue_freshness_sql() -> str:
+ """Age, 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.
+
+ ``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.
+
+ Split out from its caller so the plan-shape test can EXPLAIN exactly what runs.
+ """
+ return f"""
+ WITH pending_runs AS (
+ SELECT
+ b.team_id,
+ b.schema_id,
+ b.run_uuid,
+ min(b.created_at) AS oldest_created_at,
+ count(*) AS batches
+ FROM {BATCH_TABLE} b
+ WHERE b.created_at > now() - interval '{FRESHNESS_WINDOW}'
+ AND b.latest_state = 'pending'
+ GROUP BY b.team_id, b.schema_id, b.run_uuid
+ ),
+ gated_runs AS MATERIALIZED (
+ SELECT
+ r.team_id,
+ r.schema_id,
+ r.oldest_created_at,
+ 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 pending_runs r
+ )
+ 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
+ AND oldest_created_at <= now() - make_interval(secs => %(backlog_threshold)s)
+ )
+ FROM gated_runs
+ """
+
+
def _queue_depth_sql() -> str:
"""Queue depth and how it is spread over (team_id, schema_id) groups, in one scan.
@@ -977,6 +1063,54 @@ def _lease_is_held(conn: psycopg.Connection[Any], *, team_id: int, schema_id: st
return bool(row and row[0])
+@asynccontextmanager
+async def _gauge_cursor(
+ conn: psycopg.AsyncConnection[Any], *, statement_timeout_ms: int
+) -> AsyncIterator[psycopg.AsyncCursor[Any]]:
+ """Cursor whose statements stop at ``statement_timeout_ms``; raises ``QueryCanceled`` past it.
+
+ The timeout is transaction-local, so it never leaks into the session the
+ caller shares with the sweeps (or into a pooled server connection).
+ """
+ async with conn.transaction():
+ async with conn.cursor() as cur:
+ await cur.execute("SELECT set_config('statement_timeout', %s, true)", (str(statement_timeout_ms),))
+ yield cur
+
+
+async def _try_acquire_fleet_slot(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ schema_id: str,
+ owner_token: str,
+ ttl_seconds: int,
+ reentrant: bool,
+) -> bool:
+ """CAS-acquire a sentinel lease row; True means this caller holds it until ``ttl_seconds`` pass."""
+ reentry_clause = f" OR {LEASE_TABLE}.owner_token = excluded.owner_token" if reentrant else ""
+ async with conn.cursor() as cur:
+ await cur.execute(
+ f"""
+ INSERT INTO {LEASE_TABLE} (team_id, schema_id, owner_token, expires_at, acquired_at, updated_at)
+ VALUES (%(team_id)s, %(schema_id)s, %(owner)s, now() + make_interval(secs => %(ttl)s), now(), now())
+ ON CONFLICT (team_id, schema_id) DO UPDATE
+ SET owner_token = excluded.owner_token,
+ expires_at = excluded.expires_at,
+ acquired_at = now(),
+ updated_at = now()
+ WHERE {LEASE_TABLE}.expires_at <= now(){reentry_clause}
+ RETURNING id
+ """,
+ {
+ "team_id": RECONCILE_SWEEP_LEASE_TEAM_ID,
+ "schema_id": schema_id,
+ "owner": owner_token,
+ "ttl": ttl_seconds,
+ },
+ )
+ return await cur.fetchone() is not None
+
+
class BatchQueue:
"""
Async interface to the Postgres batch queue tables. Each method runs
@@ -1274,27 +1408,37 @@ class BatchQueue:
session must not be able to hold the slot forever — a crashed winner's
slot frees itself at expiry.
"""
- async with conn.cursor() as cur:
- await cur.execute(
- f"""
- INSERT INTO {LEASE_TABLE} (team_id, schema_id, owner_token, expires_at, acquired_at, updated_at)
- VALUES (%(team_id)s, %(schema_id)s, %(owner)s, now() + make_interval(secs => %(ttl)s), now(), now())
- ON CONFLICT (team_id, schema_id) DO UPDATE
- SET owner_token = excluded.owner_token,
- expires_at = excluded.expires_at,
- acquired_at = now(),
- updated_at = now()
- WHERE {LEASE_TABLE}.expires_at <= now()
- RETURNING id
- """,
- {
- "team_id": RECONCILE_SWEEP_LEASE_TEAM_ID,
- "schema_id": RECONCILE_SWEEP_LEASE_SCHEMA_ID,
- "owner": owner_token,
- "ttl": ttl_seconds,
- },
- )
- return await cur.fetchone() is not None
+ return await _try_acquire_fleet_slot(
+ conn,
+ schema_id=RECONCILE_SWEEP_LEASE_SCHEMA_ID,
+ owner_token=owner_token,
+ ttl_seconds=ttl_seconds,
+ reentrant=False,
+ )
+
+ @staticmethod
+ async def try_acquire_queue_gauges_slot(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ owner_token: str,
+ slot_key: str = QUEUE_GAUGES_LEASE_SCHEMA_ID_PREFIX,
+ ttl_seconds: int = QUEUE_GAUGES_SLOT_TTL_SECONDS,
+ ) -> bool:
+ """Claim the gauge-sampling slot of one fleet; True means this pod samples the queue gauges.
+
+ Unlike the sweep slot, the holder can renew its own live slot. The owner
+ token is stable for the life of a consumer, and it asks once per reconcile
+ interval. So when the interval is shorter than the TTL, the holder keeps
+ the slot and samples on its own cadence. Without renewal it would lose its
+ own slot to itself, and for the rest of the TTL no pod would sample.
+ """
+ return await _try_acquire_fleet_slot(
+ conn,
+ schema_id=slot_key,
+ owner_token=owner_token,
+ ttl_seconds=ttl_seconds,
+ reentrant=True,
+ )
@staticmethod
async def renew_lease(
@@ -1772,6 +1916,7 @@ class BatchQueue:
conn: psycopg.AsyncConnection[Any],
*,
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``.
@@ -1791,37 +1936,11 @@ class BatchQueue:
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``.
"""
- async with conn.cursor() as cur:
- await cur.execute(
- f"""
- 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},
- )
+ async with _gauge_cursor(conn, statement_timeout_ms=statement_timeout_ms) as cur:
+ 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)
@@ -1832,7 +1951,11 @@ class BatchQueue:
)
@staticmethod
- async def get_queue_depth(conn: psycopg.AsyncConnection[Any]) -> QueueDepth:
+ async def get_queue_depth(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ statement_timeout_ms: int = GAUGE_STATEMENT_TIMEOUT_MS,
+ ) -> 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``
@@ -1846,8 +1969,10 @@ class BatchQueue:
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.
+
+ Raises ``psycopg.errors.QueryCanceled`` past ``statement_timeout_ms``.
"""
- async with conn.cursor() as cur:
+ 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()
if row is None:
diff --git a/products/warehouse_sources_queue/backend/core/metrics.py b/products/warehouse_sources_queue/backend/core/metrics.py
index 1e528a12025c..db02cdc30b69 100644
--- a/products/warehouse_sources_queue/backend/core/metrics.py
+++ b/products/warehouse_sources_queue/backend/core/metrics.py
@@ -1,3 +1,4 @@
+import math
import time
import asyncio
from collections.abc import Iterator
@@ -99,9 +100,9 @@ RUNS_TERMINALIZED_STALE_TOTAL = Counter(
# The loader's data-freshness signal: it rises whenever loading stalls,
# regardless of why (wedged consumers, claim-query degradation, crashloops).
-# Every pod reports the same queue-wide value, so aggregate with max().
-# livemax matches that: it stays accurate even if two consumer processes
-# briefly co-exist in one pod, where livesum would double the age.
+# One elected pod per fleet samples it (see clear_queue_sample_gauges), so
+# aggregate with max(). liveall keeps each process's sample separate: during a
+# restart, one process's NaN must not hide the elected process's finite sample.
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 "
@@ -109,7 +110,7 @@ OLDEST_UNCLAIMED_BATCH_SECONDS = Gauge(
"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",
+ multiprocess_mode="liveall",
)
# The population the age gauge above excludes. Split out rather than dropped: these
@@ -121,7 +122,7 @@ 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",
+ multiprocess_mode="liveall",
)
# Breadth companion to the age gauge. The age is a fleet-wide max, so a single wedged
@@ -131,7 +132,7 @@ 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",
+ multiprocess_mode="liveall",
)
# Depth companion to the age gauge above: age says how stale the head of the queue
@@ -142,7 +143,7 @@ CLAIMABLE_BATCHES = Gauge(
"Batches whose state makes them claimable right now (pending or waiting_retry, "
"within the claim eligibility window; per-run and lease gates not applied). "
"Sampled on the reconcile cadence.",
- multiprocess_mode="livemax",
+ multiprocess_mode="liveall",
)
# Concentration companions to the depth gauge. The loader drains each (team,
@@ -156,7 +157,7 @@ CLAIMABLE_GROUPS = Gauge(
"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",
+ multiprocess_mode="liveall",
)
TOP_GROUPS_CLAIMABLE_SHARE = Gauge(
@@ -165,7 +166,7 @@ TOP_GROUPS_CLAIMABLE_SHARE = Gauge(
"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",
+ multiprocess_mode="liveall",
)
SLOT_WAITING_BATCHES = Gauge(
@@ -175,7 +176,7 @@ SLOT_WAITING_BATCHES = Gauge(
"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",
+ multiprocess_mode="liveall",
)
SERIALIZED_BATCHES = Gauge(
@@ -183,9 +184,34 @@ SERIALIZED_BATCHES = Gauge(
"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",
+ multiprocess_mode="liveall",
)
+QUEUE_SAMPLE_GAUGES: tuple[Gauge, ...] = (
+ OLDEST_UNCLAIMED_BATCH_SECONDS,
+ BLOCKED_BATCHES,
+ BACKLOGGED_GROUPS,
+ CLAIMABLE_BATCHES,
+ CLAIMABLE_GROUPS,
+ TOP_GROUPS_CLAIMABLE_SHARE,
+ SLOT_WAITING_BATCHES,
+ SERIALIZED_BATCHES,
+)
+
+
+def clear_queue_sample_gauges() -> None:
+ """Mark this pod's queue-wide gauges as "no sample" until it takes a fresh one.
+
+ Only the pod that holds the gauge slot samples the queue. A Prometheus gauge
+ exports its last value forever, so a pod that sampled in an earlier round
+ would keep exporting that old value, and max() across pods would pin it.
+ NaN is the "no value" marker: PromQL and MetricsQL max() skip it while any
+ pod has a real value.
+ """
+ for gauge in QUEUE_SAMPLE_GAUGES:
+ gauge.set(math.nan)
+
+
# 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_queue/backend/tests/test_metrics.py b/products/warehouse_sources_queue/backend/tests/test_metrics.py
index 61755407f453..61b90be9a32c 100644
--- a/products/warehouse_sources_queue/backend/tests/test_metrics.py
+++ b/products/warehouse_sources_queue/backend/tests/test_metrics.py
@@ -1,8 +1,13 @@
+import sys
+import math
import asyncio
+import subprocess
+from pathlib import Path
import pytest
import psycopg
+from prometheus_client import CollectorRegistry, multiprocess
from products.warehouse_sources_queue.backend.core.metrics import (
QUEUE_QUERY_DURATION_SECONDS,
@@ -16,6 +21,44 @@ def _duration_count(query: str) -> float:
return sum(b.get() for b in QUEUE_QUERY_DURATION_SECONDS.labels(query=query)._buckets)
[email protected]("process_order", [("holder", "non-holder"), ("non-holder", "holder")])
+def test_queue_gauge_multiprocess_collection_preserves_holder_sample(tmp_path, process_order):
+ script = """
+import os
+import sys
+
+os.environ["PROMETHEUS_MULTIPROC_DIR"] = sys.argv[1]
+
+from products.warehouse_sources_queue.backend.core.metrics import ( # noqa: E402
+ OLDEST_UNCLAIMED_BATCH_SECONDS,
+ clear_queue_sample_gauges,
+)
+
+clear_queue_sample_gauges()
+if sys.argv[2] == "holder":
+ OLDEST_UNCLAIMED_BATCH_SECONDS.set(37)
+"""
+ repository_root = Path(__file__).resolve().parents[4]
+ for process in process_order:
+ subprocess.run(
+ [sys.executable, "-c", script, str(tmp_path), process],
+ check=True,
+ cwd=repository_root,
+ )
+
+ registry = CollectorRegistry()
+ multiprocess.MultiProcessCollector(registry, path=str(tmp_path))
+ family = next(
+ metric for metric in registry.collect() if metric.name == "warehouse_pg_queue_oldest_unclaimed_batch_seconds"
+ )
+ samples = [sample for sample in family.samples if sample.name == family.name]
+
+ assert len(samples) == 2
+ assert all(set(sample.labels) == {"pid"} for sample in samples)
+ assert [sample.value for sample in samples if math.isfinite(sample.value)] == [37]
+ assert sum(math.isnan(sample.value) for sample in samples) == 1
+
+
class TestObserveQueueQuery:
def test_success_observes_duration(self):
before = _duration_count("t-success")