Skip to content

fix(orcad): refuse new terminals while an update stops the server (R32) - #29834

Merged
nwparker merged 3 commits into
mainfrom
nwparker/orcad-update-terminal-fence
Oct 21, 2026
Merged

nwparker merged 3 commits into
mainfrom
nwparker/orcad-update-terminal-fence

Conversation

@nwparker

@nwparker nwparker commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

To update a remote Orca server, the desktop counts the terminals running on it, then stops it. A terminal opened in the gap between that last count and the stop died with the stop, and nobody had counted it. Now the last count also tells the server to stop accepting new terminals until the stop happens, so nothing can start in that gap.

What Changed

Before: an SSH or WSL server update recounted terminals right before the stop (#30874), but nothing stopped a new terminal from starting after that recount. That terminal was killed by the update without warning.

After:

  • The update's last count closes the server's terminal admission first. It then waits for terminals that were already starting, and only then counts.
  • A new terminal opened in that window fails with "This server is restarting for an update. Try again in a moment." Retrying after the update works.
  • Reattaching to a terminal the server's daemon still runs is still allowed, for example after a window reload. It runs attach-only, so it can never quietly start a new process.
  • If the update leaves the old server running, the desktop reopens admission straight away. That covers three cases: the recount found terminals, the first write after the recount failed, or the stop was never sent. If the desktop disappears mid-update, the fence lapses by itself after 60 s.
  • If more than 45 s pass between the recount and the moment the stop would be sent (for example, a very slow SSH link), the desktop stops nothing, reopens admission and retries the update later. Otherwise the fence could lapse before the stop lands.

Mechanism:

  • orcad.terminalCensus takes a new optional closeAdmissionForMs (0 reopens) and returns admissionClosedUntil when asked.
  • The fence lives in TerminalUpdateAdmission (src/main/runtime/terminal/stop/terminal-update-admission.ts). It is enforced in the existing spawn lease, acquireWorktreeTerminalSpawn. Both spawn paths (renderer IPC and runtime RPC) already hold that lease across the provider spawn, so no separate spawn hook was added. Every lease counts as in flight until it is released, and the census waits up to 10 s for those leases. If they don't finish, the census answers unverifiable, the update defers, and admission reopens.
  • SSH (orcad-runtime-maintenance.ts) and WSL (wsl-orcad-incumbent.ts) build their counts with one shared helper, updateTerminalCounts. Only the last count is fenced; the first one comes before the upload, which can take minutes.
  • OrcadDeployOptions.releaseIncumbentAdmission is now required next to recountCensus, so every deploy caller has to say how its fence reopens.

Why

  • One fence, held from the last count through the stop. Counting and closing happen in one call, so there is no gap between them. The fence sits in the lease every spawn already takes, so neither spawn path can get around it. This replaces the earlier draft's separate wrapper around each spawn runner and its process-global state.
  • A timed fence rather than one held until a release arrives. A desktop that crashes or loses its connection can't lock users out for long.
  • Why not fence on the daemon side: the daemon's own idle-retirement fence is tied to its retirement state machine. It also can't see terminals that run inside orcad itself when the daemon is degraded.

Wire compatibility.

  • An older server ignores the unknown field and counts exactly as before. That host keeps today's behavior.
  • An older desktop never sends the field, so it never closes anything.
  • An older desktop, phone or CLI that tries to spawn while a newer host is mid-update gets an ordinary spawn error with a readable message. There is no new opcode, and the message doesn't look like a "daemon gone" error.

Supersedes: this rewrites the earlier version of this PR onto current main, keeping the same goal. It drops the unused capability string and reuses the existing spawn lease instead of a parallel mechanism. Its review findings are covered: the stuck test spawn, release on pre-stop failure, and release when no stop was sent.

Linked Issue

Risk R32 (SSH hardening list). No GitHub issue.

Visual Proof

N/A. The only visible change is a spawn error message during a few seconds of an update.

Testing

  • Repro on main: terminal-update-admission-census.test.ts drives the real runtime and the census RPC with the params the SSH and WSL updates send. Against origin/main, the spawn after the final census is admitted and the test fails. With this change it is refused.
  • New tests:
    • terminal-update-admission.test.ts: the fence lapses; a reattach is admitted attach-only; a failed lease is released; a spawn that never settles is reported.
    • The census handler answers unverifiable, with admission still closed, when a spawn never settles.
    • orcad-update-admission-fence.test.ts, on the fake-host harness:
      • a terminal opened between the recount and the stop is refused, and the stop goes ahead;
      • every recount deferral reopens admission (moved here from orcad-remote-deploy.test.ts);
      • a failed transaction write reopens it;
      • SIGNAL_FAILED reopens it, STILL_RUNNING keeps it closed.
    • The SSH maintenance and WSL incumbent tests check that only the last count is fenced, and how it is released.
  • Local runs:
    • 155 neighbouring test files pass (src/main/ssh/orcad-*, src/main/wsl/wsl-orcad*, src/main/managed-server, src/main/runtime/terminal/stop, spawn-lease runtime tests, pty launch parity).
    • pnpm tc passes.
    • The full static-analysis job was replayed locally on the final head, and every step passes, including the orcad boot-and-terminal smoke.
  • Live: not exercised on a real SSH host; the managed-orcad Docker lane in CI covers the deployed path.
  • Codex:
    • Round 1 found two issues, both fixed: a fence-exempt reattach could fall back to a fresh spawn, and admission stayed closed after a stop that was never sent.
    • Round 2 was clean.
    • Round 3, after the rebase, found that the fence could lapse before a slow stop was sent. Fixed with the 45 s deadline above.
    • Round 4 was clean.
  • Independent review: no P0–P2 findings.

Design check

This needed more than three review rounds, so the design was compared with how other remote-server products handle restarting while sessions are active. They follow the same pattern: the host that executes the work counts active consumers and refuses new ones while it shuts down. They don't kill sessions blindly or rely on a client-side count. Orca's version is one gate held from the final recount through the stop, and it sits in the existing spawn lease rather than a new hook. The approach is unchanged; the round-3 fix only bounds how long the desktop may rely on the gate.

  • Automated tests added/updated

Notes

Residuals:

  • An older server can't fence, so its last count behaves as before.
  • After a stop that may still land (still-running / unconfirmed), admission stays closed until it lapses, at most 60 s.
  • Rollback and restart flows also count and then stop. They could adopt the same param later.

@coderabbitai

coderabbitai Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough

The changes add a process-wide terminal admission fence and track in-flight PTY spawns. Census requests can close admission while existing spawns settle, and the census response includes fence information. PTY spawn paths enforce admission while allowing confirmed live-session reattachments. SSH and WSL update flows use fenced incumbent recounts and can release incumbent admission.

Priority: ➖ Normal

Merge Risk: 🔵 Low · up to ea991

A failed update can temporarily refuse new terminals, and the SSH recount fallback needs confirmation for older servers. Address these bounded risks before merging or accept them explicitly.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 24 functions across 19 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 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 identifies the main change: refusing new terminals while an update stops the server.
Description check Passed The description is detailed and covers ELI5, changes, rationale, testing, compatibility, visual proof, and residual risks. It is mostly complete. The Linked Issue section names Risk R32 but does not p…
Full details: Description check

Explanation

The description is detailed and covers ELI5, changes, rationale, testing, compatibility, visual proof, and residual risks. It is mostly complete. The Linked Issue section names Risk R32 but does not provide an actual issue link, and several template checklist sections are omitted.

✨ Finishing Touches: 💡 2
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks: 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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: 3


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ecb1d3c8-4454-4207-9ebb-4e2a75fa4b87
📥 Commits

Reviewing files that changed from the base of the PR and between 95d41af and ea99104.

📒 Files selected for processing: 19
  • src/main/ipc/pty/host-env/spawn-cwd-update-fence.test.ts
  • src/main/ipc/pty/host-env/spawn-cwd.ts
  • src/main/ipc/pty/ipc/spawn-run.ts
  • src/main/ipc/pty/runtime/spawn.ts
  • src/main/runtime/rpc/methods/orcad-terminal-census.test.ts
  • src/main/runtime/rpc/methods/orcad-terminal-census.ts
  • src/main/runtime/terminal-admission-fence.ts
  • src/main/ssh/orcad-installed-activation.ts
  • src/main/ssh/orcad-remote-deploy.test.ts
  • src/main/ssh/orcad-remote-deploy.ts
  • src/main/ssh/orcad-runtime-maintenance.ts
  • src/main/ssh/orcad-terminal-census-client.ts
  • src/main/ssh/orcad-update-admission-fence.test.ts
  • src/main/ssh/orcad-update-admission-fence.ts
  • src/main/wsl/wsl-orcad-deploy.ts
  • src/main/wsl/wsl-orcad-incumbent.test.ts
  • src/main/wsl/wsl-orcad-incumbent.ts
  • src/shared/orcad-runtime-capabilities.ts
  • src/shared/orcad-terminal-census.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

Comment on lines +90 to +104
it('answers unverifiable, still fenced, when an admitted spawn never settles', async () => {
vi.useFakeTimers()
const stuck = runAdmittedTerminalSpawn(
() => {},
() => new Promise<void>(() => {})
)
void stuck
const census = call({ closeAdmissionForMs: 60_000 }, 0).result
await vi.advanceTimersByTimeAsync(10_001)
await expect(census).resolves.toMatchObject({
liveSessions: null,
admissionClosedUntil: expect.any(Number)
})
expect(collect).not.toHaveBeenCalled()
})

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,125p' src/main/runtime/rpc/methods/orcad-terminal-census.test.ts
sed -n '20,75p' src/main/runtime/terminal-admission-fence.ts

Repository: stablyai/orca

Length of output: 6157


Reset the stuck admitted spawn in this test so later fenced census tests are not affected.

The stuck spawn never settles, so spawnsInFlight stays at 1 for the rest of the module. A later census test that requests the admission fence would wait the full 10 s drain timeout. The current test order does not hit this, but a future fenced test can fail or time out. Hold the spawn's resolver, release it, and await the spawn in a finally block.

Proposed fix
--- "a/src/main/runtime/rpc/methods/orcad-terminal-census.test.ts"
+++ "b/src/main/runtime/rpc/methods/orcad-terminal-census.test.ts"
@@ -87,21 +87,26 @@
     await expect(census).resolves.toMatchObject({ liveSessions: 1 })
   })
 
   it('answers unverifiable, still fenced, when an admitted spawn never settles', async () => {
     vi.useFakeTimers()
+    let release: () => void = () => {}
     const stuck = runAdmittedTerminalSpawn(
       () => {},
-      () => new Promise<void>(() => {})
+      () => new Promise<void>((resolve) => (release = resolve))
     )
-    void stuck
-    const census = call({ closeAdmissionForMs: 60_000 }, 0).result
-    await vi.advanceTimersByTimeAsync(10_001)
-    await expect(census).resolves.toMatchObject({
-      liveSessions: null,
-      admissionClosedUntil: expect.any(Number)
-    })
-    expect(collect).not.toHaveBeenCalled()
+    try {
+      const census = call({ closeAdmissionForMs: 60_000 }, 0).result
+      await vi.advanceTimersByTimeAsync(10_001)
+      await expect(census).resolves.toMatchObject({
+        liveSessions: null,
+        admissionClosedUntil: expect.any(Number)
+      })
+      expect(collect).not.toHaveBeenCalled()
+    } finally {
+      release()
+      await stuck
+    }
   })
 
   it('still counts terminals it may not close, and closes nothing for a plain census', async () => {
     collect.mockResolvedValue({ ...idle, liveSessions: 2 })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it('answers unverifiable, still fenced, when an admitted spawn never settles', async () => {
vi.useFakeTimers()
const stuck = runAdmittedTerminalSpawn(
() => {},
() => new Promise<void>(() => {})
)
void stuck
const census = call({ closeAdmissionForMs: 60_000 }, 0).result
await vi.advanceTimersByTimeAsync(10_001)
await expect(census).resolves.toMatchObject({
liveSessions: null,
admissionClosedUntil: expect.any(Number)
})
expect(collect).not.toHaveBeenCalled()
})
it('answers unverifiable, still fenced, when an admitted spawn never settles', async () => {
vi.useFakeTimers()
let release: () => void = () => {}
const stuck = runAdmittedTerminalSpawn(
() => {},
() => new Promise<void>((resolve) => (release = resolve))
)
try {
const census = call({ closeAdmissionForMs: 60_000 }, 0).result
await vi.advanceTimersByTimeAsync(10_001)
await expect(census).resolves.toMatchObject({
liveSessions: null,
admissionClosedUntil: expect.any(Number)
})
expect(collect).not.toHaveBeenCalled()
} finally {
release()
await stuck
}
})


const unstopped = incumbent ? await stopTransactionIncumbent(options, incumbent, lock) : null
if (unstopped) {
await reopenIncumbentAdmission(options)

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Reopen admission when a pre-stop step fails.

After a fenced recount permits activation, writeOrcadActivationTransaction can throw before the incumbent stop begins. The incumbent then remains running, but neither release branch runs. New terminal spawns remain refused until the fence expires. Cover the pre-stop error path with best-effort admission release before propagating the error.

Comment on lines +39 to +41
return recount.liveSessions === null && recount.admissionClosedUntil === undefined
? preUploadCensus
: recount

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Keep the pre-upload census when the server does not confirm a fence.

If an older server ignores closeAdmissionForMs, it can return a non-null liveSessions count without admissionClosedUntil. This condition accepts that unfenced recount. An SSH update can then defer on a count that the stated fallback says to ignore. Fall back whenever the marker is absent, and update the successful-recount test to include a fence marker.

nwparker added a commit that referenced this pull request Oct 18, 2026
…y code into src/main/managed-server/install/ (#30335)

orcad-remote-*, remote-install-*, remote-node-runtime-store-*, remote-versioned-install and
remote-deploy-timing leave src/main/ssh. git mv plus import and path-literal rewrites; one e2e route
regex learns the new folder. orcad-remote-deploy and orcad-remote-node-runtime-report stay for now
because open PRs #29834 and #29829 edit them.
nwparker added a commit that referenced this pull request Oct 18, 2026
…c/main/managed-server/lifecycle/ (#30343)

orcad-managed-*, orcad-runtime-*, orcad-stdio-bridge-*, orcad-decommission-* and orcad-rollback-*
leave src/main/ssh. git mv plus import and path-literal rewrites; two e2e route regexes learn the
new folder. orcad-runtime-maintenance stays for now because open #29834 edits it.
@nwparker
nwparker force-pushed the nwparker/orcad-update-terminal-fence branch from ea99104 to 6b9d4e0 Compare October 20, 2026 21:40
…the stop

The last census before an SSH or WSL update stops the server now closes the
server's terminal admission first. Every spawn lease (acquireWorktreeTerminalSpawn,
which both spawn paths hold across the provider spawn) passes the fence, the
census waits for leases taken before the close, and an update that leaves the
incumbent serving reopens it. A reattach to a session the daemon still runs is
still admitted.
@nwparker
nwparker force-pushed the nwparker/orcad-update-terminal-fence branch from 6b9d4e0 to 57a8f95 Compare October 21, 2026 01:21
@nwparker
nwparker merged commit d1ed73b into main Oct 21, 2026
65 checks passed
brennanb2025 added a commit that referenced this pull request Oct 21, 2026
Main's #29834 terminal-admission fence and this PR's restart reservation are kept side by side
(three-model panel, unanimous): a capable host ends itself through reserve/commit with no fenced
recount; an explicit Force of a host older than restart admission recounts with the fence,
reopens it after every abandoned attempt and when no stop was sent, and keeps main's 45s stop
deadline.
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