Skip to content

fix(daemon): validate spawn cwd asynchronously so one dead share cannot freeze every terminal - #14848

Merged
nwparker merged 2 commits into
mainfrom
nwparker/sta-4470-async-cwd-validation
Aug 16, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/sta-4470-async-cwd-validation

Conversation

@nwparker

@nwparker nwparker commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 13 +456 −253 +203
Prod 6 +95 −13 +82

Closes STA-4470.

Problem

createOrAttach validated the working directory synchronously on the daemon's shared event loop. On Windows 11, existsSync against an unreachable UNC share blocked for about 21 seconds; a cold wsl.exe probe took about 1.3 seconds. One dead workspace could therefore stall every terminal RPC and push unrelated creates past the client's 30-second request ceiling.

Change

  • Validate daemon spawn cwd asynchronously, using one stat instead of exists followed by stat.
  • Deduplicate only byte-identical in-flight cwd probes; case- or Unicode-distinct filesystem paths remain independent.
  • Serialize creates per session id while preserving parallel creates for distinct sessions.
  • Carry request-scoped cancellation through validation, native spawn, publication, disconnect, kill, timeout, and shutdown.
  • If cancellation arrives after publication, consume the committed create response instead of dropping ownership. If cancellation settlement itself fails, use the existing generation-fenced disconnect cleanup.
  • Bump the daemon protocol to v35 so fresh sessions use the new lifecycle while preserved v34 sessions remain attachable.

The affected tab may still wait for the filesystem's accurate answer. The fix removes daemon-wide head-of-line blocking without guessing that a slow VPN mount is missing.

Reliability contract

  • Invariant (daemon-pty.spawn-admission-cleanup): a slow cwd probe cannot block unrelated daemon RPCs, and no canceled, disconnected, timed-out, or shutdown-fenced create can publish an unowned PTY.
  • Failure source: STA-4470 plus the async lifecycle races found while reviewing this PR.
  • Oracle: event-loop progress during cwd validation; same-id/different-id controlled spawn gates; request-scoped abort/timeout/kill/disconnect/shutdown tests; delayed post-publication response harness; v34-owner/v35-fresh routing tests.
  • Gate: deterministic Vitest coverage in working-directory-validation.test.ts, terminal-host-concurrent-create.test.ts, daemon-server-async-spawn-cancellation.test.ts, and daemon-client-rpc-request.test.ts. The absence of a dedicated STA-4470 entry in reliability-gates.jsonc is an accepted residual gap for this PR.
  • Provider/platform coverage: daemon/local lifecycle is covered deterministically; WSL UNC yes/no/inconclusive and byte-distinct paths are covered; existing POSIX semantics remain covered. SSH/relay, folder workspaces, and mobile-facing protocols are unchanged. Preserved v34 owners and fresh v35 routing are covered.
  • Performance budget: distinct cwd probes remain parallel; identical probes share one promise; no polling, retry loop, subprocess fanout, listener, timer, or unbounded cache was added. Validation entries are removed on both resolve and reject.
  • Diagnostics: existing daemon request/session logs retain the session id and cancellation/attach errors; focused tests expose ownership and pending-request counts.

Verification

  • pnpm run typecheck
  • pnpm lint (including reliability manifest and max-lines ratchet)
  • 1,530 daemon/provider/cross-version tests passed; 3 skipped
  • Full repository run: 52,946 passed, 119 skipped
  • A later full run after the final cancellation-settlement hardening completed with one unrelated worktree-base-directory-poller.test.ts timeout under parallel load; that exact 23-test file passed three consecutive isolated runs
  • Independent final release review: CLEAN, no P0/P1/P2 findings
  • Real in-memory delayed-response boundary: sessions=1, preparations=0, canceled=false, original create resolved, tracked sessions remained 1, pending requests returned to 0

Residual gaps

  • No physical dead-UNC or WSL-host end-to-end run was available locally.
  • Live native Windows/Linux PTY, live SSH/relay/folder-workspace, simultaneous real v34/v35 daemon, and mobile journeys remain environment-dependent; Windows and packaging CI are required before merge.
  • No dependency, lockfile, mobile/E2EE surface, runtime stream opcode, persisted user state, schema, or Git/provider behavior changed.

