Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

perf(wsl): a held WSL spawn reads the running list once, reusing only its own read (#36077)

Neil4f18d01a97c7
diff --git a/src/main/daemon/daemon-wsl-hold-read-anchor.test.ts b/src/main/daemon/daemon-wsl-hold-read-anchor.test.ts
new file mode 100644
index 00000000000..e168a095d2d
--- /dev/null
+++ b/src/main/daemon/daemon-wsl-hold-read-anchor.test.ts
@@ -0,0 +1,99 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type * as WslModule from '../wsl'
+import {
+ _resetWslBackgroundDistroGateForTests,
+ noteWslDistroMayHaveStopped
+} from '../wsl-background-distro-gate'
+import {
+ _resetRunningWslDistroCacheForTests,
+ resolveRunningWslDistros
+} from '../wsl-running-distro-cache'
+import { parseWslDistroHold } from '../../shared/wsl-distro-stopped-hold'
+import {
+ holdPassiveRestoreOfStoppedWslDistro,
+ WSL_HOLD_READ_MAX_AGE_MS,
+ wslHoldReadAnchor
+} from './daemon-wsl-passive-restore-hold'
+
+const running = vi.hoisted(() => {
+ const value: { distros: string[] } = { distros: ['Ubuntu'] }
+ return value
+})
+const probe = vi.hoisted(() => vi.fn(async () => [...running.distros]))
+vi.mock('../wsl', async (importOriginal) => ({
+ ...(await importOriginal<typeof WslModule>()),
+ listRunningWslDistrosAsync: (options: Parameters<typeof resolveRunningWslDistros>[1]) =>
+ resolveRunningWslDistros(probe, options)
+}))
+
+const HELD = { wslBackgroundStart: true as const, isNewSession: true }
+// The startup-target hold and the provider hold of one spawn share that spawn's anchor.
+const hold = (anchor?: number) =>
+ holdPassiveRestoreOfStoppedWslDistro(
+ anchor === undefined ? HELD : { ...HELD, wslHoldReadAnchor: anchor },
+ 'Ubuntu'
+ )
+const heldState = (error: unknown) =>
+ error instanceof Error ? parseWslDistroHold(error.message)?.state : undefined
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['performance', 'Date', 'setTimeout'] })
+ running.distros = ['Ubuntu']
+ probe.mockClear()
+})
+
+afterEach(() => {
+ _resetWslBackgroundDistroGateForTests()
+ _resetRunningWslDistroCacheForTests()
+ vi.useRealTimers()
+})
+
+describe('a held WSL spawn reuses only its own running read (E9)', () => {
+ it('runs one probe across its startup-target and provider holds', async () => {
+ const anchor = wslHoldReadAnchor()
+ await hold(anchor)
+ await hold(anchor)
+ expect(probe).toHaveBeenCalledTimes(1)
+ })
+
+ it('holds a stopped distro at both, still with one probe', async () => {
+ running.distros = []
+ const anchor = wslHoldReadAnchor()
+ expect(heldState(await hold(anchor).catch((error: unknown) => error))).toBe('stopped')
+ expect(heldState(await hold(anchor).catch((error: unknown) => error))).toBe('stopped')
+ expect(probe).toHaveBeenCalledTimes(1)
+ })
+
+ it("never reuses another spawn's read", async () => {
+ await hold(wslHoldReadAnchor())
+ vi.advanceTimersByTime(2)
+ await hold(wslHoldReadAnchor())
+ expect(probe).toHaveBeenCalledTimes(2)
+ })
+
+ it('reads fresh without an anchor (a spawn that skipped the startup-target hold)', async () => {
+ await hold(wslHoldReadAnchor())
+ await hold()
+ expect(probe).toHaveBeenCalledTimes(2)
+ })
+
+ it('reads fresh, and holds, after a stop noted between the two holds', async () => {
+ const anchor = wslHoldReadAnchor()
+ await hold(anchor)
+ noteWslDistroMayHaveStopped('Ubuntu')
+ running.distros = []
+ // The stop's settle window has to pass before a read counts.
+ const provider = hold(anchor).catch((error: unknown) => error)
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(heldState(await provider)).toBe('stopped')
+ expect(probe).toHaveBeenCalledTimes(2)
+ })
+
+ it("reads fresh once the spawn's own read is older than the cap (a respawn between holds)", async () => {
+ const anchor = wslHoldReadAnchor()
+ await hold(anchor)
+ vi.advanceTimersByTime(WSL_HOLD_READ_MAX_AGE_MS + 1)
+ await hold(anchor)
+ expect(probe).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/src/main/daemon/daemon-wsl-passive-restore-hold.ts b/src/main/daemon/daemon-wsl-passive-restore-hold.ts
index 39295d10995..794593bcebd 100644
--- a/src/main/daemon/daemon-wsl-passive-restore-hold.ts
+++ b/src/main/daemon/daemon-wsl-passive-restore-hold.ts
@@ -2,6 +2,16 @@ import { readWslDistroRunningState } from '../wsl-background-distro-gate'
import { wslDistroHoldMessage } from '../../shared/wsl-distro-stopped-hold'
import type { PtySpawnOptions } from '../providers/pty-provider-contract'
+/** A probe started this close before a hold still counts as that spawn's own read. */
+const WSL_HOLD_READ_ANCHOR_SLACK_MS = 1
+/** Even this spawn's own read goes stale: a daemon respawn or a session lock can sit between holds. */
+export const WSL_HOLD_READ_MAX_AGE_MS = 2_000
+
+/** The anchor a spawn's first hold reads after; later holds of the same spawn reuse that read. */
+export function wslHoldReadAnchor(): number {
+ return performance.now() - WSL_HOLD_READ_ANCHOR_SLACK_MS
+}
+
/**
* Launch restore, a reload, a remount or main's background start (orchestration, automations,
* recovery) the user did not ask for would start a stopped distro's `wsl.exe` (E9). It starts
@@ -11,7 +21,12 @@ import type { PtySpawnOptions } from '../providers/pty-provider-contract'
export async function holdPassiveRestoreOfStoppedWslDistro(
opts: Pick<
PtySpawnOptions,
- 'wslPassiveRestore' | 'wslBackgroundStart' | 'sessionId' | 'isNewSession' | 'attachOnly'
+ | 'wslPassiveRestore'
+ | 'wslBackgroundStart'
+ | 'wslHoldReadAnchor'
+ | 'sessionId'
+ | 'isNewSession'
+ | 'attachOnly'
>,
wslDistro: string | undefined
): Promise<void> {
@@ -21,7 +36,18 @@ export async function holdPassiveRestoreOfStoppedWslDistro(
if (!wslDistro || opts.attachOnly === true || !(passiveRestore || opts.wslBackgroundStart)) {
return
}
- const state = await readWslDistroRunningState(wslDistro, { retryUnverifiable: true })
+ // Without this spawn's anchor the read is fresh; a noted stop or wake still raises the floor.
+ const state = await readWslDistroRunningState(wslDistro, {
+ ...(opts.wslHoldReadAnchor === undefined
+ ? {}
+ : {
+ startedAfter: Math.max(
+ opts.wslHoldReadAnchor,
+ performance.now() - WSL_HOLD_READ_MAX_AGE_MS
+ )
+ }),
+ retryUnverifiable: true
+ })
if (state !== 'running') {
throw new Error(wslDistroHoldMessage(wslDistro, state))
}
diff --git a/src/main/ipc/pty/ipc/spawn-options.ts b/src/main/ipc/pty/ipc/spawn-options.ts
index b14d47e2290..49d523bfc4a 100644
--- a/src/main/ipc/pty/ipc/spawn-options.ts
+++ b/src/main/ipc/pty/ipc/spawn-options.ts
@@ -53,6 +53,9 @@ export async function buildPtyIpcSpawnOptions(ctx: PtyIpcSpawnState): Promise<vo
if (args.wslPassiveRestore === true) {
ctx.spawnOptions.wslPassiveRestore = true
}
+ if (ctx.wslHoldReadAnchor !== undefined) {
+ ctx.spawnOptions.wslHoldReadAnchor = ctx.wslHoldReadAnchor
+ }
ctx.spawnEnv = launch.env
ctx.launchCommand = launch.launchCommand
ctx.provisionalPtySize = seedPtySpawnSize({
diff --git a/src/main/ipc/pty/ipc/spawn-preflight.ts b/src/main/ipc/pty/ipc/spawn-preflight.ts
index cd303bbf6f7..5f00527778f 100644
--- a/src/main/ipc/pty/ipc/spawn-preflight.ts
+++ b/src/main/ipc/pty/ipc/spawn-preflight.ts
@@ -110,6 +110,7 @@ export async function preparePtyIpcSpawnPreflight(ctx: PtyIpcSpawnState): Promis
ctx.startupCwdFallback = target.startupCwdFallback
ctx.terminalRuntimeOptions = target.terminalRuntimeOptions
ctx.expectedWslDistro = target.expectedWslDistro
+ ctx.wslHoldReadAnchor = target.wslHoldReadAnchor
ctx.codexSelectionTarget = target.codexSelectionTarget
ctx.spawnTiming.mark('preflight')
args.env = withClaudeProfileTerminalEnv(args.env, ctx.codexSelectionTarget)
diff --git a/src/main/ipc/pty/ipc/spawn-state.ts b/src/main/ipc/pty/ipc/spawn-state.ts
index b8687560e7a..3f033a7c3d5 100644
--- a/src/main/ipc/pty/ipc/spawn-state.ts
+++ b/src/main/ipc/pty/ipc/spawn-state.ts
@@ -65,6 +65,7 @@ export type PtyIpcSpawnState = {
effectiveSessionId: string | undefined
effectiveSessionAppId: string | undefined
expectedWslDistro: string | null
+ wslHoldReadAnchor: number | undefined
baseEnv: Record<string, string> | undefined
effectiveLaunchConfig: SleepingAgentLaunchConfig | undefined
preAllocatedHandle: string | null
@@ -143,6 +144,7 @@ export function createPtyIpcSpawnState(
effectiveSessionId: undefined,
effectiveSessionAppId: undefined,
expectedWslDistro: null,
+ wslHoldReadAnchor: undefined,
baseEnv: undefined,
effectiveLaunchConfig: undefined,
preAllocatedHandle: null,
diff --git a/src/main/ipc/pty/pty-spawn-wsl-passive-restore-hold.test.ts b/src/main/ipc/pty/pty-spawn-wsl-passive-restore-hold.test.ts
index 54c1d71048a..0695eca8f28 100644
--- a/src/main/ipc/pty/pty-spawn-wsl-passive-restore-hold.test.ts
+++ b/src/main/ipc/pty/pty-spawn-wsl-passive-restore-hold.test.ts
@@ -51,7 +51,7 @@ vi.mock('../../codex/codex-state-db-backfill-recovery', () =>
import('./pty-ipc-mock-registry').then((m) => m.codexBackfillRecoveryModuleMock())
)
const runningStateMock = vi.hoisted(() =>
- vi.fn(async (_distro: string, _options?: unknown) => 'stopped')
+ vi.fn(async (_distro: string, _options?: { startedAfter?: number }) => 'stopped')
)
vi.mock('../../wsl-background-distro-gate', async (importOriginal) => ({
...(await importOriginal<object>()),
@@ -129,4 +129,18 @@ describe('a passive WSL restore with a stopped distro', () => {
expect(runningStateMock).not.toHaveBeenCalled()
expect(spawnMock).toHaveBeenCalledTimes(2)
})
+
+ it("hands the provider this spawn's read anchor, so its hold reuses only that read", async () => {
+ const providerSpawn = vi.fn().mockResolvedValue({ id: 'pty-daemon' })
+ installDaemonTestProvider({ spawn: providerSpawn })
+ register()
+ runningStateMock.mockResolvedValue('running')
+ await restore()
+
+ const anchor = runningStateMock.mock.calls[0]?.[1]?.startedAfter
+ expect(anchor).toEqual(expect.any(Number))
+ expect(providerSpawn).toHaveBeenCalledWith(
+ expect.objectContaining({ wslHoldReadAnchor: anchor })
+ )
+ })
})
diff --git a/src/main/ipc/pty/runtime/spawn-options.ts b/src/main/ipc/pty/runtime/spawn-options.ts
index 75f7dbfe4c9..1ceaa5a386a 100644
--- a/src/main/ipc/pty/runtime/spawn-options.ts
+++ b/src/main/ipc/pty/runtime/spawn-options.ts
@@ -128,6 +128,9 @@ export async function buildRuntimePtySpawnOptions(
if (!ctx.preAdoptedStablePane && args.wslUserAct !== true) {
ctx.spawnOptions.wslBackgroundStart = true
}
+ if (ctx.wslHoldReadAnchor !== undefined) {
+ ctx.spawnOptions.wslHoldReadAnchor = ctx.wslHoldReadAnchor
+ }
if (
args.onPtySpawnCommitted &&
(ctx.provider instanceof LocalPtyProvider || routesFreshSpawnsToLocalProvider(ctx.provider))
diff --git a/src/main/ipc/pty/runtime/spawn-preflight.ts b/src/main/ipc/pty/runtime/spawn-preflight.ts
index 69031e67195..91c54d93b2a 100644
--- a/src/main/ipc/pty/runtime/spawn-preflight.ts
+++ b/src/main/ipc/pty/runtime/spawn-preflight.ts
@@ -90,6 +90,7 @@ export async function prepareRuntimePtySpawn(
ctx.terminalRuntimeOptions = target.terminalRuntimeOptions
ctx.daemonShellOverride = ctx.terminalRuntimeOptions.shellOverride
ctx.expectedWslDistro = target.expectedWslDistro
+ ctx.wslHoldReadAnchor = target.wslHoldReadAnchor
ctx.codexSelectionTarget = target.codexSelectionTarget
args.env = withClaudeProfileTerminalEnv(args.env, ctx.codexSelectionTarget)
ctx.claudeAuth =
diff --git a/src/main/ipc/pty/runtime/spawn-state.ts b/src/main/ipc/pty/runtime/spawn-state.ts
index d123c915189..bb60bf77261 100644
--- a/src/main/ipc/pty/runtime/spawn-state.ts
+++ b/src/main/ipc/pty/runtime/spawn-state.ts
@@ -58,6 +58,7 @@ export type RuntimePtySpawnState = {
effectiveSessionAppId: string | undefined
ownsNewIncarnation: boolean
expectedWslDistro: string | null
+ wslHoldReadAnchor: number | undefined
/** The host's verdict on the spawn's resume; a refused one starts the pane's plain shell. */
resumeAdmission: ResumeSpawnAdmission | null
codexSelectionTarget: CodexAccountSelectionTarget
@@ -206,6 +207,7 @@ export function createRuntimePtySpawnState(
effectiveSessionAppId: undefined,
ownsNewIncarnation: false,
expectedWslDistro: null,
+ wslHoldReadAnchor: undefined,
resumeAdmission: null,
codexSelectionTarget: { runtime: 'host' },
launchCommand: undefined,
diff --git a/src/main/ipc/pty/spawn-startup-target.ts b/src/main/ipc/pty/spawn-startup-target.ts
index eea1c28725e..0e3cc9ee490 100644
--- a/src/main/ipc/pty/spawn-startup-target.ts
+++ b/src/main/ipc/pty/spawn-startup-target.ts
@@ -14,7 +14,10 @@ import {
type ProjectRuntimeResolutionStore
} from '../../local-project-runtime-resolution'
import type { PtySpawnOptions, PtySpawnResult } from '../../providers/pty-provider-contract'
-import { holdPassiveRestoreOfStoppedWslDistro } from '../../daemon/daemon-wsl-passive-restore-hold'
+import {
+ holdPassiveRestoreOfStoppedWslDistro,
+ wslHoldReadAnchor as wslHoldReadAnchorNow
+} from '../../daemon/daemon-wsl-passive-restore-hold'
import { normalizeWindowsTerminalCwd } from '../../providers/windows-shell-args'
import { wslUncDirectoryExistsAsync } from '../../wsl'
import { getCodexSelectionTargetForPty } from './host-env/codex-home'
@@ -36,6 +39,8 @@ export type PtySpawnStartupTarget = {
terminalRuntimeOptions: LocalWindowsTerminalRuntimeOptions
expectedWslDistro: string | null
codexSelectionTarget: CodexAccountSelectionTarget
+ /** Set when this hold read the running list: the provider hold reuses that read, not another spawn's. */
+ wslHoldReadAnchor?: number
}
type PtySpawnStartupArgs = {
@@ -76,16 +81,22 @@ export async function resolvePtySpawnStartupTarget(
args.shellOverride,
process.env.COMSPEC || 'powershell.exe'
)
- if (args.wslStartHold && !args.preAdopted) {
+ const heldWslDistro =
+ args.wslStartHold && !args.preAdopted
+ ? resolveWslSessionContext({
+ cwd: args.cwd,
+ sessionId: args.sessionId,
+ shellOverride: terminalRuntimeOptions.shellOverride,
+ terminalWindowsWslDistro: terminalRuntimeOptions.terminalWindowsWslDistro
+ })?.distro
+ : undefined
+ // The provider hold reuses this read (and only this spawn's) through the anchor.
+ const wslHoldReadAnchor = heldWslDistro ? wslHoldReadAnchorNow() : undefined
+ if (args.wslStartHold && wslHoldReadAnchor !== undefined) {
// E9: whichever provider runs (daemon, degraded or off), and before the cwd probe's `wsl.exe`.
await holdPassiveRestoreOfStoppedWslDistro(
- args.wslStartHold,
- resolveWslSessionContext({
- cwd: args.cwd,
- sessionId: args.sessionId,
- shellOverride: terminalRuntimeOptions.shellOverride,
- terminalWindowsWslDistro: terminalRuntimeOptions.terminalWindowsWslDistro
- })?.distro
+ { ...args.wslStartHold, wslHoldReadAnchor },
+ heldWslDistro
)
}
const startup = args.preAdopted
@@ -109,6 +120,7 @@ export async function resolvePtySpawnStartupTarget(
: startup.cwd,
terminalRuntimeOptions,
expectedWslDistro,
+ ...(wslHoldReadAnchor === undefined ? {} : { wslHoldReadAnchor }),
codexSelectionTarget: getCodexSelectionTargetForPty(
terminalRuntimeOptions.shellOverride,
startup.cwd,
diff --git a/src/main/providers/pty-provider-contract.ts b/src/main/providers/pty-provider-contract.ts
index 9df9433f049..d0a16c91098 100644
--- a/src/main/providers/pty-provider-contract.ts
+++ b/src/main/providers/pty-provider-contract.ts
@@ -99,6 +99,8 @@ export type PtySpawnOptions = {
wslPassiveRestore?: true
/** A main-side start no user act asked for (orchestration, automations, recovery): held like a passive restore. */
wslBackgroundStart?: true
+ /** performance.now() before this spawn's startup-target hold read: the provider hold reuses only that read. */
+ wslHoldReadAnchor?: number
agentSessionEnsure?: {
claim: AgentSessionExecutionClaim
surface: AgentSessionSurfaceBinding