From 36b2352bb4fd20094721a1787db8b99ad8646caa Mon Sep 17 00:00:00 2001 From: Alex Date: Sat, 5 Dec 2026 21:25:53 -0400 Subject: [PATCH] fix(host-kit): publish the reclaim guard atomically createReclaimMutex created daemon.reclaim.lock with open('wx') and wrote the holder record with a separate write. A process killed between the two left an empty guard that readGuardHolder cannot attribute, so it was never reaped and every later daemon start failed with "Daemon registration busy". Publish the holder from a temporary sibling with link-exclusive, as the lock owner file already does, so the guard is either complete or absent. Fixes #5423 Co-Authored-By: Claude Sonnet 5.5 --- .../src/internal/process-lock-guard.test.ts | 34 ++++++++++++++----- .../src/internal/process-lock.fixtures.ts | 19 +++++------ .../src/internal/process-lock.test.ts | 23 ++++++------- .../host-kit/src/internal/process-lock.ts | 19 +++++------ 4 files changed, 54 insertions(+), 41 deletions(-) diff --git a/packages/host-kit/src/internal/process-lock-guard.test.ts b/packages/host-kit/src/internal/process-lock-guard.test.ts index 5494246c2d1..78e5ff655b2 100644 --- a/packages/host-kit/src/internal/process-lock-guard.test.ts +++ b/packages/host-kit/src/internal/process-lock-guard.test.ts @@ -130,26 +130,42 @@ test('only one contender may reap a dead holder guard', async () => { assert.equal(fs.readFileSync(mutexPath, 'utf8'), JSON.stringify(DEAD_GUARD_HOLDER)); }); -test('a guard this process takes names its holder', async () => { +test('a guard this process takes names its holder and is never visible without one', async () => { const lockDirPath = path.join(tmpDir, 'named-guard.lock'); - const written: string[] = []; + const mutexPath = path.join(tmpDir, 'named-guard.reclaim.lock'); + // Whether the guard was already standing when its holder record was written: a holder that dies + // at that moment leaves an empty guard no contender can attribute or reap. + const written: { data: string; guardStanding: boolean }[] = []; + const record = (data: unknown) => { + if (typeof data === 'string' && data.includes('"token"')) { + written.push({ data, guardStanding: fs.existsSync(mutexPath) }); + } + }; const realWrite = fs.writeSync; - const writeSpy = vi.spyOn(fs, 'writeSync').mockImplementation((( - descriptor: number, - data: string, - ) => { - written.push(data); + const realWriteFile = fs.writeFileSync; + vi.spyOn(fs, 'writeSync').mockImplementation(((descriptor: number, data: string) => { + record(data); return realWrite(descriptor, data); }) as typeof fs.writeSync); + vi.spyOn(fs, 'writeFileSync').mockImplementation((( + file: fs.PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: fs.WriteFileOptions, + ) => { + record(data); + return realWriteFile(file, data, options); + }) as typeof fs.writeFileSync); let attempt: ReturnType; try { attempt = tryAcquireProcessLock({ lockDirPath, owner: currentProcessOwner() }); } finally { - writeSpy.mockRestore(); + vi.restoreAllMocks(); } assert.equal(attempt.status, 'acquired'); if (attempt.status === 'acquired') await attempt.acquisition.release(); - const holder = JSON.parse(written[0]!) as { pid: number; token: string }; + assert.equal(written.length, 1); + assert.equal(written[0]!.guardStanding, false); + const holder = JSON.parse(written[0]!.data) as { pid: number; token: string }; assert.equal(holder.pid, process.pid); assert.match(holder.token, /^[0-9a-f-]{36}$/); }); diff --git a/packages/host-kit/src/internal/process-lock.fixtures.ts b/packages/host-kit/src/internal/process-lock.fixtures.ts index 33fbc988a4d..89ff85e8a10 100644 --- a/packages/host-kit/src/internal/process-lock.fixtures.ts +++ b/packages/host-kit/src/internal/process-lock.fixtures.ts @@ -45,21 +45,20 @@ export function listReclaimSiblings(directory: string): string[] { .sort(); } -/** Runs `action` the first time a contender opens the guard file, before the open itself. */ -export function onFirstGuardOpen(mutexPath: string, action: () => void) { +/** Runs `action` the first time a contender publishes the guard file, before the publish itself. */ +export function onFirstGuardPublish(mutexPath: string, action: () => void) { let fired = false; - const realOpen = fs.openSync; - const spy = vi.spyOn(fs, 'openSync').mockImplementation((( - target: fs.PathLike, - flags: fs.OpenMode, - mode?: fs.Mode, + const realLink = fs.linkSync; + const spy = vi.spyOn(fs, 'linkSync').mockImplementation((( + existingPath: fs.PathLike, + newPath: fs.PathLike, ) => { - if (String(target) === mutexPath && !fired) { + if (String(newPath) === mutexPath && !fired) { fired = true; action(); } - return realOpen(target, flags, mode); - }) as typeof fs.openSync); + return realLink(existingPath, newPath); + }) as typeof fs.linkSync); return { fired: () => fired, restore: () => spy.mockRestore() }; } diff --git a/packages/host-kit/src/internal/process-lock.test.ts b/packages/host-kit/src/internal/process-lock.test.ts index bccc87f9cf7..50913440c7c 100644 --- a/packages/host-kit/src/internal/process-lock.test.ts +++ b/packages/host-kit/src/internal/process-lock.test.ts @@ -21,7 +21,7 @@ import { UNINFORMATIVE_OWNER_RECORDS, failUnlinkForPath, listReclaimSiblings, - onFirstGuardOpen, + onFirstGuardPublish, stampDirectoryAbandoned, writeDeadLockFixture, writeLockOwnerFixture, @@ -380,7 +380,7 @@ test('a contender that claims the path during a reclaim keeps its lock', async ( // The moment a contender is admitted to judging this lock, another process clears the dead // claim and publishes its own. Nothing is removed: the record re-read under the mutex names a // claim token the dead one cannot answer to, and the judge walks away from the path. - const guard = onFirstGuardOpen(mutexPath, () => { + const guard = onFirstGuardPublish(mutexPath, () => { fs.rmSync(lockDirPath, { recursive: true, force: true }); fs.mkdirSync(lockDirPath); fs.writeFileSync( @@ -436,7 +436,7 @@ test('a claim published while a reclaim holds the mutex outlives the empty direc // Writing the record is also what re-dates the directory, which is the fact the reclaim re-asks // for under its mutex before it removes anything. - const guard = onFirstGuardOpen(mutexPath, () => { + const guard = onFirstGuardPublish(mutexPath, () => { fs.writeFileSync( ownerFilePath, // See the contender above: another process's claim names another pid. @@ -481,7 +481,7 @@ test('a lock directory made anew while a reclaim holds the mutex is not the one // A replacement directory has a new identity and a fresh age. let refilledAtMs = 0; - const guard = onFirstGuardOpen(mutexPath, () => { + const guard = onFirstGuardPublish(mutexPath, () => { fs.rmSync(lockDirPath, { recursive: true, force: true }); fs.mkdirSync(lockDirPath); refilledAtMs = fs.statSync(lockDirPath).mtimeMs; @@ -522,15 +522,14 @@ test('a reclaim mutex another contender holds leaves the abandoned lock standing fs.mkdirSync(path.join(tmpDir, 'judged-by-another.reclaim.lock')); let lockAttempts = 0; - const realOpen = fs.openSync; - const guardSpy = vi.spyOn(fs, 'openSync').mockImplementation((( - target: fs.PathLike, - flags: fs.OpenMode, - mode?: fs.Mode, + const realLink = fs.linkSync; + const guardSpy = vi.spyOn(fs, 'linkSync').mockImplementation((( + existingPath: fs.PathLike, + newPath: fs.PathLike, ) => { - if (String(target) === path.join(tmpDir, 'judged-by-another.reclaim.lock')) lockAttempts += 1; - return realOpen(target, flags, mode); - }) as typeof fs.openSync); + if (String(newPath) === path.join(tmpDir, 'judged-by-another.reclaim.lock')) lockAttempts += 1; + return realLink(existingPath, newPath); + }) as typeof fs.linkSync); try { await assert.rejects( diff --git a/packages/host-kit/src/internal/process-lock.ts b/packages/host-kit/src/internal/process-lock.ts index 9dc46c21ef7..512eafa91ec 100644 --- a/packages/host-kit/src/internal/process-lock.ts +++ b/packages/host-kit/src/internal/process-lock.ts @@ -698,21 +698,20 @@ function createReclaimMutex(lockDirPath: string, holderStartTime: string | null) startTime: holderStartTime, token: crypto.randomUUID(), }; - let descriptor: number; + // Published whole from a temporary sibling, so a holder that dies while taking the guard leaves + // either no guard or one that names it: never an empty guard nobody can attribute or reap. try { - descriptor = fs.openSync(mutexPath, 'wx', 0o600); + publishFileSync({ + destination: mutexPath, + contents: JSON.stringify(holder), + mode: 0o600, + exactMode: true, + publish: 'link-exclusive', + }); } catch (error) { if (errorCode(error) !== 'EEXIST') throw error; return false; } - try { - fs.writeSync(descriptor, JSON.stringify(holder)); - } catch (error) { - fs.closeSync(descriptor); - fs.unlinkSync(mutexPath); - throw error; - } - fs.closeSync(descriptor); return true; }