Skip to content

Gate WSL transcript fs ops with timeout and capacity limits - #14090

Merged
OrcaWin merged 2 commits into
mainfrom
P1-STA-3885-minimal-wsl-transcript-gate
Aug 12, 2026
Merged

OrcaWin merged 2 commits into
mainfrom
P1-STA-3885-minimal-wsl-transcript-gate

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

PR visulization: https://share.onorca.dev/a/ERRjcWfDlaLx

Problem

WSL filesystem operations over 9P protocol can hang indefinitely if a distro is stalled. Without protection, one slow distro stalls all transcript access, callers accumulate without bounds, and users see confusing "not found" errors instead of "temporarily unavailable."

Solution

Added deadline-based admission control with per-operation timeouts (30s for file checks, 60s for scans) and capacity limits (64 pending tasks, 64 waiters per task). When I/O hangs, stuck-task detection prevents cascading failures — later operations fail fast rather than timing out. Gate refusals degrade gracefully: later distros/roots still surface their hits, and transient unavailability is distinguished from a permanently missing file.

What Changed

  • Added WslTranscriptFsError with failure codes: 'timeout', 'capacity', 'unavailable'
  • Task scheduler enforces deadlines, queue bounds, and marks stalled I/O as stuck
  • Stuck-work detection: callers waiting on stuck tasks fail fast instead of burning full deadline
  • Resolver logic now distinguishes gate refusals from actual missing files
    • Hits on later distros/roots surface even after earlier gate refusals
    • Refusals when no distro was probed report unavailability, not a miss
  • Guarded the transcript-agent dispatch with an exhaustiveness check so a future agent cannot silently fall through to the OMP session scan
  • Gate refusals in title-request, tail-read, and watch-subscribe paths degrade to fallbacks
  • Comprehensive test coverage for timeout, capacity, stuck-task, and graceful-degradation scenarios

Why

WSL mounts can stall for extended periods (slow network, kernel issues, etc). Without protection, Orca's transcript access becomes completely blocked, and users can't tell if a session is actually missing or just inaccessible. Deadline-based gating ensures the app remains responsive and users get accurate error messages for transient issues.

Visual Proof

N/A — No UI/interaction changes; this is infrastructure hardening for WSL filesystem access.

Testing

  • Manually tested locally — end-to-end on Windows 11 + WSL2, see Validation below
  • Automated tests added/updated, or explained why not below
    • Added 40+ test cases covering timeout enforcement, capacity rejection, stuck-task prevention, and graceful degradation across all resolver paths

Scope of the guarantee

Two limits worth knowing when reviewing:

  • A route is a whole distro, not a path. When a mount stalls, every WSL transcript on that distro fast-fails, not just the stalled path (measured: a healthy transcript refused in 15ms). This is deliberate — the stuckBlocker doc comment explains that spending the other permit on a hung mount would escalate one bad distro into a global outage. It does mean that on a single-distro machine, the common case, all WSL transcripts degrade together.
  • Recovery is bound to the underlying 9P call returning. When it does, the route clears automatically (measured: recovered once a 45s stall settled). 9P calls cannot be aborted, so a call that never returns holds its permit until the process exits — which is what the "restart Orca if the issue continues" guidance covers.

Validation

Exercised end-to-end on Windows 11 + WSL2 Ubuntu-24.04, driven through the real nativeChat IPC surface against a live 9P mount:

Scenario Result
Real WSL transcript read (guest path to UNC) 2 messages, 166-1578ms
Genuinely missing file notFound: true in 13ms, not mislabelled as unavailable
250 concurrent distinct paths 184 capacity refusals, none marked notFound; IPC round-trip stayed at 8ms
Read immediately after that flood clean re-resolve — refusals are not cached
Stalled access (fault-injected, never returns) deadline fired at 30.02s, then 15ms fast-fail on the same route
After the stalled I/O settled route recovered automatically
subscribe() while the route was stuck no error frame; degraded to resolve-poll and self-healed with a clean snapshot

Review

Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • 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)
    • Windows/WSL only; SSH and local paths unaffected
  • pnpm lint, pnpm typecheck, and pnpm test pass on Windows (the 22 failures in src/main/native-chat and src/main/ai-vault are byte-identical on HEAD~1 — pre-existing)

Why: WSL filesystem access can stall when a distro hangs, and stalled
operations must degrade gracefully rather than misreport as "not found".

