The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): the repair lock judges its holder with the marker judge's own rule
Tekniumee1c1982f466
diff --git a/apps/desktop/electron/desktop-installation.test.ts b/apps/desktop/electron/desktop-installation.test.tsindex f4c32c1d03e..741fbefff47 100644--- a/apps/desktop/electron/desktop-installation.test.ts+++ b/apps/desktop/electron/desktop-installation.test.ts@@ -1,5 +1,5 @@import assert from 'node:assert/strict'-import { spawnSync } from 'node:child_process'+import { spawn, spawnSync } from 'node:child_process'import fs from 'node:fs'import os from 'node:os'import path from 'node:path'@@ -118,13 +118,19 @@ test('a repair lock whose holder died is reclaimed instead of bricking launch',const gone = spawnSync(process.execPath, ['-e', 'process.stdout.write(String(process.pid))'], { encoding: 'utf8' })fs.writeFileSync(`${filePath}.repair.lock`, `${gone.stdout}\n`)- assert.equal(loadOrCreateInstallationId(filePath, () => ID_A), ID_A)+ assert.equal(+ loadOrCreateInstallationId(filePath, () => ID_A),+ ID_A+ )assert.equal(fs.existsSync(`${filePath}.repair.lock`), false)// A pre-fix crash left an EMPTY lock (no owner to probe): reclaimed too.fs.rmSync(filePath)fs.writeFileSync(`${filePath}.repair.lock`, '')- assert.equal(loadOrCreateInstallationId(filePath, () => ID_B), ID_B)+ assert.equal(+ loadOrCreateInstallationId(filePath, () => ID_B),+ ID_B+ )}))// Review G5: reclaiming a dead repair lock by read/compare/unlink-by-name could@@ -168,3 +174,48 @@ test('reclaiming a dead repair lock never deletes a lock a peer created meanwhil'no rename claim is left behind')}))++// Review 5411222842: the repair lock judged its holder with a second copy of+// the marker identity rule that had no own-pid check and no v1 age ceiling, so+// a lock naming our own pid (a previous incarnation reusing it) or a live+// unrelated pid with no creation time wedged every launch. It now runs the+// judge's rule (identityStateSync).+test('a repair lock naming our pid without our creation time is a previous incarnation, reclaimed', () =>+ withTempDir(directory => {+ const filePath = path.join(directory, 'desktop-installation.json')+ fs.writeFileSync(`${filePath}.repair.lock`, `${process.pid}\n`)++ assert.equal(+ loadOrCreateInstallationId(filePath, () => ID_A),+ ID_A+ )+ assert.equal(fs.existsSync(`${filePath}.repair.lock`), false)+ }))++test('a live holder with no creation time is live only within the v1 ceiling', async () => {+ const holder = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' })++ try {+ await new Promise(resolve => holder.once('spawn', resolve))++ withTempDir(directory => {+ const filePath = path.join(directory, 'desktop-installation.json')+ const repairPath = `${filePath}.repair.lock`+ fs.writeFileSync(repairPath, `${holder.pid}\n`)++ // Fresh: a live unknown identity is waited on, never reclaimed.+ assert.throws(() => loadOrCreateInstallationId(filePath, () => ID_A), /Could not repair/)+ assert.equal(fs.readFileSync(repairPath, 'utf8'), `${holder.pid}\n`)++ // Past the v1 ceiling the pid may be reused by anything: reclaimed.+ const old = Date.now() / 1000 - 2 * 1200+ fs.utimesSync(repairPath, old, old)+ assert.equal(+ loadOrCreateInstallationId(filePath, () => ID_B),+ ID_B+ )+ })+ } finally {+ holder.kill()+ }+})diff --git a/apps/desktop/electron/desktop-installation.ts b/apps/desktop/electron/desktop-installation.tsindex 0a2421d0948..271ccb72219 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, processCreateTimeSync, processIsLiveSync } from './update-marker'+import { formatCreateTime, lockHolderIsLiveSync, 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@@ -60,9 +60,11 @@ function repairLockBody(): string {function reclaimDeadRepairLock(repairPath: string, emptyPolls: number): boolean {let raw: Buffer+ let writtenAtS: numbertry {raw = fs.readFileSync(repairPath)+ writtenAtS = fs.statSync(repairPath).mtimeMs / 1000} catch {return false}@@ -72,7 +74,9 @@ function reclaimDeadRepairLock(repairPath: string, emptyPolls: number): booleanconst ctMatch = /^ct:(\d+(?:\.\d+)?)$/.exec(lines[1] || '')const dead =- pid === null ? emptyPolls >= EMPTY_LOCK_RECLAIM_POLLS : !processIsLiveSync(pid, ctMatch ? Number(ctMatch[1]) : null)+ pid === null+ ? emptyPolls >= EMPTY_LOCK_RECLAIM_POLLS+ : !lockHolderIsLiveSync(pid, ctMatch ? Number(ctMatch[1]) : null, writtenAtS)if (!dead) {return falsediff --git a/apps/desktop/electron/update-marker-judge.ts b/apps/desktop/electron/update-marker-judge.tsindex e91b3654a9d..ed6b8eeaae6 100644--- a/apps/desktop/electron/update-marker-judge.ts+++ b/apps/desktop/electron/update-marker-judge.ts@@ -60,7 +60,10 @@ function u32(text: string): number | null {/** Positional parse, identical in every reader. Null = MALFORMED. */export function parseUpdateMarker(raw: string): UpdateMarker | null {- const lines = String(raw).replace(/^\uFEFF/, '').split('\n').map(cleanLine)+ const lines = String(raw)+ .replace(/^\uFEFF/, '')+ .split('\n')+ .map(cleanLine)if (lines.length < 2 || !INT_RE.test(lines[0]) || !INT_RE.test(lines[1])) {return null@@ -131,12 +134,26 @@ export interface JudgeEnv {nowS: number}-async function identityState(+/** {@link JudgeEnv} whose process facts answer synchronously. */+export interface SyncJudgeEnv {+ ourPid: number+ ourCt: () => number | null+ isAlive: (pid: number) => boolean+ createTime: (pid: number) => number | null+ nowS: number+}++/**+ * The identity rule itself, the one copy every Desktop reader runs: the+ * async judge resolves the facts first, the module-init repair lock reads+ * them synchronously. `startedAt` anchors the v1 ceiling.+ */+export function identityStateSync(pid: number,recordedCt: number | null,startedAt: number,- env: JudgeEnv-): Promise<IdentityState> {+ env: SyncJudgeEnv+): IdentityState {if (pid === 0) {return 'dead'}@@ -144,7 +161,7 @@ async function identityState(if (pid === env.ourPid) {// A7 rule 4: our pid is ours only at our exact incarnation; a no-ct claim// naming our pid is a previous incarnation, never live.- const ourCt = await env.ourCt()+ const ourCt = env.ourCt()return recordedCt !== null && ourCt !== null && Math.abs(recordedCt - ourCt) <= OWN_CT_EPSILON_S ? 'ours' : 'dead'}@@ -153,7 +170,7 @@ async function identityState(return 'dead'}- const actual = recordedCt === null ? null : await env.createTime(pid)+ const actual = recordedCt === null ? null : env.createTime(pid)if (recordedCt === null || actual === null) {return env.nowS - startedAt <= V1_MAX_AGE_S ? 'unknown' : 'dead'@@ -162,6 +179,27 @@ async function identityState(return Math.abs(recordedCt - actual) <= CREATE_TIME_TOLERANCE_S ? 'match' : 'dead'}+/** Read exactly the facts {@link identityStateSync} consults, then apply it. */+async function identityState(+ pid: number,+ recordedCt: number | null,+ startedAt: number,+ env: JudgeEnv+): Promise<IdentityState> {+ const own = pid !== 0 && pid === env.ourPid+ const ourCt = own ? await env.ourCt() : null+ const alive = pid !== 0 && !own && (await env.isAlive(pid))+ const actual = alive && recordedCt !== null ? await env.createTime(pid) : null++ return identityStateSync(pid, recordedCt, startedAt, {+ ourPid: env.ourPid,+ ourCt: () => ourCt,+ isAlive: () => alive,+ createTime: () => actual,+ nowS: env.nowS+ })+}+export function isLiveIdentity(state: IdentityState | null): boolean {return state === 'ours' || state === 'match' || state === 'unknown'}diff --git a/apps/desktop/electron/update-marker.ts b/apps/desktop/electron/update-marker.tsindex 9b84cb04549..31c478ff991 100644--- a/apps/desktop/electron/update-marker.ts+++ b/apps/desktop/electron/update-marker.ts@@ -29,8 +29,9 @@ import { randomBytes } from 'node:crypto'import path from 'path'import {- CREATE_TIME_TOLERANCE_S,hasForeignLiveIdentity,+ identityStateSync,+ isLiveIdentity,type JudgeEnv,judgeMarkerText,type MarkerJudgement,@@ -127,7 +128,10 @@ let linuxClockTicks: number | null = nullfunction linuxCreateTime(pid: number): number | null {try {const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8')- const fields = stat.slice(stat.lastIndexOf(')') + 1).trim().split(/\s+/)+ const fields = stat+ .slice(stat.lastIndexOf(')') + 1)+ .trim()+ .split(/\s+/)// Field 22 of /proc/<pid>/stat (starttime, clock ticks since boot) is index// 19 once pid and comm are stripped.const ticks = Number(fields[19])@@ -139,7 +143,8 @@ function linuxCreateTime(pid: number): number | null {if (linuxClockTicks === null) {try {- linuxClockTicks = Number(execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8', timeout: 2000 }).trim()) || 100+ linuxClockTicks =+ Number(execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8', timeout: 2000 }).trim()) || 100} catch {linuxClockTicks = 100}@@ -292,19 +297,22 @@ export function cachedCreateTimeProbe(probe: CreateTimeProbe = processCreateTime}}-/** C1 rule 3 for a (pid, recorded ct) pair, synchronously. */-export function processIsLiveSync(pid: number, recordedCt: number | null): boolean {- if (!isPidAlive(pid) || isZombieState(posixProcessState(pid))) {- return false- }-- if (recordedCt === null) {- return true- }-- const actual = processCreateTimeSync(pid)-- return actual === null || Math.abs(actual - recordedCt) <= CREATE_TIME_TOLERANCE_S+/**+ * 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).+ */+export function lockHolderIsLiveSync(pid: number, recordedCt: number | null, writtenAtS: number): boolean {+ return isLiveIdentity(+ identityStateSync(pid, recordedCt, writtenAtS, {+ ourPid: process.pid,+ ourCt: () => processCreateTimeSync(process.pid),+ isAlive: candidate => isPidAlive(candidate) && !isZombieState(posixProcessState(candidate)),+ createTime: processCreateTimeSync,+ nowS: Date.now() / 1000+ })+ )}export function formatCreateTime(seconds: number): string {@@ -341,7 +349,14 @@ export type MarkerInspection =* Someone else's update is running (a live identity that is not this* process), or a 0-byte claim is being written (`judgement` null, A3).*/- | { state: 'live'; raw: Buffer; marker: UpdateMarker | null; ageMs: number; livePid: number; judgement: MarkerJudgement | null }+ | {+ state: 'live'+ raw: Buffer+ marker: UpdateMarker | null+ ageMs: number+ livePid: number+ judgement: MarkerJudgement | null+ }/** A bridge of THIS process incarnation and nothing foreign alive in it. */| { state: 'ours'; raw: Buffer; marker: UpdateMarker; judgement: MarkerJudgement }/** Dead or malformed (`judgement` null for a stale 0-byte file). */