Skip to content

The agent that grows with you

fix: the installation-id repair lock no longer spawns ps per poll

Tekniumb728467842c3
diff --git a/apps/desktop/electron/desktop-installation.test.ts b/apps/desktop/electron/desktop-installation.test.ts
index 741fbefff47..9be308a121e 100644
--- a/apps/desktop/electron/desktop-installation.test.ts
+++ b/apps/desktop/electron/desktop-installation.test.ts
@@ -1,4 +1,5 @@
import assert from 'node:assert/strict'
+import type * as ChildProcess from 'node:child_process'
import { spawn, spawnSync } from 'node:child_process'
import fs from 'node:fs'
import os from 'node:os'
@@ -9,6 +10,39 @@ import { test, vi } from 'vitest'
import { loadOrCreateInstallationId, parseInstallationId, sshOwnershipId } from './desktop-installation'
import { formatCreateTime, processCreateTimeSync } from './update-marker'
+// Every `ps` the marker probes run, answerable by a test that plays macOS.
+const ps = vi.hoisted(() => ({ calls: [] as string[][], stub: null as null | ((args: string[]) => string) }))
+
+vi.mock('node:child_process', async importOriginal => {
+ const actual = await importOriginal<typeof ChildProcess>()
+
+ const execFileSync = ((file: string, args: string[], options: any) => {
+ if (file !== 'ps' || !ps.stub) {
+ return actual.execFileSync(file, args, options)
+ }
+
+ ps.calls.push(args)
+
+ return ps.stub(args)
+ }) as typeof actual.execFileSync
+
+ return { ...actual, default: { ...actual, execFileSync }, execFileSync }
+})
+
+function asMacOS(stub: (args: string[]) => string, run: () => void) {
+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
+ Object.defineProperty(process, 'platform', { ...platform, value: 'darwin' })
+ ps.calls = []
+ ps.stub = stub
+
+ try {
+ run()
+ } finally {
+ ps.stub = null
+ Object.defineProperty(process, 'platform', platform)
+ }
+}
+
const ID_A = '11111111-1111-4111-8111-111111111111'
const ID_B = '22222222-2222-4222-8222-222222222222'
@@ -219,3 +253,52 @@ test('a live holder with no creation time is live only within the v1 ceiling', a
holder.kill()
}
})
+
+// Review (kshitijk4poor, P3): the repair lock ran a synchronous `ps` (macOS) /
+// PowerShell (Windows, up to 15 s) on the main thread for our OWN creation time,
+// which Electron already knows, and re-probed the holder's every 25 ms poll.
+test('the repair lock records our creation time from Electron, without a ps spawn', () =>
+ withTempDir(directory => {
+ const filePath = path.join(directory, 'desktop-installation.json')
+ const writes = vi.spyOn(fs, 'writeSync')
+ let lockBody = ''
+ const electron = process as { getCreationTime?: () => number | null }
+ electron.getCreationTime = () => 1_791_079_000_250
+
+ try {
+ asMacOS(
+ () => 'Sun Oct 4 12:00:00 2026',
+ () => assert.equal(loadOrCreateInstallationId(filePath, () => ID_A), ID_A)
+ )
+ lockBody = String(writes.mock.calls[0]?.[1])
+ } finally {
+ delete electron.getCreationTime
+ writes.mockRestore()
+ }
+
+ assert.equal(lockBody, `${process.pid}\nct:1791079000.250\n`)
+ assert.deepEqual(
+ ps.calls.filter(args => args.includes(String(process.pid))),
+ [],
+ 'no ps for our own pid'
+ )
+ }))
+
+test('a contended repair lock probes its holder creation time once per wait, liveness every poll', () =>
+ withTempDir(directory => {
+ const filePath = path.join(directory, 'desktop-installation.json')
+ const holder = process.ppid // alive to signal 0
+ const started = Date.UTC(2026, 9, 4, 12) / 1000
+ fs.writeFileSync(`${filePath}.repair.lock`, `${holder}\nct:${formatCreateTime(started)}\n`)
+ let statPolls = 0
+
+ // The holder matches its recorded creation time, then dies into a zombie on the 5th poll.
+ asMacOS(
+ args => (args.includes('lstart=') ? 'Sun Oct 4 12:00:00 2026' : ++statPolls >= 5 ? 'Z' : 'S'),
+ () => assert.equal(loadOrCreateInstallationId(filePath, () => ID_A), ID_A)
+ )
+
+ assert.equal(statPolls, 5, 'liveness is re-read every poll')
+ const holderProbes = ps.calls.filter(args => args.includes('lstart=') && args.includes(String(holder)))
+ assert.equal(holderProbes.length, 1, 'one creation-time probe for the holder')
+ }))
diff --git a/apps/desktop/electron/desktop-installation.ts b/apps/desktop/electron/desktop-installation.ts
index 271ccb72219..11241ca26c5 100644
--- a/apps/desktop/electron/desktop-installation.ts
+++ b/apps/desktop/electron/desktop-installation.ts
@@ -2,7 +2,7 @@ import crypto from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
-import { formatCreateTime, lockHolderIsLiveSync, processCreateTimeSync } from './update-marker'
+import { formatCreateTime, lockHolderIsLiveSync, ownCreateTimeSync, processCreateTimeSync } from './update-marker'
const INSTALLATION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
@@ -52,13 +52,35 @@ function waitForRepair() {
*/
const EMPTY_LOCK_RECLAIM_POLLS = 20
+type RepairLockHolderJudge = (pid: number, recordedCt: number | null, writtenAtS: number) => boolean
+
+/**
+ * The repair lock holder's liveness for ONE wait: liveness is re-read every
+ * 25 ms poll, but each pid's creation time is probed once — on macOS a `ps`,
+ * on Windows a PowerShell of up to 15 s, both blocking the main thread at
+ * module init. Scoped to the wait like `cachedCreateTimeProbe`.
+ */
+function repairLockHolderJudge(): RepairLockHolderJudge {
+ const createTimes = new Map<number, number | null>()
+
+ const createTime = (pid: number) => {
+ if (!createTimes.has(pid)) {
+ createTimes.set(pid, processCreateTimeSync(pid))
+ }
+
+ return createTimes.get(pid) ?? null
+ }
+
+ return (pid, recordedCt, writtenAtS) => lockHolderIsLiveSync(pid, recordedCt, writtenAtS, createTime)
+}
+
function repairLockBody(): string {
- const ct = processCreateTimeSync(process.pid)
+ const ct = ownCreateTimeSync()
return `${process.pid}\n${ct === null ? '' : `ct:${formatCreateTime(ct)}\n`}`
}
-function reclaimDeadRepairLock(repairPath: string, emptyPolls: number): boolean {
+function reclaimDeadRepairLock(repairPath: string, emptyPolls: number, holderIsLive: RepairLockHolderJudge): boolean {
let raw: Buffer
let writtenAtS: number
@@ -76,7 +98,7 @@ function reclaimDeadRepairLock(repairPath: string, emptyPolls: number): boolean
const dead =
pid === null
? emptyPolls >= EMPTY_LOCK_RECLAIM_POLLS
- : !lockHolderIsLiveSync(pid, ctMatch ? Number(ctMatch[1]) : null, writtenAtS)
+ : !holderIsLive(pid, ctMatch ? Number(ctMatch[1]) : null, writtenAtS)
if (!dead) {
return false
@@ -136,7 +158,7 @@ function dropReclaimClaim(claim: string) {
}
/** Count consecutive empty-lock polls, then reclaim a dead lock or back off. */
-function waitOnContendedRepairLock(repairPath: string, emptyPolls: number): number {
+function waitOnContendedRepairLock(repairPath: string, emptyPolls: number, holderIsLive: RepairLockHolderJudge): number {
let polls: number
try {
@@ -145,7 +167,7 @@ function waitOnContendedRepairLock(repairPath: string, emptyPolls: number): numb
polls = 0
}
- if (!reclaimDeadRepairLock(repairPath, polls)) {
+ if (!reclaimDeadRepairLock(repairPath, polls, holderIsLive)) {
waitForRepair()
}
@@ -206,6 +228,7 @@ function loadOrCreateInstallationId(filePath, randomUUID = crypto.randomUUID) {
const repairPath = `${filePath}.repair.lock`
+ const holderIsLive = repairLockHolderJudge()
let emptyPolls = 0
let ownedBody: Buffer | null = null
@@ -225,7 +248,7 @@ function loadOrCreateInstallationId(filePath, randomUUID = crypto.randomUUID) {
return winner
}
- emptyPolls = waitOnContendedRepairLock(repairPath, emptyPolls)
+ emptyPolls = waitOnContendedRepairLock(repairPath, emptyPolls, holderIsLive)
continue
}
diff --git a/apps/desktop/electron/update-marker.ts b/apps/desktop/electron/update-marker.ts
index 59f55660d21..e85a1ec9284 100644
--- a/apps/desktop/electron/update-marker.ts
+++ b/apps/desktop/electron/update-marker.ts
@@ -356,19 +356,30 @@ export function cachedCreateTimeProbe(probe: CreateTimeProbe = processCreateTime
}
}
+/** This process's creation time without a spawn when Electron can tell it (plain Node probes). */
+export function ownCreateTimeSync(): number | null {
+ return ownCreateTime() ?? processCreateTimeSync(process.pid)
+}
+
/**
* The judge's identity rule (A7 rule 4) for a lock holder, synchronously, for
* the module-init repair lock: our own pid is live only at this exact
* incarnation, and an identity with no comparable creation time is live only
* within the v1 ceiling counted from `writtenAtS` (the lock's mtime).
+ * `createTime` lets a polling caller probe each holder once per wait.
*/
-export function lockHolderIsLiveSync(pid: number, recordedCt: number | null, writtenAtS: number): boolean {
+export function lockHolderIsLiveSync(
+ pid: number,
+ recordedCt: number | null,
+ writtenAtS: number,
+ createTime: (pid: number) => number | null = processCreateTimeSync
+): boolean {
return isLiveIdentity(
identityStateSync(pid, recordedCt, writtenAtS, {
ourPid: process.pid,
- ourCt: () => processCreateTimeSync(process.pid),
+ ourCt: ownCreateTimeSync,
isAlive: candidate => isPidAlive(candidate) && !isZombieState(posixProcessState(candidate)),
- createTime: processCreateTimeSync,
+ createTime,
nowS: Date.now() / 1000
})
)