Distinguish gate refusals (timeout, capacity, unavailable) from actual
missing files so callers can retry or fall through to alternatives. Fail
fast when stuck I/O holds a permit to prevent caller pileup. Route-level
sequencing and waiter deadlines keep one stalled distro from blocking
others.
@coderabbitai

coderabbitai Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds a bounded WSL transcript filesystem gate with timeout, capacity, waiter, route, and stuck-task handling. Transcript discovery now continues across WSL distributions and roots after gate refusals. Resolver fallbacks defer refusal propagation until discovery fails. Transcript readers return retryable refusal errors, watchers use resolve polling, and AI Vault title requests can degrade to ID-only requests. Tests cover scheduling, fallback, timeout, capacity, recovery, and consumer behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.04% 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
Title check ✅ Passed The title clearly summarizes the main change: WSL transcript filesystem operations gain timeout and capacity limits.
Description check ✅ Passed The description explains the problem, solution, scope, testing, and compatibility impact, but it omits the required linked issue and AI disclosure sections.
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 💡 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 commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ddf4ae18-d5c0-4504-9d06-c8c25492cfc9

📥 Commits

Reviewing files that changed from the base of the PR and between 3234a79 and ed070ed.

📒 Files selected for processing (1)
  • src/main/native-chat/session-file-resolver.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/native-chat/session-file-resolver.ts

📝 Walkthrough

Walkthrough

The change adds a bounded WSL transcript filesystem gate with timeout, capacity, waiter, route, and stuck-task handling. Transcript discovery now continues across WSL distributions and roots after gate refusals. Resolver fallbacks defer refusal propagation until discovery fails. Transcript readers return retryable refusal errors, watchers use resolve polling, and AI Vault title requests can degrade to ID-only requests. Tests cover scheduling, fallback, timeout, capacity, recovery, and consumer behavior.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.04% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is detailed, but it omits the required Linked Issue section and does not provide a Fixes issue reference. Add the required Linked Issue section with a valid issue reference, such as Fixes #123``, and complete any missing checklist items.
✅ 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 identifies the main change: timeout and capacity limits for WSL transcript filesystem operations.
✨ 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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5972b719-8918-4b2f-b75b-330084ae9a95

📥 Commits

Reviewing files that changed from the base of the PR and between 09ec516 and 3234a79.

📒 Files selected for processing (16)
  • src/main/ai-vault/session-scanner-discovery-wsl-gate.test.ts
  • src/main/ai-vault/session-scanner-discovery.ts
  • src/main/ai-vault/session-title-request-paths.ts
  • src/main/native-chat/host-readable-transcript-path-fs-gate.test.ts
  • src/main/native-chat/host-readable-transcript-path.test.ts
  • src/main/native-chat/host-readable-transcript-path.ts
  • src/main/native-chat/session-file-resolver-wsl-scan-gate.test.ts
  • src/main/native-chat/session-file-resolver.ts
  • src/main/native-chat/transcript-read-cache.ts
  • src/main/native-chat/transcript-reader.ts
  • src/main/native-chat/transcript-tail-reader-wsl-gate.test.ts
  • src/main/native-chat/transcript-tail-reader.ts
  • src/main/native-chat/transcript-watch-resolve-poll.test.ts
  • src/main/native-chat/transcript-watch.ts
  • src/main/native-chat/wsl-transcript-fs-gate.test.ts
  • src/main/native-chat/wsl-transcript-fs-gate.ts

Why: the resolver refactor replaced the explicit `omp` branch with an
unconditional `return resolveOmpSessionFile(...)`. That is behaviour-identical
today, but a future member of NativeChatTranscriptAgent would silently scan
OMP's session root with a foreign session id, and the tail return stays
well-typed so nothing fails the build.

Restore the explicit branch and add a `satisfies never` check so adding an
agent is a compile error at this line instead of a wrong resolve at runtime.
@OrcaWin
OrcaWin merged commit 8ffed25 into main Aug 12, 2026
168 of 176 checks passed
AmethystLiang added a commit that referenced this pull request Aug 13, 2026
* fix(ai-vault): gate post-resolution WSL transcript I/O (STA-4049)

PR #14090 admitted only path *resolution* through the WSL transcript
filesystem gate. Every byte read afterwards from the resulting
\\wsl.localhost\... UNC path ran raw, so a distro that answers the first
access() and then stalls hung Native Chat at "loading" and AI Vault at
"scanning" with no timeout and no error.

