Repository navigation
feat(wsl): detached distro holder re-adopted from a pid file (WSL-via-orcad C3) - #27800
Conversation
655fbd7 to
aed9fca
Compare
4eba961 to
6e18d3a
Compare
6e18d3a to
cdb14ef
Compare
23df239 to
470ebaa
Compare
cdb14ef to
0eaeacd
Compare
📝 Walkthrough
Priority: ⬇️ Low Merge Risk: 🔵 Low · up to
|
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
0178fe1c-8b90-425d-b886-5ef1b7cf85bc
📒 Files selected for processing (4)
src/main/wsl/wsl-distro-holder-command.tssrc/main/wsl/wsl-distro-holder-record.tssrc/main/wsl/wsl-distro-holder.test.tssrc/main/wsl/wsl-distro-holder.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.
| /** | ||
| * Distro names that have a record file; sweeps temp files a crashed writer left behind. | ||
| * Why decode the file name: the record may be corrupt, and its file is still owed a verdict. | ||
| */ | ||
| export async function listWslDistroHolderRecordDistros(userDataPath: string): Promise<string[]> { | ||
| const directory = wslDistroHolderDirectory(userDataPath) | ||
| let entries: string[] | ||
| try { | ||
| entries = await readdir(directory) | ||
| } catch (error) { | ||
| if (isMissingFileError(error)) { | ||
| return [] | ||
| } | ||
| throw error | ||
| } | ||
| const distros: string[] = [] | ||
| for (const entry of entries) { | ||
| if (!entry.endsWith(RECORD_SUFFIX)) { | ||
| continue | ||
| } | ||
| const path = join(directory, entry) | ||
| await removeStaleDurableWriteTempFiles(path, { minimumAgeMs: 60_000 }).catch(() => {}) | ||
| try { | ||
| const distro = decodeURIComponent(entry.slice(0, -RECORD_SUFFIX.length)) | ||
| if (wslDistroHolderKey(distro) !== '') { | ||
| distros.push(distro) | ||
| } | ||
| } catch { | ||
| await rm(path, { force: true }) | ||
| } | ||
| } | ||
| return distros | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
sed -n '95,150p' src/main/wsl/wsl-distro-holder-record.ts
rg -n 'writeFileDurable|durableWrite|listWslDistroHolderRecordDistros|adoptHolders' src/mainRepository: stablyai/orca
Length of output: 19120
🏁 Script executed:
printf '%s\n' '--- durable-file-write.ts ---'
sed -n '1,175p' src/main/durable-file-write.ts
printf '%s\n' '--- wsl-distro-holder-record.ts ---'
sed -n '1,155p' src/main/wsl/wsl-distro-holder-record.ts
printf '%s\n' '--- wsl-distro-holder.ts ---'
sed -n '1,330p' src/main/wsl/wsl-distro-holder.ts
printf '%s\n' '--- holder tests around concurrency ---'
sed -n '1,240p' src/main/wsl/wsl-distro-holder.test.tsRepository: stablyai/orca
Length of output: 32372
🏁 Script executed:
rg -n -F -- 'renameFileWithWindowsRetryAsync' src/main/codex-accounts/fs-utils.ts src/main/codex-accounts
sed -n '1,240p' src/main/codex-accounts/fs-utils.tsRepository: stablyai/orca
Length of output: 7012
🏁 Script executed:
rg -n -F -- 'export async function renameFileWithWindowsRetryAsync' src/shared/windows-retry-file-operations.ts
sed -n '1,260p' src/shared/windows-retry-file-operations.tsRepository: stablyai/orca
Length of output: 2367
Match stale temp files to the exact record path.
a and a.json are different distro keys, but their record paths are a.json and a.json.json. A temp file for a.json therefore matches cleanup for a. If the write remains between fsync and rename for more than 60 seconds, adoptHolders() can remove that temp file. The following rename then receives ENOENT, so ensureHeld() fails without publishing its record.
Suggested fix
if (!name.startsWith(prefix) || !name.endsWith('.tmp')) {
return false
}
+ if (!/^\d+\./.test(name.slice(prefix.length))) {
+ return false
+ }
// The caller must await owner exit before reclaiming its current-process files.| await writeWslDistroHolderRecord(userDataPath, record) | ||
| try { | ||
| await waitForDistroRunning(distro, () => observed.exit) | ||
| } catch (error) { | ||
| await stopRecordedHolder(record) | ||
| throw error | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Stop the spawned holder if the record write fails.
spawnAndRecord starts a detached holder and calls unref() on it. After that, writeWslDistroHolderRecord can throw, for example on a disk-full or permission error. In that case, the error propagates past the try block that only wraps waitForDistroRunning. Nothing kills the holder, and no record of it exists. Later ensureHeld calls then start another holder. Each failed write leaks one detached wsl.exe that keeps the distro running and that release cannot find. Kill the child when the write fails.
🐛 Proposed fix
--- "a/src/main/wsl/wsl-distro-holder.ts"
+++ "b/src/main/wsl/wsl-distro-holder.ts"
@@ -199,7 +199,16 @@
creationTimeMs: evidence.status === 'present' ? evidence.startedAtMs : null,
startedAtMs: now()
}
- await writeWslDistroHolderRecord(userDataPath, record)
+ try {
+ await writeWslDistroHolderRecord(userDataPath, record)
+ } catch (error) {
+ try {
+ killProcess(pid)
+ } catch {
+ // Already exited.
+ }
+ throw error
+ }
try {
await waitForDistroRunning(distro, () => observed.exit)
} catch (error) {📝 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.
| await writeWslDistroHolderRecord(userDataPath, record) | |
| try { | |
| await waitForDistroRunning(distro, () => observed.exit) | |
| } catch (error) { | |
| await stopRecordedHolder(record) | |
| throw error | |
| } | |
| try { | |
| await writeWslDistroHolderRecord(userDataPath, record) | |
| } catch (error) { | |
| try { | |
| killProcess(pid) | |
| } catch { | |
| // Already exited. | |
| } | |
| throw error | |
| } | |
| try { | |
| await waitForDistroRunning(distro, () => observed.exit) | |
| } catch (error) { | |
| await stopRecordedHolder(record) | |
| throw error | |
| } |
ELI5
WSL shuts a Linux distro down about 15 seconds after the last Windows program talking to it goes away. When Orca runs its server inside a distro, the distro must stay up even while nothing else is open, and even after Orca itself quits. This adds a tiny "holder" (a Windows-side
wsl.exethat just sleeps inside the distro), remembers it in a file, and finds it again the next time Orca starts.What Changed
New module
src/main/wsl/wsl-distro-holder.ts(plus-record.tsfor the pid file and-command.tsfor the argv), exported ascreateWslDistroHolder({ userDataPath }):ensureHeld(distro): reuses the recorded holder if it is still ours; otherwise spawnswsl.exe -d <distro> --exec /bin/sh -c 'while :; do sleep 3600; done' orca-wsl-distro-holderdetached through process-host (windowsHide is pinned there), writes the record durably, and waits untilwsl --list --runningconfirms the distro. Ifwsl.exeexits first (bad name) or the distro never starts, the holder is stopped and the record removed. This is the only path that may boot a distro.adoptHolders(): startup sweep of<userData>/wsl-distro-holders/*.json. Keeps a holder only if the pid exists, its creation time matches, and its command line is our holder for that distro. Provably stale or corrupt records are removed.release(distro): explicit stop only. Kills the holder after re-verifying identity, so it never kills a reused pid.holderState(distro):live|exited|unverifiable. If the process table can't be read, the answer isunverifiableand the record is kept, neverexited.Pid file (
<userData>/wsl-distro-holders/<encoded lowercase distro>.json):{"version":1,"distro":"Ubuntu","pid":6288,"creationTimeMs":1791784645869,"startedAtMs":1791784645900}.creationTimeMsis null only when the process table had no creation time (the CIM fallback). In that case adoption relies on the command line.There is no production caller yet. C4 wires it in.
Why
taskkill /Tof Orca's tree still reaches it, the same exposure the terminal daemon has.sleep 3600is used instead ofsleep infinityso the holder doesn't depend on how each distro'ssleepparses durations. On busybox 1.36.1 all three forms are accepted, so this is belt-and-braces.windows-process-table(viaqueryWindowsProcess), never a forked PowerShell. pid + creation time + command line guards against pid reuse.Linked Issue
N/A (WSL-via-orcad tracker row C3).
Visual Proof
N/A: no UI. This is a main-process module with no caller yet.
Testing
Unit tests (
wsl-distro-holder.test.ts, fake process table + fake spawner): spawn+record, single-flight, adopt valid, reject reused pid, reject foreign command line, stale/corrupt cleanup, unverifiable on table failure (no kill, no spawn, record kept), release kills only a verified holder, early exit before record write, boot timeout, release serialized behind ensure.Real Windows 11 host (WSL 2.7.10), throwaway non-systemd Alpine 3.20 distro, module bundled with esbuild and run under
ELECTRON_RUN_AS_NODEwith the installed Orca.exe:ensureHeldand exited (1.0–1.6 s cold). The distro stayed Running for 70 s.adopt→ live,ensure→ adopted), with no duplicate holder.release: the distro was Stopped 14–16 s later, and the record was removed.exited, record dropped, and the real holder was not killed. A live non-holder pid →exited. A missing pid →exited. A corrupt file → removed.wsl.exere-launches itself as a child with the same argv. Killing the recorded parent ends both.Gates:
pnpm tc, oxlint (root, anti-slop, native, type-aware), changed-code quality, process-host imports, max-lines, reliability, compat imports.src/main/wsl+src/main/daemonsuites pass, except the real-PTY shell-ready tests inshell-ready.test.tsandrepro-13767-*. Those fail under the bun project on this Mac even when run alone, and this PR touches no daemon code.I manually tested these changes locally
Automated tests added/updated, or explained why not below
AI Disclosure
Review
Agent skill upstream boundary
Notes
Windows-only by construction (WSL). SSH: not involved. The holder lives on the Windows desktop host that owns the distro. Liveness vocabulary is
live/unverifiable/exited. No wire changes.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)