Skip to content

Gate WSL transcript filesystem I/O to prevent stalls (STA-4049) - #14203

Merged
AmethystLiang merged 5 commits into
mainfrom
sta-4049-wsl-transcript-gate
Aug 13, 2026
Merged

AmethystLiang merged 5 commits into
mainfrom
sta-4049-wsl-transcript-gate

Conversation

@AmethystLiang

Copy link
Copy Markdown
Contributor

Problem

WSL 9P filesystem operations can stall indefinitely on stalled distros or unreachable remote hosts. A single blocked syscall on a UNC path blocks the entire transcript reader, scan discovery, or vault load until the timeout fires—and with no timeout, indefinitely. This is especially problematic on WSL where filesystem latency is unpredictable.

Solution

Implement a gating layer that schedules all WSL transcript filesystem work through a two-lane admission queue:

  • Exact lane (2 permits, 30s timeout): Live transcript reads/watches for the chat UI.
  • Scan lane (1 permit, 60s timeout): Background discovery and vault indexing.

Each lane is independent: a stalled scan does not starve live chat, and vice versa. Work is admitted per-1 MiB chunk with per-chunk deadlines, so large files don't block on whole-file timeouts. When a syscall stalls, it is refused cleanly (not cached), and the caller surfaces a retryable message instead of failing silently.

The gate also coalesces identical filesystem work (same path and priority), so concurrent readers of the same transcript share one syscall; positional reads and opens are excluded to avoid shared buffer corruption.

