Repository navigation
fix(relay): admit drained hosts through their own lane and stagger their return - #24446
Conversation
…eir return A same-cap roll's drain sends every host on the isolated cell back to the director at once. Those hosts reconnect through the sticky lane (one slot per director), and each one's re-placement holds that slot for most of a second behind the region-wide inventory lock, so ordinary reconnects time out behind them and the drained hosts retry every 2 s: ~30k 503s per drain. The reconnect verification read now also says whether the host's home cell is isolated for a roll right now (same predicate re-placement uses). Those hosts release the sticky slot after the read and take a separate drain-return lane (1 per director, matching the store's per-director placement serialization). When that lane is full the host gets a Retry-After that reserves the next free service slot, paced by the measured re-placement time and capped at 300 s. Claude-Session: ced32ebb-7155-4413-adad-1eccd14c2010
…heir own slot Review follow-ups for the drain-return lane: - The lane now borrows placement permits (never placement's last, never ahead of a queued placement), so placement + sticky still bounds the database pool. - A host's own early retry (row-busy redial, duplicate dial) gets the 2 s lane interval instead of a fresh slot behind the cohort, and a host that returns early to the same director keeps its reserved slot. - Classification also excludes an open migration row whose lease counter lapsed, matching the re-placement rule. - The load test now runs five directors behind random routing with a shared inventory lock. Claude-Session: ced32ebb-7155-4413-adad-1eccd14c2010
|
| this.activeDrainReturn < (this.options.maxDrainReturnConcurrent ?? 0) && | ||
| this.active < this.options.maxConcurrent && | ||
| this.pendingReserved === undefined && | ||
| this.pendingAssignments.length === 0 |
There was a problem hiding this comment.
Placement loses its reserved permit. With the default two placement permits, a drain return can take the second permit while a placement is already running. The next placement then has to queue and can time out, despite the intended guarantee that drain returns leave a permit for placement.
Knowledge Base Used:
| const drainReturnConcurrency = Math.min( | ||
| config.drainReturnConcurrency ?? 1, | ||
| config.publicAssignmentConcurrency - 1 | ||
| ) |
There was a problem hiding this comment.
One permit disables drain lane. If
publicAssignmentConcurrency is set to one, which configuration validation allows, this calculation makes drain-return concurrency zero. Roll-isolated reconnects then remain in the sticky lane, so this valid configuration silently loses the drain protection added by the PR.
Knowledge Base Used:
There was a problem hiding this comment.
ℹ️ Minor suggestions only.
Reviewed changes
- Server-side drain classification —
resolve(identity, { classifyHomeRollIsolation })folds the home cell's admission state, roll stamp, migration leases, and open migrations into the existing verification query via aLEFT JOIN;rollIsolationIsCurrentis extracted and shared with the re-placement gate. - Separate drain-return lane —
app.tsreleases the sticky slot after verification and routes classified hosts throughRelayDrainReturnAdmission/RelayPublicAssignmentAdmission.acquireDrainReturn, borrowing placement permits with its own concurrency, queue, and wait. - Paced
Retry-After— a per-director service-slot clock from an EWMA of measured re-placement time, bounded to[2, maxRetryAfterSeconds], with per-host reservation reuse and a short interval for a host's own redial. - Admission plumbing —
LeaseKindrefactor, drain counters/host sets, drain grants ordered behind reserved and placement waiters. - Config and metrics — four new env settings;
drainReturn*deltas and retry-after counters; rejection logs gainretryAfter=. - Tests — lane unit tests, route tests, a 2,500-host five-director fake-clock load test, and classification cases on the isolated-cell suites.
ℹ️ Classification admits hosts the store may not re-place
resolve() marks a host as a drain return whenever its home cell is roll-isolated, which is a superset of the hosts assign() will actually move: the store additionally requires a target cell with headroom and requires the host to hold no request units that no lease backs (assignment-store.ts:1044, :1115-1132), neither of which the verification read can see. Such a host is admitted to the drain lane, takes one of the four queue slots and an EWMA sample, then gets its old pin back unchanged — the homeCellRollIsolated comment at assignment-store.ts:8436-8438 ("admits the hosts the re-placement rule would move") is stronger than the predicate guarantees. This is not a regression (the same assign call ran through the sticky lane before), but it means the drain lane can be occupied by traffic it cannot service; worth confirming that is acceptable.
Technical details
# Classifier is a superset of moveable hosts
## Affected sites
- `cloud/apps/relay/src/assignment-store.ts:1372-1385` — classification has no target-availability term.
- `cloud/apps/relay/src/assignment-store.ts:1044-1046` — re-placement short-circuits when `requestUnits(existing) > leaseRequestUnits(activityLeases)`.
- `cloud/apps/relay/src/assignment-store.ts:1115-1132` — no same-region target keeps the pin and emits `orca_relay_sticky_replacement_deferred`.
- `cloud/apps/relay/src/app.ts:349-370` — a classified host consumes a drain-return permit before `assign` decides.
## Required outcome
- Decide whether the drain lane should admit hosts that may be re-pinned, or correct the comment/claim to say the classifier is a necessary-but-not-sufficient condition for re-placement.
## Open questions for the human
- Is the intended contract "route roll-isolated hosts off the sticky lane (and let `assign` keep the pin when there is no room)", or "admit exactly the hosts that will move"? If the former, the code is fine and only the comment overstates it.ℹ️ Nitpicks
- The classifier reads the roll stamp at
resolve()time with a different clock thanassign()uses, so a stamp within ~1 ms of the 2-hour bound can classify as isolated and then failrollIsolationIsCurrentat assign, re-pinning once before the next dial. Harmless at the boundary.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
| } | ||
|
|
||
| private reserveReturn(relayHostId: string, now: number): number { | ||
| const slotMs = this.serviceMs / this.options.maxConcurrent |
There was a problem hiding this comment.
Dividing the measured serialized re-placement time by the drain lane's concurrency overpaces when that concurrency is greater than 1. assign() funnels every re-placement through serializeAssignment (assignment-store.ts:698), so one director still completes only one per serviceMs regardless of how many drain leases are held; slotMs then tells deferred hosts to return faster than the lane can drain, which is the retry storm this PR removes. Defaults keep maxConcurrent at 1, so this only bites a configuration that raises both ORCA_RELAY_PUBLIC_ASSIGNMENT_CONCURRENCY and ORCA_RELAY_DRAIN_RETURN_CONCURRENCY.
Technical details
# slotMs divisor assumes parallel service
## Affected sites
- `cloud/apps/relay/src/drain-return-admission.ts:90` — `const slotMs = this.serviceMs / this.options.maxConcurrent`.
- `cloud/apps/relay/src/assignment-store.ts:698-701` — `assign()` serializes re-placements via `serializeAssignment`.
- `cloud/apps/relay/src/app.ts:169-172, 208` — `drainReturnConcurrency = min(cfg, publicAssignmentConcurrency - 1)` is reachable above 1.
## Required outcome
- Pacing should reflect one serialized re-placement per `serviceMs` per director, or the assumption that drain leases run in parallel should be made true and documented.
## Suggested approach (optional)
- Use `serviceMs` as the slot when the store serializes (divide by the effective parallelism, which is 1), or clamp `maxConcurrent` to 1 for the pacer while leaving admission concurrency configurable.| this.pendingAssignments.splice(index, 1) | ||
| this.queuedAssignmentHosts.delete(relayHostId) | ||
| resolve(this.reject('wait-timeout', notifyRejected)) | ||
| this.grantPendingDrainReturns() |
There was a problem hiding this comment.
This trigger was added to the placement timeout and reserved timeout, but the other place that shrinks pendingAssignments — cancelQueuedAssignment (called from acquireReserved) — was not updated. If queued placements were the only reason a drain return could not be granted, that drain return now waits out drainReturnWaitMs and gets a spurious wait-timeout deferral even though a permit is free.
Technical details
# cancelQueuedAssignment does not re-run the drain grant
## Affected sites
- `cloud/apps/relay/src/public-assignment-admission.ts:310-320` — `cancelQueuedAssignment` splices out a pending placement and resolves it, without calling `grantPendingDrainReturns()`.
- `cloud/apps/relay/src/public-assignment-admission.ts:165` — the placement-timeout counterpart that does call it.
## Required outcome
- After `pendingAssignments` shrinks via cancellation, a queued drain return that has become grantable should be granted rather than timed out.
## Suggested approach (optional)
- Call `this.grantPendingDrainReturns()` at the end of `cancelQueuedAssignment` (mirroring the timeout path).|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. 🧰 Additional context used📚 Code guidelines (1)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 (12)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review. 📝 WalkthroughWalkthroughThe relay can classify resolved assignments whose home cell has a current roll-isolation stamp and no open migration. Verified reconnects with this classification use a drain-return admission lane with configurable concurrency, queue, wait, and retry limits. Deferred requests receive a 503 response with Priority: ⬆️ High Merge Risk: ⚪ Minimal · up to The change separates drain-return assignment work and provides paced retry guidance while retaining existing reconnect verification. No concrete merge-blocking risk remains after normal checks. Security Architecture ReviewSecurity architecture risk: 🟡 Moderate · up to Separating rolled-host reconnects reduces contention, but their recovery now depends on the ordinary placement queue becoming empty. Sustained placement traffic can prolong a returning cohort’s outage. Authentication and overall concurrency limits remain in place. Retained concerns
Security review detailsSecurity Blast Radius
Security Findings and Attack Paths
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ 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 |

ELI5
When we roll a relay server, every desktop host on it gets disconnected and asks the relay's front desk (the director) for a new seat. The front desk had one small queue for "I was already connected" requests. A roll put about 2,500 hosts into that queue at once, so the queue overflowed. Those hosts were refused about 30,000 times over 7 minutes, and ordinary users whose connection had blipped were refused too. This PR gives hosts coming off a rolled server their own small queue. When that queue is full, the director tells each host exactly when to come back instead of letting it retry every 2 seconds.
What Changed
Before.
wait-timeoutwithRetry-After: 2and hammered the director until the cohort cleared.wait-timeout. Only 222 came from the placement lane. Re-placements ran at about 5.8 per second fleet-wide.After.
Classification. The reconnect verification read the sticky lane already does now also reads the host's home cell's admission row. It marks the host as a drain return when that cell is
migration-onlywith a roll stamp under 2 hours old, the host holds no migration lease, and it has no open migration row. That is the same rule the store uses to decide to re-place the host. It costs no extra query: aLEFT JOIN, plus a migration check that only runs when the stamp is set. Nothing the client sends affects it, and the request schema is unchanged and strict.Separate lane. A drain-return host gives back its sticky slot right after that read. It then waits in its own lane: 1 slot per director, a queue of 4 and a 3 second wait. The slot is borrowed from the placement lane's permits, and the lane never takes placement's last permit or goes ahead of a queued placement. So placement plus sticky still bounds the database pool of 3 per director, exactly as before.
Server-told return time. When the lane is full, the director answers 503 with a
Retry-Afterthat books the next free service slot on that director. The slot length is a moving average of the measured re-placement time, starting at the measured 860 ms. The value is at least 2 s and at most 300 s, the desktop's own cap.Metrics. Runtime metrics gain:
drainReturnAssignmentsDeltadrainReturnDeferralsDeltadrainReturnRejectionsByReasonDeltadrainReturnRetryAfterSecondsMaxdrainReturnRetryAfterSecondsSumRejection logs read
lane=drain-return ... retryAfter=N, and grants readassignment granted lane=drain-return.Unchanged.
/v1/resolve, which phones use, is untouched.resolve()without the new option, so their query is identical.Why
The bottleneck was never the database pool. Director pool waits stayed at 0 during c29. The real limit was one lane doing two jobs: cheap ordinary reconnects and expensive re-placements that serialize behind a fleet-wide lock. Splitting the lane gives ordinary reconnects their 30–50 ms service back. Telling deferred hosts a real return time cuts the retry storm. The test model predicts about 1 deferral per drained host, against about 13 today.
Alternatives considered:
serializeAssignment). Extra slots would only add NOWAIT lock retries against Cloud SQL (356 lock-unavailable per metrics interval during c29) and break the pool budget.Retry-After. This is deterministic and works across directors, but rolls drain with no grace period, so every deferred second is a second the host is offline. A host drained in the first minute whose hash lands late would wait up to 5 minutes even when the lane is idle at that point. The slot clock only adds the wait the lane actually needs, and stays bounded. Each director paces its own share of a load-balanced cohort, so the fleet paces at the fleet rate.Linked Issue
N/A. This is internal relay operations work.
Visual Proof
N/A. This is a director admission change with no UI.
Testing
Tests run.
pnpm typecheckfor the whole cloud workspace passes.vitest run: 824 passed and 149 Postgres cases skipped without a database.ORCA_RELAY_TEST_POSTGRES_URL: 974 passed, 1 skipped.New tests.
drain-return-admission.test.tscovers lane accounting, pacing, the cap, determinism, the moving average, the per-host interval and slot reuse. It also covers borrowing placement permits without taking placement's last permit or going ahead of a queued placement.public-assignment-drain-return-lane.test.tscovers the route.Retry-Afterand a log line.Retry-Afterassignment-isolated-cell-replacement.test.tsand its Postgres twin check classification on a real store. They cover the roll stamp, its expiry, restore, an unstamped park, a migration lease, an open migration with a lapsed lease, and the one-query cost.Rollout order.
publish, and note the image digest.image-digest. Setregional-placement-modeandregion-correction-cohort-percenttopreserve.No cell roll and no Terraform change is needed: the new settings have code defaults. Desktop clients already honour
Retry-Afteras a floor on the drain retry path.What to watch on the next roll's drain.
/v1/assignshould drop from about 5,000 per minute to roughly the drained-host rate.lane=drain-returnwithretryAfter=values, andlane=sticky reason=wait-timeoutshould be near 0.drainReturnDeferralsDeltaagainstdrainReturnAssignmentsDelta,stickyRejectionsByReasonDeltanear empty, anddatabasePoolWaitMsMaxstill low.AI Disclosure
Review
An adversarial review asked:
It found no spoofing path and no SQL issue. Its pool-budget, own-retry, open-migration and multi-director load-test findings are fixed in the second commit.
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
Retry-Afterretries on its own schedule. It lands in the drain lane and is deferred immediately when the lane is full, instead of holding a sticky slot for 2 s, so it is never worse than today./v1/resolve, which this change does not touch.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)