Repository navigation
feat(relay): pace the drain send during a same-cap cell roll - #21284
Conversation
A same-cap roll drains a cell with graceMs 0, which sends `drain` to all ~800 controls in one pass. Every desktop re-dials on receipt regardless of graceMs, so the whole cell reconnects inside a second. On 2026-09-16 that stampede hit a Cloud SQL stall: attaches timed out, each leaving 10 minutes of late-arrival debt on connection headroom, and placement answered relay_capacity_exhausted fleet-wide for ~13 minutes. Spreading the sends spreads the re-dials. `HostSessionRegistry.drain` takes an optional pacing window and schedules each session's send evenly across it; admission is fenced for every session up front, and each host keeps its own full grace after its own send. /v1/admin/drain accepts `paceWindowMs` (<= 5 min) and echoes what it applied. The same-cap job asks for 120 s, and the drain-completion wait grew by the same amount. A cell still on an older image rejects the field, so the deploy script falls back to an unpaced drain rather than failing the roll.
|
This run was cancelled 🛑 The workflow was cancelled before completion. Please check the link below for details. |
|
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 (3)
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review. 📝 WalkthroughWalkthroughThe relay drain API now accepts a validated pacing window up to five minutes. The session registry schedules drain messages across that window and cancels stale queued sends when a later drain starts. The production canary parses the pacing option, reports the applied value, and falls back to an unpaced request on a Priority: ➖ Normal Merge Risk: 🔵 Low · up to This round's changes correctly scope per-host drain admission fencing to hosts that have actually received their drain message, fixing the earlier problem where phones on not-yet-drained hosts could be rejected throughout the whole pacing window, and drain timers are properly cleared and unreferenced on supersession. One narrow, previously reported issue remains open: an empty pace-window CLI argument can silently disable pacing instead of being rejected, which is a low-impact operator-facing edge case rather than a merge-blocking defect. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description clearly explains the change, motivation, implementation, compatibility behavior, testing, and operational impact. However, the required Linked Issue section is incomplete because it contains only
✨ 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: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 6c66e8f5-57dc-40b0-8ade-0fea6fb41ab6
📒 Files selected for processing (9)
.github/workflows/cloud-deploy-relay-production-same-cap-job.ymlcloud/apps/relay/src/app.tscloud/apps/relay/src/host-session-registry.test.tscloud/apps/relay/src/host-session-registry.tscloud/apps/relay/src/regional-host-drain-app.test.tscloud/apps/relay/src/relay-server.tscloud/dev/scripts/prepare-relay-production-capacity-canary.mjscloud/dev/scripts/prepare-relay-production-capacity-canary.test.mjscloud/dev/scripts/relay-same-cap-script-census.test.mjs
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| : Number(values['pace-window-ms']) | ||
| if ( | ||
| !Number.isSafeInteger(paceWindowMs) || | ||
| paceWindowMs < 0 || | ||
| paceWindowMs > MAX_PACE_WINDOW_MS | ||
| ) { | ||
| throw new Error('--pace-window-ms must be an integer between 0 and 300000') |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
sed -n '1,155p' cloud/dev/scripts/prepare-relay-production-capacity-canary.mjs
rg -n -- '--pace-window-ms|Number\(values\[|safe integer|trim\(' cloud/dev/scripts cloud/dev/scripts/prepare-relay-production-capacity-canary.test.mjs
sed -n '210,255p' cloud/dev/scripts/prepare-relay-production-capacity-canary.test.mjsRepository: stablyai/orca
Length of output: 13777
Reject empty pace window arguments.
parseProductionCapacityCellArguments passes the supplied string directly to Number(). Number('') and Number(' ') both produce 0, so a quoted empty or whitespace-only --pace-window-ms value passes validation and disables pacing. Reject these raw values before conversion.
Proposed fix
- const paceWindowMs = values['pace-window-ms'] === undefined
+ const rawPaceWindowMs = values['pace-window-ms']
+ const paceWindowMs = rawPaceWindowMs === undefined
? 0
- : Number(values['pace-window-ms'])
+ : Number(rawPaceWindowMs)
if (
+ (rawPaceWindowMs !== undefined && !/^\d+$/.test(rawPaceWindowMs)) ||
!Number.isSafeInteger(paceWindowMs) ||
paceWindowMs < 0 ||Review of the paced drain found two problems, both from treating "this cell is draining" as one instant when pacing makes it a window. Timers: the sends queued by a paced drain were neither cleared when a later drain superseded them nor unref'd. A SIGTERM mid-window left up to 800 no-op timers holding the event loop open until systemd escalated to SIGKILL. Drain timers are now tracked, cleared on the next drain, and unref'd, so a retry re-arms a session's teardown instead of stacking a second one. Phones: the client fence read the global draining flag, so every phone was refused for the whole window even though its own host had not been told yet and was still serving. The director keeps pointing phones at this cell until their host moves, so they would have looped for up to two minutes. A session is now fenced when its drain is sent, not when the drain starts, and the client paths key off that. New control connections and re-attaches stay fenced globally: nothing new should land on a cell that is going away.
…i#21284) * feat(relay): pace the drain send during a same-cap cell roll A same-cap roll drains a cell with graceMs 0, which sends `drain` to all ~800 controls in one pass. Every desktop re-dials on receipt regardless of graceMs, so the whole cell reconnects inside a second. On 2026-09-16 that stampede hit a Cloud SQL stall: attaches timed out, each leaving 10 minutes of late-arrival debt on connection headroom, and placement answered relay_capacity_exhausted fleet-wide for ~13 minutes. Spreading the sends spreads the re-dials. `HostSessionRegistry.drain` takes an optional pacing window and schedules each session's send evenly across it; admission is fenced for every session up front, and each host keeps its own full grace after its own send. /v1/admin/drain accepts `paceWindowMs` (<= 5 min) and echoes what it applied. The same-cap job asks for 120 s, and the drain-completion wait grew by the same amount. A cell still on an older image rejects the field, so the deploy script falls back to an unpaced drain rather than failing the roll. * fix(relay): scope the drain fence to the hosts already told Review of the paced drain found two problems, both from treating "this cell is draining" as one instant when pacing makes it a window. Timers: the sends queued by a paced drain were neither cleared when a later drain superseded them nor unref'd. A SIGTERM mid-window left up to 800 no-op timers holding the event loop open until systemd escalated to SIGKILL. Drain timers are now tracked, cleared on the next drain, and unref'd, so a retry re-arms a session's teardown instead of stacking a second one. Phones: the client fence read the global draining flag, so every phone was refused for the whole window even though its own host had not been told yet and was still serving. The director keeps pointing phones at this cell until their host moves, so they would have looped for up to two minutes. A session is now fenced when its drain is sent, not when the drain starts, and the client paths key off that. New control connections and re-attaches stay fenced globally: nothing new should land on a cell that is going away.

ELI5
When we roll a new image onto one Relay cell, we first tell every desktop on that
cell to go find a new home. Today we tell all ~800 of them in the same instant, so
they all come knocking at once. Now we tell them one at a time over two minutes, so
the knocking is spread out and the front door stays open.
What Changed
Before. The rollout drains a cell with
graceMs: 0. The cell walks its sessionmap and sends
drainto every control in one pass. The desktop re-dials the directorthe moment it reads that frame, whatever
graceMssays, so a whole cell reconnectsinside about a second.
On 2026-09-16 at 19:24Z that landed on cell c7 (~700 hosts) during a Cloud SQL stall.
Many hosts could not finish attaching before their reservation timed out, and each
timeout parks ten minutes of late-arrival debt against connection headroom. Placement
ran out of headroom and answered every request with
relay_capacity_exhaustedforabout thirteen minutes. One desktop had no home for eighteen minutes.
After. The drain send is paced. Three pieces:
HostSessionRegistry.draintakes an optional pacing window and schedules eachsession's send evenly across it. A host is fenced when its own drain is sent, not
when the drain starts, so a host that has not been told yet keeps serving its phones
normally instead of refusing them for the whole window. Each host gets its full grace
measured from its own send. New control connections and re-attaches are refused for
the whole cell from the first call, because nothing new should land on a cell that is
going away. A later drain (shutdown, or a human emergency drain) clears the sends
still queued by a paced one, and every drain timer is unref'd so a window in flight
can never hold the process open past a shutdown.
/v1/admin/drainaccepts an optionalpaceWindowMs, capped at five minutes, andechoes back the window it applied.
for a cell of 800. The director's assign limit is 5 x 80 = 400 in flight, and the
observed p99 during the unpaced c7 drain was 79.75. The job's drain-completion wait
grew from 900000 ms to 1020000 ms, exactly the pacing window, so a paced drain
cannot turn into a wait timeout.
Cells update independently of the rollout scripts, so a cell still running an older
image rejects the unknown
paceWindowMsfield outright. The deploy script treats a400 on the paced attempt as "this cell does not know about pacing", retries the drain
unpaced, and reports
paceWindowMs: 0. Any other status still fails the roll.Why
Pacing the send is the only lever that works on desktops already in the field.
graceMslooks like the natural knob but only delays the socket close; the desktophas already re-dialed by then, so raising it changes nothing about the stampede and
just keeps doomed sockets open longer.
The alternative considered was suppressing late-arrival debt for re-dials caused by a
drain. That debt is what reserves headroom for a host that has not arrived yet, so
dropping it would make the accounting undercount real in-flight attaches, and telling
a drain-driven re-dial apart from any other one means threading a reason through the
assign path. Left as follow-up; see below.
Not in scope, deliberately: running several cells of a batch in parallel. Each cell
job asserts an exact selector generation derived from its predecessors, and all cells
share one Terraform state lock, so that is a rewrite rather than a flag.
Follow-up worth its own change: when a host is placed on a different cell, retire the
late-arrival debt it left on the previous one. The host is demonstrably elsewhere and
cannot arrive at the old reservation, so holding that headroom for ten minutes is pure
loss. It needs care around a host that is still mid-attach on the old cell.
Linked Issue
Fixes #
Visual Proof
N/A. This is server-side rollout behavior with no user interface; the only thing a
user sees is that a rollout stops making them homeless.
Testing
Automated, all local:
cloud/apps/relay: 65 files, 679 tests pass, 21 Postgres files skipped (no databaselocally). New coverage for pacing under fake timers: unpaced sends stay in one pass,
paced sends land evenly across the window, admission is fenced before the first
paced send, each host's grace runs from its own send, and an emergency drain cancels
the queued paced sends.
cloud: full suite, 606 script tests pass. New coverage for the route (pass-through,echo, the cap itself, negative/fractional/over-cap rejection, unauthenticated), the
deploy script (paced body, fallback on 400, failure on any other status, argument
validation), and a census check that the job passes the window and that its
completion wait outlasts it.
cloud:pnpm typecheckclean.actionlinton the changed workflow: one pre-existing finding, the customblacksmith-2vcpu-ubuntu-2204runner label, unchanged by this PR.No manual production exercise. The pacing only takes effect once a cell runs an image
built from this commit; until then every cell falls back to the drain it does today.
AI Disclosure
Review
Agent skill upstream boundary
Notes
Backwards compatibility is the main risk and is handled in both directions. A new cell
still accepts a drain with no
paceWindowMsand behaves exactly as today, which iswhat the shutdown path and every other drain caller send. An old cell rejects the new
field and the script falls back. No desktop change, no mobile surface, no SSH surface.
Performance is the point of the change: the paced path adds one timer per session for
the length of the window, and none at all when the window is zero.
Checklist
N/Awith reasonpnpm typecheckandpnpm testpass locally incloud