Skip to content

fix(relay): check the rehome dispatch budget before planning the candidate join - #21517

Merged
Jinwoo-H merged 2 commits into
mainfrom
fix/relay-rehome-poll-dispatch-gate
Sep 18, 2026
Merged

Jinwoo-H merged 2 commits into
mainfrom
fix/relay-rehome-poll-dispatch-gate

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

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.selectIdleRegionalRehomeCandidates now reads
relay_region_rehome_worker_state (a single-row primary-key lookup on
worker_id = 'global') right after the enable-control check, and returns no
candidates while paused_until or next_dispatch_at is in the future.

An absent row opens the gate. That is deliberate and matches the existing
contract: commitIdleRegionalRehome creates the row with
INSERT ... ON CONFLICT (worker_id) DO NOTHING, so "no row" means the budget
has never been spent, not "closed".

Before, per poll that found candidates while the budget was closed:

  1. SELECT * FROM relay_cell_runtime + SELECT * FROM relay_cell_rehome_safety
  2. the connection-headroom query
  3. the candidate join — relay_region_rehome_control x relay_region_decisions
    x relay_assignments x relay_cells (twice) x relay_cell_regions (twice)
    x relay_cell_admission (twice) x relay_cell_runtime (twice) x
    relay_cell_capabilities (twice) x relay_control_capabilities x
    relay_assignment_activity_leases, plus a correlated capacity aggregate per
    (host, target-cell) pair, two NOT EXISTS anti-joins, and a sort for
    LIMIT 100 OFFSET n
  4. up to 100 HTTPS POSTs to source cells, each opening a write transaction that
    takes FOR UPDATE on relay_region_rehome_control('global') and on
    relay_region_rehome_worker_state('global') before discovering the budget is
    closed and returning deferred

After, the same poll costs two single-row reads and stops.

No dispatch changes outcome: every one this skips is one
commitIdleRegionalRehome already refuses at the same two fields. The candidate
page 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_minute on the control row is the knob, and
raising 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_failed with "canceling statement due to
statement 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_timeout is POSTGRES_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_until after a spent failure budget made all 250 polls in that window
pure overhead.

Measured on PostgreSQL 17 against the real schema (openRelayDatabase applying
relayPostgresSchemaStatements()), with the statement captured from
selectIdleRegionalRehomes itself rather than retyped, 23 cells over the two
regions in RELAY_REGIONS, 30% of hosts preferring the other region,
EXPLAIN (ANALYZE, BUFFERS) after ANALYZE:

hosts cohort candidate rows shared buffer accesses planning execution
25k 1% 0 - 77 ms 69 ms
25k 5% 14,347 164,178 77 ms 118 ms
25k 25% 57,391 - 79 ms 523 ms
25k 100% 68,869 - 84 ms 683 ms
150k 100% - 1,111,644 (+ temp read 3,696 / written 4,110) 88 ms 559 ms

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 two
external-merge sorts spilling to disk (Sort Method: external merge Disk: 11576kB and 5152kB). An on-disk sort on a Cloud SQL instance under disk
pressure 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

  • Not an index. I built relay_region_decisions(cohort_bucket) WHERE outcome = 'conclusive' AND policy_version = 1 in the harness and re-measured: the
    planner 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 SCHEMA without being
    built CONCURRENTLY out of band first — see the RULE comment above SCHEMA
    in database.ts.
  • Not a longer statement_timeout or a separate pool. That hides the tail
    instead of removing the work, and the derivation of the 5s bound (control
    renewals landing inside their own 30s tick) is deliberate.
  • Not rewriting the join yet. The fanout is real and worth fixing — the
    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 100 of an ordering that leads with a.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.targetCellId in
    startRegionalRehomeCandidate) and baked into the UUIDv5 attemptId that
    keeps 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
gcloud credentials for onorca-cloud needed an interactive re-login for the
whole 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
deferred for every one. The window is now bounded by one poll rather than
being 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 tests
    passed, 121 skipped.
  • npx tsc -p tsconfig.json --noEmit — clean.

Three new cases in idle-regional-rehome-store.test.ts:

  • a closed next_dispatch_at and a closed paused_until each hold the poll to
    exactly 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;
  • a deleted worker-state row still yields a candidate, pinning the
    absent-means-open contract;
  • the candidate page offset survives a skipped poll — the page returned after
    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:17 in Docker that captured the statement out of
selectIdleRegionalRehomes rather than retyping it. The harness is not
committed.

Platforms: server-side only; no macOS / Linux / Windows / SSH surface.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

AI Disclosure

Internal contributor.

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Backwards compatibility: no wire, contract, or schema change. The field
    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.
  • Remote wire: nothing a paired client and host exchange changes.
  • SSH / folder workspaces / cross-platform: not reached.
  • Security: no new input, no new authorization decision. The gate can only
    make the worker do less.
  • Performance: the point of the change. It never adds work to a poll that
    would have proceeded — the extra read happens only on polls that then stop.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

…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.
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

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 abortExpiredEvacuations with the !registered branch — the target cell never registered the migration. Five clustered 18:40-18:43Z.