Route that I/O through a new wsl-transcript-fs-access accessor, which is
a verbatim node:fs passthrough off UNC and an admitted, deadlined task on
it. open/positional-read opt out of coalescing (dedupe: false): joiners
would share one FileHandle or one caller's buffer.

Refusals now surface as the existing retryable message rather than
notFound, per-root scan failures are contained to an AiVaultScanIssue,
and the memoized Codex/Kimi indexes evict on refusal so a stall cannot
pin "no titles"/"no cwd" until the index changes.

* fix(ai-vault): stop caching WSL gate refusals as results (STA-4049)

Code review 1 P1 fixes on top of the transcript gate:

- transcript-read-cache: never store a gate refusal. The refusal leaves the
  file's mtime untouched, so the cached error would have been served to every
  later call until the transcript itself changed.
- kimi/grok/opencode parsers: rethrow WslTranscriptFsError instead of folding it
  into "no session"/"no transcript", so the session parse cache cannot store a
  null or partial answer under an unchanged mtime. Ordinary missing/half-written
  files stay contained.
- opencode-usage scanner: gate the data-directory readdir and the absolute
  OPENCODE_DB stat. The AI Vault's primary OpenCode source reaches them
  transitively, which is why the direct-import guard never saw them.
- gated stat/lstat: accept an AbortSignal, matching gated open/read, so a
  cancelled watch install or title probe detaches immediately instead of holding
  a waiter to its deadline.
- gated open: close a FileHandle whose syscall lands after the last waiter gave
  up, and close handles off UNC verbatim (awaited, failures surfaced).

Co-authored-by: Orca <[email protected]>

* fix(native-chat): decode gated chunks incrementally and cancel drain I/O (STA-4049)

Addresses the CR2 blockers.

UTF-8 chunk-boundary corruption: the UNC branch yielded raw 1 MiB Buffer
slices that `decodeTranscriptStream` decoded independently, so any multibyte
codepoint straddling a boundary became U+FFFD on both sides — corrupting the
JSONL line and shifting `consumedBytes` (which seeds fallback message ids).
`gatedChunks` now holds a StringDecoder when `encoding` is set, and
`decodeTranscriptStream` holds one for the Buffer path, matching what
`createReadStream`'s decoder already did off UNC.

Watcher teardown: `installTranscriptWatcher` owns an AbortController that
`unsubscribe()` aborts, threaded through every gated call on the drain path.
Waiters now detach at teardown instead of holding to the 30s deadline, and
the gate's aborted-signal pre-check stops an in-flight drain from admitting
new tasks after close.

Rovo `session_context.json`: `readJsonObjectIfExists` rethrows
WslTranscriptFsError so `parseSessionCandidate` records a scan issue, instead
of caching an un-enriched session under an unchanged mtime that never re-reads.

Primary OpenCode source: `listOpenCodeDatabases` takes an optional refusal
reporter so a refused `OPENCODE_DB`/`XDG_DATA_HOME` surfaces an
AiVaultScanIssue, matching `listOpenCodeDatabasesInDirectory`.

`boundaryFingerprint` moved to its own module to keep the watcher engine
under the max-lines cap.

* refactor(native-chat): consolidate transcript I/O and remove fallback te

- Move boundaryFingerprint from its own module to transcript-file-version.ts
- Extract runPathOperation helper to eliminate duplicate UNC path routing
- Remove tests for fallback behaviors when transcripts are unavailable or incomplete
- Clean up implementation comments and verbose test documentation

* consolidate scan issues and gate session scanner I/O (STA-4049)

Both local and remote session scans hit stalled WSL distros identically:
one failed probe per discovered path. Unifying issue recording and gate
refusal handling prevents duplication and ensures consistent behavior.

- Gate all file operations (stat, readdir, read, open) through WSL
  stall detection instead of scattered or missing gates
- Serve cached transcripts when stat stalls; distinguish gate refusals
  from missing files
- Serialize UNC close operations to prevent thread pool exhaustion
- Incremental chunk decoding in streams handles codepoint boundaries
  correctly

---------

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…lyai#14203)

* fix(ai-vault): gate post-resolution WSL transcript I/O (STA-4049)

