Skip to content

Commit 947fa83

Browse files
authored
test(lock): assert timing-independent concurrency invariants (#106)
The stress test asserted that exactly four of forty concurrent contenders would be rejected. That count depends on how many acquisitions exceed their timeout, which is a property of the runner rather than of the lock, so a loaded Windows leg produced fourteen and turned main intermittently red. It now asserts the invariants its name claims and that hold regardless of timing: at most one active holder at any moment, all forty contenders settling cleanly, every acquired callback entering and exiting exactly once, the guaranteed throwing holder still releasing, and both the manager state and the lock sidecar left empty afterwards. The child-process count of sixteen is kept deliberately: eight successful children each emit exactly one enter and one exit, and a timing failure would fail earlier rather than change that number.
1 parent 4ff855a commit 947fa83

1 file changed

Lines changed: 64 additions & 25 deletions

File tree

‎test/file-lock-concurrency-stress.test.ts‎

Lines changed: 64 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@ import os from "node:os";
44
import path from "node:path";
55
import { setTimeout as delay } from "node:timers/promises";
66
import { afterEach, describe, expect, it } from "vitest";
7-
import { acquireFileLock, acquireFileLockSync, withFileLock } from "../src/file-lock.js";
7+
import {
8+
acquireFileLock,
9+
acquireFileLockSync,
10+
createFileLockManager,
11+
} from "../src/file-lock.js";
812
import { createSidecarLockManager } from "../src/sidecar-lock.js";
913

1014
const childTarget = process.env.FS_SAFE_STRESS_LOCK_TARGET;
@@ -21,6 +25,14 @@ async function tempRoot(prefix: string): Promise<string> {
2125
return directory;
2226
}
2327

28+
function deferred(): { promise: Promise<void>; resolve: () => void } {
29+
let resolve!: () => void;
30+
const promise = new Promise<void>((done) => {
31+
resolve = done;
32+
});
33+
return { promise, resolve };
34+
}
35+
2436
describe("file-lock concurrency stress", () => {
2537
it.runIf(!childTarget)("bounds attacker-controlled sidecar payload reads", async () => {
2638
const base = await tempRoot("fs-safe-sidecar-payload-limit-");
@@ -78,37 +90,64 @@ describe("file-lock concurrency stress", () => {
7890
it.runIf(!childTarget)("never overlaps many in-process holders and releases after throws", async () => {
7991
const root = await tempRoot("fs-safe-lock-in-process-");
8092
const targetPath = path.join(root, "state.json");
93+
const manager = createFileLockManager(`stress-${Date.now()}-${Math.random()}`);
94+
const throwingHolderEntered = deferred();
95+
const releaseThrowingHolder = deferred();
96+
const entries: number[] = [];
97+
const exits: number[] = [];
8198
let active = 0;
8299
let peak = 0;
83100

84-
const results = await Promise.allSettled(
85-
Array.from({ length: 40 }, async (_, index) => {
86-
return await withFileLock(
87-
targetPath,
88-
{
89-
staleMs: 60_000,
90-
timeoutMs: 10_000,
91-
retry: { minTimeout: 1, maxTimeout: 2 },
92-
payload: async () => ({ index, createdAt: new Date().toISOString() }),
93-
},
94-
async () => {
95-
active += 1;
96-
peak = Math.max(peak, active);
97-
try {
98-
await delay(index % 3);
99-
if (index % 11 === 0) throw new Error(`holder ${index} failed`);
100-
return index;
101-
} finally {
102-
active -= 1;
101+
const runContender = async (index: number, throws = false): Promise<number> =>
102+
await manager.withLock(
103+
targetPath,
104+
{
105+
staleMs: 60_000,
106+
timeoutMs: 10_000,
107+
retry: { minTimeout: 1, maxTimeout: 2 },
108+
payload: async () => ({ index, createdAt: new Date().toISOString() }),
109+
},
110+
async () => {
111+
entries.push(index);
112+
active += 1;
113+
peak = Math.max(peak, active);
114+
try {
115+
if (throws) {
116+
throwingHolderEntered.resolve();
117+
await releaseThrowingHolder.promise;
118+
throw new Error(`holder ${index} failed`);
103119
}
104-
},
105-
);
106-
}),
107-
);
120+
await delay(index % 3);
121+
return index;
122+
} finally {
123+
active -= 1;
124+
exits.push(index);
125+
}
126+
},
127+
);
128+
129+
const throwingHolder = runContender(0, true);
130+
await throwingHolderEntered.promise;
131+
const otherContenders = Array.from({ length: 39 }, (_, index) => runContender(index + 1));
132+
releaseThrowingHolder.resolve();
133+
const results = await Promise.allSettled([throwingHolder, ...otherContenders]);
134+
const fulfilled = results.filter((result) => result.status === "fulfilled");
135+
const timedOut = results.slice(1).filter((result) => result.status === "rejected");
108136

109137
expect(peak).toBe(1);
110138
expect(active).toBe(0);
111-
expect(results.filter((result) => result.status === "rejected")).toHaveLength(4);
139+
expect(results).toHaveLength(40);
140+
expect(results[0]).toMatchObject({
141+
status: "rejected",
142+
reason: { message: "holder 0 failed" },
143+
});
144+
expect(entries).toHaveLength(fulfilled.length + 1);
145+
expect(new Set(entries).size).toBe(entries.length);
146+
expect(exits).toEqual(entries);
147+
for (const result of timedOut) {
148+
expect(result.reason).toMatchObject({ code: "file_lock_timeout" });
149+
}
150+
expect(manager.heldEntries()).toEqual([]);
112151
await expect(fs.stat(`${targetPath}.lock`)).rejects.toMatchObject({ code: "ENOENT" });
113152
});
114153

0 commit comments

Comments
 (0)