Skip to content

Commit 72d35db

Browse files
cliffhallclaude
andcommitted
fix(memory): track a lock from its create until its release completes
Copilot round 1 on #5530: a signal during the token write or during the release found no tracked entry and left the lock. Track it as soon as the exclusive open returns, treat a file holding a prefix of our token as ours at exit, and untrack only after the release's unlink. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: cliffhall <cliff@futurescale.com>
1 parent 37bff57 commit 72d35db

2 files changed

Lines changed: 61 additions & 8 deletions

File tree

‎src/memory/__tests__/file-lock.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -460,6 +460,51 @@ describe("releasing held locks on exit (#5485)", () => {
460460
expect(await fs.readFile(taken, "utf-8")).toBe("someone else");
461461
});
462462

463+
it("removes a lock whose token was still being written at exit", async () => {
464+
const lockPath = path.join(dir, "memory.jsonl.lock");
465+
const realOpen = fs.open;
466+
let finishWrite!: () => void;
467+
let writing!: () => void;
468+
const writeStarted = new Promise<void>((resolve) => (writing = resolve));
469+
vi.spyOn(fs, "open").mockImplementationOnce(async (...args) => {
470+
const handle = await realOpen(...args);
471+
const realWrite = handle.writeFile.bind(handle);
472+
// Hold the token write open, with nothing written yet.
473+
handle.writeFile = async (data) => {
474+
writing();
475+
await new Promise<void>((resolve) => (finishWrite = resolve));
476+
return realWrite(data);
477+
};
478+
return handle;
479+
});
480+
481+
const held = withFileLock(lockPath, async () => "ran");
482+
await writeStarted;
483+
expect(await fs.readFile(lockPath, "utf-8")).toBe("");
484+
485+
releaseHeldLocks();
486+
487+
expect(await exists(lockPath)).toBe(false);
488+
finishWrite();
489+
expect(await held).toBe("ran");
490+
});
491+
492+
it("still tracks a lock while its release is in progress", async () => {
493+
const lockPath = path.join(dir, "memory.jsonl.lock");
494+
const realUnlink = fs.unlink;
495+
let trackedDuringRelease: string[] = [];
496+
await withFileLock(lockPath, async () => {
497+
// The release's removal of the lock is the next unlink.
498+
vi.spyOn(fs, "unlink").mockImplementationOnce(async (file) => {
499+
trackedDuringRelease = heldLockPaths();
500+
return realUnlink(file);
501+
});
502+
});
503+
expect(trackedDuringRelease).toEqual([lockPath]);
504+
expect(heldLockPaths()).toEqual([]);
505+
expect(await exists(lockPath)).toBe(false);
506+
});
507+
463508
it("keeps tracking a lock the same process re-took after breaking it", async () => {
464509
const lockPath = path.join(dir, "memory.jsonl.lock");
465510
let releaseFirst!: () => void;

‎src/memory/index.ts‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -294,10 +294,13 @@ export function heldLockPaths(): string[] {
294294
// exits: an `exit` listener cannot wait on a promise. As in withFileLock's own
295295
// release, a lock is removed only while it still holds this process's token,
296296
// so a lock broken as stale and re-taken by another process stays in place.
297+
// A lock is tracked from the moment its exclusive create returns, before its
298+
// token is written, so a file holding only the start of the token (or none of
299+
// it) is ours too: the exit interrupted the write.
297300
export function releaseHeldLocks(): void {
298301
for (const [lockPath, token] of heldLocks) {
299302
try {
300-
if (readFileSync(lockPath, "utf-8") === token) {
303+
if (token.startsWith(readFileSync(lockPath, "utf-8"))) {
301304
unlinkSync(lockPath);
302305
}
303306
} catch {
@@ -359,6 +362,10 @@ export async function withFileLock<T>(
359362
}
360363
}
361364
if (handle) {
365+
// Track the lock before anything else is awaited: a signal is handled
366+
// only between tasks, never between the open's completion and this
367+
// line, so from here on the exit hook can remove it (#5485).
368+
heldLocks.set(lockPath, token);
362369
try {
363370
await handle.writeFile(token);
364371
await handle.close();
@@ -367,6 +374,7 @@ export async function withFileLock<T>(
367374
// every other writer waiting for it to go stale.
368375
await handle.close().catch(ignoreError);
369376
await fs.unlink(lockPath).catch(ignoreError);
377+
heldLocks.delete(lockPath);
370378
throw error;
371379
}
372380
break;
@@ -424,24 +432,24 @@ export async function withFileLock<T>(
424432
.catch(ignoreError);
425433
}, staleMs / 2);
426434
heartbeat.unref();
427-
heldLocks.set(lockPath, token);
428435

429436
try {
430437
return await operation();
431438
} finally {
432439
clearInterval(heartbeat);
433-
// Stop tracking the lock before releasing it. A lock this same process
434-
// broke as stale and re-took in another withFileLock call carries that
435-
// call's token, and stays tracked for it.
436-
if (heldLocks.get(lockPath) === token) {
437-
heldLocks.delete(lockPath);
438-
}
439440
// Release only our own lock: if it was broken as stale while we held it,
440441
// the file may now belong to another process.
441442
const current = await fs.readFile(lockPath, "utf-8").catch(() => null);
442443
if (current === token) {
443444
await fs.unlink(lockPath).catch(ignoreError);
444445
}
446+
// Stop tracking the lock only once the release is done, so an exit during
447+
// it still removes the lock. A lock this same process broke as stale and
448+
// re-took in another withFileLock call carries that call's token, and
449+
// stays tracked for it.
450+
if (heldLocks.get(lockPath) === token) {
451+
heldLocks.delete(lockPath);
452+
}
445453
}
446454
}
447455

0 commit comments

Comments
 (0)