Repository navigation
fix(relay): rehome hosts to their preferred region in either direction - #19241
Conversation
The regional-rehome worker only moved hosts from a us-central1 cell to an asia-east2 one, so a host whose desktop later records us-central1 stays where it was put. Rehoming now compares the fresh preference against the region of the cell the host is on and moves it to a general cell in the preferred region either way, through the same drain, migrate, safety, and rate-limit machinery. - relay_region_rehome_attempts.preferred_region accepts both regions; existing databases are upgraded in place by an idempotent named-constraint swap that is safe when several directors start at once. - A target must carry the drain protocol too: moving a host onto a cell it can never be drained off again is the trap this change exists to undo. The fleet whose health gates a rehome is now every general drainable cell, which is exactly the set of legal sources and targets. - The trust probe accepts a source cell in any region. No wire change, and no behaviour change while the durable control is off.
Moving hosts in both directions removed the property that made the old one-way worker self-terminating: a desktop whose region probe flips would be dragged back and forth, one full drain and migrate per flip, because the preference age never expires while the host keeps reconnecting. - relay_region_rehome_control gains host_cooldown_ms, an operator input plumbed like preference_max_age_ms (workflow, ops script, admin route, durable row) and defaulted to seven days. A host with any attempt row inside the window, whichever way that move went, is not a candidate; the claim re-reads it under lock so an attempt landing between scan and claim cannot start a second move. Skips are named host_cooldown, and the lookup rides a new index on (user_id, relay_host_id, created_at). - The candidate scan now also requires the target cell to be enabled, so it mirrors the claim-time filter exactly and stops spending batch slots on candidates that are certain to be skipped. - Region CHECK lists are rendered from the shared region list instead of being written out four times. - The operations runbook states that cells without the drain protocol are neither sources, targets, nor members of the safety gate.
…rollout The ops script validated hostCooldownMs on every inspected control, so against any director image predating the field inspect, pause, disable, and failed-enable recovery all threw client-side. The workflow always runs from main while the director image is operator-supplied, so that window opened at merge and reopened on every rollback: the operator lost read-only visibility and both emergency brakes while the worker could still be enabled. The field is now validated only when the director reports it, and every apply body that echoes an inspected control omits the key when that control lacks it, so a legacy director never sees an unknown key. The write path stays fail-closed the other way: enable refuses up front, before any mutation, when the director does not report a cooldown it could honour. Also replaces two bare 'us-central1' defaults with RELAY_DEFAULT_REGION.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (18)
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review. 📝 WalkthroughWalkthroughThe change adds a required per-host rehome cooldown across workflows, API validation, persisted control state, and the operation script. Regional rehoming now supports configured regions in either direction, with protocol, runtime, fleet-safety, target-region, and cooldown checks. PostgreSQL schemas use shared region definitions and include migrations for the cooldown column, named constraints, and host-recency indexing. Tests cover migration concurrency, legacy directors, bidirectional selection, cooldown expiry, and trust probes. Documentation describes the updated operational rules. Merge Risk: ⚪ Minimal · up to The regional rehome control, migration, selection, and legacy-operation paths have no identified actionable merge risk. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the main behavior, motivation, rollout safety, schema changes, and verification. However, it omits or does not complete several required template sections, including ELI5, Linked Issue, Visual Proof or N/A, Testing checkboxes, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist. Resolution Complete the required template sections. Add an ELI5 summary, provide the linked issue after "Fixes #", add visual proof or state "N/A" with a reason, complete the Testing section and checkboxes, fill or explicitly address AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist items. Full details: Docstring CoverageExplanation Docstring coverage is 18.92% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 37 functions across 15 files. (3 skipped: 3 unsupported.)
✨ 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.
ℹ️ No blocking issues — one rollout-safety consideration worth a look.
Reviewed changes
- Direction generalized. The candidate scan now keys on
preference.preferred_region <> region.region; source, target, and fleet-safety selection all require the drain protocol (regional_rehome_protocol >= 1) in any region instead of hardcodingasia-east2/us-central1. - Per-host cooldown.
host_cooldown_ms(default 7 days) is plumbed from the workflow through the ops script and director schema into the durable control row, and enforced at scan (NOT EXISTSon a recent attempt) and under the claim lock (newhost_cooldownskip reason). - Schema. The
relay_region_rehome_attempts.preferred_regioncheck is widened via a named constraint, ahost_cooldown_mscolumn and a host-recency index are added, andPOSTGRES_SCHEMA_MIGRATIONSruns the changes with42710onADD CONSTRAINTtreated as already applied. - Ops rollout safety.
inspect,pause,disable, andrecover-enabletolerate a director that predates the cooldown field;enablerefuses it. The trust probe is gated on the protocol rather than the region.
The concurrency and migration seams check out: claimRegionalRehome takes FOR UPDATE on the global worker row before the candidate scan, so claims are serialized across directors and the claim-time cooldown re-read cannot miss a concurrent move; and the constraint migration is idempotent on both fresh (_valid already present → 42710 → applied) and legacy (_check dropped, _valid added) databases.
ℹ️ The new apply schema makes the emergency brakes one-directionally compatible
RegionalRehomeControlSchema's apply branch adds hostCooldownMs as a required field on a .strict() object, so any apply without it is a 400. The PR hardens the script so the new script can still pause/disable a pre-cooldown director (cooldownField omits the key when before.hostCooldownMs === undefined), but the mirror direction is left open: an operator running a pre-cooldown script against the new director gets 400 on every apply, including the pause/disable brakes. The PR's own bar — "both brakes keep working" — currently only covers one rollout direction.
Technical details
# Rollout asymmetry for the rehome control brakes
## Affected sites
- cloud/apps/relay/src/app.ts:1416-1426 — `hostCooldownMs` is required and the object is `.strict()`, so an apply body lacking it fails validation.
- cloud/dev/scripts/operate-relay-regional-rehome.mjs:171-173 — `cooldownField` omits the key only when the *director* already reports it (new script → old director), not the reverse.
## Required outcome
- Decide whether a stale (pre-cooldown) script must retain the ability to `pause`/`disable` against the new director. The canonical workflow + script are versioned together in this repo and are the normal invocation path, so the exposure is limited to a manual run from an old checkout.
## Suggested approach (optional)
- Make `hostCooldownMs` optional on the `apply` branch (or accept its absence for non-enable actions) so the brakes stay reachable from a stale script, relying on the script's existing `enable` guard to refuse enabling without a stated cooldown.
## Open questions for the human
- Is a stale-script-against-new-director scenario in scope for the "both brakes keep working" guarantee, or is the repo-versioned workflow the only supported invocation?DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
stablyai#19241) * fix(relay): rehome hosts to their preferred region in either direction The regional-rehome worker only moved hosts from a us-central1 cell to an asia-east2 one, so a host whose desktop later records us-central1 stays where it was put. Rehoming now compares the fresh preference against the region of the cell the host is on and moves it to a general cell in the preferred region either way, through the same drain, migrate, safety, and rate-limit machinery. - relay_region_rehome_attempts.preferred_region accepts both regions; existing databases are upgraded in place by an idempotent named-constraint swap that is safe when several directors start at once. - A target must carry the drain protocol too: moving a host onto a cell it can never be drained off again is the trap this change exists to undo. The fleet whose health gates a rehome is now every general drainable cell, which is exactly the set of legal sources and targets. - The trust probe accepts a source cell in any region. No wire change, and no behaviour change while the durable control is off. * fix(relay): bound bidirectional rehoming with a per-host cooldown Moving hosts in both directions removed the property that made the old one-way worker self-terminating: a desktop whose region probe flips would be dragged back and forth, one full drain and migrate per flip, because the preference age never expires while the host keeps reconnecting. - relay_region_rehome_control gains host_cooldown_ms, an operator input plumbed like preference_max_age_ms (workflow, ops script, admin route, durable row) and defaulted to seven days. A host with any attempt row inside the window, whichever way that move went, is not a candidate; the claim re-reads it under lock so an attempt landing between scan and claim cannot start a second move. Skips are named host_cooldown, and the lookup rides a new index on (user_id, relay_host_id, created_at). - The candidate scan now also requires the target cell to be enabled, so it mirrors the claim-time filter exactly and stops spending batch slots on candidates that are certain to be skipped. - Region CHECK lists are rendered from the shared region list instead of being written out four times. - The operations runbook states that cells without the drain protocol are neither sources, targets, nor members of the safety gate. * fix(relay): keep rehome reads and brakes working across the cooldown rollout The ops script validated hostCooldownMs on every inspected control, so against any director image predating the field inspect, pause, disable, and failed-enable recovery all threw client-side. The workflow always runs from main while the director image is operator-supplied, so that window opened at merge and reopened on every rollback: the operator lost read-only visibility and both emergency brakes while the worker could still be enabled. The field is now validated only when the director reports it, and every apply body that echoes an inspected control omits the key when that control lacks it, so a legacy director never sees an unknown key. The write path stays fail-closed the other way: enable refuses up front, before any mutation, when the director does not report a cooldown it could honour. Also replaces two bare 'us-central1' defaults with RELAY_DEFAULT_REGION.

