: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(data-warehouse): bound the queue claim query cost during a backlog (#112751)
Tom Owers55e3e899ca7a
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.pyindex 0b040c4c6aa8..30816bc3f6d1 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@@ -71,6 +71,7 @@ from products.warehouse_sources_queue.backend.core.jobs_db import (GAUGE_STATEMENT_TIMEOUT_MS,TAKEOVER_STALE_THRESHOLD_SECONDS,BatchQueue,+ ClaimCursor,FailedRunRef,PendingBatch,QueueDepth,@@ -249,6 +250,7 @@ class DeltaBatchConsumerAdapter:# slot holder keeps one; it is re-exported while the depth probe times out.self._depth_sample: QueueDepth | None = Noneself._depth_sampled_at = 0.0+ self._claim_cursor = ClaimCursor()# 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@@ -272,6 +274,7 @@ class DeltaBatchConsumerAdapter:lease_ttl_seconds=lease_ttl_seconds,sync_types=self._claim_sync_types,exclude_sync_types=self._claim_exclude_sync_types,+ cursor=self._claim_cursor,)async def unlock(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.pyindex 5f670ab05cf3..e3bb98da78f0 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@@ -1583,7 +1583,10 @@ class TestStatementTimeoutBackstop:await consumer._ensure_poll_conn()assert "options" not in mock_connect.call_args.kwargs- fresh.execute.assert_awaited_once_with("SET statement_timeout = 210000")+ assert [call.args[0] for call in fresh.execute.await_args_list] == [+ "SET statement_timeout = 210000",+ "SET jit = off",+ ]class TestPollBackoff: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.pyindex 7e6689aae3ca..0f99f21b9085 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@@ -23,18 +23,23 @@ from products.warehouse_sources_queue.backend.core.jobs_db import (BATCH_TABLE,CLAIM_ELIGIBILITY_INTERVAL,LEASE_TABLE,+ PARTITION_PRUNING_INTERVAL,STATUS_TABLE,TAKEOVER_STALE_THRESHOLD_SECONDS,BatchQueue,+ ClaimCursor,PendingBatch,QueueDepth,+ _claim_window_sql,_claimable_count_sql,_orphaned_candidate_runs_sql,_queue_depth_sql,_queue_freshness_sql,+ _state_claim_candidates_sql,_sync_connection_pool,build_status_dual_write_sql,queue_gauges_slot_key,+ sync_type_scope_sql,)from products.warehouse_sources_queue.backend.testing import (BATCH_DEFAULTS as _BATCH_DEFAULTS,@@ -1868,15 +1873,13 @@ class TestClaimGates:# A per-batch gate probe that the planner answers from a non-partial# run_uuid index reads the whole run for every candidate, so a backlog# of long runs grows quadratically. One probe per run bounds it.- from products.warehouse_sources_queue.backend.core.jobs_db import _claim_window_sql-for i in range(40):await _insert_batch(conn, run_uuid="long-run", schema_id="s-long", batch_index=i)await _insert_batch(conn, run_uuid="short-run", schema_id="s-short", batch_index=0)cur = await conn.execute("EXPLAIN (ANALYZE, FORMAT JSON) WITH " + _claim_window_sql() + " SELECT * FROM narrow",- {"backoff": 0, "owner": OWNER_A, "limit": 50},+ {"backoff": 0, "owner": OWNER_A, "limit": 50, "team_cursor": 0},)row = await cur.fetchone()assert row is not None@@ -1897,8 +1900,6 @@ class TestClaimGates:await _insert_batch(conn)await conn.execute("SET enable_seqscan = off")try:- from products.warehouse_sources_queue.backend.core.jobs_db import _state_claim_candidates_sql-cur = await conn.execute("EXPLAIN (FORMAT TEXT) " + _state_claim_candidates_sql() + " LIMIT 50",{"backoff": 0},@@ -1926,6 +1927,347 @@ class TestClaimGates:assert "sb_job_id_idx" in plan+def _unbounded_claim_window_sql(sync_type_scope: str = "") -> str:+ # The claim window with no team window and no depth: every claimable batch+ # is a candidate. The bounded query must give the same claims while the+ # queue fits inside its bounds.+ return f"""+ claimable AS MATERIALIZED (+ {_state_claim_candidates_sql(sync_type_scope)}+ ),+ open_groups AS MATERIALIZED (+ SELECT g.team_id, g.schema_id+ FROM (SELECT DISTINCT c.team_id, c.schema_id FROM claimable c) g+ WHERE NOT EXISTS (+ SELECT 1+ FROM {BATCH_TABLE} x+ WHERE x.team_id = g.team_id+ AND x.schema_id = g.schema_id+ AND x.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND x.latest_state = 'executing'+ )+ AND NOT EXISTS (+ SELECT 1+ FROM {LEASE_TABLE} l+ WHERE l.team_id = g.team_id+ AND l.schema_id = g.schema_id+ AND l.expires_at > now()+ AND l.owner_token != %(owner)s+ )+ ),+ narrow AS MATERIALIZED (+ SELECT c.id, c.created_at+ FROM claimable c+ JOIN open_groups g ON g.team_id = c.team_id AND g.schema_id = c.schema_id+ WHERE NOT EXISTS (+ SELECT 1+ FROM {BATCH_TABLE} f+ WHERE f.run_uuid = c.run_uuid+ AND f.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND f.latest_state = 'failed'+ )+ AND NOT EXISTS (+ SELECT 1+ FROM {BATCH_TABLE} h+ WHERE h.run_uuid = c.run_uuid+ AND h.batch_index < c.batch_index+ AND h.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND (+ h.latest_state = 'executing'+ OR (+ h.latest_state = 'waiting_retry'+ AND h.state_changed_at > now() - make_interval(+ secs => %(backoff)s * GREATEST(h.latest_attempt, 1)+ )+ )+ )+ )+ ORDER BY+ row_number() OVER (+ PARTITION BY c.team_id ORDER BY c.created_at ASC, c.batch_index ASC+ ) ASC,+ c.created_at ASC,+ c.batch_index ASC+ LIMIT %(limit)s+ )+ """+++# (team_id, schema_id, run_uuid, batch_index, latest state, sync_type), oldest first.+_BatchSpec = tuple[int, str, str, int, str, str]++_SERIALIZED_GROUPS: list[_BatchSpec] = [+ (1, "s-busy", "run-1", 0, "executing", "incremental"),+ (1, "s-busy", "run-1", 1, "pending", "incremental"),+ (1, "s-busy", "run-2", 0, "pending", "incremental"),+ (1, "s-open", "run-3", 0, "pending", "incremental"),+ (1, "s-open", "run-3", 1, "pending", "incremental"),+ (2, "s-other", "run-4", 0, "pending", "incremental"),+ (2, "s-other", "run-5", 0, "pending", "incremental"),+]+_GATED_RUNS: list[_BatchSpec] = [+ (1, "s-failed", "run-1", 0, "failed", "incremental"),+ (1, "s-failed", "run-1", 1, "pending", "incremental"),+ (1, "s-failed", "run-2", 0, "pending", "incremental"),+ (2, "s-retry", "run-3", 0, "pending", "incremental"),+ (2, "s-retry", "run-3", 1, "waiting_retry", "incremental"),+ (2, "s-retry", "run-3", 2, "pending", "incremental"),+ (3, "s-healthy", "run-4", 0, "pending", "incremental"),+ (3, "s-waiting", "run-5", 0, "waiting", "incremental"),+ (3, "s-done", "run-6", 0, "succeeded", "incremental"),+]+_LEASED_GROUPS: list[_BatchSpec] = [+ (1, "s-foreign", "run-1", 0, "pending", "incremental"),+ (1, "s-free", "run-2", 0, "pending", "incremental"),+ (2, "s-own", "run-3", 0, "pending", "incremental"),+ (3, "s-expired", "run-4", 0, "pending", "incremental"),+]+_MIXED_TEAMS: list[_BatchSpec] = [+ (1, "s-a", "run-1", 0, "pending", "full_refresh"),+ (1, "s-a", "run-1", 1, "pending", "full_refresh"),+ (1, "s-b", "run-2", 0, "pending", "cdc"),+ (2, "s-c", "run-3", 0, "pending", "incremental"),+ (1, "s-a", "run-1", 2, "pending", "full_refresh"),+ (3, "s-d", "run-4", 0, "pending", "cdc"),+ (3, "s-d", "run-4", 1, "pending", "cdc"),+ (2, "s-e", "run-5", 0, "pending", "append"),+]+# (team_id, schema_id, owner, seconds until expiry)+_LEASES: list[tuple[int, str, str, int]] = [+ (1, "s-foreign", OWNER_B, 300),+ (2, "s-own", OWNER_A, 300),+ (3, "s-expired", OWNER_B, -1),+]+++async def _bulk_insert_batches(+ conn: psycopg.AsyncConnection[Any], *, teams: int = 1, per_team: int, **overrides: Any+) -> None:+ # One statement for many rows: batch_index 0..per_team-1 for team_id 1..teams (or the team_id override).+ values = {**_BATCH_DEFAULTS, **overrides}+ columns = [k for k in values if k not in ("team_id", "batch_index", "metadata")]+ team_sql = "%(team_id)s" if "team_id" in overrides else "t"+ await conn.execute(+ f"INSERT INTO {BATCH_TABLE} (team_id, batch_index, {', '.join(columns)}) "+ f"SELECT {team_sql}, %(first_index)s + i, {', '.join(f'%({k})s' for k in columns)} "+ "FROM generate_series(1, %(teams)s) t, generate_series(0, %(per_team)s - 1) i",+ {**values, "teams": teams, "per_team": per_team, "first_index": overrides.get("batch_index", 0)},+ )+++async def _explain_claim_window(conn: psycopg.AsyncConnection[Any], *, limit: int) -> dict[str, Any]:+ cur = await conn.execute(+ "EXPLAIN (ANALYZE, FORMAT JSON) WITH " + _claim_window_sql() + " SELECT * FROM narrow",+ {"backoff": 0, "owner": OWNER_A, "limit": limit, "team_cursor": 0},+ )+ row = await cur.fetchone()+ assert row is not None+ plan = row[0] if isinstance(row[0], list) else json.loads(row[0])+ return plan[0]["Plan"]+++def _plan_nodes(node: dict[str, Any]) -> list[dict[str, Any]]:+ return [node] + [n for child in node.get("Plans", []) for n in _plan_nodes(child)]++[email protected]_db(transaction=True)+class TestClaimWindow:+ async def _seed(self, conn, batches: list[_BatchSpec]) -> None:+ for team_id, schema_id, run_uuid, batch_index, state, sync_type in batches:+ bid = await _insert_batch(+ conn,+ team_id=team_id,+ schema_id=schema_id,+ run_uuid=run_uuid,+ batch_index=batch_index,+ sync_type=sync_type,+ )+ if state != "pending":+ await BatchQueue.update_status(conn, batch_id=bid, job_state=state, attempt=1)++ async def _lease(self, conn, team_id: int, schema_id: str, owner: str, ttl: int = 300) -> None:+ await conn.execute(+ f"INSERT INTO {LEASE_TABLE} (team_id, schema_id, owner_token, expires_at) "+ "VALUES (%s, %s, %s, now() + make_interval(secs => %s))",+ (team_id, schema_id, owner, ttl),+ )++ @pytest.mark.parametrize("limit", [2, 3, 50])+ @pytest.mark.parametrize("start", [None, 2], ids=["no_cursor", "cursor_mid_queue"])+ @pytest.mark.parametrize(+ "batches,leases,sync_types",+ [+ pytest.param(_SERIALIZED_GROUPS, [], None, id="serialized_groups"),+ pytest.param(_GATED_RUNS, [], None, id="gated_runs"),+ pytest.param(_LEASED_GROUPS, _LEASES, None, id="leases_held"),+ pytest.param(_MIXED_TEAMS, [], None, id="mixed_teams"),+ pytest.param(_MIXED_TEAMS, [], ["cdc", "append"], id="mixed_teams_one_fleet"),+ ],+ )+ @pytest.mark.asyncio+ async def test_bounded_window_claims_what_an_unbounded_scan_claims(+ self, conn, batches, leases, sync_types, start, limit+ ):+ await self._seed(conn, batches)+ for team_id, schema_id, owner, ttl in leases:+ await self._lease(conn, team_id, schema_id, owner, ttl)+ scope_sql, scope_params = sync_type_scope_sql(sync_types=sync_types)+ cur = await conn.execute(+ "WITH " + _unbounded_claim_window_sql(scope_sql) + " SELECT id::text FROM narrow",+ {"backoff": 3600, "owner": OWNER_A, "limit": limit, **scope_params},+ )+ expected = {row[0] for row in await cur.fetchall()}++ claimed = await _claim(+ conn,+ limit=limit,+ retry_backoff_base_seconds=3600,+ sync_types=sync_types,+ cursor=None if start is None else ClaimCursor(team_id=start),+ )++ assert expected, "the scenario must leave something to claim"+ assert {str(b.id) for b in claimed} == expected++ @pytest.mark.parametrize(+ "teams,window,start,random_start,expected_windows",+ [+ pytest.param(5, 2, 0, None, [[1, 2], [3, 4], [1, 5]], id="rotates_and_wraps"),+ pytest.param(5, 2, 4, None, [[1, 5], [2, 3]], id="wraps_inside_one_window"),+ pytest.param(5, 2, 99, None, [[1, 2]], id="cursor_past_the_last_team_starts_over"),+ pytest.param(5, 2, None, 3, [[4, 5], [1, 2]], id="first_claim_starts_at_a_random_team"),+ pytest.param(3, 3, 0, None, [[1, 2, 3], [1, 2, 3]], id="queue_of_exactly_one_window"),+ pytest.param(4, 3, 0, None, [[1, 2, 3], [1, 2, 4]], id="one_team_more_than_the_window"),+ ],+ )+ @pytest.mark.asyncio+ async def test_consecutive_claims_rotate_through_every_team(+ self, conn, teams, window, start, random_start, expected_windows+ ):+ for team_id in range(1, teams + 1):+ await _insert_batch(conn, team_id=team_id, schema_id=f"s-{team_id}", run_uuid=f"run-{team_id}")+ cursor = ClaimCursor(team_id=start)++ windows = []+ with (+ patch(f"{_JOBS_DB}.CLAIM_WINDOW_TEAMS", window),+ patch(f"{_JOBS_DB}.random.randint", return_value=random_start),+ ):+ for _ in expected_windows:+ claimed = await _claim(conn, cursor=cursor)+ windows.append(sorted(b.team_id for b in claimed))++ assert windows == expected_windows++ @pytest.mark.parametrize(+ "open_team,max_windows,expected_teams,expected_cursor",+ [+ pytest.param(6, 20, [6], 6, id="reads_on_past_windows_with_nothing_open"),+ pytest.param(6, 1, [], 2, id="an_empty_window_still_moves_the_cursor"),+ pytest.param(None, 20, [], 2, id="stops_after_one_turn_over_all_teams"),+ ],+ )+ @pytest.mark.asyncio+ async def test_windows_with_nothing_open_do_not_end_the_claim(+ self, conn, open_team, max_windows, expected_teams, expected_cursor+ ):+ for team_id in range(1, 7):+ await _insert_batch(conn, team_id=team_id, schema_id=f"s-{team_id}", run_uuid=f"run-{team_id}")+ if team_id != open_team:+ await self._lease(conn, team_id, f"s-{team_id}", OWNER_B)+ cursor = ClaimCursor(team_id=0)++ with patch(f"{_JOBS_DB}.CLAIM_WINDOW_TEAMS", 2), patch(f"{_JOBS_DB}.CLAIM_MAX_EMPTY_WINDOWS", max_windows):+ claimed = await _claim(conn, cursor=cursor)++ assert ([b.team_id for b in claimed], cursor.team_id) == (expected_teams, expected_cursor)++ @pytest.mark.parametrize("outcome", ["no_team_holds_work", "claim_fails"])+ @pytest.mark.asyncio+ async def test_cursor_is_unset_when_a_claim_finds_no_team_or_fails(self, conn, outcome):+ cursor = ClaimCursor(team_id=5)++ if outcome == "claim_fails":+ await conn.close()+ with pytest.raises(psycopg.Error):+ await _claim(conn, cursor=cursor)+ else:+ assert await _claim(conn, cursor=cursor) == []++ assert cursor.team_id is None++ @pytest.mark.asyncio+ async def test_backlog_of_a_closed_group_does_not_hide_the_other_groups_of_its_team(self, conn):+ busy = await _insert_batch(conn, schema_id="s-busy", run_uuid="run-busy", batch_index=0)+ await BatchQueue.update_status(conn, batch_id=busy, job_state="executing", attempt=1)+ for i in range(1, 5):+ await _insert_batch(conn, schema_id="s-busy", run_uuid="run-busy", batch_index=i)+ await _insert_batch(conn, schema_id="s-open", run_uuid="run-open")++ with patch(f"{_JOBS_DB}.CLAIM_WINDOW_TEAM_DEPTH", 2):+ claimed = await _claim(conn, limit=1)++ assert [b.schema_id for b in claimed] == ["s-open"]++ @pytest.mark.parametrize("held", [49, 60])+ @pytest.mark.parametrize("blocker_state", ["failed", "waiting_retry"])+ @pytest.mark.asyncio+ async def test_batches_held_by_a_run_gate_do_not_hide_the_other_groups_of_their_team(+ self, conn, blocker_state, held+ ):+ blocker = await _insert_batch(conn, schema_id="s-held", run_uuid="run-held", batch_index=0)+ await BatchQueue.update_status(conn, batch_id=blocker, job_state=blocker_state, attempt=1)+ await _bulk_insert_batches(+ conn, team_id=1, per_team=held, schema_id="s-held", run_uuid="run-held", batch_index=1+ )+ for i in range(3):+ await _insert_batch(conn, schema_id="s-open", run_uuid="run-open", batch_index=i)++ claimed = await _claim(conn, limit=50, retry_backoff_base_seconds=3600)++ assert [(b.schema_id, b.batch_index) for b in claimed] == [("s-open", 0), ("s-open", 1), ("s-open", 2)]++ @pytest.mark.asyncio+ async def test_claim_reads_only_the_closed_groups_of_its_window(self, conn):+ # Past a few thousand rows a hashed sub-plan over every closed group stops fitting in+ # work_mem, and the plan compares each candidate with the whole set.+ await _insert_batch(conn, team_id=1, schema_id="s-leased", run_uuid="run-leased")+ await _insert_batch(conn, team_id=1, schema_id="s-open", run_uuid="run-open")+ await self._lease(conn, 1, "s-leased", OWNER_B)+ await conn.execute(+ f"INSERT INTO {LEASE_TABLE} (team_id, schema_id, owner_token, expires_at) "+ "SELECT 1000 + g, 's-' || g, %s, now() + interval '5 minutes' FROM generate_series(1, 20000) g",+ (OWNER_B,),+ )+ await conn.execute(f"ANALYZE {LEASE_TABLE}")++ plan = await _explain_claim_window(conn, limit=50)+ claimed = await _claim(conn)++ closed = [n for n in _plan_nodes(plan) if n.get("Subplan Name") == "CTE closed_groups"]+ assert [n["Actual Rows"] for n in closed] == [1]+ assert [b.schema_id for b in claimed] == ["s-open"]++ @pytest.mark.asyncio+ async def test_claim_reads_a_bounded_window_of_a_deep_backlog(self, conn):+ teams, per_team, window_teams, depth = 40, 5, 3, 2+ await _bulk_insert_batches(conn, teams=teams, per_team=per_team)+ # Tables this small make a scan of everything the cheapest plan. The settings+ # leave the index-driven plans that a production-size table gets. Sorts stay+ # enabled: a per-team scan that sorts is a plan production can pick.+ for setting in ("enable_seqscan", "enable_bitmapscan"):+ await conn.execute(f"SET {setting} = off")+ with patch(f"{_JOBS_DB}.CLAIM_WINDOW_TEAMS", window_teams), patch(f"{_JOBS_DB}.CLAIM_WINDOW_TEAM_DEPTH", depth):+ plan = await _explain_claim_window(conn, limit=2)++ rows_read = sum(+ n["Actual Rows"] * n["Actual Loops"] for n in _plan_nodes(plan) if n.get("Relation Name") == BATCH_TABLE+ )+ # One row per team seek, plus at most every candidate of the window's teams+ # when the scan sorts. The other 37 teams of the backlog do not enter.+ assert rows_read <= (window_teams + 1) + window_teams * per_team++@pytest.mark.django_db(transaction=True)class TestGetQueueDepth:@pytest.mark.asynciodiff --git a/products/warehouse_sources_queue/backend/README.md b/products/warehouse_sources_queue/backend/README.mdindex dda240589245..4bb708a0d3eb 100644--- a/products/warehouse_sources_queue/backend/README.md+++ b/products/warehouse_sources_queue/backend/README.md@@ -39,6 +39,15 @@ All SQL lives in `core/jobs_db.py`; the polling/retry/recovery engine is `core/b- **Claim-or-renew in one statement**: `get_unprocessed_and_lock` selects narrow claim candidates from the denormalized columns (with per-team round-robin fairness, head-of-line gating per run, a failed-run gate, and a schema-busy gate), then claims or renews the group leases for the winners inside a single writable CTE.The candidate CTE is `MATERIALIZED` so its `LIMIT` fully resolves before the lease upsert runs, and candidate groups are deduplicated because `INSERT ... ON CONFLICT DO UPDATE` cannot touch the same lease row twice in one statement.(The old README's `MATERIALIZED` rationale, preventing `pg_try_advisory_lock` from acquiring phantom locks in a `WHERE` clause, no longer applies: there are no advisory locks.)+- **A bounded claim window**: one claim does not read the whole claimable set.+ It reads the next `CLAIM_WINDOW_TEAMS` teams that hold claimable work, in `team_id` order from the consumer's cursor (`ClaimCursor`), and at most `CLAIM_WINDOW_TEAM_DEPTH` candidates per team (or the claim's limit, if larger).+ Batches of a closed group (executing, or leased by another pod) do not count toward the depth.+ Batches held by a run gate do not count either: the scan runs in rounds, and each round reads past the runs that the round before found held, up to `CLAIM_WINDOW_GATE_ROUNDS` rounds.+ Each claim moves the cursor to the end of its window, and the walk wraps, so consecutive claims rotate through every team.+ A full window that gives no batch does not end the claim call: it reads the next windows, up to `CLAIM_MAX_EMPTY_WINDOWS` or one turn over all teams.+ A consumer starts at a random team, so pods started together read different windows. A claim that finds no team with work, or that fails, unsets the cursor, and the next claim starts at a new random team.+ While the queue fits in one window, a claim sees all of it and the order is the same as an unbounded scan: round-robin across teams, oldest first.+ During a larger backlog the order is oldest first among the teams of the window, not across the queue, and a team outside the window waits for the rotation.- **Async consumer**: single asyncio process that polls every ~2s, groups batches by `(team_id, schema_id)`, processes groups concurrently, batches within a group sequentially.Each batch renews the lease on entry, heartbeats it (and re-inserts `executing` status) during processing, and verifies ownership before writing `succeeded`.- **Three sweeps**, not one:@@ -79,7 +88,11 @@ Three changes in August 2026 restructured the hot queries after a production loaA fourth change followed an October 2026 claim stall, after an analyze of the current daily partition:-- The claim query's gates were correlated probes per candidate batch. On a hot partition the partial indexes churn and bloat, so the planner can answer a probe from `sb_run_uuid_idx`, `sb_run_uuid_bi_idx` or `sb_team_schema_idx` instead, and each probe then reads the whole run or group. A backlog of long runs made every poll quadratic. The gates now run once per group (`busy_groups`, `open_groups`) and once per run (`open_runs`), so a bad index choice costs at most one read of each candidate run. The loader also backs off failed polls with full jitter, so the fleet does not retry a struggling claim query in lockstep.+- The claim query's gates were correlated probes per candidate batch. On a hot partition the partial indexes churn and bloat, so the planner can answer a probe from `sb_run_uuid_idx`, `sb_run_uuid_bi_idx` or `sb_team_schema_idx` instead, and each probe then reads the whole run or group. A backlog of long runs made every poll quadratic. The gates now run once per group (`closed_groups`) and once per scanned run (`gates`), so a bad index choice costs at most one read of each candidate run. The loader also backs off failed polls with full jitter, so the fleet does not retry a struggling claim query in lockstep.++A fifth change followed a backlog that stayed claimable but drained slowly:++- The claim query materialized every claimable batch on every poll, so one claim cost as much as the backlog was deep, and the loaders spent their time in claims while group slots stayed empty. The query now reads a bounded window: a loose index scan over `sb_claimable_idx` finds the next teams with work (one index descent per team and partition), and a per-team scan reads the oldest candidates of those teams only. See "A bounded claim window" above for the ordering rule that comes with it. The planner can price this statement above `jit_above_cost` although it runs in milliseconds, and JIT compilation then costs more than the statement, so the consumer connections set `jit = off`.The shared lesson: every query on these tables must scale with the size of its answer (the claimable set, the candidate runs), never with retained failure history, because failure history is largest exactly when the fleet is least healthy.The `core/jobs_db.py` docstrings on `_state_claim_candidates_sql`, `_claim_window_sql`, `get_failed_runs` and `_stranded_candidate_runs_sql` carry the details, and plan-shape tests in `test_jobs_db.py` pin the query shapes.@@ -95,7 +108,7 @@ The migration must be `atomic = False` and re-runnable (a cancelled `CONCURRENTL- **COPY bulk inserts**: the producer inserts one row per batch. At our volume, row-level INSERT is fine. (We can always move to bulk insert if needed)- **Compaction**: RudderStack runs a background process to merge/drop completed datasets, it stores tables up to 100k rows and then they roll to the next one. We don't need it at the moment, but if we end up implementing rolling datasets, we will implement this compaction too.- **Caching layers**: RudderStack uses "no jobs" caches and active pipeline caches to reduce query load. We have not needed them, but only because the claim path was restructured to run off partial indexes and denormalized state (see above); "proper indexing" alone was not enough.-- **Recursive CTE loose index scans**: their trick for finding distinct pipeline IDs efficiently. Our claim query gets the same effect from the partial indexes.+- **Recursive CTE loose index scans**: no longer left out. The claim query uses one over `sb_claimable_idx` to find the teams of its window (`window_teams` in `_claim_window_sql`).- **Active Partitions**: RudderStack designs a partition and then it assigns each partition to one processor instance, this is similar to how Kafka partitions work. We don't need this, this will be an overkill as we don't have any specifics for a partition.### Architecturediff --git a/products/warehouse_sources_queue/backend/core/batch_consumer.py b/products/warehouse_sources_queue/backend/core/batch_consumer.pyindex 420f6577900f..4c17f4ffc8f0 100644--- a/products/warehouse_sources_queue/backend/core/batch_consumer.py+++ b/products/warehouse_sources_queue/backend/core/batch_consumer.py@@ -533,12 +533,16 @@ class BatchConsumer:# Session-scoped SET, not a libpq startup option: PgBouncer rejects# statement_timeout inside the `options` startup parameter.timeout_ms = self._statement_timeout_ms(statement_timeout_seconds)- if timeout_ms is not None:- try:+ try:+ if timeout_ms is not None:await conn.execute(f"SET statement_timeout = {timeout_ms}")- except psycopg.Error:- await conn.close()- raise+ # The queue statements are index probes that take milliseconds, but the planner+ # can price the claim query above jit_above_cost. JIT compilation then costs+ # more than the whole statement, on every poll.+ await conn.execute("SET jit = off")+ except psycopg.Error:+ await conn.close()+ raisereturn connasync def _drop_conn(self, attr: str) -> None:diff --git a/products/warehouse_sources_queue/backend/core/jobs_db.py b/products/warehouse_sources_queue/backend/core/jobs_db.pyindex fd2a9c126b25..bae6ae00ec0e 100644--- a/products/warehouse_sources_queue/backend/core/jobs_db.py+++ b/products/warehouse_sources_queue/backend/core/jobs_db.py@@ -17,6 +17,7 @@ from __future__ import annotationsimport jsonimport time+import randomimport threadingfrom collections.abc import AsyncIterator, Iteratorfrom contextlib import asynccontextmanager, contextmanager, suppress@@ -99,6 +100,30 @@ PARTITION_PRUNING_INTERVAL = "14 days"# long as they exist.CLAIM_ELIGIBILITY_INTERVAL = "6 days 12 hours"+# One claim reads a window of the queue, not the whole claimable set, so its cost+# does not grow with a backlog. The window is the next CLAIM_WINDOW_TEAMS teams that+# hold claim candidates, in team_id order from the consumer's cursor, with wrap. A+# backlog over more teams than this is served in rotation: oldest first inside the+# window, not oldest first across the queue.+CLAIM_WINDOW_TEAMS = 100++# Candidates one claim reads per window team and scan round, oldest first.+# The effective depth is never below the claim's LIMIT, so one team can fill a claim.+CLAIM_WINDOW_TEAM_DEPTH = 50++# Scan rounds per window team. A round that finds candidates held by a run gate+# makes the next round read past those runs, so gated batches cannot fill the depth+# and hide the open ones behind them. The cap bounds the cost: a team with gated+# candidates deeper than rounds x depth waits until a gate clears.+CLAIM_WINDOW_GATE_ROUNDS = 5++# Full windows one claim call may read when they give no batch, before it returns+# empty. Without this, each window of teams with nothing open costs the consumer one+# poll interval. The call also stops after one turn over all teams.+CLAIM_MAX_EMPTY_WINDOWS = 20++_MAX_TEAM_ID = 2**63 - 1+# Quiet time (no batch inserts or status writes) before lock takeover treats a run as# abandoned. Must exceed worst-case loader backlog latency — an unclaimed backlog is still live.TAKEOVER_STALE_THRESHOLD_SECONDS = 6 * 60 * 60@@ -358,6 +383,23 @@ FAIL_RUN_SCOPED_SQL = _bulk_fail_dual_write_sql()+def _claim_candidate_predicate_sql(sync_type_scope: str = "") -> str:+ """WHERE body that makes batch ``b`` a claim candidate. See :func:`_state_claim_candidates_sql`."""+ return f"""+ b.created_at > now() - interval '{CLAIM_ELIGIBILITY_INTERVAL}'+ {sync_type_scope}+ AND (+ b.latest_state = 'pending'+ OR (+ b.latest_state = 'waiting_retry'+ AND b.state_changed_at <= now() - make_interval(+ secs => %(backoff)s * GREATEST(b.latest_attempt, 1)+ )+ )+ )+ """++def _state_claim_candidates_sql(sync_type_scope: str = "") -> str:"""Claimable batches read from the denormalized state columns, before any gate.@@ -383,26 +425,15 @@ def _state_claim_candidates_sql(sync_type_scope: str = "") -> str:return f"""SELECT b.id, b.created_at, b.batch_index, b.team_id, b.schema_id, b.run_uuidFROM {BATCH_TABLE} b- WHERE- b.created_at > now() - interval '{CLAIM_ELIGIBILITY_INTERVAL}'- {sync_type_scope}- AND (- b.latest_state = 'pending'- OR (- b.latest_state = 'waiting_retry'- AND b.state_changed_at <= now() - make_interval(- secs => %(backoff)s * GREATEST(b.latest_attempt, 1)- )- )- )+ WHERE {_claim_candidate_predicate_sql(sync_type_scope)}"""def _claim_window_sql(sync_type_scope: str = "") -> str:"""CTEs that end in ``narrow``: the gated, fairness-ranked ``(id, created_at)`` claim window.- The gates are evaluated once per group and once per run, never once per- candidate batch. A per-batch correlated probe is only cheap while the+ The gates are evaluated once per group and once per scanned run, never once+ per candidate batch. A per-batch correlated probe is only cheap while theplanner answers it from the partial indexes. On a hot daily partitionthose indexes churn and bloat, and after an analyze the planner can pick``sb_run_uuid_idx``, ``sb_run_uuid_bi_idx`` or ``sb_team_schema_idx``@@ -412,84 +443,204 @@ def _claim_window_sql(sync_type_scope: str = "") -> str:Each gate keeps the semantics of the per-batch form:- - ``busy_groups``: a group with an 'executing' batch is not claimable. It- is one scan of the executing set, which only ``sb_schema_busy_idx``- answers cheaply.- - ``open_groups``: the busy gate, plus no live lease of another owner.- - ``open_runs``: one ``sb_run_gate_idx`` probe per candidate run. A run- with a 'failed' batch is not claimable. ``first_blocked_index`` is the- lowest batch_index that is 'executing' or 'waiting_retry' inside its- backoff. "No such batch earlier than mine" is the same as "my- batch_index <= that minimum". The probe is an aggregate in a LATERAL,- so the planner cannot flatten it into an anti-join whose hash side is- every failed batch in the pruning window.+ - ``closed_groups``: a group with an 'executing' batch is not claimable,+ and neither is a group with a live lease of another owner. Only the+ groups of the window's teams are read, so the set stays small however+ many groups the fleet holds, and the per-team filter is an array+ comparison that does not depend on a hashed sub-plan fitting in+ ``work_mem``.+ - ``gates``: one ``sb_run_gate_idx`` probe per scanned run. A run with a+ 'failed' batch is not claimable. ``first_blocked_index`` is the lowest+ batch_index that is 'executing' or 'waiting_retry' inside its backoff.+ "No such batch earlier than mine" is the same as "my batch_index <=+ that minimum". The probe is an aggregate in a LATERAL, so the planner+ cannot flatten it into an anti-join whose hash side is every failed+ batch in the pruning window.The fairness ranking then runs over the gated rows only, which is the setthe per-batch form ranked. Per team, oldest first; round-robin acrossteams; the LIMIT applies last.++ The candidates are a bounded window, so the cost of a claim does not grow+ with the backlog:++ - ``window_teams``: a loose index scan over ``sb_claimable_idx``. Each step+ seeks the next team_id that holds a candidate, so a step costs one index+ descent per partition, whatever the depth of the team. The walk starts+ after ``%(team_cursor)s``, wraps at the highest team, and stops after+ ``CLAIM_WINDOW_TEAMS`` teams or one full turn. The row with+ ``is_team = false`` only marks the wrap.+ - ``team_scan``: per window team, rounds of ``scanned`` then ``gates``.+ ``scanned`` reads the oldest candidates up to ``CLAIM_WINDOW_TEAM_DEPTH``+ (or the LIMIT, if larger). The closed-group filter is inside the scan,+ so a deep backlog behind an executing batch cannot fill the depth and+ hide the other groups of the team. The run gates cannot be a filter of+ the scan without a probe per batch, so they work in rounds: a round+ that finds held batches records their runs in ``gated_runs`` and+ ``gated_after`` (-1 for a failed run, else the blocked index), and the+ next round reads past exactly those batches. A team is done when a+ round finds nothing new to skip or has enough open batches for the+ LIMIT, or after ``CLAIM_WINDOW_GATE_ROUNDS`` rounds. Only the open+ batches of the last round leave the scan, so the skip list never+ decides what is claimable; the gates of that round do.++ When the queue holds no more than ``CLAIM_WINDOW_TEAMS`` teams and no team+ exceeds the depth, the window is the whole claimable set and the result is+ the same as an unbounded scan. Past those bounds:++ - A claim ranks the teams of its window only. A team outside the window+ waits for the rotation, even if its batch is older.+ - A team's open candidates past the depth stay unseen until earlier ones+ leave the queue.+ - A team whose held candidates run deeper than rounds x depth gives+ nothing until a gate clears (the backoff ends, or the reconcile sweep+ drains the failed run).++ Two costs stay outside the bound. The sync-type scope is a heap filter on+ the walk, so a fleet whose scope matches few of the claimable rows reads+ past the others to find its teams. And the per-team scan stops at the depth+ only when the plan reads the index in order; a plan that sorts reads every+ candidate of the window's teams."""+ candidate = _claim_candidate_predicate_sql(sync_type_scope)return f"""- claimable AS MATERIALIZED (- {_state_claim_candidates_sql(sync_type_scope)}+ window_teams AS MATERIALIZED (+ WITH RECURSIVE walk (team_id, n, wrapped, is_team) AS (+ SELECT %(team_cursor)s::bigint, 0, false, false+ UNION ALL+ SELECT+ COALESCE(seek.team_id, -1),+ w.n + (seek.team_id IS NOT NULL)::int,+ w.wrapped OR seek.team_id IS NULL,+ seek.team_id IS NOT NULL+ FROM walk w+ CROSS JOIN LATERAL (+ SELECT (+ SELECT b.team_id+ FROM {BATCH_TABLE} b+ WHERE {candidate}+ AND b.team_id > w.team_id+ AND b.team_id <= CASE WHEN w.wrapped THEN %(team_cursor)s ELSE {_MAX_TEAM_ID} END+ ORDER BY b.team_id ASC+ LIMIT 1+ ) AS team_id+ OFFSET 0+ ) seek+ WHERE w.n < {CLAIM_WINDOW_TEAMS}+ AND (seek.team_id IS NOT NULL OR NOT w.wrapped)+ )+ SELECT walk.team_id, walk.n, walk.wrapped FROM walk WHERE walk.is_team),- busy_groups AS MATERIALIZED (- SELECT DISTINCT b_busy.team_id, b_busy.schema_id+ closed_groups AS MATERIALIZED (+ SELECT b_busy.team_id, b_busy.schema_idFROM {BATCH_TABLE} b_busyWHERE b_busy.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'AND b_busy.latest_state = 'executing'+ AND b_busy.team_id = ANY (ARRAY(SELECT t.team_id FROM window_teams t))+ UNION+ SELECT l_live.team_id, l_live.schema_id+ FROM {LEASE_TABLE} l_live+ WHERE l_live.expires_at > now()+ AND l_live.owner_token != %(owner)s+ AND l_live.team_id = ANY (ARRAY(SELECT t.team_id FROM window_teams t))),- open_groups AS MATERIALIZED (- SELECT g.team_id, g.schema_id- FROM (SELECT DISTINCT c.team_id, c.schema_id FROM claimable c) g- WHERE NOT EXISTS (- SELECT 1- FROM busy_groups x- WHERE x.team_id = g.team_id AND x.schema_id = g.schema_id- )- AND NOT EXISTS (- SELECT 1- FROM {LEASE_TABLE} l_live- WHERE l_live.team_id = g.team_id- AND l_live.schema_id = g.schema_id- AND l_live.expires_at > now()- AND l_live.owner_token != %(owner)s- )- ),- open_runs AS MATERIALIZED (- SELECT r.run_uuid, gate.first_blocked_index- FROM (- SELECT DISTINCT c.run_uuid- FROM claimable c- JOIN open_groups g ON g.team_id = c.team_id AND g.schema_id = c.schema_id- ) r- CROSS JOIN LATERAL (+ team_scan AS MATERIALIZED (+ WITH RECURSIVE scan (+ team_id, round, gated_runs, gated_after, done, ids, created_ats, batch_indexes+ ) AS (+ SELECT+ t.team_id, 0, '{{}}'::varchar[], '{{}}'::int[], false,+ '{{}}'::uuid[], '{{}}'::timestamptz[], '{{}}'::int[]+ FROM window_teams t+ UNION ALLSELECT- bool_or(b_gate.latest_state = 'failed') AS has_failed,- min(b_gate.batch_index) FILTER (- WHERE b_gate.latest_state = 'executing'- OR (- b_gate.latest_state = 'waiting_retry'- AND b_gate.state_changed_at > now() - make_interval(- secs => %(backoff)s * GREATEST(b_gate.latest_attempt, 1)- )+ s.team_id,+ s.round + 1,+ s.gated_runs || r.new_runs,+ s.gated_after || r.new_after,+ cardinality(r.new_runs) = 0 OR cardinality(r.ids) >= %(limit)s,+ r.ids,+ r.created_ats,+ r.batch_indexes+ FROM scan s+ CROSS JOIN LATERAL (+ WITH scanned AS MATERIALIZED (+ SELECT b.id, b.created_at, b.batch_index, b.run_uuid+ FROM {BATCH_TABLE} b+ WHERE {candidate}+ AND b.team_id = s.team_id+ AND b.schema_id <> ALL (ARRAY(+ SELECT g.schema_id FROM closed_groups g WHERE g.team_id = s.team_id+ ))+ AND (+ b.run_uuid <> ALL (s.gated_runs)+ OR b.batch_index <= (s.gated_after)[array_position(s.gated_runs, b.run_uuid)])- ) AS first_blocked_index- FROM {BATCH_TABLE} b_gate- WHERE b_gate.run_uuid = r.run_uuid- AND b_gate.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND b_gate.latest_state IN ('executing', 'waiting_retry', 'failed')- ) gate- WHERE gate.has_failed IS NOT TRUE+ ORDER BY b.created_at ASC, b.batch_index ASC+ LIMIT GREATEST(%(limit)s, {CLAIM_WINDOW_TEAM_DEPTH})+ ),+ gates AS MATERIALIZED (+ SELECT sr.run_uuid, gate.has_failed, gate.first_blocked_index+ FROM (SELECT DISTINCT sc.run_uuid FROM scanned sc) sr+ CROSS JOIN LATERAL (+ SELECT+ bool_or(b_gate.latest_state = 'failed') AS has_failed,+ min(b_gate.batch_index) FILTER (+ WHERE b_gate.latest_state = 'executing'+ OR (+ b_gate.latest_state = 'waiting_retry'+ AND b_gate.state_changed_at > now() - make_interval(+ secs => %(backoff)s * GREATEST(b_gate.latest_attempt, 1)+ )+ )+ ) AS first_blocked_index+ FROM {BATCH_TABLE} b_gate+ WHERE b_gate.run_uuid = sr.run_uuid+ AND b_gate.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND b_gate.latest_state IN ('executing', 'waiting_retry', 'failed')+ ) gate+ )+ SELECT open.ids, open.created_ats, open.batch_indexes, held.new_runs, held.new_after+ FROM (+ SELECT+ COALESCE(array_agg(sc.id), '{{}}'::uuid[]) AS ids,+ COALESCE(array_agg(sc.created_at), '{{}}'::timestamptz[]) AS created_ats,+ COALESCE(array_agg(sc.batch_index), '{{}}'::int[]) AS batch_indexes+ FROM scanned sc+ JOIN gates g ON g.run_uuid = sc.run_uuid+ WHERE g.has_failed IS NOT TRUE+ AND (g.first_blocked_index IS NULL OR sc.batch_index <= g.first_blocked_index)+ ) open+ CROSS JOIN (+ SELECT+ COALESCE(array_agg(g.run_uuid), '{{}}'::varchar[]) AS new_runs,+ COALESCE(+ array_agg(CASE WHEN g.has_failed THEN -1 ELSE g.first_blocked_index END),+ '{{}}'::int[]+ ) AS new_after+ FROM gates g+ WHERE g.run_uuid <> ALL (s.gated_runs)+ AND EXISTS (+ SELECT 1+ FROM scanned sc+ WHERE sc.run_uuid = g.run_uuid+ AND (g.has_failed OR sc.batch_index > g.first_blocked_index)+ )+ ) held+ ) r+ WHERE NOT s.done AND s.round < {CLAIM_WINDOW_GATE_ROUNDS}+ )+ SELECT scan.team_id, scan.ids, scan.created_ats, scan.batch_indexes+ FROM scan+ WHERE scan.done OR scan.round = {CLAIM_WINDOW_GATE_ROUNDS}),narrow AS MATERIALIZED (SELECT c.id, c.created_at- FROM claimable c- JOIN open_groups g ON g.team_id = c.team_id AND g.schema_id = c.schema_id- JOIN open_runs r ON r.run_uuid = c.run_uuid- WHERE r.first_blocked_index IS NULL OR c.batch_index <= r.first_blocked_index+ FROM team_scan ts+ CROSS JOIN LATERAL unnest(ts.ids, ts.created_ats, ts.batch_indexes) AS c (id, created_at, batch_index)ORDER BYrow_number() OVER (- PARTITION BY c.team_id ORDER BY c.created_at ASC, c.batch_index ASC+ PARTITION BY ts.team_id ORDER BY c.created_at ASC, c.batch_index ASC) ASC,c.created_at ASC,c.batch_index ASC@@ -783,6 +934,34 @@ def _stale_executing_sql(scope_sql: str = "") -> str:"""+@dataclass(frozen=False, slots=True)+class ClaimCursor:+ """Where one consumer's next claim starts its team window.++ Mutable on purpose: each claim moves it to the last team of the window it+ read, so consecutive claims rotate through every team that holds work.++ Pods that read the same windows compete for the same groups, so the+ position is spread at random where that costs no fairness: ``None`` makes+ the next claim start at a random team, and a claim whose window held the+ whole queue leaves the cursor on a random team of it. A claim that finds+ no team with work, or that fails, leaves ``None``.+ """++ team_id: int | None = None+++@dataclass(frozen=True, slots=True)+class _ClaimedWindow:+ batches: list[PendingBatch]+ # None when no team holds a claim candidate.+ next_team_cursor: int | None+ # The window held CLAIM_WINDOW_TEAMS teams, so more teams can wait past it.+ full: bool+ # The walk passed the highest team and continued from the lowest.+ wrapped: bool++@dataclass(frozen=True, slots=True)class PendingBatch:"""A batch row fetched from the queue, ready to be processed by the consumer."""@@ -1211,6 +1390,7 @@ class BatchQueue:lease_ttl_seconds: int = LEASE_TTL_SECONDS,sync_types: list[str] | None = None,exclude_sync_types: list[str] | None = None,+ cursor: ClaimCursor | None = None,) -> list[PendingBatch]:"""Fetch unprocessed batches whose (team_id, schema_id) group lease is claimable by ``owner_token``.@@ -1230,13 +1410,18 @@ class BatchQueue:Ranking runs over narrow ``(id, created_at)`` candidates and the widerows are fetched only for the LIMIT winners (the ``candidates``- join-back, ~LIMIT primary-key probes): the fairness sort has to process- the whole claimable set, so its input must stay narrow or a backlog- turns every poll into a disk-spilling sort of full rows (see- :func:`_state_claim_candidates_sql`). The gates below run once per- group and once per run, not once per candidate batch (see+ join-back, ~LIMIT primary-key probes), so the fairness sort never+ handles full rows (see :func:`_state_claim_candidates_sql`). The+ candidates are a bounded window of teams, not the whole claimable set,+ and the run gate runs once per run, not once per candidate batch (see:func:`_claim_window_sql`).+ ``cursor`` carries the window position between the claims of one+ consumer. Without it every claim starts at the lowest team, which reads+ the whole queue only while it fits in one window. With it, a full+ window that gives no batch is not the answer: the call reads the next+ windows, up to ``CLAIM_MAX_EMPTY_WINDOWS`` or one turn over all teams.+Uses a MATERIALIZED CTE so that candidate selection (with LIMIT) isfully resolved before the lease claim runs. ``candidate_groups`` is``SELECT DISTINCT`` because ``INSERT ... ON CONFLICT DO UPDATE`` cannot@@ -1266,6 +1451,7 @@ class BatchQueue:Per-team fairness: candidates are interleaved round-robin across teams so oneteam's deep backlog cannot monopolize the ``LIMIT`` window; within a team,oldest-first order (and so per-run ``batch_index`` ordering) is preserved.+ Across teams the order is oldest first among the teams of the claim's window.Disjoint windows across pods: groups live-leased by *another* owner areexcluded from candidates entirely, not merely dropped at the claim step.@@ -1283,11 +1469,42 @@ class BatchQueue:sync_type_scope, scope_params = sync_type_scope_sql(sync_types=sync_types, exclude_sync_types=exclude_sync_types)- window_sql = _claim_window_sql(sync_type_scope)+ params = {+ "limit": limit,+ "backoff": retry_backoff_base_seconds,+ "owner": owner_token,+ "ttl": lease_ttl_seconds,+ **scope_params,+ }+ if cursor is None:+ return (await BatchQueue._claim_window(conn, sync_type_scope, {**params, "team_cursor": 0})).batches++ start = cursor.team_id if cursor.team_id is not None else await BatchQueue._random_team_cursor(conn)+ # A claim that fails or times out must not come back to the same window forever.+ cursor.team_id = None+ position = start+ wraps = 0+ for _ in range(CLAIM_MAX_EMPTY_WINDOWS):+ window = await BatchQueue._claim_window(conn, sync_type_scope, {**params, "team_cursor": position})+ if window.next_team_cursor is None:+ # No team holds work. The cursor stays unset, so the next claim picks a new random start.+ return []+ position = window.next_team_cursor+ wraps += window.wrapped+ full_turn = wraps > 1 or (wraps == 1 and position >= start)+ if window.batches or not window.full or full_turn:+ break+ cursor.team_id = position+ return window.batches++ @staticmethod+ async def _claim_window(+ conn: psycopg.AsyncConnection[Any], sync_type_scope: str, params: dict[str, Any]+ ) -> _ClaimedWindow:async with conn.cursor(row_factory=dict_row) as cur:await cur.execute(f"""- WITH {window_sql},+ WITH {_claim_window_sql(sync_type_scope)},candidates AS MATERIALIZED (SELECTb.id, b.team_id, b.schema_id, b.source_id, b.job_id,@@ -1319,22 +1536,58 @@ class BatchQueue:WHERE {LEASE_TABLE}.expires_at < now()OR {LEASE_TABLE}.owner_token = excluded.owner_tokenRETURNING team_id, schema_id+ ),+ window_info AS (+ SELECT+ count(*) >= {CLAIM_WINDOW_TEAMS} AS window_full,+ COALESCE(bool_or(t.wrapped), false) AS window_wrapped,+ (array_agg(t.team_id ORDER BY t.n DESC))[1] AS last_team_id,+ (array_agg(t.team_id ORDER BY random()))[1] AS random_team_id+ FROM window_teams t)- SELECT c.*- FROM candidates c- JOIN claimed USING (team_id, schema_id)+ SELECT+ CASE WHEN w.window_full THEN w.last_team_id ELSE w.random_team_id END AS next_team_cursor,+ w.window_full,+ w.window_wrapped,+ c.*+ FROM window_info w+ LEFT JOIN (+ candidates c+ JOIN claimed ON claimed.team_id = c.team_id AND claimed.schema_id = c.schema_id+ ) ON trueORDER BY c.created_at ASC, c.batch_index ASC""",- {- "limit": limit,- "backoff": retry_backoff_base_seconds,- "owner": owner_token,- "ttl": lease_ttl_seconds,- **scope_params,- },+ params,)rows = await cur.fetchall()- return [PendingBatch(**row) for row in rows]+ # The window row is always present; the batch columns are NULL when nothing was claimed.+ next_team_cursor, full, wrapped = None, False, False+ for row in rows:+ next_team_cursor = row.pop("next_team_cursor")+ full = row.pop("window_full")+ wrapped = row.pop("window_wrapped")+ return _ClaimedWindow(+ batches=[PendingBatch(**row) for row in rows if row["id"] is not None],+ next_team_cursor=next_team_cursor,+ full=full,+ wrapped=wrapped,+ )++ @staticmethod+ async def _random_team_cursor(conn: psycopg.AsyncConnection[Any]) -> int:+ """A uniform point between the lowest and highest team_id that hold claimable-state batches."""+ cur = await conn.execute(+ f"""+ SELECT min(b.team_id), max(b.team_id)+ FROM {BATCH_TABLE} b+ WHERE b.created_at > now() - interval '{CLAIM_ELIGIBILITY_INTERVAL}'+ AND b.latest_state IN ('pending', 'waiting_retry')+ """+ )+ row = await cur.fetchone()+ if row is None or row[0] is None:+ return 0+ return random.randint(row[0] - 1, row[1])@staticmethodasync def update_status(