Repository navigation
feat(desktop): measure relay regions and reconnect after idle cutover - #20106
Conversation
2b08104 to
a8a38a6
Compare
a13d28a to
3f46aa2
Compare
There was a problem hiding this comment.
Important
One new safety path is not wired into the running app: the final pending-request retirement notification is dropped at the RelayControlOrigin → RelayControlClient boundary, so the origin-retirement trigger the new tests pin never fires in production. Details inline.
Reviewed changes
- Region measurement + correction protocol — new window/report schema in
relay-region-correction-protocol, measurement logic inrelay-region-decision, and a broker-ownedRelayRegionRefreshscheduler wired intoRelaySessionBroker. - Origin-pool refactor — extracts
RelayOriginRetirementandRelayControlRotation, addsapplyAssignmentMetadatawith deferred-assignment handling, and threadsonPendingChangedthroughRelayControlRequests. - Capability + wire compatibility — advertises
idle-regional-rehome-v1on the control upgrade header, adds a 400 fallback forregionCorrection, and bumps the preference cache schema v1→v2 (invalidating legacy placement caches on upgrade). - Tests + docs — real two-cell TCP WebSocket e2e harness with an independent execution oracle, pinned mixed-version compatibility tests, retirement/refresh unit tests, and the design/acceptance/rollout docs.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| }, | ||
| onDrain: (origin, message) => this.handleDrain(origin, message), | ||
| onPendingChanged: (origin) => this.retirement.maybeClose(origin), |
There was a problem hiding this comment.
The retirement notification wired here never fires. RelayControlOrigin stores onPendingChanged in its options but openControl never forwards it to the RelayControlClient instances it creates, so RelayControlRequests is constructed with onPendingChanged === undefined and the queueMicrotask in finish() is a no-op. relay-control-request-retirement.test.ts passes only because it exercises RelayControlRequests directly with a standalone callback.
Technical details
# onPendingChanged dropped at the origin → client boundary
## Affected sites
- src/main/runtime/relay/relay-control-origin.ts:177 — `openControl` builds each `RelayControlClient` without `onPendingChanged`, so `this.options.onPendingChanged` is never consumed.
- src/main/runtime/relay/relay-control-client.ts:47 — `new RelayControlRequests(options.onPendingChanged)` receives `undefined`.
- src/main/runtime/relay/relay-control-requests.ts:186 — `queueMicrotask(() => this.onPendingChanged?.())` is a no-op.
## Required outcome
- A drained source whose last outstanding item is a pending control request is retired as soon as that request settles (reply/denial/timeout/send-failure/close), without waiting for the grace deadline.
## Suggested approach
- Forward the callback in `RelayControlOrigin.openControl`: `onPendingChanged: () => this.options.onPendingChanged?.(this)`.
- Add a component-level test asserting `retirement.maybeClose` is invoked after a pending request on the source settles (the current isolated `RelayControlRequests` test cannot catch this).| ) | ||
| private readonly drainingOrigins = this.retirement.draining | ||
| private readonly basisOrigins = this.retirement.basis | ||
| private authorityVersion = 0 |
There was a problem hiding this comment.
authorityVersion is declared but never reassigned, so both guards — resolveDrainTarget (line 184) and activateTarget (line 254) — are always false and the stale_relay_target throw is unreachable. deferredAssignment and assertCurrent() already cover the races this field appears to target, so it reads as a leftover: either wire up an increment on the authority-changing transition it is meant to fence, or drop the field and its guards.
3f46aa2 to
d8f8a11
Compare
📝 WalkthroughWalkthroughThe change adds idle relay regional correction across the desktop client, relay session broker, assignment protocol, and origin pool. It introduces measurement windows, decision reporting, compatibility fallbacks, refresh scheduling, lease rotation, request retirement, and origin retirement. It adds protocol, integration, compatibility, and end-to-end tests. It also adds reliability gates, rollout documentation, acceptance records, and CI dependency preparation. Priority: ➖ Normal Merge Risk: 🟠 High · up to Failed or stale relay cutovers can leave desktop relay state inconsistent and cause retries to use outdated assignments. The dependency and rollout evidence also remains inconsistent, so these issues should be resolved before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description provides a useful change summary and testing results, but it does not follow the required template. It omits the required section headings and checklist details, does not include a Resolution Complete the template sections. Add ELI5, What Changed, Why, Linked Issue with
✨ 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: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/runtime/relay/relay-control-origin.ts (1)
177-206: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winForward
onPendingChangedtoRelayControlClient.Lines 177-206 create the client without the callback from
RelayControlOriginOptions.RelayOriginPool.createOriginprovides that callback to recheck retirement. When the final request on a draining source completes,RelayOriginRetirement.maybeClosedoes not run. The idle source then remains open until its grace timer expires.Proposed fix
onClose: (code) => { this.controls.delete(control) const timer = this.retiredControlTimers.get(control) if (timer) { clearTimeout(timer) this.retiredControlTimers.delete(control) } if (this.activeControl === control) { this.activeControl = null this.options.onClose(this, code) } }, + onPendingChanged: () => this.options.onPendingChanged?.(this), createSocket: this.options.createControlSocket
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 22ab8167-9976-46af-9e25-d20876211e7b
📒 Files selected for processing (39)
.github/workflows/unit-tests.ymlconfig/reliability-gates.jsoncdocs/relay-region-correction/RELAY-INTERRUPTION-FINDINGS.mddocs/relay-region-correction/RELAY-REGION-CORRECTION-ACCEPTANCE.mddocs/relay-region-correction/RELAY-REGION-CORRECTION-API.mddocs/relay-region-correction/RELAY-REGION-CORRECTION-CHECKLIST.mddocs/relay-region-correction/RELAY-REGION-CORRECTION-IDLE-CUTOVER-PLAN.mddocs/relay-region-correction/RELAY-REGION-CORRECTION-PLAN.mddocs/relay-region-correction/RELAY-REGION-CORRECTION-ROLLOUT.mdsrc/main/global-fetch-call-site-audit.test.tssrc/main/runtime/relay/desktop-relay-service.tssrc/main/runtime/relay/relay-control-client-options.tssrc/main/runtime/relay/relay-control-client.test.tssrc/main/runtime/relay/relay-control-client.tssrc/main/runtime/relay/relay-control-origin-options.tssrc/main/runtime/relay/relay-control-origin.tssrc/main/runtime/relay/relay-control-protocol.tssrc/main/runtime/relay/relay-control-request-retirement.test.tssrc/main/runtime/relay/relay-control-requests.tssrc/main/runtime/relay/relay-control-rotation.tssrc/main/runtime/relay/relay-http-client.tssrc/main/runtime/relay/relay-origin-pool-options.tssrc/main/runtime/relay/relay-origin-pool.tssrc/main/runtime/relay/relay-origin-retirement.tssrc/main/runtime/relay/relay-region-correction-protocol.tssrc/main/runtime/relay/relay-region-correction.test.tssrc/main/runtime/relay/relay-region-decision.tssrc/main/runtime/relay/relay-region-preference-reader.tssrc/main/runtime/relay/relay-region-preference.test.tssrc/main/runtime/relay/relay-region-preference.tssrc/main/runtime/relay/relay-region-probe-log.test.tssrc/main/runtime/relay/relay-region-refresh.test.tssrc/main/runtime/relay/relay-region-refresh.tssrc/main/runtime/relay/relay-session-broker-contract.tssrc/main/runtime/relay/relay-session-broker.tstests/e2e/helpers/relay-execution-process.tstests/e2e/relay-region-compatibility.unit.test.tstests/e2e/relay-region-correction.unit.test.tstests/tools/relay-bench/find-cell.mjs
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
| Cloud draft20037 still points to `0462a87011d8783f91f9a9e977ea7a68437a0d5b`; | ||
| desktop draft20031 still points to `f9e5b0193448e6c524603836b9278878b96cf51c`. |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🤖 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: 42112
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- target document ---'
cat -n docs/relay-region-correction/RELAY-REGION-CORRECTION-ACCEPTANCE.md
printf '%s\n' '--- relevant diff/stat ---'
git diff --stat -- docs/relay-region-correction/RELAY-REGION-CORRECTION-ACCEPTANCE.md
git diff -- docs/relay-region-correction/RELAY-REGION-CORRECTION-ACCEPTANCE.md
printf '%s\n' '--- matching cloud references ---'
rg -n -i '20105|20037|cloud draft|cloud PR|cloud.*branch|draft20037' docs/relay-region-correction .Repository: stablyai/orca
Length of output: 50371
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- repository status and relevant files ---'
git status --short
fd -i 'relay-region-correction' docs
printf '%s\n' '--- idle cutover plan references ---'
rg -n -i -C 3 'cloud|desktop|draft|pull request|PR|branch|20105|20037|20031' docs/relay-region-correction
printf '%s\n' '--- target history metadata ---'
git log -5 --oneline -- docs/relay-region-correction/RELAY-REGION-CORRECTION-ACCEPTANCE.md
printf '%s\n' '--- GitHub PR metadata, if available ---'
if command -v gh >/dev/null 2>&1; then
gh pr view 20105 --repo stablyai/orca-cloud --json number,title,state,isDraft,headRefName,headRepositoryOwner,headRepository,baseRefName,headRefOid,url
gh pr view 20037 --repo stablyai/orca-cloud --json number,title,state,isDraft,headRefName,headRepositoryOwner,headRepository,baseRefName,headRefOid,url
gh pr view 20031 --repo stablyai/orca --json number,title,state,isDraft,headRefName,headRepositoryOwner,headRepository,baseRefName,headRefOid,url
else
printf '%s\n' 'gh unavailable'
fiRepository: stablyai/orca
Length of output: 233
🏁 Script executed:
#!/bin/bash
set +e
printf '%s\n' '--- tracked relay-region-correction files ---'
git ls-files 'docs/relay-region-correction/*'
printf '%s\n' '--- plan and acceptance references ---'
grep -RniE -C 3 '20105|20037|20031|cloud|desktop|draft|pull request|branch' docs/relay-region-correction 2>/dev/null
printf '%s\n' '--- GitHub CLI availability ---'
if command -v gh >/dev/null 2>&1; then
for spec in 'stablyai/orca-cloud 20105' 'stablyai/orca-cloud 20037' 'stablyai/orca 20031'; do
set -- $spec
printf '%s\n' "--- $1#$2 ---"
gh pr view "$2" --repo "$1" --json number,title,state,isDraft,headRefName,headRepositoryOwner,headRepository,baseRefName,headRefOid,url
printf 'exit=%s\n' "$?"
done
else
printf '%s\n' 'gh unavailable'
fiRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set +e
printf '%s\n' '--- local split artifacts ---'
for f in .tmp/idle-cutover-review/cloud-pr-body.md .tmp/idle-cutover-review/desktop-pr-body.md .tmp/idle-cutover-review/split-manifest.json; do
if [ -f "$f" ]; then
printf '%s\n' "--- $f ---"
grep -n -i -E -C 3 '20105|20037|20031|PR|pull|branch|head|cloud' "$f"
else
printf '%s\n' "$f: unavailable"
fi
done
printf '%s\n' '--- exact GitHub lookup ---'
if command -v gh >/dev/null 2>&1; then
for repo_pr in 'stablyai/orca-cloud:20105' 'stablyai/orca-cloud:20037' 'stablyai/orca:20031'; do
repo=${repo_pr%:*}; pr=${repo_pr#*:}
printf '%s\n' "--- $repo#$pr ---"
gh pr view "$pr" --repo "$repo" --json number,title,state,isDraft,headRefName,baseRefName,headRefOid,url 2>&1
printf 'status=%s\n' "$?"
done
else
printf '%s\n' 'gh unavailable'
fiRepository: stablyai/orca
Length of output: 996
🏁 Script executed:
#!/bin/bash
set +e
for pr in 20105 20037; do
printf '%s\n' "--- stablyai/orca#$pr ---"
gh pr view "$pr" --repo stablyai/orca --json number,title,state,isDraft,headRefName,baseRefName,headOid,url 2>&1
printf 'status=%s\n' "$?"
doneRepository: stablyai/orca
Length of output: 1563
🏁 Script executed:
#!/bin/bash
set +e
for pr in 20105 20037; do
printf '%s\n' "--- stablyai/orca#$pr ---"
gh pr view "$pr" --repo stablyai/orca --json number,title,state,isDraft,headRefName,headRefOid,baseRefName,url 2>&1
printf 'status=%s\n' "$?"
doneRepository: stablyai/orca
Length of output: 809
Correct the cloud PR reference before publication.
Cloud PR #20037 is closed and contains the older relay-region-cloud head. The authoritative idle implementation is cloud PR #20105, merged from relay-idle-cloud. Replace 20037 at lines 8–9 and revise lines 105–106 so they do not instruct maintainers to update the closed PR.
| Every test/app command uses `ORCA_BACKGROUND_LAUNCH=1`. Cloud commands run from | ||
| `cloud/apps/relay`; root commands run from this worktree. All logs below are under | ||
| `.tmp/idle-cutover-review/`. |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Make the validation commands reproducible.
The document has no preceding export or wrapper that sets ORCA_BACKGROUND_LAUNCH=1. Add export ORCA_BACKGROUND_LAUNCH=1 before the table, or set it inline for each Electron-launching command. Otherwise, copied validation can use the normal foreground mode and show windows or take focus.
| Status: **REVISION 2 — DESIGN APPROVED; implementation and verification pending.** | ||
|
|
||
| Independent GPT-6-astra low review found no remaining design blocker. Approval is | ||
| conditional on the implementation gates below: pre-await ownership accounting, | ||
| shared assignment-row serialization, locked ambiguous-outcome reconciliation, | ||
| operation identity deduplication and late-callback fencing must be proven in tests. |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Align the idle-cutover status with the acceptance evidence.
The acceptance document records local implementation and validation as complete, with the fifth implementation audit approved. Published PR updates, fresh CI, packaged/device checks, and release evidence remain open. Update the plan header and lines 207–210 to separate completed implementation/audit gates from the still-open page-boundary fairness test and release gates. Use the same distinction in the checklist so “final implementation audit” does not conflict with the open final-acceptance work.
| @@ -0,0 +1,177 @@ | |||
| # Relay automatic region correction — implementation plan v2 | |||
|
|
|||
| Status: **IMPLEMENTED AND LOCALLY VALIDATED; RELEASE GATES REMAIN**. Section 5a is normative for first-grant adoption, retained-source rollback, renewal and cleanup. This replaces the idle-only proposal. Historical design reviews are preserved in the combined backup revision; current verification and remaining gaps are recorded in the acceptance document. | |||
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Do not mark the retained-source contract as implemented.
The status says “IMPLEMENTED AND LOCALLY VALIDATED,” but Line [76] says Section 5 is only a required contract and Line [111] says the renewal correction is not implemented. This can make the document appear to authorize release before retained-source rollback and lifetime fencing are present. State which obligations are implemented and which Section 5a requirements remain design-only.
Suggested status clarification
-Status: **IMPLEMENTED AND LOCALLY VALIDATED; RELEASE GATES REMAIN**. Section 5a is normative for first-grant adoption, retained-source rollback, renewal and cleanup. This replaces the idle-only proposal. Historical design reviews are preserved in the combined backup revision; current verification and remaining gaps are recorded in the acceptance document.
+Status: **PARTIALLY IMPLEMENTED AND LOCALLY VALIDATED; SECTION 5a AND RELEASE GATES REMAIN**. Section 5a is normative for first-grant adoption, retained-source rollback, renewal and cleanup; identify which obligations remain design-only. This replaces the idle-only proposal. Historical design reviews are preserved in the combined backup revision; current verification and remaining gaps are recorded in the acceptance document.| - Performance acceptance: matched post-move assigned-cell control RTT improves by | ||
| >=25ms AND>=20% median per host for at least80% of evaluable moved hosts; require | ||
| two independent samples before and after. Identify samples using | ||
| assignment epoch/cell identity. Log sample insufficiency as unevaluable. |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift
Require a minimum evaluable performance sample before expansion.
The criterion requires improvement for “at least 80% of evaluable moved hosts” and allows insufficient samples to be marked unevaluable. The 30 completed moves in Line [35] do not prevent the denominator from shrinking to one host. One favorable host could then satisfy the gate while most moved hosts lack evidence. Define a minimum count and coverage for evaluable hosts, and keep the gate pending when telemetry is insufficient.
🧰 Tools
🪛 LanguageTool
[grammar] ~45-~45: Ensure spelling is correct
Context: ... >=25ms AND>=20% median per host for at least80% of evaluable moved hosts; require two...
(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)
[grammar] ~47-~47: Ensure spelling is correct
Context: ...l identity. Log sample insufficiency as unevaluable. - Client connection setup p95 must not...
(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)
| const done = (r) => { | ||
| try { | ||
| ws.terminate() | ||
| } catch {} | ||
| resolve({ cell, ms: Math.round(performance.now() - t0), ...r }) | ||
| } | ||
| ws.on('open', () => | ||
| ws.send(JSON.stringify({ type: 'relay-auth', v: 1, mode: 'connect', credential: bogus })) | ||
| ) | ||
| ws.on('message', (m) => done({ hello: JSON.parse(m.toString()).code })) | ||
| ws.on('error', (e) => done({ error: e.code ?? e.message })) | ||
| ws.on('close', (c) => done({ close: c })) | ||
| setTimeout(() => done({ error: 'timeout' }), 8000) |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win
Clear the timeout after probe completion.
done does not clear the timer from Line 23. A successful probe leaves an active eight-second timer, so the command remains alive after all probes have resolved. Guard done so close and timeout events cannot repeat cleanup.
| ws.on('open', () => | ||
| ws.send(JSON.stringify({ type: 'relay-auth', v: 1, mode: 'connect', credential: bogus })) | ||
| ) | ||
| ws.on('message', (m) => done({ hello: JSON.parse(m.toString()).code })) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Handle malformed relay responses.
JSON.parse throws if a cell returns a non-JSON frame. That uncaught event-handler error terminates the benchmark instead of reporting the unexpected response. Catch parse errors and complete this probe with a diagnostic result.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/main/runtime/relay/relay-control-origin.ts (1)
118-118: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winValidate the assignment epoch before activating the rebound control.
rebindcallsactivate(control, ack)beforeupdateAssignment(assignment). If the assignment epoch is lower,updateAssignmentthrows after the new control is active. The origin then has a control opened with the older epoch while its stored assignment still has the newer epoch. The pool treats the rejection as a failed rebind and starts another target, but the original origin remains inconsistent until retirement. Reject stale epochs beforeopenControl, then keep the final assignment update after successful activation.src/main/runtime/relay/relay-origin-pool.ts (1)
188-188: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winKeep the deferred assignment until cutover succeeds.
The resolver clears
deferredAssignmentbeforeorigin.rebindoractivateTargetcompletes. If target opening fails, the retry is scheduled with the deferred assignment already lost. The next attempt can use a stale director response and miss the newer assignment. Clear the value only after successful cutover, and preserve a newer value that arrives while the operation is in progress.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 7ac86b1f-6c52-4626-ad4f-921ab0ec5b43
📒 Files selected for processing (2)
src/main/runtime/relay/relay-control-origin.tssrc/main/runtime/relay/relay-origin-pool.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
Static analysis on #5 failed because the generated catalog lagged upstream stablyai#20106 region-measure RPC params.
* feat(own-relay): add Coolify Docker deploy channel Ship a Node 22 image, Coolify compose (expose 8093, two Traefik hosts, no host ports), env names, and karlorz-only multi-arch image CI so cloud01 can run own-mobile-relay without a second process. * chore(rpc): regenerate params catalog after fork-sync Static analysis on #5 failed because the generated catalog lagged upstream stablyai#20106 region-measure RPC params. * chore(i18n): add Mac speech keys to en catalog Fork-sync brought VoiceMacSpeechSection keys that static analysis requires in en.json. Sync only; no other locale drive-by. * simplify(own-relay): shrink Coolify image context and tests GHA layer cache, ignore renderer/cli in docker context, parse compose once.

Refresh relay-region measurements against the current assignment and advertise support for idle-only correction. When the cloud closes an empty source control after a committed move, the desktop uses normal director resolution and reconnect. Devices already connected prevent optimization; no retained source or restoration loop is needed.
Depends on #20105 (cloud); this PR targets its branch. No mobile protocol change. Includes the real two-cell TCP WebSocket harness, independent execution/mutation oracle, pinned compatibility checks, CI dependency setup and updated acceptance docs.
Validation: 177 desktop relay tests;16 transport/compatibility tests including three real TCP WebSocket scenarios;7 background Docker SSH/folder-restart tests;node typecheck, focused lint and121 reliability manifest gates pass. Global-fetch audit regression was reproduced and its verified consumer count corrected. Cloud dependency install/build commands for CI pass locally.
Remaining: fresh CI for this head and packaged/device/platform release evidence. SSH tests exercise real provider recovery, not a physical phone-to-SSH regional cutover. Draft until review/CI requirements are satisfied; 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.