…ot freeze every terminal

createOrAttach validated the working directory synchronously on the daemon's
only thread. Measured on Windows 11 + Ubuntu-24.04:

  existsSync on an unreachable UNC share   21,022 ms
  wsl.exe probe, cold distro                1,266 ms
  wsl.exe probe, warm distro                   59 ms
  existsSync/statSync on healthy \\wsl.localhost  4 ms / 1 ms

A single unreachable share therefore blocks the whole RPC loop past the
client's 30s request ceiling, so every other terminal stalls behind it and
reports `DaemonProtocolError: Request createOrAttach timed out after 30000ms`.
The main process already validates asynchronously and passes prevalidatedCwd
(ipc/pty.ts); the daemon never got the same treatment.

Add validateWorkingDirectoryAsync (one stat, not exists-then-stat, so an
unreachable share is not paid for twice) and await it from the daemon spawn
preflights. spawnSubprocess now returns SubprocessHandle | Promise<...>, which
existing sync stubs still satisfy.

Deliberately not bounding the stat with a timeout: the 30s ceiling comes from
blocking the shared loop, not from the duration. A timeout cannot tell "slow
share" from "gone share", so it would fail spawns that succeed today at 3-8s
on a cold VPN mount, and trade an accurate "working directory does not exist"
for a guess.

The new await opened a race: it sits between the "already exists?" check and
the sessions.set that publishes the session, so two concurrent creates for one
session id both spawned. Gate creation per session id; distinct ids still spawn
in parallel.

STA-4470
@coderabbitai

coderabbitai Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

PTY working-directory validation now uses asynchronous filesystem and WSL checks. PTY preflight and creation return promises. Terminal session creation accepts asynchronous subprocess handles and serializes concurrent creation attempts for the same session ID. Daemon RPC requests now support abort signals, request-scoped cancellation, bounded cancellation, and cleanup. PTY, daemon, terminal session, protocol, and end-to-end tests cover asynchronous creation, cancellation, concurrency, and protocol version 35.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.32% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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 summarizes the main change: asynchronous spawn cwd validation to prevent daemon-wide terminal stalls.
Description check ✅ Passed The description clearly explains the problem, changes, rationale, linked issue, reliability contract, testing, and residual gaps.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

🧹 Nitpick comments (1)
src/main/providers/local-pty-utils.ts (1)

153-163: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten this rationale comment.

Keep the durable reason in one brief comment. Move measurements and incident detail to PR or issue documentation.

As per coding guidelines, comments must be concise, non-obvious, and brief; prefer one line.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4cf45caa-b089-4104-a80c-02bd773114a8

📥 Commits

Reviewing files that changed from the base of the PR and between 8b04e06 and c06d16a.

📒 Files selected for processing (19)
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/pty-subprocess-env-inheritance.test.ts
  • src/main/daemon/pty-subprocess-foreground-degraded-scan.test.ts
  • src/main/daemon/pty-subprocess-foreground-identity.test.ts
  • src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts
  • src/main/daemon/pty-subprocess-git-credential-guard.test.ts
  • src/main/daemon/pty-subprocess-handle-lifecycle.test.ts
  • src/main/daemon/pty-subprocess-managed-agent-env.test.ts
  • src/main/daemon/pty-subprocess-windows-shell-launch.test.ts
  • src/main/daemon/pty-subprocess-wsl-launch.test.ts
  • src/main/daemon/pty-subprocess.test.ts
  • src/main/daemon/pty-subprocess.ts
  • src/main/daemon/repro-13767-shell-ready-marker-lost-to-exec.test.ts
  • src/main/daemon/terminal-host-concurrent-create.test.ts
  • src/main/daemon/terminal-host-options.ts
  • src/main/daemon/terminal-host-session-create.ts
  • src/main/daemon/terminal-host.ts
  • src/main/providers/local-pty-utils.ts
  • src/main/providers/working-directory-validation.test.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 1 remains after this review.

Comment on lines +94 to +115
let settleCreation: () => void = () => {}
deps.pendingCreations.set(
opts.sessionId,
new Promise<void>((resolve) => {
settleCreation = resolve
})
)
try {
return await spawnAndPublishSession(opts, deps, { size, wslDistro })
} finally {
deps.pendingCreations.delete(opts.sessionId)
settleCreation()
}
}

