Skip to content

The agent that grows with you

fix(desktop): skip dead-backend ledger records before attach

finn763f94da6232a20
diff --git a/apps/desktop/electron/backend-discovery.test.ts b/apps/desktop/electron/backend-discovery.test.ts
index 969bbfc9cd1..349e03a8a69 100644
--- a/apps/desktop/electron/backend-discovery.test.ts
+++ b/apps/desktop/electron/backend-discovery.test.ts
@@ -7,6 +7,7 @@ import { test } from 'vitest'
import { attachOrReserveSpawn, attachToHostBackend } from './host-backend-attach'
import { claimHostSpawnGate } from './host-spawn-gate'
+import { spawnOrAttach } from './backend-discovery'
import { runPrimaryBackendStartup } from './primary-backend-startup'
const LEDGER = JSON.stringify([
@@ -369,3 +370,80 @@ test('a published token the websocket rejects is not adopted', async () => {
assert.equal(attached, null)
assert.equal(probed, 1)
})
+
+/**
+ * #123586: the ledger survives the process it describes, so after any
+ * shutdown the newest record points at a dead PID. Attaching to it dials a
+ * port nobody listens on and burns the wait budget (a squatted port can burn
+ * all of it); a PID that is gone must decide `spawn` before any network I/O.
+ */
+test('a record whose pid is dead decides spawn instead of attach', () => {
+ const decision = spawnOrAttach({
+ isolated: false,
+ isPidAlive: () => false,
+ records: JSON.parse(LEDGER)
+ } as Parameters<typeof spawnOrAttach>[0])
+
+ assert.deepEqual(decision, { action: 'spawn', reason: 'no-running-backend' })
+})
+
+test('a dead pid is skipped before any network probe runs', async () => {
+ let servedTokenCalls = 0
+ let readyCalls = 0
+ let probeCalls = 0
+
+ const attached = await attachToHostBackend({ isolated: false, ledgerPath: '/ledger.json' }, {
+ ...attachDeps(LEDGER),
+ isPidAlive: () => false,
+ probeWebSocket: async () => {
+ probeCalls += 1
+
+ return { ok: true }
+ },
+ resolveServedToken: async () => {
+ servedTokenCalls += 1
+
+ return 'served-token'
+ },
+ waitForReady: async () => {
+ readyCalls += 1
+ }
+ } as Parameters<typeof attachToHostBackend>[1])
+
+ assert.equal(attached, null)
+ assert.equal(servedTokenCalls, 0, 'a dead pid must not be probed over HTTP')
+ assert.equal(readyCalls, 0)
+ assert.equal(probeCalls, 0)
+})
+
+test('a dead newest record falls through to a live older one', async () => {
+ const [ordinary] = JSON.parse(LEDGER)
+ const probedPorts: number[] = []
+
+ const ledger = JSON.stringify([
+ ordinary,
+ { ...ordinary, pid: 5150, port: 61_000, registered_at: ordinary.registered_at - 1 }
+ ])
+
+ const attached = await attachToHostBackend({ isolated: false, ledgerPath: '/ledger.json' }, {
+ ...attachDeps(ledger),
+ isPidAlive: (pid: number) => pid !== 4711,
+ resolveServedToken: async (baseUrl: string) => {
+ probedPorts.push(Number(new URL(baseUrl).port))
+
+ return 'served-token'
+ }
+ } as Parameters<typeof attachToHostBackend>[1])
+
+ assert.equal(attached?.pid, 5150)
+ assert.deepEqual(probedPorts, [61_000], 'only the live record may be dialled')
+})
+
+test('a live pid still attaches (liveness gate must not break the hot path)', async () => {
+ const attached = await attachToHostBackend({ isolated: false, ledgerPath: '/ledger.json' }, {
+ ...attachDeps(LEDGER),
+ isPidAlive: () => true
+ } as Parameters<typeof attachToHostBackend>[1])
+
+ assert.equal(attached?.pid, 4711)
+})
diff --git a/apps/desktop/electron/backend-discovery.ts b/apps/desktop/electron/backend-discovery.ts
index dcd62411afa..07b269ba6da 100644
--- a/apps/desktop/electron/backend-discovery.ts
+++ b/apps/desktop/electron/backend-discovery.ts
@@ -117,19 +117,32 @@ export function parseSpawnLedger(contents: unknown): HostBackendRecord[] {
*
* Newest registration first, so a host that briefly holds a stale record and a
* fresh one tries the live one before falling back.
+ *
+ * `isPidAlive` skips records whose backend is already gone (#123586): the
+ * ledger survives the process it describes, so after any shutdown the newest
+ * record points at a dead PID and dialling its port only burns the wait
+ * budget. Absent the probe, every record is assumed live (today's behaviour).
+ *
+ * ponytail: PID-only check — a reused PID still faces the HTTP probe and the
+ * session-token handshake below, which stay the boundary that validates a
+ * record. Read the other end's start time too if a same-PID impostor ever
+ * attaches in the wild (no stdlib way to ask another PID's create_time).
*/
export function spawnOrAttach({
isolated = false,
- records = []
+ records = [],
+ isPidAlive
}: {
isolated?: boolean
records?: HostBackendRecord[]
+ isPidAlive?: (pid: number) => boolean
}): SpawnOrAttachDecision {
if (isolated) {
return { action: 'spawn', reason: 'isolated' }
}
- const [newest] = [...records].sort((left, right) => right.registeredAt - left.registeredAt)
+ const live = isPidAlive ? records.filter(record => isPidAlive(record.pid)) : records
+ const [newest] = [...live].sort((left, right) => right.registeredAt - left.registeredAt)
return newest ? { action: 'attach', record: newest } : { action: 'spawn', reason: 'no-running-backend' }
}
diff --git a/apps/desktop/electron/host-backend-attach.ts b/apps/desktop/electron/host-backend-attach.ts
index 44a603f4529..ccb756c8534 100644
--- a/apps/desktop/electron/host-backend-attach.ts
+++ b/apps/desktop/electron/host-backend-attach.ts
@@ -42,6 +42,12 @@ export interface HostBackendAttachDeps {
waitForReady: (baseUrl: string, token: string) => Promise<unknown>
/** Reject unless `/api/ws` accepts the token — the leg the renderer uses. */
probeWebSocket: (wsUrl: string) => Promise<{ ok: boolean; reason?: string }>
+ /**
+ * PID liveness probe (real: `isPidAliveWindows`). Records whose backend is
+ * already gone are skipped before any network I/O (#123586). Absent, every
+ * record is probed as before.
+ */
+ isPidAlive?: (pid: number) => boolean
log: (message: string) => void
}
@@ -118,7 +124,7 @@ export async function attachToHostBackend(
deps: HostBackendAttachDeps
): Promise<AttachedBackend | null> {
const records = parseSpawnLedger(deps.readLedger(ledgerPath))
- const decision = spawnOrAttach({ isolated, records })
+ const decision = spawnOrAttach({ isolated, records, isPidAlive: deps.isPidAlive })
if (decision.action === 'spawn') {
if (decision.reason === 'isolated') {
@@ -129,7 +135,14 @@ export async function attachToHostBackend(
}
// Newest first, then the rest: a stale record must not cost us a live one.
- const ordered = [decision.record, ...records.filter(candidate => candidate !== decision.record)]
+ // Dead PIDs are skipped here too, so the fallback rung never dials a port
+ // whose owner is already gone (#123586).
+ const ordered = [
+ decision.record,
+ ...records.filter(
+ candidate => candidate !== decision.record && (!deps.isPidAlive || deps.isPidAlive(candidate.pid))
+ )
+ ]
for (const record of ordered) {
const attached = await validate(record, deps)
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 55da3c1fd14..420f27aff0b 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -12679,6 +12679,9 @@ function attachToRunningHostBackend(): Promise<AttachedBackend | null> {
function hostBackendAttachDeps() {
return {
+ // Skip ledger records whose backend is already gone before dialling
+ // anything: the ledger survives the process it describes (#123586).
+ isPidAlive: isPidAliveWindows,
log: rememberLog,
readLedger: (target: string) => {
try {