Repository navigation
fix(relay): check the rehome dispatch budget before planning the candidate join - #21517
Conversation
…idate join `selectIdleRegionalRehomeCandidates` read the enable control and the fleet safety snapshot, then ran the twenty-table candidate join, then handed every row to the worker, which POSTed each one to its source cell. Only there — in `commitIdleRegionalRehome`, three statements into a write transaction that takes `FOR UPDATE` on two global single-row tables — was the durable dispatch budget consulted. The budget is ten moves a minute (`next_dispatch_at = now + 6s`), and five directors poll every six seconds, so most of that work was spent to be told the budget was closed. A five-minute `paused_until` made every poll in the window do it. The gate is a single-row primary-key read, so it goes in front. An absent row means the budget has never been spent and opens the gate, matching the INSERT ... ON CONFLICT DO NOTHING the commit path already relies on.
|
Findings for the second defect from the same production hour, recorded here because it produced no code change. Symptom. 8 of 245 rehome attempts (3.3%, against 1 of 139 lifetime before) were rolled back to their source by The deadline is 15 minutes and is not rehome-specific. Registration requires a full desktop reconnect. The only production writer that moves The deadline is not structurally unmeetable for idle hosts. I expected the desktop's reconnect to be demand-gated; it is not. What can still exceed 15 minutes, in order of likelihood:
Rate/duplication is not a factor. Verdict: no fix proposed. The rollback is the correct outcome (host returns to a live source, the 7-day host cooldown prevents thrash), and 3.3% is consistent with the tail of a desktop reconnect distribution for a population selected for being idle. Changing the deadline in either direction needs the per-attempt log correlation. Not established. I could not run |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review. 📝 WalkthroughWalkthrough
Priority: ⬇️ Low Merge Risk: ⚪ Minimal · up to The change prevents unnecessary rehome planning while preserving candidate behavior when the budget reopens, with no concrete merge-blocking risk identified. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Description checkExplanation The description is detailed and covers the change, rationale, testing, compatibility, and performance impact. However, the required Linked Issue section is incomplete because it contains only
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the initial revision of #21517 and independently re-ran the relay suite; the change adds a durable dispatch-budget gate at the top of the idle regional rehome poll.
- Early dispatch-budget gate —
selectIdleRegionalRehomeCandidatesreadsrelay_region_rehome_worker_state('global')right after the enable check and returns no candidates whilepaused_untilornext_dispatch_atis in the future, skipping the fleet-safety read, the connection-headroom query, the candidate join, and up to 100 source-cell POSTs. - Absent-row contract — a missing worker-state row opens the gate, matching
commitIdleRegionalRehome'sINSERT ... ON CONFLICT DO NOTHINGfollowed by the same two-field check. - Tests — three new cases pin the closed-budget short-circuit at exactly two queries across three ticks, the absent-row open contract, and that the candidate page offset is untouched across a skipped poll.
The gate uses the same two fields and the same > comparison as commitIdleRegionalRehome, so every skipped dispatch is one the commit path would have deferred; I traced all writers of both fields and found no path that leaves them in the future while control is enabled. I also verified the new tests can fail: neutering the gate condition makes both it.each cases fail, and the full relay suite passes (68 files / 721 tests, matching the PR body).
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…Postgres The two gate cases zeroed both `next_dispatch_at` and `paused_until` and then set the one under test, which names that column twice in a single `SET`. SQLite accepts it; Postgres raises "multiple assignments to same column", so both cases failed whenever `ORCA_IDLE_REHOME_POSTGRES_URL` pointed the suite at a real server -- exactly the backend the gate has to hold on. Setup already leaves both fields at 0, so naming the other one bought nothing.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Re-reviewed the delta since the prior pullfrog review — one new commit, 65db3b8, a test-only fix so the new closed-budget case runs on real Postgres.
- Closed-budget test made Postgres-valid — the first
UPDATEin theit.eachcase now assigns only${column}instead ofSET next_dispatch_at = 0, paused_until = 0, ${column} = ?. The old form namednext_dispatch_at/paused_untiltwice; Postgres rejects that with42601 multiple assignments to same column, while SQLite tolerated it silently. Setup already leaves both fields at0, so the dropped reset was redundant and the assertion intent is unchanged.
I verified this on both backends: on SQLite the file passes (16 passed / 1 skipped), and on a local PostgreSQL 16 (ORCA_IDLE_REHOME_POSTGRES_URL) all 17 pass. Restoring the old SQL makes both it.each cases fail on Postgres with the expected 42601, so the fix is necessary rather than cosmetic and the tests are not theatre.
ℹ️ The Postgres path for this test file is not exercised in CI
65db3b8 only manifests on Postgres, yet CI never runs these cases against Postgres: idle-regional-rehome-store.test.ts opts in via ORCA_IDLE_REHOME_POSTGRES_URL, which no workflow sets, and vitest.config.ts routes only files referencing ORCA_RELAY_TEST_POSTGRES_URL into the serialized relay-postgres project. Not blocking — the product logic is covered on SQLite — but a regression of this exact shape would again reach main unnoticed.
Technical details
# Idle-rehome tests never run on Postgres in CI
## Affected sites
- `.github/workflows/cloud-verify.yml:94` — sets `ORCA_RELAY_TEST_POSTGRES_URL` but not `ORCA_IDLE_REHOME_POSTGRES_URL`.
- `cloud/apps/relay/vitest.config.ts:12-19` — the `relay-postgres` project is selected by `ORCA_RELAY_TEST_POSTGRES_URL` alone.
- `cloud/apps/relay/src/idle-regional-rehome-test-database.ts:6` — falls back to SQLite when `ORCA_IDLE_REHOME_POSTGRES_URL` is unset.
## Required outcome
- Decide whether the idle-rehome store suite should also be validated against Postgres in CI, or document that its Postgres path is developer-only.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

