Skip to content

fix(daemon): bound cwd validation per UNC route - #14967

Merged
nwparker merged 1 commit into
mainfrom
neil/sta-4543-cwd-validation-fanout
Aug 16, 2026
Merged

nwparker merged 1 commit into
mainfrom
neil/sta-4543-cwd-validation-fanout

Conversation

@nwparker

@nwparker nwparker commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​74 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​74
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​71 $\color{#cf222e}{\Huge{\mathbf{−}}}$​7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​64

Follow-up hardening on #14848 (merged, not reverted).

Stacked on #14966 (STA-4541), which extracts working-directory-validation.ts. Base will retarget to main once that merges.

What is actually wrong

Async cwd validation dedupes by exact path with no concurrency bound. A dead UNC share answers stat in ~21s (per #14848's own Windows 11 measurement) while holding one of libuv's 4 default fs threads (UV_THREADPOOL_SIZE is unset repo-wide). Four distinct paths on one unreachable server therefore starve every other async fs read in the daemon — including history-reader.ts:251, the cold-restore replay running alongside them.

That relocates the head-of-line stall #14848 removed from the event loop into the thread pool.

Fix

A per-route lane of 2, reusing the existing PrioritySemaphore and mirroring the per-distro lane in rate-limits/auth-filesystem-operation.ts ("a few disconnected distros must not occupy libuv's entire filesystem pool").

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, which is what actually folds the byte-exact dedupe miss.

Local-disk paths bypass the lane entirely: a global cap (the ticket's "bound by host" wording) would queue a healthy local spawn behind a dead share.

Scoping notes

  • This bounds pool occupancy, which cancellation cannot: an aborted stat still holds its libuv thread until the OS returns. Complementary to fix(daemon): bound cwd validation and attach-only requests on a dead share #14966, not redundant with it.
  • A cap does not help the affected panes — it makes them slower. Its only value is protecting unrelated daemon work.
  • Severity is closer to P3 than the filed P2. The ticket's trigger (restore fanout) barely fires: validation runs on spawn only, a warm-daemon restore does zero probes, worktrees mount lazily, and panes in one worktree share a cwd so dedupe collapses them to one probe. The trigger that matters is 4+ distinct paths on one unreachable non-WSL share.

Testing

New tests for the cap, lane isolation per server, and local paths bypassing a stalled queue. Daemon + providers + ipc: 5271 passed. Typecheck and lint clean.

STA-4543

@nwparker
nwparker force-pushed the neil/sta-4543-cwd-validation-fanout branch from 666b29a to af9a353 Compare August 16, 2026 22:26
@nwparker

Copy link
Copy Markdown
Contributor Author

Pushed two follow-ups from a review pass:

Layering. PrioritySemaphore moved to src/shared. Importing it from src/main/daemon into src/main/providers inverted the direction that already runs daemon → providers (pty-subprocess.ts → local-pty-utils). It has zero imports, so the move is mechanical.

Eviction interaction. The dedupe eviction added in #14966 re-probes a path whose previous probe is still in flight — deliberately, so a recovered mount is noticed instead of being pinned to a promise that can never settle. On a still-dead path each eviction wave would otherwise add another overlapping probe. The lane bounds that, which makes it a same-path argument for this change, not just the distinct-path one in the ticket. Added a test asserting peak concurrency stays at 2 across four eviction waves, and a comment recording that the eviction is only safe because the lane caps the overlap.

Daemon + providers + shared: 7089 tests pass. Typecheck and lint clean.

@nwparker
nwparker force-pushed the neil/sta-4543-cwd-validation-fanout branch from af9a353 to ccd1a54 Compare August 16, 2026 23:06
@nwparker
nwparker changed the base branch from neil/sta-4541-dead-share-cwd-cancel to main August 16, 2026 23:28
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
nwparker force-pushed the neil/sta-4543-cwd-validation-fanout branch from ccd1a54 to a00e81c Compare August 16, 2026 23:29
@coderabbitai

coderabbitai Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 53254eb2-dfb5-435b-8b65-4844d9f33ab6

📥 Commits

Reviewing files that changed from the base of the PR and between d670355 and a00e81c.

📒 Files selected for processing (5)
  • src/main/daemon/history-reader.ts
  • src/main/providers/working-directory-validation.test.ts
  • src/main/providers/working-directory-validation.ts
  • src/shared/priority-semaphore.test.ts
  • src/shared/priority-semaphore.ts

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


📝 Walkthrough

Walkthrough

Adds the shared PrioritySemaphore with priority ordering, FIFO tie-breaking, capacity limits, and idempotent release callbacks. Integrates per-route semaphore lanes into UNC working-directory validation, grouping WSL paths by distro and other UNC paths by server. Adds state reset support and tests for concurrency, isolation, lane independence, probe sharing, and semaphore behavior. Updates history-reader.ts to import the shared semaphore module.

Merge Risk: 🟡 Moderate · up to a00e8

The new per-route validation cap does not apply to slash-form WSL UNC paths, so stalled validations can still exhaust filesystem workers and delay unrelated daemon work; this should be fixed before merging. The semaphore also needs basic input validation.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the problem, fix, scope, linked issue, and testing, but it omits most required template sections and checklist items. Add the required ELI5, What Changed, Why, Linked Issue, Visual Proof with N/A rationale, Review, Notes, Checklist, and Author sections.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary change: limiting working-directory validation concurrency per UNC route.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 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: 2

🧹 Nitpick comments (1)
src/main/providers/working-directory-validation.ts (1)

13-17: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Condense the implementation rationale comment.

Keep the non-obvious reason in one concise line. The added five-line comment is longer than necessary.

As per coding guidelines: “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 53254eb2-dfb5-435b-8b65-4844d9f33ab6

📥 Commits

Reviewing files that changed from the base of the PR and between d670355 and a00e81c.

📒 Files selected for processing (5)
  • src/main/daemon/history-reader.ts
  • src/main/providers/working-directory-validation.test.ts
  • src/main/providers/working-directory-validation.ts
  • src/shared/priority-semaphore.test.ts
  • src/shared/priority-semaphore.ts

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

Comment on lines +32 to +41
function uncRouteKey(cwd: string): string | null {
if (!cwd.startsWith('\\\\')) {
return null
}
const wslInfo = parseWslUncPath(cwd)
if (wslInfo) {
return `wsl:${wslInfo.distro.trim().toLowerCase()}`
}
const server = cwd.slice(2).split(/[\\/]/, 1)[0]
return `unc:${server.toLowerCase()}`

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

Recognize slash-form WSL UNC paths before the backslash guard.

parseWslUncPath accepts //wsl.localhost/..., but the startsWith('\\\\') guard returns null first. Those paths bypass the lane, so distinct stalled probes can again consume all filesystem worker threads.

Normalize the prefix check after handling the WSL parser result.

Proposed fix
 function uncRouteKey(cwd: string): string | null {
-  if (!cwd.startsWith('\\\\')) {
-    return null
-  }
   const wslInfo = parseWslUncPath(cwd)
   if (wslInfo) {
     return `wsl:${wslInfo.distro.trim().toLowerCase()}`
   }
-  const server = cwd.slice(2).split(/[\\/]/, 1)[0]
-  return `unc:${server.toLowerCase()}`
+  const normalizedCwd = cwd.replace(/\\/g, '/')
+  if (!normalizedCwd.startsWith('//')) {
+    return null
+  }
+  const server = normalizedCwd.slice(2).split('/', 1)[0]
+  return server ? `unc:${server.toLowerCase()}` : null
 }
📝 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
function uncRouteKey(cwd: string): string | null {
if (!cwd.startsWith('\\\\')) {
return null
}
const wslInfo = parseWslUncPath(cwd)
if (wslInfo) {
return `wsl:${wslInfo.distro.trim().toLowerCase()}`
}
const server = cwd.slice(2).split(/[\\/]/, 1)[0]
return `unc:${server.toLowerCase()}`
function uncRouteKey(cwd: string): string | null {
const wslInfo = parseWslUncPath(cwd)
if (wslInfo) {
return `wsl:${wslInfo.distro.trim().toLowerCase()}`
}
const normalizedCwd = cwd.replace(/\\/g, '/')
if (!normalizedCwd.startsWith('//')) {
return null
}
const server = normalizedCwd.slice(2).split('/', 1)[0]
return server ? `unc:${server.toLowerCase()}` : null
}

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

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/main/providers/working-directory-validation.ts (1)

13-17: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Condense the implementation rationale comment.

Keep the non-obvious reason in one concise line. The added five-line comment is longer than necessary.

As per coding guidelines: “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 53254eb2-dfb5-435b-8b65-4844d9f33ab6

📥 Commits

Reviewing files that changed from the base of the PR and between d670355 and a00e81c.

📒 Files selected for processing (5)
  • src/main/daemon/history-reader.ts
  • src/main/providers/working-directory-validation.test.ts
  • src/main/providers/working-directory-validation.ts
  • src/shared/priority-semaphore.test.ts
  • src/shared/priority-semaphore.ts

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

🛑 Comments failed to post (1)
src/shared/priority-semaphore.ts (1)

10-12: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Reject invalid concurrency values.

A zero, negative, fractional, or non-finite value makes permit behavior invalid. Reject values that are not positive safe integers in the constructor.

Proposed fix
 constructor(concurrency: number) {
+  if (!Number.isSafeInteger(concurrency) || concurrency < 1) {
+    throw new RangeError('concurrency must be a positive safe integer')
+  }
   this.available = concurrency
 }
📝 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.

  constructor(concurrency: number) {
    if (!Number.isSafeInteger(concurrency) || concurrency < 1) {
      throw new RangeError('concurrency must be a positive safe integer')
    }
    this.available = concurrency
  }

@nwparker
nwparker merged commit 3f58d5c into main Aug 16, 2026
51 checks passed
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
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