Skip to content

fix(relay): rehome hosts to their preferred region in either direction - #19241

Merged
Jinwoo-H merged 3 commits into
mainfrom
relay/bidirectional-rehome
Sep 7, 2026
Merged

Jinwoo-H merged 3 commits into
mainfrom
relay/bidirectional-rehome

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​973 $\color{#cf222e}{\Huge{\mathbf{−}}}$​29 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​944
Prod 10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​216 $\color{#cf222e}{\Huge{\mathbf{−}}}$​35 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​181

Why

The regional rehome worker only ever moved hosts with preferred_region = asia-east2 sitting 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

  • Direction generalized. Candidate scan uses preference.preferred_region <> region.region and requires an enabled, general, ready, heartbeating cell with regional_rehome_protocol >= 1 in 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 from RELAY_REGIONS.
  • Per-host cooldown. relay_region_rehome_control.host_cooldown_ms (default 7 days, bounds 60 s to 30 days), plumbed like preference_max_age_ms from 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 reason host_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.
  • Schema. relay_region_rehome_attempts.preferred_region check relaxed to the region catalog via a named constraint; host_cooldown_ms column with a default; recency index on attempts. Postgres migrations run through POSTGRES_SCHEMA_MIGRATIONS; 42710 on ADD CONSTRAINT is treated as already applied. SQLite keeps the old check on pre-existing files.
  • Ops script rollout safety. inspect, pause, disable, and recover-enable work against a director that predates the cooldown field (the key is validated only when present and omitted on echo-back). enable refuses, before any mutation, when the director does not report the field.
  • Trust probe no longer region-gated. Ops doc gains a regional rehoming section: a cell without the drain protocol is neither source, target, nor safety-gate member.

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-moved as today; protocol-0 desktops are excluded by the existing capability check.

Verification

  • Fresh Postgres on 55440 after rebase on main: relay 72 files / 620 tests; relay-contract build; pnpm typecheck; ops-script 17 tests. Workspace dev-script and contract suites passed in the agent run.
  • Migration verified against a legacy-shaped table holding a live control row: 3 sequential and 10 concurrent startups, zero rejections, one correct constraint, the row kept its generation and gained the default.
  • Independent adversarial review, three rounds: round 1 added the cooldown and the enabled predicate; round 2 fixed the ops script losing inspect and both brakes against an older director; round 3 approved.

Not for merge until the owner gives the go.

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.
@coderabbitai

coderabbitai Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 3860dea6-dbef-4748-97c1-dfd641be9fcf

📥 Commits

Reviewing files that changed from the base of the PR and between 3145060 and 71224de.

📒 Files selected for processing (18)
  • .github/workflows/cloud-operate-relay-production-rehome-job.yml
  • .github/workflows/cloud-operate-relay-production-rehome.yml
  • cloud/apps/relay/src/app.ts
  • cloud/apps/relay/src/assignment-inventory-snapshot.ts
  • cloud/apps/relay/src/assignment-store.ts
  • cloud/apps/relay/src/cell-heartbeat-client.ts
  • cloud/apps/relay/src/database-postgres-timeout.test.ts
  • cloud/apps/relay/src/database.test.ts
  • cloud/apps/relay/src/database.ts
  • cloud/apps/relay/src/postgres-schema-startup.ts
  • cloud/apps/relay/src/regional-host-drain-app.test.ts
  • cloud/apps/relay/src/regional-rehome-constraint-migration-postgres.test.ts
  • cloud/apps/relay/src/regional-rehome-postgres.test.ts
  • cloud/apps/relay/src/regional-rehome-store.test.ts
  • cloud/apps/relay/src/regional-rehome-target-selection.test.ts
  • cloud/dev/scripts/operate-relay-regional-rehome.mjs
  • cloud/dev/scripts/operate-relay-regional-rehome.test.mjs
  • cloud/docs/orca-relay-operations.md

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


📝 Walkthrough

Walkthrough

The 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 71224

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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, Lin… 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, Re…
Docstring Coverage ⚠️ Warning 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:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: bidirectional regional rehoming to the host's preferred region.
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.
Full details: Description check

Explanation

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 Coverage

Explanation

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.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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 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 hardcoding asia-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 EXISTS on a recent attempt) and under the claim lock (new host_cooldown skip reason).
  • Schema. The relay_region_rehome_attempts.preferred_region check is widened via a named constraint, a host_cooldown_ms column and a host-recency index are added, and POSTGRES_SCHEMA_MIGRATIONS runs the changes with 42710 on ADD CONSTRAINT treated as already applied.
  • Ops rollout safety. inspect, pause, disable, and recover-enable tolerate a director that predates the cooldown field; enable refuses 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?

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit f5be177 into main Sep 7, 2026
26 checks passed
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 7, 2026
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.
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