|
1 | 1 | // Unit tests for withFileLock, the lock file that orders mutations from |
2 | 2 | // separate server processes sharing one graph file (#4797): mutual exclusion, |
3 | | -// release, breaking an abandoned lock, and giving up on a held one. |
| 3 | +// release, breaking an abandoned lock, and giving up on a held one; and the |
| 4 | +// exit-time release of the locks this process still holds (#5485). |
4 | 5 | import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; |
5 | 6 | import { promises as fs } from "fs"; |
6 | 7 | import os from "os"; |
7 | 8 | import path from "path"; |
8 | | -import { spawnSync } from "child_process"; |
9 | | -import { KnowledgeGraphManager, withFileLock } from "../index.js"; |
| 9 | +import { spawn, spawnSync } from "child_process"; |
| 10 | +import { fileURLToPath, pathToFileURL } from "url"; |
| 11 | +import { |
| 12 | + KnowledgeGraphManager, |
| 13 | + heldLockPaths, |
| 14 | + installLockCleanup, |
| 15 | + releaseHeldLocks, |
| 16 | + withFileLock, |
| 17 | +} from "../index.js"; |
10 | 18 | import { makeTempGraph } from "./helpers.js"; |
11 | 19 |
|
12 | 20 | const fast = { staleMs: 60_000, timeoutMs: 100, retryMs: 5 }; |
@@ -401,3 +409,214 @@ describe("withFileLock", () => { |
401 | 409 | expect(await fs.readdir(dir)).toEqual(["memory.jsonl"]); |
402 | 410 | }); |
403 | 411 | }); |
| 412 | + |
| 413 | +describe("releasing held locks on exit (#5485)", () => { |
| 414 | + let dir: string; |
| 415 | + let cleanup: () => Promise<void>; |
| 416 | + |
| 417 | + beforeEach(async () => { |
| 418 | + ({ dir, cleanup } = await makeTempGraph()); |
| 419 | + }); |
| 420 | + |
| 421 | + afterEach(async () => { |
| 422 | + vi.restoreAllMocks(); |
| 423 | + await cleanup(); |
| 424 | + }); |
| 425 | + |
| 426 | + async function exists(file: string): Promise<boolean> { |
| 427 | + return fs.access(file).then( |
| 428 | + () => true, |
| 429 | + () => false, |
| 430 | + ); |
| 431 | + } |
| 432 | + |
| 433 | + it("tracks a lock only while it is held", async () => { |
| 434 | + const lockPath = path.join(dir, "memory.jsonl.lock"); |
| 435 | + await withFileLock(lockPath, async () => { |
| 436 | + expect(heldLockPaths()).toEqual([lockPath]); |
| 437 | + }); |
| 438 | + expect(heldLockPaths()).toEqual([]); |
| 439 | + }); |
| 440 | + |
| 441 | + it("removes each lock still held, and only those still ours", async () => { |
| 442 | + const ours = path.join(dir, "ours.lock"); |
| 443 | + const taken = path.join(dir, "taken.lock"); |
| 444 | + const gone = path.join(dir, "gone.lock"); |
| 445 | + await withFileLock(ours, () => |
| 446 | + withFileLock(taken, () => |
| 447 | + withFileLock(gone, async () => { |
| 448 | + // Another process broke and re-took one lock, and another vanished. |
| 449 | + await fs.writeFile(taken, "someone else"); |
| 450 | + await fs.unlink(gone); |
| 451 | + |
| 452 | + releaseHeldLocks(); |
| 453 | + |
| 454 | + expect(heldLockPaths()).toEqual([]); |
| 455 | + expect(await exists(ours)).toBe(false); |
| 456 | + expect(await fs.readFile(taken, "utf-8")).toBe("someone else"); |
| 457 | + }), |
| 458 | + ), |
| 459 | + ); |
| 460 | + expect(await fs.readFile(taken, "utf-8")).toBe("someone else"); |
| 461 | + }); |
| 462 | + |
| 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("leaves another writer's empty replacement of a written lock in place", async () => { |
| 493 | + const lockPath = path.join(dir, "memory.jsonl.lock"); |
| 494 | + await withFileLock(lockPath, async () => { |
| 495 | + // Our lock was broken as stale, and a new writer has created its own |
| 496 | + // but not yet written its token. |
| 497 | + await fs.writeFile(lockPath, ""); |
| 498 | + |
| 499 | + releaseHeldLocks(); |
| 500 | + |
| 501 | + expect(await exists(lockPath)).toBe(true); |
| 502 | + }); |
| 503 | + }); |
| 504 | + |
| 505 | + it("still tracks a lock while its release is in progress", async () => { |
| 506 | + const lockPath = path.join(dir, "memory.jsonl.lock"); |
| 507 | + const realUnlink = fs.unlink; |
| 508 | + let trackedDuringRelease: string[] = []; |
| 509 | + await withFileLock(lockPath, async () => { |
| 510 | + // The release's removal of the lock is the next unlink. |
| 511 | + vi.spyOn(fs, "unlink").mockImplementationOnce(async (file) => { |
| 512 | + trackedDuringRelease = heldLockPaths(); |
| 513 | + return realUnlink(file); |
| 514 | + }); |
| 515 | + }); |
| 516 | + expect(trackedDuringRelease).toEqual([lockPath]); |
| 517 | + expect(heldLockPaths()).toEqual([]); |
| 518 | + expect(await exists(lockPath)).toBe(false); |
| 519 | + }); |
| 520 | + |
| 521 | + it("keeps tracking a lock the same process re-took after breaking it", async () => { |
| 522 | + const lockPath = path.join(dir, "memory.jsonl.lock"); |
| 523 | + let releaseFirst!: () => void; |
| 524 | + const firstHolds = new Promise<void>((resolve) => (releaseFirst = resolve)); |
| 525 | + let firstStarted!: () => void; |
| 526 | + const started = new Promise<void>((resolve) => (firstStarted = resolve)); |
| 527 | + vi.spyOn(console, "error").mockImplementation(() => {}); |
| 528 | + |
| 529 | + const first = withFileLock( |
| 530 | + lockPath, |
| 531 | + async () => { |
| 532 | + firstStarted(); |
| 533 | + await firstHolds; |
| 534 | + }, |
| 535 | + { staleMs: 60_000 }, |
| 536 | + ); |
| 537 | + await started; |
| 538 | + // Age the first holder's lock past a short staleMs, so a second holder in |
| 539 | + // this process breaks it and takes it over. |
| 540 | + const old = new Date(Date.now() - 10_000); |
| 541 | + await fs.utimes(lockPath, old, old); |
| 542 | + await withFileLock( |
| 543 | + lockPath, |
| 544 | + async () => { |
| 545 | + releaseFirst(); |
| 546 | + await first; |
| 547 | + // The first holder's release left the second's lock, and its entry. |
| 548 | + expect(heldLockPaths()).toEqual([lockPath]); |
| 549 | + expect(await exists(lockPath)).toBe(true); |
| 550 | + }, |
| 551 | + { staleMs: 1_000, timeoutMs: 1_000, retryMs: 5 }, |
| 552 | + ); |
| 553 | + expect(heldLockPaths()).toEqual([]); |
| 554 | + }); |
| 555 | + |
| 556 | + it("installs an exit hook and SIGINT and SIGTERM handlers, once", () => { |
| 557 | + const handlers = new Map<string | symbol, () => void>(); |
| 558 | + const on = vi.spyOn(process, "on").mockImplementation((event, listener) => { |
| 559 | + handlers.set(event, listener as () => void); |
| 560 | + return process; |
| 561 | + }); |
| 562 | + const exit = vi |
| 563 | + .spyOn(process, "exit") |
| 564 | + .mockImplementation((() => undefined) as typeof process.exit); |
| 565 | + |
| 566 | + installLockCleanup(); |
| 567 | + installLockCleanup(); |
| 568 | + |
| 569 | + expect(on).toHaveBeenCalledTimes(3); |
| 570 | + expect(handlers.get("exit")).toBe(releaseHeldLocks); |
| 571 | + handlers.get("SIGINT")?.(); |
| 572 | + expect(exit).toHaveBeenLastCalledWith(130); |
| 573 | + handlers.get("SIGTERM")?.(); |
| 574 | + expect(exit).toHaveBeenLastCalledWith(143); |
| 575 | + }); |
| 576 | + |
| 577 | + // A real signal, sent to a real process holding a lock mid-operation. |
| 578 | + // Windows has no SIGTERM to deliver: process.kill() there ends the process |
| 579 | + // outright, so no handler can run. |
| 580 | + it.skipIf(process.platform === "win32")( |
| 581 | + "removes the lock when SIGTERM stops a process mid-mutation", |
| 582 | + async () => { |
| 583 | + const lockPath = path.join(dir, "memory.jsonl.lock"); |
| 584 | + const distIndex = pathToFileURL( |
| 585 | + path.join( |
| 586 | + path.dirname(fileURLToPath(import.meta.url)), |
| 587 | + "..", |
| 588 | + "dist", |
| 589 | + "index.js", |
| 590 | + ), |
| 591 | + ).href; |
| 592 | + const script = ` |
| 593 | + const { installLockCleanup, withFileLock } = await import(${JSON.stringify(distIndex)}); |
| 594 | + installLockCleanup(); |
| 595 | + await withFileLock(${JSON.stringify(lockPath)}, () => { |
| 596 | + console.log("held"); |
| 597 | + return new Promise(() => setInterval(() => {}, 1000)); |
| 598 | + }); |
| 599 | + `; |
| 600 | + const child = spawn( |
| 601 | + process.execPath, |
| 602 | + ["--input-type=module", "-e", script], |
| 603 | + { stdio: ["ignore", "pipe", "inherit"] }, |
| 604 | + ); |
| 605 | + const exited = new Promise<number | null>((resolve) => |
| 606 | + child.on("exit", (code) => resolve(code)), |
| 607 | + ); |
| 608 | + await new Promise<void>((resolve, reject) => { |
| 609 | + child.stdout.on("data", (data: Buffer) => { |
| 610 | + if (data.toString().includes("held")) resolve(); |
| 611 | + }); |
| 612 | + child.on("exit", () => reject(new Error("exited before holding"))); |
| 613 | + }); |
| 614 | + expect(await exists(lockPath)).toBe(true); |
| 615 | + |
| 616 | + child.kill("SIGTERM"); |
| 617 | + |
| 618 | + expect(await exited).toBe(143); |
| 619 | + expect(await exists(lockPath)).toBe(false); |
| 620 | + }, |
| 621 | + ); |
| 622 | +}); |
0 commit comments