async function spawnAndPublishSession(
opts: InternalCreateOrAttachOptions,
deps: TerminalHostSessionCreateDependencies,
ctx: { size: { cols: number; rows: number }; wslDistro: string | undefined }
): Promise<CreateOrAttachResult> {
const { size, wslDistro } = ctx
const subprocess = await deps.spawnSubprocess({

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 | 🟠 Major | 🏗️ Heavy lift

Stop in-flight creation during shutdown.

creationFenced is captured before await deps.spawnSubprocess(...). If shutdown starts during that await, this flow can still publish a new Session after disposeSessions() has completed. That PTY is not included in shutdown cleanup.

Pass a live fence predicate. Recheck it after spawning. If shutdown started, terminate and dispose the handle before sessions.set. Make shutdown wait for pending creations to settle.

@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

🧹 Nitpick comments (1)
src/main/daemon/terminal-host-concurrent-create.test.ts (1)

128-145: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Pre-attach a rejection handler to spawnGate.

rejectSpawn() on Line 145 runs in the same synchronous block as the two createOrAttach calls. At that moment the mock has not yet reached await spawnGate, so the rejected promise has no handler. Node checks for unhandled rejections after the microtask queue drains, and the handler attaches during that drain, so the test passes today. If the path from createOrAttach to deps.spawnSubprocess ever gains a macrotask boundary, this becomes an unhandled rejection and can fail the suite.

♻️ Proposed hardening
     const spawnGate = new Promise<void>((_resolve, reject) => {
       rejectSpawn = () => reject(new Error('spawn failed'))
     })
+    // Keep the gate handled before the mock awaits it.
+    spawnGate.catch(() => {})

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 481cbe47-f732-4f4a-8a09-352e1684868d

📥 Commits

Reviewing files that changed from the base of the PR and between c06d16a and 42b25c3.

📒 Files selected for processing (26)
  • src/main/daemon/client.ts
  • src/main/daemon/daemon-client-rpc-request.test.ts
  • src/main/daemon/daemon-client-rpc-request.ts
  • src/main/daemon/daemon-foreground-confirmation-protocol.test.ts
  • src/main/daemon/daemon-protocol-version.test.ts
  • src/main/daemon/daemon-protocol-version.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-pty-router.test.ts
  • src/main/daemon/daemon-server-async-spawn-cancellation.test.ts
  • src/main/daemon/daemon-server.test.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/pty-subprocess.test.ts
  • src/main/daemon/pty-subprocess.ts
  • src/main/daemon/terminal-host-agent-session-claim.ts
  • src/main/daemon/terminal-host-agent-session.test.ts
  • src/main/daemon/terminal-host-concurrent-create.test.ts
  • src/main/daemon/terminal-host-options.ts
  • src/main/daemon/terminal-host-session-create.ts
  • src/main/daemon/terminal-host.ts
  • src/main/daemon/types.ts
  • src/main/providers/local-pty-utils.ts
  • src/main/providers/working-directory-validation.test.ts
  • src/shared/local-build-compatibility-contract.json
  • src/shared/local-build-compatibility-contract.ts
  • tests/e2e/fixtures/daemon-generation-entry.ts
  • tests/e2e/terminal-foreground-confirmation.unit.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/daemon/terminal-host-options.ts
  • src/main/providers/working-directory-validation.test.ts
  • src/main/daemon/pty-subprocess.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 7 remain after this review.

Comment on lines +49 to +79
const cancelCreate = (error: Error): void => {
if (cancellationStarted) {
return
}
cancellationStarted = true
clearTimeout(timer)
if (!sent || typeof createSessionId !== 'string') {
rejectAndDrop(error)
return
}
void opts
.settleCreateCancellation(createSessionId, opts.id)
.then((result) => {
if (result.canceled) {
rejectAndDrop(error)
}
})
.catch(() => {
if (!settled) {
opts.onCreateCancellationFailure()
}
})
}
const timer = setTimeout(() => {
const error = new DaemonProtocolError(`Request ${type} timed out after ${opts.timeoutMs}ms`)
if (typeof createSessionId === 'string') {
cancelCreate(error)
} else {
rejectAndDrop(error)
}
}, opts.timeoutMs)

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 | 🟠 Major | ⚡ Quick win

Bound the wait after a cancellation reports canceled: false.

cancelCreate clears timer at Line 54 before it asks the daemon to cancel. If settleCreateCancellation resolves with canceled: false, the code neither rejects nor re-arms a timer. The pending request then has no deadline. If the matching createOrAttach reply never arrives, the caller's promise never settles.

The canceled: false case is expected when the daemon already finished the preparation, so a reply is usually in flight. It is not guaranteed: the daemon can fail the create between the preparation window and the reply write, or the reply can be lost on a half-open socket. In that case spawn() hangs and the pane never resolves.

Re-arm a bounded fallback timer so the request always settles.

🛡️ Proposed fallback deadline
     const cancelCreate = (error: Error): void => {
       if (cancellationStarted) {
         return
       }
       cancellationStarted = true
       clearTimeout(timer)
       if (!sent || typeof createSessionId !== 'string') {
         rejectAndDrop(error)
         return
       }
+      // The daemon may still answer the original create; do not wait forever for it.
+      const fallbackTimer = setTimeout(() => rejectAndDrop(error), CREATE_CANCELLATION_GRACE_MS)
+      fallbackTimer.unref?.()
       void opts
         .settleCreateCancellation(createSessionId, opts.id)
         .then((result) => {
           if (result.canceled) {
+            clearTimeout(fallbackTimer)
             rejectAndDrop(error)
           }
         })
         .catch(() => {
+          clearTimeout(fallbackTimer)
           if (!settled) {
             opts.onCreateCancellationFailure()
           }
         })
     }

Note that rejectAndDrop calls clearTimeout(timer) on the stale handle, which is harmless.

📝 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
const cancelCreate = (error: Error): void => {
if (cancellationStarted) {
return
}
cancellationStarted = true
clearTimeout(timer)
if (!sent || typeof createSessionId !== 'string') {
rejectAndDrop(error)
return
}
void opts
.settleCreateCancellation(createSessionId, opts.id)
.then((result) => {
if (result.canceled) {
rejectAndDrop(error)
}
})
.catch(() => {
if (!settled) {
opts.onCreateCancellationFailure()
}
})
}
const timer = setTimeout(() => {
const error = new DaemonProtocolError(`Request ${type} timed out after ${opts.timeoutMs}ms`)
if (typeof createSessionId === 'string') {
cancelCreate(error)
} else {
rejectAndDrop(error)
}
}, opts.timeoutMs)
const cancelCreate = (error: Error): void => {
if (cancellationStarted) {
return
}
cancellationStarted = true
clearTimeout(timer)
if (!sent || typeof createSessionId !== 'string') {
rejectAndDrop(error)
return
}
// The daemon may still answer the original create; do not wait forever for it.
const fallbackTimer = setTimeout(() => rejectAndDrop(error), CREATE_CANCELLATION_GRACE_MS)
fallbackTimer.unref?.()
void opts
.settleCreateCancellation(createSessionId, opts.id)
.then((result) => {
if (result.canceled) {
clearTimeout(fallbackTimer)
rejectAndDrop(error)
}
})
.catch(() => {
clearTimeout(fallbackTimer)
if (!settled) {
opts.onCreateCancellationFailure()
}
})
}
const timer = setTimeout(() => {
const error = new DaemonProtocolError(`Request ${type} timed out after ${opts.timeoutMs}ms`)
if (typeof createSessionId === 'string') {
cancelCreate(error)
} else {
rejectAndDrop(error)
}
}, opts.timeoutMs)

@nwparker
nwparker merged commit fd1dba9 into main Aug 16, 2026
51 checks passed
nwparker added a commit that referenced this pull request Aug 16, 2026
Async cwd validation dedupes by exact path but had no concurrency bound, and a
dead UNC share answers `stat` in ~21s while holding one of libuv's 4 default fs
threads. Four distinct paths on one unreachable server therefore starved every
other async fs read in the daemon — including the cold-restore history replay
running alongside them — which moves the head-of-line stall #14848 removed from
the event loop into the thread pool.

Adds a per-route lane of 2, reusing PrioritySemaphore and matching the per-distro
lane in rate-limits/auth-filesystem-operation.ts. Keyed by the host that has to
answer (WSL distro, or the `\\server` prefix) so many dead subdirectories of one
share fold into one lane. Local-disk paths bypass the lane entirely: a global cap
would queue a healthy local spawn behind a dead share.

The lane also bounds a same-path case: the dedupe eviction added alongside it
re-probes a path whose previous probe is still in flight, so that a recovered
mount is noticed rather than pinned to a promise that can never settle. Without a
cap each eviction wave would add another overlapping probe against the same dead
share.

Moves PrioritySemaphore to src/shared. It has no imports, and reaching into
src/main/daemon from src/main/providers inverted the dependency direction that
already runs daemon -> providers.

Note this bounds pool occupancy, which cancellation cannot: an aborted `stat`
still holds its libuv thread until the OS returns.

STA-4543
nwparker added a commit that referenced this pull request Aug 16, 2026
Review follow-ups on this PR.

The 30s dedupe eviction retired an entry whose probe was still running. `fs.stat`
is uninterruptible, so that freed no libuv thread — it only let the next caller
pin another. A few retries against one dead mount exhaust the default pool of 4
and stall every other async fs read in the daemon, which is the cross-session
freeze #14848 set out to remove. Drop the timer and clear on settle only: the
AbortSignal added here already lets callers escape a shared hung probe, so
sharing one no longer strands them, and a mount whose stat eventually returns
still re-probes on the next call.

The abort also introduced a second cancellation identity on the wire.
WorkingDirectoryValidationAbortedError propagated out of createPtySubprocess as
the request's error, and the client's mapping only recognizes the attach-cancel
message — so a canceled create could reach the rollback branch that closes a
terminal the user still has (#7718). Translate it at the daemon boundary so the
wire carries one identity.
nwparker added a commit that referenced this pull request Aug 16, 2026
…share (#14966)

* fix(daemon): bound cwd validation and attach-only requests on a dead share

#14848 made cwd validation async so one dead share could not freeze every
terminal, but left two ways for a single unreachable path to strand work.

Canceling a create did not abort the probe: `isCanceled` is only polled between
spawn steps, so `fs.stat` on a dead SMB/NFS/UNC path ran to completion. The
create stayed in flight, later creates for that session queued behind it, and
shutdown/idle waited on it. Carry an AbortSignal next to the existing poll so a
canceled caller abandons the probe, and make the per-session queue wait abortable
so a canceled queued request stops waiting too. The shared probe is left running
for whoever still wants it, and the dedupe entry is evicted on a hard cap so a
never-settling mount cannot poison that path across sessions forever.

Attach-only requests registered no cancellable preparation, so the daemon could
not match the client's cancel and the client had already cleared its timer —
neither side bounded the request. Register the preparation for every
createOrAttach and run spawn preflight only when it is not attach-only, and give
the client a bounded grace window when the daemon reports an unmatched cancel.

The cancellation reason now wins over a racing daemon rejection: callers key
recovery off `client_disconnected`, and letting the race pick would roll back
terminals it should keep (#7718).

Splits working-directory validation out of local-pty-utils to stay under the
line cap.

STA-4541

* fix(daemon): keep a hung cwd probe to one thread and one cancel identity

Review follow-ups on this PR.

The 30s dedupe eviction retired an entry whose probe was still running. `fs.stat`
is uninterruptible, so that freed no libuv thread — it only let the next caller
pin another. A few retries against one dead mount exhaust the default pool of 4
and stall every other async fs read in the daemon, which is the cross-session
freeze #14848 set out to remove. Drop the timer and clear on settle only: the
AbortSignal added here already lets callers escape a shared hung probe, so
sharing one no longer strands them, and a mount whose stat eventually returns
still re-probes on the next call.

The abort also introduced a second cancellation identity on the wire.
WorkingDirectoryValidationAbortedError propagated out of createPtySubprocess as
the request's error, and the client's mapping only recognizes the attach-cancel
message — so a canceled create could reach the rollback branch that closes a
terminal the user still has (#7718). Translate it at the daemon boundary so the
wire carries one identity.
nwparker added a commit that referenced this pull request Aug 16, 2026
Async cwd validation dedupes by exact path but had no concurrency bound, and a
dead UNC share answers `stat` in ~21s while holding one of libuv's 4 default fs
threads. Four distinct paths on one unreachable server therefore starved every
other async fs read in the daemon — including the cold-restore history replay
running alongside them — which moves the head-of-line stall #14848 removed from
the event loop into the thread pool.

Adds a per-route lane of 2, reusing PrioritySemaphore and matching the per-distro
lane in rate-limits/auth-filesystem-operation.ts. Keyed by the host that has to
answer (WSL distro, or the `\\server` prefix) so many dead subdirectories of one
share fold into one lane. Local-disk paths bypass the lane entirely: a global cap
would queue a healthy local spawn behind a dead share.

Moves PrioritySemaphore to src/shared. It has no imports, and reaching into
src/main/daemon from src/main/providers inverted the dependency direction that
already runs daemon -> providers.

Note this bounds pool occupancy, which cancellation cannot: an aborted `stat`
still holds its libuv thread until the OS returns.

STA-4543
nwparker added a commit that referenced this pull request Aug 16, 2026
Async cwd validation dedupes by exact path but had no concurrency bound, and a
dead UNC share answers `stat` in ~21s while holding one of libuv's 4 default fs
threads. Four distinct paths on one unreachable server therefore starved every
other async fs read in the daemon — including the cold-restore history replay
running alongside them — which moves the head-of-line stall #14848 removed from
the event loop into the thread pool.

Adds a per-route lane of 2, reusing PrioritySemaphore and matching the per-distro
lane in rate-limits/auth-filesystem-operation.ts. Keyed by the host that has to
answer (WSL distro, or the `\\server` prefix) so many dead subdirectories of one
share fold into one lane. Local-disk paths bypass the lane entirely: a global cap
would queue a healthy local spawn behind a dead share.

Moves PrioritySemaphore to src/shared. It has no imports, and reaching into
src/main/daemon from src/main/providers inverted the dependency direction that
already runs daemon -> providers.

Note this bounds pool occupancy, which cancellation cannot: an aborted `stat`
still holds its libuv thread until the OS returns.

STA-4543
AmethystLiang pushed a commit that referenced this pull request Aug 17, 2026
…ot freeze every terminal (#14848)

* fix(daemon): validate spawn cwd asynchronously so one dead share cannot freeze every terminal

createOrAttach validated the working directory synchronously on the daemon's
only thread. Measured on Windows 11 + Ubuntu-24.04:

  existsSync on an unreachable UNC share   21,022 ms
  wsl.exe probe, cold distro                1,266 ms
  wsl.exe probe, warm distro                   59 ms
  existsSync/statSync on healthy \\wsl.localhost  4 ms / 1 ms

A single unreachable share therefore blocks the whole RPC loop past the
client's 30s request ceiling, so every other terminal stalls behind it and
reports `DaemonProtocolError: Request createOrAttach timed out after 30000ms`.
The main process already validates asynchronously and passes prevalidatedCwd
(ipc/pty.ts); the daemon never got the same treatment.

Add validateWorkingDirectoryAsync (one stat, not exists-then-stat, so an
unreachable share is not paid for twice) and await it from the daemon spawn
preflights. spawnSubprocess now returns SubprocessHandle | Promise<...>, which
existing sync stubs still satisfy.

Deliberately not bounding the stat with a timeout: the 30s ceiling comes from
blocking the shared loop, not from the duration. A timeout cannot tell "slow
share" from "gone share", so it would fail spawns that succeed today at 3-8s
on a cold VPN mount, and trade an accurate "working directory does not exist"
for a guess.

The new await opened a race: it sits between the "already exists?" check and
the sessions.set that publishes the session, so two concurrent creates for one
session id both spawned. Gate creation per session id; distinct ids still spawn
in parallel.

STA-4470

* fix(daemon): fence async spawn lifecycle
AmethystLiang pushed a commit that referenced this pull request Aug 17, 2026
…share (#14966)

* fix(daemon): bound cwd validation and attach-only requests on a dead share

#14848 made cwd validation async so one dead share could not freeze every
terminal, but left two ways for a single unreachable path to strand work.

Canceling a create did not abort the probe: `isCanceled` is only polled between
spawn steps, so `fs.stat` on a dead SMB/NFS/UNC path ran to completion. The
create stayed in flight, later creates for that session queued behind it, and
shutdown/idle waited on it. Carry an AbortSignal next to the existing poll so a
canceled caller abandons the probe, and make the per-session queue wait abortable
so a canceled queued request stops waiting too. The shared probe is left running
for whoever still wants it, and the dedupe entry is evicted on a hard cap so a
never-settling mount cannot poison that path across sessions forever.

Attach-only requests registered no cancellable preparation, so the daemon could
not match the client's cancel and the client had already cleared its timer —
neither side bounded the request. Register the preparation for every
createOrAttach and run spawn preflight only when it is not attach-only, and give
the client a bounded grace window when the daemon reports an unmatched cancel.

The cancellation reason now wins over a racing daemon rejection: callers key
recovery off `client_disconnected`, and letting the race pick would roll back
terminals it should keep (#7718).

Splits working-directory validation out of local-pty-utils to stay under the
line cap.

STA-4541

* fix(daemon): keep a hung cwd probe to one thread and one cancel identity

Review follow-ups on this PR.

The 30s dedupe eviction retired an entry whose probe was still running. `fs.stat`
is uninterruptible, so that freed no libuv thread — it only let the next caller
pin another. A few retries against one dead mount exhaust the default pool of 4
and stall every other async fs read in the daemon, which is the cross-session
freeze #14848 set out to remove. Drop the timer and clear on settle only: the
AbortSignal added here already lets callers escape a shared hung probe, so
sharing one no longer strands them, and a mount whose stat eventually returns
still re-probes on the next call.

The abort also introduced a second cancellation identity on the wire.
WorkingDirectoryValidationAbortedError propagated out of createPtySubprocess as
the request's error, and the client's mapping only recognizes the attach-cancel
message — so a canceled create could reach the rollback branch that closes a
terminal the user still has (#7718). Translate it at the daemon boundary so the
wire carries one identity.
AmethystLiang pushed a commit that referenced this pull request Aug 17, 2026
Async cwd validation dedupes by exact path but had no concurrency bound, and a
dead UNC share answers `stat` in ~21s while holding one of libuv's 4 default fs
threads. Four distinct paths on one unreachable server therefore starved every
other async fs read in the daemon — including the cold-restore history replay
running alongside them — which moves the head-of-line stall #14848 removed from
the event loop into the thread pool.

Adds a per-route lane of 2, reusing PrioritySemaphore and matching the per-distro
lane in rate-limits/auth-filesystem-operation.ts. Keyed by the host that has to
answer (WSL distro, or the `\\server` prefix) so many dead subdirectories of one
share fold into one lane. Local-disk paths bypass the lane entirely: a global cap
would queue a healthy local spawn behind a dead share.

Moves PrioritySemaphore to src/shared. It has no imports, and reaching into
src/main/daemon from src/main/providers inverted the dependency direction that
already runs daemon -> providers.

Note this bounds pool occupancy, which cancellation cannot: an aborted `stat`
still holds its libuv thread until the OS returns.

STA-4543
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ot freeze every terminal (stablyai#14848)

* fix(daemon): validate spawn cwd asynchronously so one dead share cannot freeze every terminal

createOrAttach validated the working directory synchronously on the daemon's
only thread. Measured on Windows 11 + Ubuntu-24.04:

  existsSync on an unreachable UNC share   21,022 ms
  wsl.exe probe, cold distro                1,266 ms
  wsl.exe probe, warm distro                   59 ms
  existsSync/statSync on healthy \\wsl.localhost  4 ms / 1 ms

A single unreachable share therefore blocks the whole RPC loop past the
client's 30s request ceiling, so every other terminal stalls behind it and
reports `DaemonProtocolError: Request createOrAttach timed out after 30000ms`.
The main process already validates asynchronously and passes prevalidatedCwd
(ipc/pty.ts); the daemon never got the same treatment.

Add validateWorkingDirectoryAsync (one stat, not exists-then-stat, so an
unreachable share is not paid for twice) and await it from the daemon spawn
preflights. spawnSubprocess now returns SubprocessHandle | Promise<...>, which
existing sync stubs still satisfy.

Deliberately not bounding the stat with a timeout: the 30s ceiling comes from
blocking the shared loop, not from the duration. A timeout cannot tell "slow
share" from "gone share", so it would fail spawns that succeed today at 3-8s
on a cold VPN mount, and trade an accurate "working directory does not exist"
for a guess.

The new await opened a race: it sits between the "already exists?" check and
the sessions.set that publishes the session, so two concurrent creates for one
session id both spawned. Gate creation per session id; distinct ids still spawn
in parallel.

STA-4470

* fix(daemon): fence async spawn lifecycle
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…share (stablyai#14966)

* fix(daemon): bound cwd validation and attach-only requests on a dead share

stablyai#14848 made cwd validation async so one dead share could not freeze every
terminal, but left two ways for a single unreachable path to strand work.

Canceling a create did not abort the probe: `isCanceled` is only polled between
spawn steps, so `fs.stat` on a dead SMB/NFS/UNC path ran to completion. The
create stayed in flight, later creates for that session queued behind it, and
shutdown/idle waited on it. Carry an AbortSignal next to the existing poll so a
canceled caller abandons the probe, and make the per-session queue wait abortable
so a canceled queued request stops waiting too. The shared probe is left running
for whoever still wants it, and the dedupe entry is evicted on a hard cap so a
never-settling mount cannot poison that path across sessions forever.

Attach-only requests registered no cancellable preparation, so the daemon could
not match the client's cancel and the client had already cleared its timer —
neither side bounded the request. Register the preparation for every
createOrAttach and run spawn preflight only when it is not attach-only, and give
the client a bounded grace window when the daemon reports an unmatched cancel.

The cancellation reason now wins over a racing daemon rejection: callers key
recovery off `client_disconnected`, and letting the race pick would roll back
terminals it should keep (stablyai#7718).

Splits working-directory validation out of local-pty-utils to stay under the
line cap.

STA-4541

* fix(daemon): keep a hung cwd probe to one thread and one cancel identity

Review follow-ups on this PR.

The 30s dedupe eviction retired an entry whose probe was still running. `fs.stat`
is uninterruptible, so that freed no libuv thread — it only let the next caller
pin another. A few retries against one dead mount exhaust the default pool of 4
and stall every other async fs read in the daemon, which is the cross-session
freeze stablyai#14848 set out to remove. Drop the timer and clear on settle only: the
AbortSignal added here already lets callers escape a shared hung probe, so
sharing one no longer strands them, and a mount whose stat eventually returns
still re-probes on the next call.

The abort also introduced a second cancellation identity on the wire.
WorkingDirectoryValidationAbortedError propagated out of createPtySubprocess as
the request's error, and the client's mapping only recognizes the attach-cancel
message — so a canceled create could reach the rollback branch that closes a
terminal the user still has (stablyai#7718). Translate it at the daemon boundary so the
wire carries one identity.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
Async cwd validation dedupes by exact path but had no concurrency bound, and a
dead UNC share answers `stat` in ~21s while holding one of libuv's 4 default fs
threads. Four distinct paths on one unreachable server therefore starved every
other async fs read in the daemon — including the cold-restore history replay
running alongside them — which moves the head-of-line stall stablyai#14848 removed from
the event loop into the thread pool.

Adds a per-route lane of 2, reusing PrioritySemaphore and matching the per-distro
lane in rate-limits/auth-filesystem-operation.ts. Keyed by the host that has to
answer (WSL distro, or the `\\server` prefix) so many dead subdirectories of one
share fold into one lane. Local-disk paths bypass the lane entirely: a global cap
would queue a healthy local spawn behind a dead share.

Moves PrioritySemaphore to src/shared. It has no imports, and reaching into
src/main/daemon from src/main/providers inverted the dependency direction that
already runs daemon -> providers.

Note this bounds pool occupancy, which cancellation cannot: an aborted `stat`
still holds its libuv thread until the OS returns.

STA-4543
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