Skip to content

feat(wsl): detached distro holder re-adopted from a pid file (WSL-via-orcad C3) - #27800

Merged
nwparker merged 3 commits into
mainfrom
nwparker/wsl-c3-distro-holder
Oct 13, 2026
Merged

nwparker merged 3 commits into
mainfrom
nwparker/wsl-c3-distro-holder

Conversation

@nwparker

@nwparker nwparker commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​307 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​307
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​476 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​476

Stacked on #27792 (C1, the WSL orcad host transport). Base is that branch; review only the C3 commits.

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.exe that 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.ts for the pid file and -command.ts for the argv), exported as createWslDistroHolder({ userDataPath }):

  • ensureHeld(distro): reuses the recorded holder if it is still ours; otherwise spawns wsl.exe -d <distro> --exec /bin/sh -c 'while :; do sleep 3600; done' orca-wsl-distro-holder detached through process-host (windowsHide is pinned there), writes the record durably, and waits until wsl --list --running confirms the distro. If wsl.exe exits 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 is unverifiable and the record is kept, never exited.
  • Ensure, release and adoption for the same distro run one at a time (single-flight), and different distros run independently.

Pid file (<userData>/wsl-distro-holders/<encoded lowercase distro>.json):
{"version":1,"distro":"Ubuntu","pid":6288,"creationTimeMs":1791784645869,"startedAtMs":1791784645900}. creationTimeMs is 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

  • Detached, not attached: an attached child sits in libuv's kill-on-close job and dies with Orca. The design decision is that the holder outlives a full quit. A taskkill /T of Orca's tree still reaches it, the same exposure the terminal daemon has.
  • A Windows-side client is the only thing measured to keep a distro running. A detached process or a systemd unit inside the distro does not.
  • The loop of sleep 3600 is used instead of sleep infinity so the holder doesn't depend on how each distro's sleep parses durations. On busybox 1.36.1 all three forms are accepted, so this is belt-and-braces.
  • Identity is checked through windows-process-table (via queryWindowsProcess), 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_NODE with the installed Orca.exe:

    • A harness process ran ensureHeld and exited (1.0–1.6 s cold). The distro stayed Running for 70 s.
    • Later harness runs adopted the holder (adopt → live, ensure → adopted), with no duplicate holder.
    • release: the distro was Stopped 14–16 s later, and the record was removed.
    • Pid reuse (creation time off by 1 s) → exited, record dropped, and the real holder was not killed. A live non-holder pid → exited. A missing pid → exited. A corrupt file → removed.
    • Note: wsl.exe re-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/daemon suites pass, except the real-PTY shell-ready tests in shell-ready.test.ts and repro-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

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

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

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • 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)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@nwparker
nwparker force-pushed the nwparker/wsl-c1-wsl-orcad-host-transport branch from 655fbd7 to aed9fca Compare October 12, 2026 10:38
@nwparker
nwparker force-pushed the nwparker/wsl-c3-distro-holder branch from 4eba961 to 6e18d3a Compare October 12, 2026 10:38
@nwparker
nwparker force-pushed the nwparker/wsl-c3-distro-holder branch from 6e18d3a to cdb14ef Compare October 12, 2026 12:00
@nwparker
nwparker force-pushed the nwparker/wsl-c1-wsl-orcad-host-transport branch from 23df239 to 470ebaa Compare October 13, 2026 05:42
@nwparker
nwparker force-pushed the nwparker/wsl-c3-distro-holder branch from cdb14ef to 0eaeacd Compare October 13, 2026 06:33
@nwparker
nwparker changed the base branch from nwparker/wsl-c1-wsl-orcad-host-transport to main October 13, 2026 06:33
@nwparker
nwparker marked this pull request as ready for review October 13, 2026 06:33
@coderabbitai

coderabbitai Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough

Adds command construction and matching for WSL distro-holder processes. Adds validated persistent records for holder processes. Adds lifecycle operations to create, adopt, inspect, and release holders, with process verification, boot polling, and per-distro operation serialization. Tests cover command matching, record and process states, lifecycle failures, and concurrent operations.

Priority: ⬇️ Low

Merge Risk: 🔵 Low · up to 0eaea

Rare record-write failures can leave a holder running or prevent a holder record from being saved. These bounded cases merit fixes, but do not establish a broader deployment failure.

Pre-merge checks · Passed 4 · Failed 1

Failed Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 25 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed 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 identifies the main change: a detached WSL distro holder that can be re-adopted from a PID file.
Description check Passed The description is detailed and covers the change, rationale, testing, scope, and checklist. The Linked Issue section contains "N/A" despite the template requiring an actual issue link, and the full l…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0178fe1c-8b90-425d-b886-5ef1b7cf85bc
📥 Commits

Reviewing files that changed from the base of the PR and between 1e48f44 and 0eaeacd.

📒 Files selected for processing (4)
  • src/main/wsl/wsl-distro-holder-command.ts
  • src/main/wsl/wsl-distro-holder-record.ts
  • src/main/wsl/wsl-distro-holder.test.ts
  • src/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.

Comment on lines +113 to +145
/**
* 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
}

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.

🗄️ 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/main

Repository: 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.ts

Repository: 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.ts

Repository: 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.ts

Repository: 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.

Comment on lines +202 to +208
await writeWslDistroHolderRecord(userDataPath, record)
try {
await waitForDistroRunning(distro, () => observed.exit)
} catch (error) {
await stopRecordedHolder(record)
throw error
}

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

Suggested change
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
}

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