Skip to content

The agent that grows with you

fix(desktop): bound orphan-reap sweep so slow probes cannot stall boot

cez0060405bb319d0d7800
diff --git a/apps/desktop/electron/backend-claim.ts b/apps/desktop/electron/backend-claim.ts
index f00a4d5bc9a..16793d33ae8 100644
--- a/apps/desktop/electron/backend-claim.ts
+++ b/apps/desktop/electron/backend-claim.ts
@@ -36,13 +36,26 @@ export function execText(command: string, args: string[], { timeout = 3000 } = {
})
}
+/**
+ * Probe budget for the ORPHAN-REAP path (matchesParent / matchesIdentity /
+ * stopOwnedBackend). The claim path keeps the full 30s headroom — a freshly
+ * spawned backend's marker is load-bearing and a slow probe must not kill a
+ * healthy child (#93608). Reap only needs to tell "same process" from "gone
+ * or reused" for OLD records, and the ownership file can accumulate dozens of
+ * them (one per profile per launch), so a 30s budget per record would let a
+ * cold PowerShell 5.1 stall boot for minutes (#87169). 5s is plenty for a
+ * warm probe; a timeout degrades to "unknown" and the record is preserved for
+ * the next launch instead of blocking boot.
+ */
+export const REAP_PROBE_TIMEOUT_MS = 5_000
+
/**
* Cross-platform process start marker: a value that changes when a PID is
* reused, so `pid + marker` identifies one specific process incarnation.
* Throws when the probe fails — callers decide what a failure means (see
* `claimDecision` / `probeStartMarker`).
*/
-export async function processStartMarker(pid: number): Promise<string> {
+export async function processStartMarker(pid: number, timeoutMs: number = 30_000): Promise<string> {
// Cheap native dead-PID gate. Windows Get-Process / macOS `ps -p` exit 1
// on a missing PID (not ESRCH), so the identity matchers used to keep the
// orphan and re-probe it every launch (#92875). ESRCH is the code those
@@ -85,7 +98,9 @@ export async function processStartMarker(pid: number): Promise<string> {
],
// PowerShell 5.1 cold starts routinely exceed the default 3s execText
// budget (2.4-8s observed in #87169); give the marker probe headroom.
- { timeout: 30_000 }
+ // The claim path keeps this 30s budget; the orphan-reap path passes
+ // REAP_PROBE_TIMEOUT_MS so a slow probe cannot stall boot.
+ { timeout: timeoutMs }
)
if (!/^\d+$/.test(ticks)) {
diff --git a/apps/desktop/electron/backend-ownership.test.ts b/apps/desktop/electron/backend-ownership.test.ts
index 7910478a679..1e3b519ede3 100644
--- a/apps/desktop/electron/backend-ownership.test.ts
+++ b/apps/desktop/electron/backend-ownership.test.ts
@@ -178,6 +178,49 @@ test('startup reap preserves failed stops for the next launch', async () => {
assert.deepEqual(parseBackendOwnership(store.value()), [entry])
})
+test('startup reap stops at the deadline and preserves the unprocessed records', async () => {
+ const first = ownershipEntry({ pid: 60 })
+ const second = ownershipEntry({ pid: 61 })
+ const store = memoryStore(stored([first, second]))
+ const stop = vi.fn()
+
+ const ownership = createOwnership(store, {
+ // Each probe is slow enough to blow a 1ms budget after the first entry.
+ matchesIdentity: async () => {
+ await new Promise(resolve => setTimeout(resolve, 10))
+ return false
+ },
+ stop,
+ reapDeadlineMs: 1
+ })
+
+ assert.deepEqual(await ownership.reapOrphans(), [])
+ // The first entry was processed (dropped); the second was preserved for the
+ // next launch instead of stalling boot on a slow identity probe.
+ assert.deepEqual(parseBackendOwnership(store.value()), [second])
+})
+
+test('startup reap preserves would-be-reaped records when the budget runs out', async () => {
+ const first = ownershipEntry({ pid: 62 })
+ const second = ownershipEntry({ pid: 63 })
+ const store = memoryStore(stored([first, second]))
+ const stop = vi.fn()
+
+ const ownership = createOwnership(store, {
+ matchesIdentity: async () => {
+ await new Promise(resolve => setTimeout(resolve, 10))
+ return true
+ },
+ stop,
+ reapDeadlineMs: 1
+ })
+
+ assert.deepEqual(await ownership.reapOrphans(), [62])
+ // The second would have been reaped too, but the budget ran out — it is
+ // preserved so a later launch retries it.
+ assert.deepEqual(parseBackendOwnership(store.value()), [second])
+})
+
test('startup reap never stops a backend whose parent Electron is still alive', async () => {
const entry = { ...ownershipEntry({ pid: 54 }), parentPid: 100, parentStartMarker: 'os-start-parent' }
const store = memoryStore(stored([entry]))
diff --git a/apps/desktop/electron/backend-ownership.ts b/apps/desktop/electron/backend-ownership.ts
index 682dbe3f5b8..3ef1080f0eb 100644
--- a/apps/desktop/electron/backend-ownership.ts
+++ b/apps/desktop/electron/backend-ownership.ts
@@ -28,8 +28,22 @@ export interface BackendOwnershipDeps {
matchesParent: (entry: BackendOwnershipEntry) => Promise<boolean | undefined>
stop: (identity: BackendIdentity) => Promise<void> | void
store: BackendOwnershipStore
+ /**
+ * Overall time budget for one reap sweep. The ownership file legitimately
+ * accumulates one record per profile per launch, and each record can cost
+ * up to two identity probes (parent + backend) plus a stop — on Windows
+ * those shell out to PowerShell, whose 5.1 cold starts are slow (#87169).
+ * Without a bound, a large roster could stall boot for minutes while the
+ * renderer's 45s backend-boot budget expires and the user stares at the
+ * connecting screen. When the budget is exhausted the sweep preserves the
+ * unprocessed records for the next launch and returns what it reaped.
+ */
+ reapDeadlineMs?: number
}
+/** Default budget for one reap sweep (see `reapDeadlineMs`). */
+export const REAP_ORPHANS_DEADLINE_MS = 5_000
+
export interface BackendClaim extends BackendIdentity {
command?: string
parentPid?: number
@@ -222,8 +236,21 @@ export function createBackendOwnership(deps: BackendOwnershipDeps) {
const survivors: BackendOwnershipEntry[] = []
const reaped: number[] = []
+ const deadline = Date.now() + (deps.reapDeadlineMs ?? REAP_ORPHANS_DEADLINE_MS)
+
+ for (let i = 0; i < entries.length; i += 1) {
+ // Budget exhausted: preserve the unprocessed records so a later launch
+ // can retry them. A slow identity probe must never stall boot — the
+ // renderer's backend-boot budget is 45s and the spawn itself needs
+ // most of it.
+ if (Date.now() >= deadline) {
+ survivors.push(...entries.slice(i))
+
+ break
+ }
+
+ const entry = entries[i]
- for (const entry of entries) {
// A backend whose Electron parent is still running is NOT an orphan:
// reaping it would kill a live instance's session. This is what stops
// a second launch from SIGTERMing the running instance's backend even
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 583f6223a34..4c86f7a8ca9 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -42,7 +42,8 @@ import {
isPidOnlyStartMarker,
pidOnlyStartMarker,
probeStartMarker,
- processStartMarker
+ processStartMarker,
+ REAP_PROBE_TIMEOUT_MS
} from './backend-claim'
import { dashboardFallbackArgs, sourceDeclaresServe } from './backend-command'
import { createBackendConnectionState } from './backend-connection-state'
@@ -3401,7 +3402,7 @@ async function backendCommandForPid(pid) {
}
}
-async function processIdentityMatches(identity) {
+async function processIdentityMatches(identity, timeoutMs: number = 30_000) {
// Degraded PID-only identity (#93608): the start-marker probe failed while
// the child was verifiably alive, so only PID liveness can be checked here.
// backendIdentityMatches layers the command-line check on top before
@@ -3419,14 +3420,14 @@ async function processIdentityMatches(identity) {
}
try {
- return (await processStartMarker(identity.pid)) === identity.startMarker
+ return (await processStartMarker(identity.pid, timeoutMs)) === identity.startMarker
} catch (error) {
return error?.code === 'ENOENT' || error?.code === 'ESRCH' ? false : undefined
}
}
async function backendIdentityMatches(identity) {
- const processMatches = await processIdentityMatches(identity)
+ const processMatches = await processIdentityMatches(identity, REAP_PROBE_TIMEOUT_MS)
if (processMatches !== true) {
return processMatches
@@ -3447,17 +3448,26 @@ async function backendParentMatches(entry) {
}
try {
- return (await processStartMarker(entry.parentPid)) === entry.parentStartMarker
+ return (await processStartMarker(entry.parentPid, REAP_PROBE_TIMEOUT_MS)) === entry.parentStartMarker
} catch (error) {
return error?.code === 'ENOENT' || error?.code === 'ESRCH' ? false : undefined
}
}
async function stopOwnedBackend(identity) {
- if ((await processIdentityMatches(identity)) !== true) {
+ const matches = await processIdentityMatches(identity, REAP_PROBE_TIMEOUT_MS)
+
+ if (matches === false) {
return
}
+ if (matches !== true) {
+ // Identity probe failed (not confirmed gone): preserve the record so a
+ // later launch retries the stop instead of dropping it and leaking the
+ // backend. reapOrphans keeps the entry when stop() throws.
+ throw new Error(`Could not verify backend PID ${identity.pid} before stopping it.`)
+ }
+
if (IS_WINDOWS) {
forceKillProcessTree(identity.pid)
} else {
@@ -3474,7 +3484,7 @@ async function stopOwnedBackend(identity) {
const deadline = Date.now() + 1500
while (Date.now() < deadline) {
- if ((await processIdentityMatches(identity)) !== true) {
+ if ((await processIdentityMatches(identity, REAP_PROBE_TIMEOUT_MS)) !== true) {
return
}
@@ -3483,7 +3493,7 @@ async function stopOwnedBackend(identity) {
// Revalidate immediately before escalation so PID reuse cannot target a
// replacement process.
- if ((await processIdentityMatches(identity)) === true) {
+ if ((await processIdentityMatches(identity, REAP_PROBE_TIMEOUT_MS)) === true) {
try {
process.kill(-identity.pid, 'SIGKILL')
} catch {
@@ -3493,7 +3503,7 @@ async function stopOwnedBackend(identity) {
}
await new Promise(resolve => setTimeout(resolve, 50))
- const remaining = await processIdentityMatches(identity)
+ const remaining = await processIdentityMatches(identity, REAP_PROBE_TIMEOUT_MS)
if (remaining !== false) {
throw new Error(`Backend PID ${identity.pid} did not stop cleanly.`)