Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 25 additions & 9 deletions packages/host-kit/src/internal/process-lock-guard.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof tryAcquireProcessLock>;
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}$/);
});
19 changes: 9 additions & 10 deletions packages/host-kit/src/internal/process-lock.fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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() };
}

Expand Down
23 changes: 11 additions & 12 deletions packages/host-kit/src/internal/process-lock.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
UNINFORMATIVE_OWNER_RECORDS,
failUnlinkForPath,
listReclaimSiblings,
onFirstGuardOpen,
onFirstGuardPublish,
stampDirectoryAbandoned,
writeDeadLockFixture,
writeLockOwnerFixture,
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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(
Expand Down
19 changes: 9 additions & 10 deletions packages/host-kit/src/internal/process-lock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: createReclaimMutex now requires a hard link for every guard acquisition. On a Windows exFAT state volume, fs.linkSync fails because hard links are unsupported; this catch rethrows that error, so lock acquisition fails instead of contending. Add a capability-aware fallback for filesystems without hard-link support.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/host-kit/src/internal/process-lock.ts, line 709:

<comment>`createReclaimMutex` now requires a hard link for every guard acquisition. On a Windows exFAT state volume, `fs.linkSync` fails because hard links are unsupported; this catch rethrows that error, so lock acquisition fails instead of contending. Add a capability-aware fallback for filesystems without hard-link support.</comment>

<file context>
@@ -698,21 +698,20 @@ function createReclaimMutex(lockDirPath: string, holderStartTime: string | null)
+      contents: JSON.stringify(holder),
+      mode: 0o600,
+      exactMode: true,
+      publish: 'link-exclusive',
+    });
   } catch (error) {
</file context>

});
} 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;
}

Expand Down
Loading