Key changes

  • wsl-transcript-fs-access.ts: Centralized gated accessor for stat, open, read, readdir, readFile, etc. Routes UNC paths through the gate; local paths bypass it.
  • wsl-transcript-fs-gate.ts: Two-lane scheduler with per-lane concurrency limits, deadlines, and task coalescing. Handles abandoned resources (late results with no waiting receiver).
  • Updated all transcript I/O in native-chat/* (reader, watcher, cache) and ai-vault/* (parsers, discovery, title reader) to use gated accessors.
  • Consolidated scan issue recording into session-scan-issues.ts; removed remote-session-scan-issues.ts.
  • Comprehensive test coverage for stall scenarios: gate refusals don't cache, abandoned resources clean up, per-chunk deadlines work, codepoints don't split across chunk boundaries.

Testing

  • Added 11 new test files covering stall scenarios in transcript reading, watching, caching, parsing, discovery, and title extraction.
  • Verified gate refusals are retried on next call (not cached as missing).
  • Verified abandoned opens/handles are closed, not leaked.
  • Verified per-chunk deadlines allow slow-but-healthy transcripts to succeed.
  • All new tests pass with fake timers.

AmethystLiang and others added 5 commits August 12, 2026 18:45
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.
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]>
…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.
- 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
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
@coderabbitai

coderabbitai Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds WSL-gated filesystem access for transcript metadata, directory reads, file reads, streams, positioned reads, and handles. AI Vault scanners, Native Chat readers, watchers, and OpenCode discovery now use these helpers. Gate refusals propagate or become scan issues according to each caller. Cache entries are evicted after refusals. Watcher operations support abort signals and cleanup. Tests cover stalls, retries, cancellation, cleanup, cache recovery, and UTF-8 chunk boundaries.

Mergeability Score: 🟠 High · up to 9cfb3

The current implementation can leave file descriptors queued indefinitely when one WSL route stalls, causing healthy routes to accumulate resources, and parser failures can keep filesystem work active until deadlines and delay later scans. These concrete availability and cleanup risks should be fixed before merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the problem, solution, scope, and tests, but it omits required template sections and provides no linked issue after “Fixes #”. Add the required template sections, provide a valid issue link, state N/A for visual proof if applicable, and complete testing, review, checklist, and AI disclosure fields.
Docstring Coverage ⚠️ Warning Docstring coverage is 16.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: gating WSL transcript filesystem I/O to prevent stalls.
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 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: 5

🧹 Nitpick comments (4)
src/main/opencode-usage/scanner-wsl-gate.test.ts (1)

83-95: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the refusal callback for both stalled probes.

The empty-list assertion also matches ordinary missing or invalid database paths. Pass onRefusal to both calls and assert the callback receives the stalled path and a WslTranscriptFsError. This verifies the scan-issue contract used by src/main/ai-vault/session-scanner-opencode-sources.ts.

Proposed test assertions
+import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate'
+
 it('gates the data-directory listing instead of hanging the scan', async () => {
   mocks.readdir.mockImplementation(stalls)
+  const onRefusal = vi.fn()
 
-  expect(await settlesOnlyAtTheScanDeadline(listOpenCodeDatabases())).toEqual([])
+  expect(await settlesOnlyAtTheScanDeadline(listOpenCodeDatabases(onRefusal))).toEqual([])
+  expect(onRefusal).toHaveBeenCalledWith(UNC_DATA_DIR, expect.any(WslTranscriptFsError))
 })
src/main/native-chat/wsl-transcript-fs-access.test.ts (2)

58-67: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reset the gate's module state between tests, or the suite becomes order-dependent.

beforeEach clears the mock call logs. It does not reset the real gate's module-level state, because the gate mock factory delegates to original.runWslTranscriptFsTask. The gate retains inFlightTasks, queuedTasks, activeTasks, activeScanCount, and per-task stuck flags across tests in this file.

Two tests leave that state dirty. The test at Line 320 makes the second read return new Promise(() => {}), so that task never settles. It holds a permit and its route is marked stuck for the remainder of the module. The module-level close queue in wsl-transcript-fs-access.ts has the same property: the test at Line 183 leaves queuedCloses drained only because releaseFirst is called, and a future failure there would strand activeCloses at 1.

Today the suite passes because the stalling test is last. Any test appended after it on UNC_PATH will fast-fail through stuckBlocker. Export a test-only reset from wsl-transcript-fs-gate.ts and call it in beforeEach, or use vi.resetModules() with dynamic imports per test.


288-297: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Import the chunk size instead of duplicating 1024 * 1024.

WSL_TRANSCRIPT_READ_CHUNK_BYTES is private to wsl-transcript-fs-access.ts. This test re-derives it as chunkBytes. The straddling emoji only lands on the boundary while the two values match. If the production constant changes, the emoji moves inside a single chunk, the assertions at Line 315 and Line 316 still pass, and the chunk-boundary case is no longer covered.

Export the constant and use it here so the fixture tracks production.

src/main/native-chat/wsl-transcript-fs-gate.test.ts (1)

662-671: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Drop the unused buffer parameter from gatedRead.

gatedRead accepts buffer and then discards it with void buffer. The gate never receives the buffer, and each task closure captures its own buffer directly. The parameter implies a data flow that does not exist, in a test whose purpose is to document buffer ownership.

♻️ Proposed simplification
-  function gatedRead(
-    buffer: Buffer,
-    task: (signal: AbortSignal) => Promise<Buffer>
-  ): Promise<Buffer> {
-    void buffer
+  function gatedRead(task: (signal: AbortSignal) => Promise<Buffer>): Promise<Buffer> {
     return runWslTranscriptFsTask(
       { operation: 'read', path: READ_PATH, priority: 'exact', dedupe: false },
       task
     )
   }

Update the two call sites at Line 679 and Line 683 to pass only the task.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5846f65f-ae10-4b48-8794-8e7c85f18ec3

📥 Commits

Reviewing files that changed from the base of the PR and between 889dd4c and 9cfb38f.

📒 Files selected for processing (61)
  • src/main/ai-vault/remote-session-file-stat.ts
  • src/main/ai-vault/remote-session-scan-issues.ts
  • src/main/ai-vault/remote-session-scanner-discovery.ts
  • src/main/ai-vault/remote-session-scanner.ts
  • src/main/ai-vault/session-first-user-prompt-read.ts
  • src/main/ai-vault/session-scan-issues.ts
  • src/main/ai-vault/session-scanner-antigravity-history.ts
  • src/main/ai-vault/session-scanner-antigravity-parser.ts
  • src/main/ai-vault/session-scanner-claude-subagents.ts
  • src/main/ai-vault/session-scanner-codex-parser.ts
  • src/main/ai-vault/session-scanner-codex-title-index.ts
  • src/main/ai-vault/session-scanner-copilot-parser.ts
  • src/main/ai-vault/session-scanner-core-parser-wsl-stall.test.ts
  • src/main/ai-vault/session-scanner-cursor-parser.ts
  • src/main/ai-vault/session-scanner-devin-parser.ts
  • src/main/ai-vault/session-scanner-discovery-wsl-gate.test.ts
  • src/main/ai-vault/session-scanner-discovery.ts
  • src/main/ai-vault/session-scanner-droid-parser.ts
  • src/main/ai-vault/session-scanner-fs-import-guard.test.ts
  • src/main/ai-vault/session-scanner-gemini-parsers.ts
  • src/main/ai-vault/session-scanner-graph-parsers.ts
  • src/main/ai-vault/session-scanner-grok-parser.ts
  • src/main/ai-vault/session-scanner-hermes-parser.ts
  • src/main/ai-vault/session-scanner-index-cache-wsl-stall.test.ts
  • src/main/ai-vault/session-scanner-kimi-parser.ts
  • src/main/ai-vault/session-scanner-kimi-paths.ts
  • src/main/ai-vault/session-scanner-omp-subagent-listing.ts
  • src/main/ai-vault/session-scanner-omp-subagent-transcripts.ts
  • src/main/ai-vault/session-scanner-opencode-parser.ts
  • src/main/ai-vault/session-scanner-opencode-sources-wsl-stall.test.ts
  • src/main/ai-vault/session-scanner-opencode-sources.ts
  • src/main/ai-vault/session-scanner-parse-cache.ts
  • src/main/ai-vault/session-scanner-parse-wsl-stall.test.ts
  • src/main/ai-vault/session-scanner-primary-parsers.ts
  • src/main/ai-vault/session-scanner-scope-discovery.ts
  • src/main/ai-vault/session-scanner-subagent-transcripts.ts
  • src/main/ai-vault/session-scanner-values.ts
  • src/main/ai-vault/session-scanner.ts
  • src/main/ai-vault/session-title-file-reader-wsl-stall.test.ts
  • src/main/ai-vault/session-title-file-reader.ts
  • src/main/native-chat/transcript-file-version.ts
  • src/main/native-chat/transcript-incremental-reader.ts
  • src/main/native-chat/transcript-read-cache-refusal-recovery.test.ts
  • src/main/native-chat/transcript-read-cache-wsl-stall.test.ts
  • src/main/native-chat/transcript-read-cache.ts
  • src/main/native-chat/transcript-reader-wsl-stall.test.ts
  • src/main/native-chat/transcript-reader.ts
  • src/main/native-chat/transcript-stream-lines.test.ts
  • src/main/native-chat/transcript-stream-lines.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-engine.ts
  • src/main/native-chat/transcript-watch-wsl-exact-path.test.ts
  • src/main/native-chat/transcript-watch-wsl-stall.test.ts
  • src/main/native-chat/transcript-watch.ts
  • src/main/native-chat/wsl-transcript-fs-access.test.ts
  • src/main/native-chat/wsl-transcript-fs-access.ts
  • src/main/native-chat/wsl-transcript-fs-gate.test.ts
  • src/main/native-chat/wsl-transcript-fs-gate.ts
  • src/main/opencode-usage/scanner-wsl-gate.test.ts
  • src/main/opencode-usage/scanner.ts
💤 Files with no reviewable changes (1)
  • src/main/ai-vault/remote-session-scan-issues.ts

@AmethystLiang

Copy link
Copy Markdown
Contributor Author

Fixing:

  • @coderabbitai: comment — [![Review Change Stack](https://storage.googleapis.com/coderabbit_publi…
  • @coderabbitai: review summary — Actionable comments posted: 5**

Will be in the next commit.

@coderabbitai

coderabbitai Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@AmethystLiang Thanks for the update. Please request another review after you push the next commit.

You are interacting with an AI system.

@AmethystLiang
AmethystLiang merged commit 2c28b6c into main Aug 13, 2026
45 checks passed
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.

1 participant