Skip to content

feat(relay): pace the drain send during a same-cap cell roll - #21284

Merged
Jinwoo-H merged 2 commits into
mainfrom
relay-paced-cell-drain
Sep 17, 2026
Merged

Jinwoo-H merged 2 commits into
mainfrom
relay-paced-cell-drain

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​349 $\color{#cf222e}{\Huge{\mathbf{−}}}$​11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​338
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​113 $\color{#cf222e}{\Huge{\mathbf{−}}}$​32 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​81

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 session
map and sends drain to every control in one pass. The desktop re-dials the director
the moment it reads that frame, whatever graceMs says, so a whole cell reconnects
inside 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_exhausted for
about thirteen minutes. One desktop had no home for eighteen minutes.

After. The drain send is paced. Three pieces:

  • HostSessionRegistry.drain takes an optional pacing window and schedules each
    session'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/drain accepts an optional paceWindowMs, capped at five minutes, and
    echoes back the window it applied.
  • The same-cap rollout job asks for 120000 ms, which is about seven re-dials a second
    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 paceWindowMs field outright. The deploy script treats a
400 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.
graceMs looks like the natural knob but only delays the socket close; the desktop
has 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 database
    locally). 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 typecheck clean.
  • actionlint on the changed workflow: one pre-existing finding, the custom
    blacksmith-2vcpu-ubuntu-2204 runner 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.

  • Automated tests added/updated, or explained why not below

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable.

Notes

Backwards compatibility is the main risk and is handled in both directions. A new cell
still accepts a drain with no paceWindowMs and behaves exactly as today, which is
what 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

  • This PR is small and focused
  • I explained what changed and why
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm typecheck and pnpm test pass locally in cloud

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

pullfrog Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

This run was cancelled 🛑

The workflow was cancelled before completion. Please check the link below for details.

Pullfrog  | View workflow run | via Pullfrog | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 76941ab0-89ba-4609-a710-9a080fad93df

📥 Commits

Reviewing files that changed from the base of the PR and between 13b2ea1 and 04cab64.

📒 Files selected for processing (3)
  • cloud/apps/relay/src/host-session-client-accept.test.ts
  • cloud/apps/relay/src/host-session-registry.test.ts
  • cloud/apps/relay/src/host-session-registry.ts

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


📝 Walkthrough

Walkthrough

The 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 400 response. The same-cap workflow configures a 120-second window and extends verification timeouts. Tests cover validation, pacing, admission fencing, supersession, fallback, and workflow arguments.

Priority: ➖ Normal

Merge Risk: 🔵 Low · up to 04cab

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 9 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description clearly explains the change, motivation, implementation, compatibility behavior, testing, and operational impact. However, the required Linked Issue section is incomplete because it co… Replace Fixes # with the actual linked issue number. Complete the AI Disclosure section when applicable, add any required Review information, and state whether pnpm lint and pnpm build passed or are covered by CI.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and concisely describes the main change: pacing Relay drain sends during same-cap cell rollouts.
Full details: Description check

Explanation

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 Fixes #; the AI Disclosure and Review sections are also empty, and the checklist does not state the status of pnpm lint or pnpm build.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 6c66e8f5-57dc-40b0-8ade-0fea6fb41ab6

📥 Commits

Reviewing files that changed from the base of the PR and between 9de6f2c and 13b2ea1.

📒 Files selected for processing (9)
  • .github/workflows/cloud-deploy-relay-production-same-cap-job.yml
  • cloud/apps/relay/src/app.ts
  • cloud/apps/relay/src/host-session-registry.test.ts
  • cloud/apps/relay/src/host-session-registry.ts
  • cloud/apps/relay/src/regional-host-drain-app.test.ts
  • cloud/apps/relay/src/relay-server.ts
  • cloud/dev/scripts/prepare-relay-production-capacity-canary.mjs
  • cloud/dev/scripts/prepare-relay-production-capacity-canary.test.mjs
  • cloud/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.

Comment on lines +72 to +78
: 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')

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.

🎯 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.mjs

Repository: 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.
@Jinwoo-H
Jinwoo-H merged commit 0e7948f into main Sep 17, 2026
24 checks passed
@Jinwoo-H
Jinwoo-H deleted the relay-paced-cell-drain branch September 17, 2026 20:45
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…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.
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