Why
The regional rehome worker only ever moved hosts with
preferred_region = asia-east2sitting on a us-central1 cell. A desktop bug (fixed in #19233) made US desktops request asia-east2, and the worker moved them to Asia cells where every phone connect pays trans-Pacific Cloud SQL round trips (~10 s to connected instead of ~0.6 s). Assignments are sticky and rehome was one-directional, so those hosts are stuck. A 2026-09-06 census found ~226 non-APAC desktops on the three Asia cells. This makes the worker move a host whenever its fresh preference disagrees with its cell's region, in either direction.What
preference.preferred_region <> region.regionand requires an enabled, general, ready, heartbeating cell withregional_rehome_protocol >= 1in the preferred region. Claim-lock re-check compares the preference to the source cell's region. Target selection picks from the preferred region. Fleet safety covers every enabled general protocol≥1 cell. After the change, the only'asia-east2'/'us-central1'literals in the relay are the schema/catalog lists, now rendered fromRELAY_REGIONS.relay_region_rehome_control.host_cooldown_ms(default 7 days, bounds 60 s to 30 days), plumbed likepreference_max_age_msfrom the workflow input through the ops script to the durable row. Any attempt row for the host (either direction, completed or aborted) inside the window skips the candidate at scan and, with the named reasonhost_cooldown, under the claim lock. Without this a desktop whose preference flips would be drained across the Pacific on every flip, since the preference row refreshes on each sticky assign.relay_region_rehome_attempts.preferred_regioncheck relaxed to the region catalog via a named constraint;host_cooldown_mscolumn with a default; recency index on attempts. Postgres migrations run throughPOSTGRES_SCHEMA_MIGRATIONS; 42710 onADD CONSTRAINTis treated as already applied. SQLite keeps the old check on pre-existing files.inspect,pause,disable, andrecover-enablework against a director that predates the cooldown field (the key is validated only when present and omitted on echo-back).enablerefuses, before any mutation, when the director does not report the field.Not live
The durable control is disabled in production (generation 12). Nothing moves until an operator enables it. The Asia cells report protocol 0 today; #19239 (draft) gives them the rehome identity and must roll only after this director is deployed.
Wire
No phone or desktop change. Desktops follow
relay-movedas today; protocol-0 desktops are excluded by the existing capability check.Verification
pnpm typecheck; ops-script 17 tests. Workspace dev-script and contract suites passed in the agent run.Not for merge until the owner gives the go.