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): per-org concurrency budget for the duckgres sink (#68808)

Eric Duongd0ad31ab4817
diff --git a/posthog/ducklake/models.py b/posthog/ducklake/models.py
index 32ff155605fe..7d5cec7473b2 100644
--- a/posthog/ducklake/models.py
+++ b/posthog/ducklake/models.py
@@ -47,6 +47,11 @@ class DuckgresServer(CreatedMetaFields, UpdatedMetaFields, UUIDModel):
# Region travels with the bucket: set alongside it, left NULL when no bucket is
# recorded yet (status_for()'s self-heal fills both in once the control plane reports them).
bucket_region = models.CharField(max_length=50, null=True, blank=True, default=None)
+ # Fleet-wide cap on the batch sink's concurrently processing groups for this
+ # org — each in-flight group holds at most one connection to the org's
+ # duckgres server, so this bounds the sink's connection footprint no matter
+ # how many consumer pods run. Soft cap: enforced at group-claim time.
+ sink_max_concurrency = models.IntegerField(default=4)
class Meta:
db_table = "posthog_duckgresserver"
diff --git a/posthog/migrations/1250_duckgresserver_sink_max_concurrency.py b/posthog/migrations/1250_duckgresserver_sink_max_concurrency.py
new file mode 100644
index 000000000000..0257115c0f08
--- /dev/null
+++ b/posthog/migrations/1250_duckgresserver_sink_max_concurrency.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.14 on 2026-07-09
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1249_duckgressinkschemastate_consecutive_failures_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="duckgresserver",
+ name="sink_max_concurrency",
+ field=models.IntegerField(default=4),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 062a454be4c4..ab3f9d5475fa 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1249_duckgressinkschemastate_consecutive_failures_and_more
+1250_duckgresserver_sink_max_concurrency
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py
index 22fdc6ec3e29..5cef94c921e9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py
@@ -29,7 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
sink_eligible_schema_ids as compute_eligible_schema_ids,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.enablement import (
- duckgres_sink_team_ids,
+ duckgres_sink_enablement,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.jobs_db import (
DuckgresBatchQueue,
@@ -86,6 +86,13 @@ SINK_SUPERSEDED_BATCHES_TOTAL = Gauge(
"Batches retired because a newer replace-run made their work obsolete (last sweep)",
multiprocess_mode="livemax",
)
+SINK_ORGS_AT_BUDGET = Gauge(
+ "duckgres_sink_orgs_at_budget",
+ "Orgs whose live group leases have reached their sink_max_concurrency budget. "
+ "Backlog growing while this is up (and pod utilization is low) means the fleet is "
+ "budget-limited, not pod-limited — raise the org's budget or duckgres capacity, not replicas.",
+ multiprocess_mode="livemax",
+)
class DuckgresBatchConsumerAdapter:
@@ -102,6 +109,10 @@ class DuckgresBatchConsumerAdapter:
# configured group-lease TTL).
self._lease_ttl_seconds = lease_ttl_seconds
self._team_ids: list[int] | None = None
+ # (team_id, org_id, sink_max_concurrency) rows for enabled teams —
+ # refreshed with the team set, passed into the claim so the per-org
+ # group budget is enforced fleet-wide. Empty in dev (no caps).
+ self._team_org_budgets: list[tuple[int, str, int]] = []
self._team_ids_fetched_at: float | None = None
self._last_maintenance_at = 0.0
# None = not yet computed; the fetch claims nothing until the first
@@ -124,7 +135,9 @@ class DuckgresBatchConsumerAdapter:
try:
first_resolution = self._team_ids_fetched_at is None
previous = self._team_ids
- self._team_ids = await sync_to_async(duckgres_sink_team_ids, thread_sensitive=False)()
+ enablement = await sync_to_async(duckgres_sink_enablement, thread_sensitive=False)()
+ self._team_ids = None if enablement is None else enablement.team_ids
+ self._team_org_budgets = [] if enablement is None else enablement.team_org_budgets
self._team_ids_fetched_at = now
if first_resolution or self._team_ids != previous:
# Only on the first resolution or an actual change — the refresh
@@ -133,6 +146,7 @@ class DuckgresBatchConsumerAdapter:
"duckgres_sink_enabled_teams_resolved",
first_resolution=first_resolution,
team_count=None if self._team_ids is None else len(self._team_ids),
+ org_count=len({org_id for _, org_id, _ in self._team_org_budgets}),
)
except Exception as e:
logger.exception("duckgres_sink_enablement_refresh_failed")
@@ -172,6 +186,10 @@ class DuckgresBatchConsumerAdapter:
SINK_BLOCKED_BACKLOG.set(blocked)
SINK_BLOCKED_OLDEST_AGE_SECONDS.set(blocked_age or 0.0)
SINK_FAILING_BLOCKED_BACKLOG.set(failing_blocked)
+ orgs_at_budget = await DuckgresBatchQueue.count_orgs_at_budget(
+ conn, team_org_budgets=self._team_org_budgets
+ )
+ SINK_ORGS_AT_BUDGET.set(orgs_at_budget)
except Exception as e:
logger.exception("duckgres_sink_maintenance_query_failed")
capture_exception(e)
@@ -212,6 +230,7 @@ class DuckgresBatchConsumerAdapter:
eligible_backlog=backlog,
blocked_backlog=blocked,
failing_blocked_backlog=failing_blocked,
+ orgs_at_budget=orgs_at_budget,
blocked_schema_count=None if self._blocked_schema_ids is None else len(self._blocked_schema_ids),
failing_schema_count=None if self._failing_schema_ids is None else len(self._failing_schema_ids),
eligible_schema_count=None if self._eligible_schema_ids is None else len(self._eligible_schema_ids),
@@ -256,6 +275,7 @@ class DuckgresBatchConsumerAdapter:
lease_ttl_seconds=lease_ttl_seconds,
max_groups=max_groups,
exclude_groups=exclude_groups,
+ team_org_budgets=self._team_org_budgets,
)
async def unlock(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.py
index 5d3d7f740170..7139adc85d40 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.py
@@ -13,6 +13,8 @@ uncoordinated duckgres writers.
from __future__ import annotations
+from dataclasses import dataclass
+
import structlog
import posthoganalytics
@@ -24,12 +26,27 @@ logger = structlog.get_logger(__name__)
DUCKGRES_BATCH_SINK_FLAG = "duckgres-batch-sink"
-def duckgres_sink_team_ids() -> list[int] | None:
- """Team ids the sink may process, or None for "no filter" (dev mode).
+@dataclass(frozen=True)
+class SinkEnablement:
+ """The sink's per-refresh view of who it serves and how hard it may push.
+
+ ``team_org_budgets`` carries one (team_id, org_id, sink_max_concurrency)
+ row per enabled team — the queue DB has no teams table, so the claim query
+ receives this mapping as unnest'd arrays to enforce the per-org group
+ budget fleet-wide.
+ """
+
+ team_ids: list[int]
+ team_org_budgets: list[tuple[int, str, int]]
+
+
+def duckgres_sink_enablement() -> SinkEnablement | None:
+ """Enabled teams plus their org's sink concurrency budget, or None for
+ "no filter, no budgets" (dev mode).
Runs sync (Django ORM + flag evaluation); call via sync_to_async from the
consumer. Raises on app-DB errors — the caller keeps its previous cached
- set so a transient app-DB blip doesn't blind the sink.
+ value so a transient app-DB blip doesn't blind the sink.
The flag is evaluated only-locally (no per-team network round-trip) with the
org/project group properties supplied inline, matching the data-warehouse-scene
@@ -42,14 +59,17 @@ def duckgres_sink_team_ids() -> list[int] | None:
from posthog.ducklake.models import DuckgresServer
from posthog.models import Team
- org_ids = list(
- DuckgresServer.objects.filter(organization_id__isnull=False).values_list("organization_id", flat=True)
+ org_budgets = dict(
+ DuckgresServer.objects.filter(organization_id__isnull=False).values_list(
+ "organization_id", "sink_max_concurrency"
+ )
)
- if not org_ids:
- return []
+ if not org_budgets:
+ return SinkEnablement(team_ids=[], team_org_budgets=[])
enabled: list[int] = []
- for team_id, team_uuid, org_id in Team.objects.filter(organization_id__in=org_ids).values_list(
+ team_org_budgets: list[tuple[int, str, int]] = []
+ for team_id, team_uuid, org_id in Team.objects.filter(organization_id__in=org_budgets.keys()).values_list(
"id", "uuid", "organization_id"
):
try:
@@ -65,9 +85,16 @@ def duckgres_sink_team_ids() -> list[int] | None:
send_feature_flag_events=False,
):
enabled.append(team_id)
+ team_org_budgets.append((team_id, str(org_id), org_budgets[org_id]))
except Exception as e:
# Flag evaluation failing for one team must not blind the whole sink;
# treat as disabled (safe direction: we skip, never wrongly claim).
logger.exception("duckgres_sink_flag_evaluation_failed", team_id=team_id)
capture_exception(e)
- return enabled
+ return SinkEnablement(team_ids=enabled, team_org_budgets=team_org_budgets)
+
+
+def duckgres_sink_team_ids() -> list[int] | None:
+ """Back-compat view of duckgres_sink_enablement: just the enabled team ids."""
+ enablement = duckgres_sink_enablement()
+ return None if enablement is None else enablement.team_ids
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py
index 48721653c6cb..c6b8782a8ce9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py
@@ -189,6 +189,7 @@ class DuckgresBatchQueue:
lease_ttl_seconds: int = LEASE_TTL_SECONDS,
max_groups: int | None = None,
exclude_groups: list[tuple[int, str]] | None = None,
+ team_org_budgets: list[tuple[int, str, int]] | None = None,
) -> list[PendingBatch]:
"""Fetch Duckgres-eligible batches whose Delta load has succeeded.
@@ -227,6 +228,19 @@ class DuckgresBatchQueue:
would apply them — including replace-head batches that bypass the unprimed
block. Computed by ``sink_eligible_schema_ids``.
+ ``team_org_budgets`` — (team_id, org_id, budget) rows — enforces a
+ fleet-wide per-org cap on concurrently leased groups. Each in-flight
+ group holds at most one connection to the org's duckgres server, so the
+ cap bounds the sink's connection footprint independently of pod count.
+ Live leases (any owner) count as usage; eligible groups are ranked
+ oldest-first per org and only the org's remaining slots are claimable,
+ so a saturated org's groups are SKIPPED — they never head-of-line block
+ the pod from filling ``max_groups`` with other orgs' work. Soft cap:
+ overlapping claims from concurrent polls can transiently overshoot by a
+ group or two for one poll window; the org's duckgres ``max_connections``
+ is the hard backstop. Teams without a mapping row are uncapped
+ (None = no caps at all, for tests/dev).
+
Intra-run head-of-line: LIVE batches stay strictly ordered (any
unapplied lower batch_index blocks). Backfill CHUNKS relax this so a
whole run drains in one claim: a pending predecessor blocks a chunk
@@ -247,6 +261,26 @@ class DuckgresBatchQueue:
await cur.execute(
f"""
WITH {ELIGIBILITY_CTES}
+ team_org AS (
+ -- Enabled-team -> (org, budget) mapping, passed in because the
+ -- queue DB has no teams table. Empty when no caps apply.
+ SELECT team_id, org_id, budget
+ FROM unnest(
+ %(budget_team_ids)s::bigint[],
+ %(budget_org_ids)s::varchar[],
+ %(budget_values)s::int[]
+ ) AS t(team_id, org_id, budget)
+ ),
+ org_usage AS (
+ -- Fleet-wide in-flight groups per org: every live lease, any
+ -- owner (including this pod's own in-flight groups, which the
+ -- candidates CTE already excludes from re-claiming).
+ SELECT m.org_id, count(*) AS live
+ FROM {DUCKGRES_LEASE_TABLE} l
+ JOIN team_org m ON m.team_id = l.team_id
+ WHERE l.expires_at > now()
+ GROUP BY m.org_id
+ ),
candidates AS MATERIALIZED (
SELECT
{pending_batch_select_columns("dgs")}
@@ -276,6 +310,20 @@ class DuckgresBatchQueue:
AND bl.expires_at > now()
AND bl.owner_token <> %(owner)s
)
+ -- Fully budget-saturated orgs are unclaimable too, and for
+ -- the same reason must be filtered BEFORE the LIMIT: a
+ -- saturated org's deep backlog (e.g. a pending backfill)
+ -- would otherwise fill the window with rows the group
+ -- filter then drops, and the pod claims nothing while
+ -- other orgs have work. Partially available orgs keep
+ -- their rows; candidate_groups ranks those per org below.
+ AND NOT EXISTS (
+ SELECT 1
+ FROM team_org m
+ JOIN org_usage u ON u.org_id = m.org_id
+ WHERE m.team_id = b.team_id
+ AND u.live >= m.budget
+ )
AND NOT {BLOCKED_LIVE_BATCH_CONDITION}
AND ds.job_state = 'succeeded'
AND (
@@ -377,11 +425,33 @@ class DuckgresBatchQueue:
candidate_groups AS (
-- Cap leased groups to the consumer's free slots, oldest work
-- first (NULL = no cap): a leased-but-unstarted group would be
- -- renewed by every poll and stay dark to other pods.
- SELECT c.team_id, c.schema_id
- FROM candidates c
- GROUP BY c.team_id, c.schema_id
- ORDER BY min(c.created_at) ASC, c.team_id ASC, c.schema_id ASC
+ -- renewed by every poll and stay dark to other pods. Groups of
+ -- an org with only PARTIAL budget left are ranked here and the
+ -- overflow skipped (fully saturated orgs never reached the
+ -- candidates window at all), so other orgs still fill max_groups.
+ SELECT g.team_id, g.schema_id
+ FROM (
+ SELECT
+ grp.team_id,
+ grp.schema_id,
+ grp.oldest,
+ CASE WHEN m.org_id IS NULL THEN NULL
+ ELSE row_number() OVER (
+ PARTITION BY m.org_id
+ ORDER BY grp.oldest ASC, grp.team_id ASC, grp.schema_id ASC
+ )
+ END AS org_rank,
+ m.budget - COALESCE(u.live, 0) AS org_remaining
+ FROM (
+ SELECT c.team_id, c.schema_id, min(c.created_at) AS oldest
+ FROM candidates c
+ GROUP BY c.team_id, c.schema_id
+ ) grp
+ LEFT JOIN team_org m ON m.team_id = grp.team_id
+ LEFT JOIN org_usage u ON u.org_id = m.org_id
+ ) g
+ WHERE g.org_rank IS NULL OR g.org_rank <= GREATEST(g.org_remaining, 0)
+ ORDER BY g.oldest ASC, g.team_id ASC, g.schema_id ASC
LIMIT COALESCE(%(max_groups)s, 2147483647)
),
claimed AS (
@@ -416,11 +486,50 @@ class DuckgresBatchQueue:
"max_groups": max_groups,
"exclude_team_ids": [team_id for team_id, _ in exclude_groups] if exclude_groups else None,
"exclude_schema_ids": [schema_id for _, schema_id in exclude_groups] if exclude_groups else None,
+ "budget_team_ids": [team_id for team_id, _, _ in team_org_budgets] if team_org_budgets else [],
+ "budget_org_ids": [org_id for _, org_id, _ in team_org_budgets] if team_org_budgets else [],
+ "budget_values": [budget for _, _, budget in team_org_budgets] if team_org_budgets else [],
},
)
rows = await cur.fetchall()
return [PendingBatch(**row) for row in rows]
+ @staticmethod
+ async def count_orgs_at_budget(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ team_org_budgets: list[tuple[int, str, int]],
+ ) -> int:
+ """How many orgs currently have live group leases at (or over) their sink
+ budget — the dashboard signal that backlog is budget-limited, not
+ pod-limited (raise the org's budget or duckgres capacity, not replicas)."""
+ if not team_org_budgets:
+ return 0
+ row = await conn.execute(
+ f"""
+ SELECT count(*)
+ FROM (
+ SELECT m.org_id
+ FROM {DUCKGRES_LEASE_TABLE} l
+ JOIN unnest(
+ %(budget_team_ids)s::bigint[],
+ %(budget_org_ids)s::varchar[],
+ %(budget_values)s::int[]
+ ) AS m(team_id, org_id, budget) ON m.team_id = l.team_id
+ WHERE l.expires_at > now()
+ GROUP BY m.org_id
+ HAVING count(*) >= max(m.budget)
+ ) saturated
+ """,
+ {
+ "budget_team_ids": [team_id for team_id, _, _ in team_org_budgets],
+ "budget_org_ids": [org_id for _, org_id, _ in team_org_budgets],
+ "budget_values": [budget for _, _, budget in team_org_budgets],
+ },
+ )
+ result = await row.fetchone()
+ return int(result[0]) if result else 0
+
@staticmethod
async def supersede_replaced_runs(
conn: psycopg.AsyncConnection[Any],
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_enablement.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_enablement.py
index 2d1a8e0e1238..bc10ac6414a0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_enablement.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_enablement.py
@@ -52,3 +52,27 @@ def test_duckgres_sink_skips_team_when_flag_unresolved_locally(
mock_feature_enabled.return_value = None
assert duckgres_sink_team_ids() == []
+
+
[email protected](enablement, "is_dev_mode", return_value=False)
[email protected](enablement.posthoganalytics, "feature_enabled")
+def test_duckgres_sink_enablement_carries_org_budgets(mock_feature_enabled: MagicMock, _mock_dev: MagicMock) -> None:
+ """The per-org sink_max_concurrency must ride along with each enabled team,
+ or the claim query silently applies no cap (empty mapping = uncapped)."""
+ org_a = Organization.objects.create(name="A")
+ org_b = Organization.objects.create(name="B")
+ team_a = Team.objects.create(organization=org_a)
+ team_b = Team.objects.create(organization=org_b)
+ DuckgresServer.objects.create(organization=org_a, host="h", username="root", password="x")
+ DuckgresServer.objects.create(organization=org_b, host="h", username="root", password="x", sink_max_concurrency=7)
+ mock_feature_enabled.return_value = True
+
+ result = enablement.duckgres_sink_enablement()
+
+ assert result is not None
+ assert sorted(result.team_ids) == sorted([team_a.id, team_b.id])
+ assert set(result.team_org_budgets) == {
+ (team_a.id, str(org_a.id), 4), # model default
+ (team_b.id, str(org_b.id), 7),
+ }
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py
index 35244e269a0e..5b0997efdf6e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py
@@ -977,3 +977,126 @@ class TestDuckgresGroupLease:
await conn.execute(f"UPDATE {DUCKGRES_LEASE_TABLE} SET expires_at = now() - interval '1 second'")
stale = await DuckgresBatchQueue.get_stale_executing(conn, grace_seconds=0)
assert [str(b.id) for b in stale] == [batch_id]
+
+
[email protected]_db(transaction=True)
+class TestOrgConcurrencyBudget:
+ # (team_id, org_id, budget) rows: teams 1 and 2 belong to org-a, team 3 to org-b.
+ TWO_ORGS = [(1, "org-a", 2), (2, "org-a", 2), (3, "org-b", 4)]
+
+ async def _eligible_group(self, conn, *, team_id: int, schema_id: str) -> str:
+ batch_id = await _insert_batch(conn, team_id=team_id, schema_id=schema_id, run_uuid=f"run-{schema_id}")
+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)
+ return batch_id
+
+ @pytest.mark.asyncio
+ async def test_budget_caps_groups_within_one_fetch(self, conn):
+ # A single poll must not lease an org's whole schema backlog at once —
+ # each leased group is a potential connection to the org's duckgres.
+ await self._eligible_group(conn, team_id=1, schema_id="s1")
+ await self._eligible_group(conn, team_id=1, schema_id="s2")
+ await self._eligible_group(conn, team_id=2, schema_id="s3")
+
+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(
+ conn, owner_token="owner-a", team_org_budgets=self.TWO_ORGS
+ )
+
+ # Oldest two groups win org-a's budget of 2; the third is left unleased.
+ assert {(b.team_id, b.schema_id) for b in batches} == {(1, "s1"), (1, "s2")}
+
+ @pytest.mark.asyncio
+ async def test_other_pods_live_leases_count_toward_budget_until_expiry(self, conn):
+ await self._eligible_group(conn, team_id=1, schema_id="s1")
+ claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(
+ conn, owner_token="other-pod", team_org_budgets=self.TWO_ORGS
+ )
+ assert len(claimed) == 1
+
+ await self._eligible_group(conn, team_id=1, schema_id="s2")
+ await self._eligible_group(conn, team_id=2, schema_id="s3")
+
+ # other-pod's live lease occupies 1 of org-a's 2 slots fleet-wide.
+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(
+ conn, owner_token="owner-a", team_org_budgets=self.TWO_ORGS
+ )
+ assert {(b.team_id, b.schema_id) for b in batches} == {(1, "s2")}
+
+ # Expired leases return their slots: the two OLDEST org-a groups claim
+ # (s1's expired lease is reclaimable, s2 re-claims), and s3 - also
+ # org-a, via team 2 - is still budget-skipped as the third-ranked group.
+ await conn.execute(f"UPDATE {DUCKGRES_LEASE_TABLE} SET expires_at = now() - interval '1 second'")
+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(
+ conn, owner_token="owner-a", team_org_budgets=self.TWO_ORGS
+ )
+ assert {(b.team_id, b.schema_id) for b in batches} == {(1, "s1"), (1, "s2")}
+
+ @pytest.mark.asyncio
+ async def test_saturated_org_does_not_block_other_orgs_groups(self, conn):
+ # Work-conservation: a capped org's OLDER work must be skipped, not
+ # deferred, or it head-of-line blocks the pod's max_groups budget.
+ one_slot = [(1, "org-a", 1), (3, "org-b", 4)]
+ await self._eligible_group(conn, team_id=1, schema_id="s1")
+ claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(
+ conn, owner_token="other-pod", team_org_budgets=one_slot
+ )
+ assert len(claimed) == 1 # org-a saturated
+
+ await self._eligible_group(conn, team_id=1, schema_id="s2") # older than org-b's work
+ await self._eligible_group(conn, team_id=3, schema_id="s3")
+
+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(
+ conn, owner_token="owner-a", max_groups=1, team_org_budgets=one_slot
+ )
+
+ assert {(b.team_id, b.schema_id) for b in batches} == {(3, "s3")}
+
+ @pytest.mark.asyncio
+ async def test_saturated_orgs_deep_backlog_cannot_fill_the_candidate_window(self, conn):
+ # The budget filter must apply BEFORE the candidate LIMIT, like the
+ # other-owner lease exclusion above it: a fully saturated org's deep
+ # backlog would otherwise fill the window with rows the group filter
+ # then drops, and the pod claims NOTHING while other orgs have work.
+ one_slot = [(1, "org-a", 1), (3, "org-b", 4)]
+ await self._eligible_group(conn, team_id=1, schema_id="s0")
+ claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(
+ conn, owner_token="other-pod", team_org_budgets=one_slot
+ )
+ assert len(claimed) == 1 # org-a saturated
+
+ for i in range(3): # org-a backlog, all older than org-b's work
+ await self._eligible_group(conn, team_id=1, schema_id=f"s{i + 1}")
+ await self._eligible_group(conn, team_id=3, schema_id="sb")
+
+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(
+ conn, owner_token="owner-a", limit=3, team_org_budgets=one_slot
+ )
+
+ assert {(b.team_id, b.schema_id) for b in batches} == {(3, "sb")}
+
+ @pytest.mark.asyncio
+ async def test_unmapped_team_is_uncapped(self, conn):
+ # The mapping caps; it must never act as an eligibility filter —
+ # team_ids/eligible_schema_ids own that. A team missing from the
+ # mapping (dev, or a mid-refresh race) claims freely.
+ await self._eligible_group(conn, team_id=1, schema_id="s1")
+ await self._eligible_group(conn, team_id=1, schema_id="s2")
+
+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(
+ conn, owner_token="owner-a", team_org_budgets=[(99, "org-x", 1)]
+ )
+
+ assert {(b.team_id, b.schema_id) for b in batches} == {(1, "s1"), (1, "s2")}
+
+ @pytest.mark.asyncio
+ async def test_count_orgs_at_budget(self, conn):
+ one_each = [(1, "org-a", 1), (3, "org-b", 2)]
+ await self._eligible_group(conn, team_id=1, schema_id="s1")
+ await self._eligible_group(conn, team_id=3, schema_id="s2")
+ claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(
+ conn, owner_token="other-pod", team_org_budgets=one_each
+ )
+ assert len(claimed) == 2
+
+ # org-a: 1 live lease of budget 1 -> saturated; org-b: 1 of 2 -> not.
+ assert await DuckgresBatchQueue.count_orgs_at_budget(conn, team_org_budgets=one_each) == 1
+ assert await DuckgresBatchQueue.count_orgs_at_budget(conn, team_org_budgets=[]) == 0