|
| 1 | +// Unit tests for withFileLock, the lock file that orders mutations from |
| 2 | +// separate server processes sharing one graph file (#4797): mutual exclusion, |
| 3 | +// release, breaking an abandoned lock, and giving up on a held one. |
| 4 | +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; |
| 5 | +import { promises as fs } from "fs"; |
| 6 | +import os from "os"; |
| 7 | +import path from "path"; |
| 8 | +import { spawnSync } from "child_process"; |
| 9 | +import { KnowledgeGraphManager, withFileLock } from "../index.js"; |
| 10 | +import { makeTempGraph } from "./helpers.js"; |
| 11 | + |
| 12 | +const fast = { staleMs: 60_000, timeoutMs: 100, retryMs: 5 }; |
| 13 | + |
| 14 | +describe("withFileLock", () => { |
| 15 | + let dir: string; |
| 16 | + let lockPath: string; |
| 17 | + let cleanup: () => Promise<void>; |
| 18 | + |
| 19 | + beforeEach(async () => { |
| 20 | + ({ dir, cleanup } = await makeTempGraph()); |
| 21 | + lockPath = path.join(dir, "memory.jsonl.lock"); |
| 22 | + }); |
| 23 | + |
| 24 | + afterEach(async () => { |
| 25 | + vi.restoreAllMocks(); |
| 26 | + await cleanup(); |
| 27 | + }); |
| 28 | + |
| 29 | + async function exists(file: string): Promise<boolean> { |
| 30 | + return fs.access(file).then( |
| 31 | + () => true, |
| 32 | + () => false, |
| 33 | + ); |
| 34 | + } |
| 35 | + |
| 36 | + it("holds the lock file while the operation runs and removes it after", async () => { |
| 37 | + const result = await withFileLock(lockPath, async () => { |
| 38 | + const owner = JSON.parse(await fs.readFile(lockPath, "utf-8")); |
| 39 | + expect(owner).toMatchObject({ |
| 40 | + pid: process.pid, |
| 41 | + hostname: os.hostname(), |
| 42 | + }); |
| 43 | + return 42; |
| 44 | + }); |
| 45 | + expect(result).toBe(42); |
| 46 | + expect(await exists(lockPath)).toBe(false); |
| 47 | + }); |
| 48 | + |
| 49 | + it("releases the lock when the operation fails", async () => { |
| 50 | + await expect( |
| 51 | + withFileLock(lockPath, async () => { |
| 52 | + throw new Error("boom"); |
| 53 | + }), |
| 54 | + ).rejects.toThrow("boom"); |
| 55 | + expect(await exists(lockPath)).toBe(false); |
| 56 | + }); |
| 57 | + |
| 58 | + it("runs overlapping holders one at a time", async () => { |
| 59 | + let active = 0; |
| 60 | + let maxActive = 0; |
| 61 | + const order: string[] = []; |
| 62 | + const hold = (name: string) => |
| 63 | + withFileLock( |
| 64 | + lockPath, |
| 65 | + async () => { |
| 66 | + active += 1; |
| 67 | + maxActive = Math.max(maxActive, active); |
| 68 | + order.push(`${name} start`); |
| 69 | + await new Promise((resolve) => setTimeout(resolve, 20)); |
| 70 | + order.push(`${name} end`); |
| 71 | + active -= 1; |
| 72 | + }, |
| 73 | + { retryMs: 2 }, |
| 74 | + ); |
| 75 | + |
| 76 | + await Promise.all([hold("a"), hold("b"), hold("c")]); |
| 77 | + |
| 78 | + expect(maxActive).toBe(1); |
| 79 | + expect(order).toHaveLength(6); |
| 80 | + for (let i = 0; i < 6; i += 2) { |
| 81 | + expect(order[i + 1]).toBe(order[i].replace("start", "end")); |
| 82 | + } |
| 83 | + }); |
| 84 | + |
| 85 | + it("breaks a lock whose owner on this host has exited", async () => { |
| 86 | + const { pid } = spawnSync(process.execPath, ["-e", ""]); |
| 87 | + await fs.writeFile( |
| 88 | + lockPath, |
| 89 | + JSON.stringify({ pid, hostname: os.hostname(), token: "dead" }), |
| 90 | + ); |
| 91 | + vi.spyOn(console, "error").mockImplementation(() => {}); |
| 92 | + |
| 93 | + expect(await withFileLock(lockPath, async () => "ran", fast)).toBe("ran"); |
| 94 | + expect(console.error).toHaveBeenCalledWith( |
| 95 | + `Breaking stale memory file lock ${lockPath}`, |
| 96 | + ); |
| 97 | + expect(await exists(lockPath)).toBe(false); |
| 98 | + }); |
| 99 | + |
| 100 | + it("breaks a lock older than staleMs", async () => { |
| 101 | + await fs.writeFile( |
| 102 | + lockPath, |
| 103 | + JSON.stringify({ pid: 1, hostname: "another-host", token: "old" }), |
| 104 | + ); |
| 105 | + const longAgo = new Date(Date.now() - 120_000); |
| 106 | + await fs.utimes(lockPath, longAgo, longAgo); |
| 107 | + vi.spyOn(console, "error").mockImplementation(() => {}); |
| 108 | + |
| 109 | + expect(await withFileLock(lockPath, async () => "ran", fast)).toBe("ran"); |
| 110 | + expect(await exists(lockPath)).toBe(false); |
| 111 | + }); |
| 112 | + |
| 113 | + it.each([ |
| 114 | + [ |
| 115 | + "a live owner on this host", |
| 116 | + JSON.stringify({ pid: process.pid, hostname: os.hostname() }), |
| 117 | + ], |
| 118 | + [ |
| 119 | + "an owner on another host", |
| 120 | + JSON.stringify({ pid: 1, hostname: "another-host" }), |
| 121 | + ], |
| 122 | + ["a lock still being written", ""], |
| 123 | + ["a lock with no owner", "null"], |
| 124 | + ])( |
| 125 | + "waits on a fresh lock held by %s and then times out", |
| 126 | + async (_, contents) => { |
| 127 | + await fs.writeFile(lockPath, contents); |
| 128 | + const operation = vi.fn(async () => "ran"); |
| 129 | + |
| 130 | + await expect(withFileLock(lockPath, operation, fast)).rejects.toThrow( |
| 131 | + `Timed out after 100 ms waiting for the memory file lock ${lockPath}`, |
| 132 | + ); |
| 133 | + expect(operation).not.toHaveBeenCalled(); |
| 134 | + expect(await fs.readFile(lockPath, "utf-8")).toBe(contents); |
| 135 | + }, |
| 136 | + ); |
| 137 | + |
| 138 | + async function writeStaleLock(contents = "stale"): Promise<void> { |
| 139 | + await fs.writeFile(lockPath, contents); |
| 140 | + const longAgo = new Date(Date.now() - 120_000); |
| 141 | + await fs.utimes(lockPath, longAgo, longAgo); |
| 142 | + } |
| 143 | + |
| 144 | + // Run hook once, the first time fs.open is called with these arguments. |
| 145 | + function onceOnOpen( |
| 146 | + file: string, |
| 147 | + flags: string, |
| 148 | + hook: () => Promise<void>, |
| 149 | + ): void { |
| 150 | + const realOpen = fs.open; |
| 151 | + let fired = false; |
| 152 | + vi.spyOn(fs, "open").mockImplementation((async ( |
| 153 | + ...args: Parameters<typeof fs.open> |
| 154 | + ) => { |
| 155 | + if (!fired && args[0] === file && args[1] === flags) { |
| 156 | + fired = true; |
| 157 | + await hook(); |
| 158 | + } |
| 159 | + return realOpen(...args); |
| 160 | + }) as typeof fs.open); |
| 161 | + } |
| 162 | + |
| 163 | + it("does not break a lock another waiter replaced while it was judged stale", async () => { |
| 164 | + await writeStaleLock(); |
| 165 | + // Another waiter breaks the stale lock and takes it after this waiter |
| 166 | + // judged it stale but before this waiter takes the breaking guard. |
| 167 | + onceOnOpen(`${lockPath}.break`, "wx", async () => { |
| 168 | + await fs.unlink(lockPath); |
| 169 | + await fs.writeFile(lockPath, "fresh"); |
| 170 | + }); |
| 171 | + |
| 172 | + await expect( |
| 173 | + withFileLock(lockPath, async () => "ran", fast), |
| 174 | + ).rejects.toThrow("Timed out"); |
| 175 | + expect(await fs.readFile(lockPath, "utf-8")).toBe("fresh"); |
| 176 | + expect(await fs.readdir(dir)).toEqual(["memory.jsonl.lock"]); |
| 177 | + }); |
| 178 | + |
| 179 | + it("leaves a stale lock to the waiter already breaking it", async () => { |
| 180 | + await writeStaleLock(); |
| 181 | + await fs.writeFile(`${lockPath}.break`, ""); |
| 182 | + |
| 183 | + await expect( |
| 184 | + withFileLock(lockPath, async () => "ran", fast), |
| 185 | + ).rejects.toThrow("Timed out"); |
| 186 | + expect(await fs.readFile(lockPath, "utf-8")).toBe("stale"); |
| 187 | + }); |
| 188 | + |
| 189 | + it("clears a breaking guard left by a crash, then breaks the stale lock", async () => { |
| 190 | + await writeStaleLock(); |
| 191 | + const breakerPath = `${lockPath}.break`; |
| 192 | + await fs.writeFile(breakerPath, ""); |
| 193 | + const longAgo = new Date(Date.now() - 120_000); |
| 194 | + await fs.utimes(breakerPath, longAgo, longAgo); |
| 195 | + vi.spyOn(console, "error").mockImplementation(() => {}); |
| 196 | + |
| 197 | + expect(await withFileLock(lockPath, async () => "ran", fast)).toBe("ran"); |
| 198 | + expect(await fs.readdir(dir)).toEqual([]); |
| 199 | + }); |
| 200 | + |
| 201 | + it("fails when the breaking guard cannot be created", async () => { |
| 202 | + await writeStaleLock(); |
| 203 | + const realOpen = fs.open; |
| 204 | + vi.spyOn(fs, "open").mockImplementation((async ( |
| 205 | + ...args: Parameters<typeof fs.open> |
| 206 | + ) => { |
| 207 | + if (args[0] === `${lockPath}.break`) { |
| 208 | + throw Object.assign(new Error("EACCES: simulated"), { |
| 209 | + code: "EACCES", |
| 210 | + }); |
| 211 | + } |
| 212 | + return realOpen(...args); |
| 213 | + }) as typeof fs.open); |
| 214 | + |
| 215 | + await expect( |
| 216 | + withFileLock(lockPath, async () => "ran", fast), |
| 217 | + ).rejects.toThrow("EACCES: simulated"); |
| 218 | + }); |
| 219 | + |
| 220 | + it("acquires the lock at once when the holder releases it mid-check", async () => { |
| 221 | + await fs.writeFile(lockPath, "held"); |
| 222 | + onceOnOpen(lockPath, "r", () => fs.unlink(lockPath)); |
| 223 | + |
| 224 | + expect(await withFileLock(lockPath, async () => "ran", fast)).toBe("ran"); |
| 225 | + }); |
| 226 | + |
| 227 | + it("keeps a lock held longer than staleMs fresh, so it is not broken", async () => { |
| 228 | + const opts = { staleMs: 100, timeoutMs: 5_000, retryMs: 5 }; |
| 229 | + const order: string[] = []; |
| 230 | + const long = withFileLock( |
| 231 | + lockPath, |
| 232 | + async () => { |
| 233 | + order.push("long start"); |
| 234 | + await new Promise((resolve) => setTimeout(resolve, 400)); |
| 235 | + order.push("long end"); |
| 236 | + }, |
| 237 | + opts, |
| 238 | + ); |
| 239 | + // Let the long holder take the lock before the waiter starts. |
| 240 | + await new Promise((resolve) => setTimeout(resolve, 20)); |
| 241 | + const waiter = withFileLock( |
| 242 | + lockPath, |
| 243 | + async () => { |
| 244 | + order.push("waiter"); |
| 245 | + }, |
| 246 | + opts, |
| 247 | + ); |
| 248 | + |
| 249 | + await Promise.all([long, waiter]); |
| 250 | + expect(order).toEqual(["long start", "long end", "waiter"]); |
| 251 | + }); |
| 252 | + |
| 253 | + it("removes the lock it created when writing it fails", async () => { |
| 254 | + const realOpen = fs.open; |
| 255 | + vi.spyOn(fs, "open").mockImplementationOnce(async (...args) => { |
| 256 | + const handle = await realOpen(...args); |
| 257 | + handle.writeFile = async () => { |
| 258 | + throw new Error("EIO: simulated write failure"); |
| 259 | + }; |
| 260 | + // The cleanup's own close failing must not mask the write failure. |
| 261 | + const realClose = handle.close.bind(handle); |
| 262 | + handle.close = async () => { |
| 263 | + await realClose(); |
| 264 | + throw new Error("EIO: simulated close failure"); |
| 265 | + }; |
| 266 | + return handle; |
| 267 | + }); |
| 268 | + |
| 269 | + await expect(withFileLock(lockPath, async () => "ran")).rejects.toThrow( |
| 270 | + "EIO: simulated write failure", |
| 271 | + ); |
| 272 | + expect(await exists(lockPath)).toBe(false); |
| 273 | + }); |
| 274 | + |
| 275 | + it("leaves a lock it no longer owns in place on release", async () => { |
| 276 | + await withFileLock(lockPath, async () => { |
| 277 | + await fs.writeFile(lockPath, "someone else"); |
| 278 | + }); |
| 279 | + expect(await fs.readFile(lockPath, "utf-8")).toBe("someone else"); |
| 280 | + }); |
| 281 | + |
| 282 | + it("releases quietly when its lock is already gone", async () => { |
| 283 | + expect( |
| 284 | + await withFileLock(lockPath, async () => { |
| 285 | + await fs.unlink(lockPath); |
| 286 | + return "ran"; |
| 287 | + }), |
| 288 | + ).toBe("ran"); |
| 289 | + expect(await exists(lockPath)).toBe(false); |
| 290 | + }); |
| 291 | + |
| 292 | + it("fails when the lock file cannot be created", async () => { |
| 293 | + const missing = path.join(dir, "no-such-dir", "memory.jsonl.lock"); |
| 294 | + await expect(withFileLock(missing, async () => "ran")).rejects.toThrow( |
| 295 | + "ENOENT", |
| 296 | + ); |
| 297 | + }); |
| 298 | + |
| 299 | + it("fails when the existing lock cannot be read", async () => { |
| 300 | + await fs.mkdir(lockPath); |
| 301 | + await expect( |
| 302 | + withFileLock(lockPath, async () => "ran", fast), |
| 303 | + ).rejects.toThrow("EISDIR"); |
| 304 | + }); |
| 305 | + |
| 306 | + it("waits, on Windows, for a lock file another process is still deleting", async () => { |
| 307 | + // Windows fails an open of a file pending deletion with EPERM, not EEXIST. |
| 308 | + vi.spyOn(process, "platform", "get").mockReturnValue("win32"); |
| 309 | + const pendingDelete = Object.assign(new Error("EPERM"), { code: "EPERM" }); |
| 310 | + const realOpen = fs.open.bind(fs); |
| 311 | + let calls = 0; |
| 312 | + vi.spyOn(fs, "open").mockImplementation((( |
| 313 | + ...args: Parameters<typeof fs.open> |
| 314 | + ) => { |
| 315 | + calls += 1; |
| 316 | + // The create, then the stale check's read, both see the pending delete. |
| 317 | + return calls <= 2 ? Promise.reject(pendingDelete) : realOpen(...args); |
| 318 | + }) as typeof fs.open); |
| 319 | + |
| 320 | + await expect( |
| 321 | + withFileLock(lockPath, async () => "done", fast), |
| 322 | + ).resolves.toBe("done"); |
| 323 | + expect(calls).toBeGreaterThan(2); |
| 324 | + expect(await exists(lockPath)).toBe(false); |
| 325 | + }); |
| 326 | + |
| 327 | + it("does not treat EPERM as a held lock off Windows", async () => { |
| 328 | + vi.spyOn(process, "platform", "get").mockReturnValue("linux"); |
| 329 | + const denied = Object.assign(new Error("EPERM"), { code: "EPERM" }); |
| 330 | + vi.spyOn(fs, "open").mockRejectedValue(denied); |
| 331 | + |
| 332 | + await expect(withFileLock(lockPath, async () => "done", fast)).rejects.toBe( |
| 333 | + denied, |
| 334 | + ); |
| 335 | + }); |
| 336 | + |
| 337 | + it("orders two managers' mutations on one graph file", async () => { |
| 338 | + const filePath = path.join(dir, "memory.jsonl"); |
| 339 | + const managers = [ |
| 340 | + new KnowledgeGraphManager(filePath, { retryMs: 1 }), |
| 341 | + new KnowledgeGraphManager(filePath, { retryMs: 1 }), |
| 342 | + ]; |
| 343 | + const names = Array.from({ length: 20 }, (_, i) => `entity-${i}`); |
| 344 | + |
| 345 | + await Promise.all( |
| 346 | + names.map((name, i) => |
| 347 | + managers[i % 2].createEntities([ |
| 348 | + { name, entityType: "thing", observations: [] }, |
| 349 | + ]), |
| 350 | + ), |
| 351 | + ); |
| 352 | + |
| 353 | + const graph = await managers[0].readGraph(); |
| 354 | + expect(graph.entities.map((e) => e.name).sort()).toEqual([...names].sort()); |
| 355 | + expect(await fs.readdir(dir)).toEqual(["memory.jsonl"]); |
| 356 | + }); |
| 357 | +}); |
0 commit comments