ELI5
Relay can move an idle desktop's connection to a relay server in a closer region. A background job on each of the five relay "director" servers wakes every six seconds and asks the database "who should move next?" — a very large question involving twenty tables.
The catch: the whole system is only allowed to move ten desktops a minute, and that allowance is recorded in the database. Until now nobody looked at the allowance until after asking the big question and after phoning up to a hundred relay servers about the answers. So most of the time the job did all of that work, only to be told at the last step "not yet, you've used your allowance".
This PR moves the allowance check to the front. One tiny lookup, and if the allowance is spent the job goes back to sleep instead of doing the expensive part.
What Changed
RelayAssignmentStore.selectIdleRegionalRehomeCandidatesnow readsrelay_region_rehome_worker_state(a single-row primary-key lookup onworker_id = 'global') right after the enable-control check, and returns nocandidates while
paused_untilornext_dispatch_atis in the future.An absent row opens the gate. That is deliberate and matches the existing
contract:
commitIdleRegionalRehomecreates the row withINSERT ... ON CONFLICT (worker_id) DO NOTHING, so "no row" means the budgethas never been spent, not "closed".
Before, per poll that found candidates while the budget was closed:
SELECT * FROM relay_cell_runtime+SELECT * FROM relay_cell_rehome_safetyrelay_region_rehome_controlxrelay_region_decisionsx
relay_assignmentsxrelay_cells(twice) xrelay_cell_regions(twice)x
relay_cell_admission(twice) xrelay_cell_runtime(twice) xrelay_cell_capabilities(twice) xrelay_control_capabilitiesxrelay_assignment_activity_leases, plus a correlated capacity aggregate per(host, target-cell) pair, two
NOT EXISTSanti-joins, and a sort forLIMIT 100 OFFSET ntakes
FOR UPDATEonrelay_region_rehome_control('global')and onrelay_region_rehome_worker_state('global')before discovering the budget isclosed and returning
deferredAfter, the same poll costs two single-row reads and stops.
No dispatch changes outcome: every one this skips is one
commitIdleRegionalRehomealready refuses at the same two fields. The candidatepage offset is untouched by a skipped poll, so pagination resumes exactly where
it was.
One side effect on pacing, by design. The budget is now sampled once per
poll instead of once per candidate POST, so a director that finds the gate shut
sits out the rest of its tick even if the gate opens a moment later. The gate
reopening is then picked up by whichever director polls next, which with five
directors on a 6 s jittered timer costs on average about a fifth of a tick.
Modelled (not measured): an effective ~8.6 moves/min against a configured 10.
This is self-correcting —
rate_per_minuteon the control row is the knob, andraising it restores the intended throughput. The old behaviour bought that last
1.4 moves/min by making every gated poll plan the join and POST its whole page.
Why
During the first production hour of regional rehome (2026-09-18 18:16-19:16Z),
orca_relay_regional_rehome_poll_failedwith "canceling statement due tostatement timeout" fired at a flat 5-6 per 10 minutes — about 1.2% of polls —
and did not vary with how many desktops actually moved. The serving pool's
statement_timeoutisPOSTGRES_STATEMENT_TIMEOUT_MS = 5_000(
cloud/apps/relay/src/database.ts), and the poll runs on that pool."Flat, regardless of throughput" is the tell. The poll's cost is set by the poll
rate and the size of the host population, not by the number of moves. Five
directors on a jittered 6s timer is 50 polls a minute chasing a 10-a-minute
budget, so at least 40 of those 50 were pure overhead, and a five-minute
paused_untilafter a spent failure budget made all 250 polls in that windowpure overhead.
Measured on PostgreSQL 17 against the real schema (
openRelayDatabaseapplyingrelayPostgresSchemaStatements()), with the statement captured fromselectIdleRegionalRehomesitself rather than retyped, 23 cells over the tworegions in
RELAY_REGIONS, 30% of hosts preferring the other region,EXPLAIN (ANALYZE, BUFFERS)afterANALYZE:Two things matter here. Planning alone is 60-105 ms every poll — the join is
re-planned 50 times a minute and never cached. And the plan is not stable: at
25k hosts it is a nested-loop cascade driven by a sequential scan of
relay_assignments; at 150k it flips to a parallel merge join with twoexternal-merge sorts spilling to disk (
Sort Method: external merge Disk: 11576kBand5152kB). An on-disk sort on a Cloud SQL instance under diskpressure is exactly the kind of thing that occasionally takes seconds while the
median stays at a few hundred milliseconds — a low, flat tail that does not
track throughput.
Why this approach
relay_region_decisions(cohort_bucket) WHERE outcome = 'conclusive' AND policy_version = 1in the harness and re-measured: theplanner does drive from it (1,250 decisions instead of 25,000), and the query
got slower — 183 ms and 172,280 buffers against 118 ms and 164,178. The
decisions scan is not the cost; the host x target-cell fanout after it is.
A new index on a table this size also cannot go into
SCHEMAwithout beingbuilt
CONCURRENTLYout of band first — see the RULE comment aboveSCHEMAin
database.ts.statement_timeoutor a separate pool. That hides the tailinstead of removing the work, and the derivation of the 5s bound (control
renewals landing inside their own 30s tick) is deliberate.
query computes every (eligible host x target cell in the preferred region)
pair, evaluates a correlated capacity aggregate per pair, sorts the lot, and
takes
LIMIT 100of an ordering that leads witha.user_id, a.relay_host_id,so a 100-row page covers only about nine distinct hosts. But the target the
query picks is authoritative: it is pinned at commit time
(
cellId === input.idleRequest.targetCellIdinstartRegionalRehomeCandidate) and baked into the UUIDv5attemptIdthatkeeps retries across directors idempotent. Changing which target a candidate
names is a change to the rehome authority model and belongs in its own PR with
its own review.
This PR removes most of the executions without changing any of them. It does not
reduce the cost of a single execution, so it should reduce the timeout rate
roughly in proportion to the polls it skips rather than eliminating it.
What is proven and what is not
Not proven: that this is the cause of the production statement timeouts. The
gcloudcredentials foronorca-cloudneeded an interactive re-login for thewhole of this investigation, so I have no production log evidence at all — I
never saw which statement was cancelled, and the 5-6-per-10-minutes figure comes
from the incident report rather than from a query I ran. What is measured is the
local scaling and plan behaviour in the table above; what is read off the source
is that the poll runs on the 5 s pool and that the budget was checked last. The
link between the two is plausible and consistent with the "flat, independent of
throughput" shape, and it is not established. Treat this as removing a large,
provably wasted load from the serving pool, and verify the timeout rate against
production logs after it deploys rather than assuming it.
An honest way to check it after deploy would be a counter that distinguishes a
gated poll from a poll that simply found no candidates; there is no such signal
today and I did not add one, because the only cheap form is a log line at tens
per minute per instance. Worth a small follow-up on the runtime-metrics event.
Residual, deliberately not fixed here
A director that reads an open gate, spends ~100 ms planning the join, and is
overtaken by another director's commit will still POST its whole page and get
deferredfor every one. The window is now bounded by one poll rather thanbeing the steady state. Two follow-ups worth considering: giving the source cell
a way to say "the global budget is closed" so the worker can stop the page
instead of walking it, and collapsing the host x target fanout.
Linked Issue
Fixes #
Visual Proof
N/A — a server-side scheduling change with no user-visible surface. The
observable effect is the rate of an internal log event.
Testing
cloud/apps/relay:pnpm test src/idle-regional-rehome-store.test.ts— 16 passed, 1 skipped.npx vitest run(full relay suite) — 68 files passed, 22 skipped; 721 testspassed, 121 skipped.
npx tsc -p tsconfig.json --noEmit— clean.Three new cases in
idle-regional-rehome-store.test.ts:next_dispatch_atand a closedpaused_untileach hold the poll toexactly two queries across three consecutive ticks, the second of which is the
worker-state read, and the join runs again once the field is moved back;
absent-means-open contract;
the gate reopens is identical to the one returned before it closed.
Negative control: with the gate condition removed and the tests unchanged, three
of the three fail (the absent-row test passes either way, as it should).
The plan measurements above came from a throwaway harness against
postgres:17in Docker that captured the statement out ofselectIdleRegionalRehomesrather than retyping it. The harness is notcommitted.
Platforms: server-side only; no macOS / Linux / Windows / SSH surface.
AI Disclosure
Internal contributor.
Review
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
read is one the commit path has always written. A director on this image and a
director on the old image can run side by side; the old one simply keeps doing
the wasted work.
make the worker do less.
would have proceeded — the extra read happens only on polls that then stop.
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)