PR stablyai#14090 admitted only path *resolution* through the WSL transcript
filesystem gate. Every byte read afterwards from the resulting
\\wsl.localhost\... UNC path ran raw, so a distro that answers the first
access() and then stalls hung Native Chat at "loading" and AI Vault at
"scanning" with no timeout and no error.

Route that I/O through a new wsl-transcript-fs-access accessor, which is
a verbatim node:fs passthrough off UNC and an admitted, deadlined task on
it. open/positional-read opt out of coalescing (dedupe: false): joiners
would share one FileHandle or one caller's buffer.

Refusals now surface as the existing retryable message rather than
notFound, per-root scan failures are contained to an AiVaultScanIssue,
and the memoized Codex/Kimi indexes evict on refusal so a stall cannot
pin "no titles"/"no cwd" until the index changes.

* fix(ai-vault): stop caching WSL gate refusals as results (STA-4049)

Code review 1 P1 fixes on top of the transcript gate:

- transcript-read-cache: never store a gate refusal. The refusal leaves the
  file's mtime untouched, so the cached error would have been served to every
  later call until the transcript itself changed.
- kimi/grok/opencode parsers: rethrow WslTranscriptFsError instead of folding it
  into "no session"/"no transcript", so the session parse cache cannot store a
  null or partial answer under an unchanged mtime. Ordinary missing/half-written
  files stay contained.
- opencode-usage scanner: gate the data-directory readdir and the absolute
  OPENCODE_DB stat. The AI Vault's primary OpenCode source reaches them
  transitively, which is why the direct-import guard never saw them.
- gated stat/lstat: accept an AbortSignal, matching gated open/read, so a
  cancelled watch install or title probe detaches immediately instead of holding
  a waiter to its deadline.
- gated open: close a FileHandle whose syscall lands after the last waiter gave
  up, and close handles off UNC verbatim (awaited, failures surfaced).

Co-authored-by: Orca <[email protected]>

* fix(native-chat): decode gated chunks incrementally and cancel drain I/O (STA-4049)

Addresses the CR2 blockers.

UTF-8 chunk-boundary corruption: the UNC branch yielded raw 1 MiB Buffer
slices that `decodeTranscriptStream` decoded independently, so any multibyte
codepoint straddling a boundary became U+FFFD on both sides — corrupting the
JSONL line and shifting `consumedBytes` (which seeds fallback message ids).
`gatedChunks` now holds a StringDecoder when `encoding` is set, and
`decodeTranscriptStream` holds one for the Buffer path, matching what
`createReadStream`'s decoder already did off UNC.

Watcher teardown: `installTranscriptWatcher` owns an AbortController that
`unsubscribe()` aborts, threaded through every gated call on the drain path.
Waiters now detach at teardown instead of holding to the 30s deadline, and
the gate's aborted-signal pre-check stops an in-flight drain from admitting
new tasks after close.

Rovo `session_context.json`: `readJsonObjectIfExists` rethrows
WslTranscriptFsError so `parseSessionCandidate` records a scan issue, instead
of caching an un-enriched session under an unchanged mtime that never re-reads.

Primary OpenCode source: `listOpenCodeDatabases` takes an optional refusal
reporter so a refused `OPENCODE_DB`/`XDG_DATA_HOME` surfaces an
AiVaultScanIssue, matching `listOpenCodeDatabasesInDirectory`.

`boundaryFingerprint` moved to its own module to keep the watcher engine
under the max-lines cap.

* refactor(native-chat): consolidate transcript I/O and remove fallback te

- Move boundaryFingerprint from its own module to transcript-file-version.ts
- Extract runPathOperation helper to eliminate duplicate UNC path routing
- Remove tests for fallback behaviors when transcripts are unavailable or incomplete
- Clean up implementation comments and verbose test documentation

* consolidate scan issues and gate session scanner I/O (STA-4049)

Both local and remote session scans hit stalled WSL distros identically:
one failed probe per discovered path. Unifying issue recording and gate
refusal handling prevents duplication and ensures consistent behavior.

- Gate all file operations (stat, readdir, read, open) through WSL
  stall detection instead of scattered or missing gates
- Serve cached transcripts when stat stalls; distinguish gate refusals
  from missing files
- Serialize UNC close operations to prevent thread pool exhaustion
- Incremental chunk decoding in streams handles codepoint boundaries
  correctly

---------

Co-authored-by: Orca <[email protected]>
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.

2 participants