Repository navigation
feat(relay): correct regional placement only when the source is idle - #20105
Conversation
2b08104 to
a8a38a6
Compare
There was a problem hiding this comment.
ℹ️ No critical issues — two non-blocking observations and a couple of nits.
Reviewed changes
This replaces the earlier live-retention rehome with an idle-gated region correction: a host measures RTT to both regions through an assignment-embedded "measurement window", the director records a per-host preferred_region decision, and a worker dispatches moves that the source cell only commits when the host session is genuinely idle.
- Idle-gated regional rehome — the director-side
claimRegionalRehomedrain loop is replaced by a candidate scan plus a cell-sideidleRehomegate that commits the move only when the source session has no connections, pending conns, or splices, fencing concurrent admission. - Region-correction measurement window — new
relay_region_decisionstable andexchangeRegionCorrection(issue-window/report) that converts host RTT measurements into a durablepreferred_region. - Capability + protocol plumbing —
idle-regional-rehome-v1host capability, anidle_regional_rehomecontrol-capability flag, andregionalRehomeProtocolbumped1 → 3with selection and commit gates. - Recovery + ops — the evacuation abort/rollback and lease-refresh sweeps are extended to cover idle rehome attempts; cohort-percent plumbing through the deploy workflow, blue-green script, and Terraform, plus new preview/outcomes admin endpoints, docs, and a large test suite.
ℹ️ Idle guarantee rests on the in-process fence, not a durable data-connection check
The "only when idle" property is enforced entirely by the single-process fence in HostSessionRegistry: idleRehome installs idleAttempts in the same synchronous block as its busy check, and every admission path (acceptClient, acceptHostData, activateControl, acceptRefresh, acceptControlCommand) funnels through beginIdleWork. The reused durable assertAssignmentActivityCounts(assignment, activityLeases, 0) does not reject active data connections — it only checks accounting consistency and that no migration is in flight. That is correct as written today, but the durable assertion is not the cross-process backstop its name implies, so any future second admission surface for the same cell would silently break the guarantee.
Technical details
# Idle gate is fence-only; durable assertion is not a data-connection check
## Affected sites
- cloud/apps/relay/src/host-session-registry.ts:235-276 — `idleRehome` busy check + `idleAttempts.set` in one synchronous block; `beginIdleWork` fences all admission.
- cloud/apps/relay/src/assignment-store.ts:5395 — `assertAssignmentActivityCounts(assignment, activityLeases, 0)`.
- cloud/apps/relay/src/assignment-store.ts:8265-8279 — the assertion only compares `ACTIVITY_COLUMN` counters to lease counts and rejects `migration !== 0`; a live splice/pending confirmation/invite passes.
## Required outcome
- Idle correctness is preserved (it is, via the fence). No code change is strictly required.
- Make the reliance on the in-process fence explicit, or add a genuine durable idle check, so a future contributor does not treat `assertAssignmentActivityCounts(..., 0)` as a connection-rejecting backstop.
## Open questions for the human (optional)
- Is the fence intended to be the sole idleness guard, or should a durable zero-connection check be added for defense in depth?ℹ️ Protocol-3 bump degrades safely but logs per-heartbeat during a mixed-version window
In a rolling deploy, a new cell (reporting regionalRehomeProtocol: 3) behind an old director (schema still capped at 1) gets a 400 on /v1/admin/cell-rehome-status, which the cell reduces to a console.warn every heartbeat interval. Liveness is unaffected because the separate /v1/admin/cell-heartbeat call still succeeds. Old cells are cleanly excluded at selection and commit (the >= 3 gates plus the missing idle_regional_rehome = 1 flag), so nothing is ever dispatched to a protocol-1 cell. Safe, but the per-interval warn could be noisy during the transition.
Technical details
# Mixed-version behavior of the protocol 1->3 bump
## Affected sites
- cloud/apps/relay/src/cell-heartbeat-client.ts:96-103 — throws on non-404 rehome-status failure.
- cloud/apps/relay/src/app.ts:1476 — `CellRegionalRehomeStatusSchema` widened to `max(3)`.
- cloud/apps/relay/src/idle-regional-rehome-selection.ts:68 — `>= 3` selection gate.
- cloud/apps/relay/src/assignment-store.ts:5464,5531 — commit re-gates source/target protocol.
## Required outcome
- No data-plane impact in either direction (verified). Nothing blocks merge.
## Open questions for the human (optional)
- Is director-first deploy ordering required to avoid the transient `console.warn` spam, and is that ordering captured anywhere?ℹ️ Nitpicks
relay_region_decisions.last_considered_at(cloud/apps/relay/src/database.ts:206) is added, migrated, and even asserted in a test, but is never read or written anywhere in this PR — a dead column.source_generationis written via a follow-upUPDATE ... SET source_generation = ? WHERE attempt_id = ?(cloud/apps/relay/src/assignment-store.ts:5707) immediately after theINSERTintorelay_region_rehome_attempts; the column could be carried in the INSERT itself.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
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 (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review. 📝 WalkthroughWalkthroughThe change adds region-correction wire contracts and durable decision state. It replaces the regional rehome claim path with idle candidate selection, commit, and reconciliation flows. Host sessions now fence concurrent cutovers and validate authority, generations, and cell incarnations. New admin endpoints expose idle rehome and eligibility preview operations. Deployment workflows, Terraform, telemetry, protocol versions, migrations, fixtures, and tests are updated. Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to Regional correction can make unsafe moves when fleet safety is omitted and may leave rehome enabled after a failed rollback. Correct these behaviors and the rollout prerequisite before enabling the feature. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the implementation and validation, but it does not follow the required template. It omits the required headings, linked issue, visual-proof statement, testing checklist, AI disclosure, review sections, boundary checklist, notes, and final checklist. Resolution Rewrite the description using the repository template. Add all required sections, provide a linked issue after "Fixes #", state "N/A" with a reason for visual proof if applicable, complete the testing and checklist items, and document review, compatibility, security, and performance considerations.
✨ Finishing Touches 💡 1📝 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.
Actionable comments posted: 5
🧹 Nitpick comments (3)
cloud/apps/relay/src/assignment-store.ts (2)
6436-6436: 🩺 Stability & Availability | 🔵 Trivial | ⚖️ Poor tradeoffIsolate per-candidate invariant failures in
abortExpiredEvacuations.The transaction callback throws
migration_assignment_missingandmigration_assignment_mismatch. The catch handler rethrows both errors, which terminates the sweep and leaves later candidates unprocessed. Record the failure for the current candidate and continue, as the regional rehome sweeps do.
6594-6599: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winDocument why this rollback leaves
relay_region_rehome_controlenabled.
abortExpiredEvacuationstreats an unregistered target as normal rollback. It aborts the migration and regional attempt without callingdisableRegionalRehomeControl.reapRegionalRehomeAttemptsthen makes no update becauseaborted_atis already set. Add a comment that this cleanup is not a regional-rehome safety signal.cloud/apps/relay/src/regional-rehome-store.test.ts (1)
1717-1717: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThe scan hook couples to an SQL alias and fails silently if that alias changes.
hookAfterCandidateScanfires only when a query string contains the exact textFROM relay_region_rehome_control policy. That text is an alias inside the production selection query. If the query is reworded or thepolicyalias is renamed or removed,firedstaysfalse, the hook never runs, and the raced state the caller wants to create never exists. The test then asserts an outcome that it did not actually race, so it can keep passing while covering nothing.Match on a stable anchor instead, and fail loudly when the hook did not fire. Returning a
firedflag fromhookAfterCandidateScanand asserting it in each caller would make the regression visible.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: cc81329e-f58f-45b3-af14-c918734c6db2
📒 Files selected for processing (52)
.github/workflows/cloud-deploy-relay-production-director.ymlcloud/apps/relay/src/admin-token-verifier.tscloud/apps/relay/src/app.tscloud/apps/relay/src/assignment-store.tscloud/apps/relay/src/cell-heartbeat-client.test.tscloud/apps/relay/src/cell-heartbeat-client.tscloud/apps/relay/src/cell-inventory-lock-census.test.tscloud/apps/relay/src/config.test.tscloud/apps/relay/src/config.tscloud/apps/relay/src/database.test.tscloud/apps/relay/src/database.tscloud/apps/relay/src/host-session-client-accept.test.tscloud/apps/relay/src/host-session-registry.test.tscloud/apps/relay/src/host-session-registry.tscloud/apps/relay/src/idle-regional-rehome-reconciliation.test.tscloud/apps/relay/src/idle-regional-rehome-selection.tscloud/apps/relay/src/idle-regional-rehome-store.test.tscloud/apps/relay/src/idle-regional-rehome-test-database.tscloud/apps/relay/src/idle-regional-rehome-worker.test.tscloud/apps/relay/src/index.tscloud/apps/relay/src/region-correction-outcomes.tscloud/apps/relay/src/region-correction-preview.tscloud/apps/relay/src/region-correction-restart.test.tscloud/apps/relay/src/region-correction-state.tscloud/apps/relay/src/region-correction-store.test.tscloud/apps/relay/src/regional-host-drain-app.test.tscloud/apps/relay/src/regional-rehome-postgres.test.tscloud/apps/relay/src/regional-rehome-store.test.tscloud/apps/relay/src/regional-rehome-target-selection.test.tscloud/apps/relay/src/regional-rehome-worker.test.tscloud/apps/relay/src/regional-rehome-worker.tscloud/apps/relay/src/relay-region-app.test.tscloud/apps/relay/src/relay-server.tscloud/apps/relay/src/relay-sweep-schedule.test.tscloud/apps/relay/src/test-fixtures/relay-contract-baseline/README.mdcloud/apps/relay/src/test-fixtures/relay-contract-baseline/control-messages.tscloud/apps/relay/src/test-fixtures/relay-contract-baseline/director-messages.tscloud/apps/relay/src/test-fixtures/relay-contract-baseline/relay-regions.tscloud/apps/relay/src/test-fixtures/relay-contract-baseline/wire-scalars.tscloud/apps/relay/tsconfig.build.jsoncloud/dev/scripts/deploy-relay-blue-green.mjscloud/dev/scripts/deploy-relay-blue-green.test.mjscloud/dev/scripts/read-relay-serving-regional-placement-version.mjscloud/dev/scripts/read-relay-serving-regional-placement-version.test.mjscloud/docs/orca-relay-operations.mdcloud/infra/terraform/relay.tfcloud/packages/relay-contract/src/control-messages.tscloud/packages/relay-contract/src/director-messages.tscloud/packages/relay-contract/src/idle-regional-rehome.tscloud/packages/relay-contract/src/index.tscloud/packages/relay-contract/src/region-correction.test.tscloud/packages/relay-contract/src/region-correction.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| slow.resolve() | ||
| await accepting | ||
| expect(control.send).not.toHaveBeenCalledWith(expect.stringContaining('conn-open')) | ||
| expect(capacity.bind).not.toHaveBeenCalled() |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Assert the capacity release after drain crosses activity acquisition.
When drainHost crosses the acquireActivity await, acceptClient skips capacity.bind and calls capacityReservation.release(). Assert capacity.release here so removing that cleanup exposes the connection-unit leak.
💚 Proposed assertion
expect(capacity.bind).not.toHaveBeenCalled()
+ expect(capacity.release).toHaveBeenCalled()📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| expect(capacity.bind).not.toHaveBeenCalled() | |
| expect(capacity.bind).not.toHaveBeenCalled() | |
| expect(capacity.release).toHaveBeenCalled() |
| const claimRegionalRehome = vi.fn() | ||
| const recordRegionalRehomeDispatchFailure = vi.fn() |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Assert continuation after a lost response.
await c.worker.run() already verifies error containment because the test fails if run() rejects. The recordRegionalRehomeDispatchFailure assertion is vacuous, and the single candidate does not test continuation. Configure two candidates, make the first request fail and the second return committed, then assert that run() resolves and fetch is called twice. Remove the unused store-method stubs and assertions.
| it('advances past a full candidate page whose destination lacks capacity', async () => { | ||
| const context = await setup() | ||
| for (let i = 0; i < 10; i++) { | ||
| await activatePreferredSource(context, { | ||
| userId: `blocked-${i}`, | ||
| relayHostId: 'abcdefghijklmnop' | ||
| }) | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Resolve IDLE_REHOME_PAGE_SIZE and its use in candidate selection.
set -euo pipefail
rg -nP -C3 '\bIDLE_REHOME_PAGE_SIZE\b' cloud/apps/relay/src
# Confirm the offset-advance condition that depends on the page size.
ast-grep run --pattern 'this.idleRegionalCandidateOffset = $$$' --lang typescript cloud/apps/relay/src/assignment-store.tsRepository: stablyai/orca
Length of output: 2611
🤖 get_repo_knowledge executed:
get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions
Length of output: 41509
🏁 Script executed:
#!/bin/bash
set -euo pipefail
sed -n '1,130p' cloud/apps/relay/src/regional-rehome-store.test.ts
sed -n '3310,3370p' cloud/apps/relay/src/assignment-store.ts
sed -n '1,120p' cloud/apps/relay/src/idle-regional-rehome-selection.tsRepository: stablyai/orca
Length of output: 13426
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C6 'function (activatePreferredSource|activateReversePreferredSource)|activatePreferredSource|activateReversePreferredSource|class IdleRehomeTestStore|tryIdleRehome' cloud/apps/relay/src/regional-rehome-store.test.tsRepository: stablyai/orca
Length of output: 33524
🏁 Script executed:
#!/bin/bash
set -euo pipefail
sed -n '650,900p' cloud/apps/relay/src/regional-rehome-store.test.ts
rg -n -C10 'tryIdleRehome|selectIdleRegionalRehomeCandidates|activatePreferredSource|activateReversePreferredSource' cloud/apps/relay/src/assignment-store.ts cloud/apps/relay/src/regional-rehome-store.test.tsRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -euo pipefail
sed -n '1670,1785p' cloud/apps/relay/src/regional-rehome-store.test.ts
sed -n '1900,1985p' cloud/apps/relay/src/regional-rehome-store.test.ts
rg -n -C4 'IDLE_REHOME_PAGE_SIZE|target\.reserved_requests|candidates\.length|idleRegionalCandidateOffset' cloud/apps/relay/src/idle-regional-rehome-selection.ts cloud/apps/relay/src/assignment-store.tsRepository: stablyai/orca
Length of output: 12365
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C12 'async tryIdleRehome|hookAfterCandidateScan|selectIdleRegionalRehomeCandidates\(' cloud/apps/relay/src/assignment-store.ts cloud/apps/relay/src/regional-rehome-store.test.tsRepository: stablyai/orca
Length of output: 19499
Make the test exercise the full-page offset.
IDLE_REHOME_PAGE_SIZE is 100. Because the test fills target before selection, the query excludes all 10 preferred sources and returns only the reverse source. Create 100 blocked sources plus the reverse source, then fill target in hookAfterCandidateScan; this makes the first page fail during commit and the next selection reach the reverse source.
| () => assignments.commitIdleRegionalRehome(input, combineRegionalRehomeSafety( | ||
| input.directorSafety, | ||
| { ...observability.regionalRehomeRuntimeSafety(), ...readRelayDatabasePoolPressure(database) } | ||
| ), input.cohortPercent), |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Pass process safety before fleet safety.
combineRegionalRehomeSafety copies reconnects from its second argument. The current call passes local process safety second, so the commit gate can omit the director fleet reconnect count. Swap the arguments.
Proposed fix
- () => assignments.commitIdleRegionalRehome(input, combineRegionalRehomeSafety(
- input.directorSafety,
- { ...observability.regionalRehomeRuntimeSafety(), ...readRelayDatabasePoolPressure(database) }
+ () => assignments.commitIdleRegionalRehome(input, combineRegionalRehomeSafety(
+ { ...observability.regionalRehomeRuntimeSafety(), ...readRelayDatabasePoolPressure(database) },
+ input.directorSafety
), input.cohortPercent),📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| () => assignments.commitIdleRegionalRehome(input, combineRegionalRehomeSafety( | |
| input.directorSafety, | |
| { ...observability.regionalRehomeRuntimeSafety(), ...readRelayDatabasePoolPressure(database) } | |
| ), input.cohortPercent), | |
| () => assignments.commitIdleRegionalRehome(input, combineRegionalRehomeSafety( | |
| { ...observability.regionalRehomeRuntimeSafety(), ...readRelayDatabasePoolPressure(database) }, | |
| input.directorSafety | |
| ), input.cohortPercent), |
| including explicit zero; only an absent service/setting bootstraps to0. Malformed | ||
| or ambiguous live settings fail the plan instead of silently resetting the cohort. | ||
| The audited director workflow owns subsequent changes. | ||
| Before the first nonzero cohort, verify compatible protocol2 cells, updated |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Require protocol3 cells in the rollout checklist.
Line 501 and the region-correction contract require regional protocol3. Line 552 instead tells operators to verify protocol2 cells. Change protocol2 to protocol3 so the launch gate checks the required capability.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The delta since the prior Pullfrog review is a single test commit that pins the target-capacity accounting for idle regional rehome, plus a clarifying comment in the selection query.
- Source-activity capacity boundary test —
idle-regional-rehome-store.test.tsgains anit.each([10, 11])case asserting a candidate is committed only when the target has room for the moving host's source activity plus its assignment (7reserved +3activity +1assignment =11); at capacity10it defers and leaves the assignment on the source. The negative control makes the boundary exact rather than a truthiness check. - Selection-query comment —
idle-regional-rehome-selection.tsnow documents that thetarget.reserved_requests + 1 + SUM(activity.request_units)predicate reserves the source's activity units plus the assignment on the target.
The production predicate itself is unchanged from the prior commit; only the comment and the locking test are new, and the test asserts concrete final state (reserved_requests, resolved cellId/assignmentEpoch), so it fails rather than passes vacuously if the accounting regresses.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Snapshot of the uncommitted working tree so nothing is lost when the worktree is removed. Superseded by main: the region-correction feature landed via #20105, #20712, #20749, and the pool-canary gate it was blocking on was retired after the contention was traced to the fleet-wide cell-inventory lock (#21067).

Automatically correct a host’s relay region when the source has no client connections or pending admission/control work. Fresh incumbent-relative measurements select an eligible target; the source gates new admissions before atomically updating the assignment, then releases its empty control. Returning devices use normal reconnect, and a failed target uses existing migration recovery.
Replaces the earlier live-retention proposal. Reuses the worker, assignment locks, reservations and recovery; no retained-source lease or mobile protocol. Correction defaults off and requires protocol3 cells plus an idle-capable desktop. Deployment and enablement remain separate.
Validation: 77 cloud files / 682 tests passed with PostgreSQL16 on55440, zero skips; cloud typecheck passes. Source admission, authority-tuple dedupe and locked reconciliation have negative-control evidence. Fifth Astra low implementation audit approved within scope. Desktop PR adds real two-cell transport coverage.
Remaining: fresh CI for this head, packaged mixed versions and platform/device release validation, then measured bounded rollout. No deployment performed.
Published from the locally validated baseline
74cc9b50390b481009b34823a35eee01a5b90e40. Main has since advanced; current-main integration and fresh hosted CI remain required. Historical status text in the acceptance document records the pre-publication snapshot.