The deadline is 15 minutes and is not rehome-specific. startRegionalRehomeCandidate sets expiresAt = input.now + ASSIGNMENT_LIMITS.migrationLeaseMs (cloud/apps/relay/src/assignment-store.ts:5605), and migrationLeaseMs is 15 * 60 * 1000 (cloud/packages/relay-contract/src/assignment-invariants.ts:7) — the generic migration lease, shared with operator evacuations. ABORTABLE_EXPIRED_MIGRATION (assignment-store.ts:413) makes an unregistered migration abortable the moment expires_at passes, and the cleanup sweep runs every 30 s (index.ts:65). The 18:40-18:43 cluster is exactly the 18:25-18:28 opening burst plus fifteen minutes.

Registration requires a full desktop reconnect. The only production writer that moves target_registered_at off NULL is markMigrationTargetRegistered, called from HostSessionRegistry.activateCurrent (host-session-registry.ts:1147) under config.role === 'cell' — i.e. the host must open a control WebSocket to the target cell. It is not capability-gated and not a cell heartbeat. expires_at is only extended for a migration that already has an activity lease (assignment-store.ts:2203-2280), so an unregistered host gets no extension.

The deadline is not structurally unmeetable for idle hosts. I expected the desktop's reconnect to be demand-gated; it is not. RelayOriginPool's onClose (src/main/runtime/relay/relay-origin-pool.ts:131-140) reacts to the socket close itself and immediately runs resolve -> /v1/assign -> connect-to-target, without consulting RelayDemandLedger. Typical close-to-registered is 1-5 s; worst case for one attempt is ~43 s. DRAINING is not special-cased — the close code is discarded at relay-origin-pool.ts:131 and 4503 behaves like a 1006.

What can still exceed 15 minutes, in order of likelihood:

  1. The machine sleeps or the app quits. No timer fires until wake. "Idle" correlates with "about to sleep", and the exposure window opens ~75 s before the commit (the cell's silence bound, relay-control-liveness.ts:14), so a host that slept up to 75 s before selection still looked active to the source cell.
  2. Sustained director 5xx/429. RelayDrainRetrySchedule is full jitter, base 1 s, cap 5 min (relay-drain-retry-schedule.ts:1-29), and once RelayAuthCoordinator arms its own retry the 5-minute liveness sweep stops firing (relay-auth-coordinator.ts:128), so both ladders stall together.
  3. Retry-After is a floor, capped at 5 minutes (relay-http-client.ts:20). Three consecutive maximal values reach 15 minutes in three attempts.

Rate/duplication is not a factor. attemptId is a UUIDv5 over the request, so every director derives the same id; the cell dedupes by relayHostId + attemptId (host-session-registry.ts:218-222), relay_region_rehome_attempts is UNIQUE (user_id, relay_host_id, assignment_epoch), and the selection excludes any host with an open migration. Two directors racing one host both get committed back from reconcileIdleRegionalRehome for a single migration — which is exactly the ~1.4x over-count in orca_relay_idle_rehome_committed, and it is benign.

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 gcloud logging read — the account needed interactive reauth for the whole session — so I have no per-attempt timeline for the 8, no /v1/admin/host-idle-rehome status codes or latencies, no orca_relay_idle_rehome_request_failed reasons, and no regional rehome inventory lines. If those eight correlate with director 5xx or Retry-After rather than with hosts that simply went away, the answer changes and item 2 above becomes the fix target.

@coderabbitai

coderabbitai Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 3b8c33ef-330c-45f1-8d13-37c827d915ac

📥 Commits

Reviewing files that changed from the base of the PR and between 84a4f27 and 65db3b8.

📒 Files selected for processing (1)
  • cloud/apps/relay/src/idle-regional-rehome-store.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.


📝 Walkthrough

Walkthrough

selectIdleRegionalRehomeCandidates now checks the global durable dispatch budget before fleet-safety reads and candidate selection. It returns no candidates when paused_until or next_dispatch_at is in the future. Tests cover both conditions, missing worker state, query counts, and stable pagination after the budget reopens.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 65db3

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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 `Fixes #… Add the issue number or link after Fixes #. For example: Fixes #12345``. Confirm that the linked issue matches this change.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 2…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the main change: checking the rehome dispatch budget before planning the candidate join.
Full details: Description check

Explanation

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 Fixes # without an issue number or link.

  • Fix all pre-merge checks with AI
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — selectIdleRegionalRehomeCandidates reads relay_region_rehome_worker_state('global') right after the enable check and returns no candidates while paused_until or next_dispatch_at is 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's INSERT ... ON CONFLICT DO NOTHING followed 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).

Pullfrog  | View workflow run | Using 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 UPDATE in the it.each case now assigns only ${column} instead of SET next_dispatch_at = 0, paused_until = 0, ${column} = ?. The old form named next_dispatch_at/paused_until twice; Postgres rejects that with 42601 multiple assignments to same column, while SQLite tolerated it silently. Setup already leaves both fields at 0, 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit 3467e5f into main Sep 18, 2026
26 checks passed
@Jinwoo-H
Jinwoo-H deleted the fix/relay-rehome-poll-dispatch-gate branch September 18, 2026 21:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant