Skip to content

Commit 71a5951

Browse files
authored
fix(sessions): honor file-lock cancellation (#117446)
1 parent e348182 commit 71a5951

3 files changed

Lines changed: 219 additions & 16 deletions

File tree

‎src/agents/session-write-lock.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,26 @@ describe("SQLite session write leases", () => {
105105
await expect(lock.release()).resolves.toBeUndefined();
106106
});
107107

108+
it("aborts while waiting without affecting the current owner", async () => {
109+
const sessionFile = target();
110+
const held = await acquire(sessionFile);
111+
const abort = new AbortController();
112+
const reason = new Error("stop waiting");
113+
const pending = acquire(sessionFile, {
114+
timeoutMs: Number.POSITIVE_INFINITY,
115+
signal: abort.signal,
116+
});
117+
const rejected = expect(pending).rejects.toBe(reason);
118+
119+
abort.abort(reason);
120+
121+
await rejected;
122+
expect(() => held.assertOwned?.()).not.toThrow();
123+
await held.release();
124+
const successor = await acquire(sessionFile, { timeoutMs: 500 });
125+
await successor.release();
126+
});
127+
108128
it("does not time-take over a live lease owner", async () => {
109129
testing.setProcessStartTimeResolverForTest(() => null);
110130
const sessionFile = target();

‎src/plugin-sdk/session-write-lock-runtime.test.ts‎

Lines changed: 193 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,34 @@
1-
import { spawn } from "node:child_process";
1+
import { spawn, spawnSync } from "node:child_process";
22
import fs from "node:fs/promises";
33
import os from "node:os";
44
import path from "node:path";
5+
import { pathToFileURL } from "node:url";
56
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
67
import {
78
SessionWriteLockStaleError,
89
SessionWriteLockTimeoutError,
910
} from "../agents/session-write-lock-error.js";
1011
import { drainSessionWriteLockStateForTest } from "../agents/session-write-lock.js";
12+
import { readSessionLockProcessStartTime } from "../infra/session-lock-file-inspection.js";
1113
import { closeOpenClawAgentDatabasesForTest } from "../state/openclaw-agent-db.js";
1214
import {
1315
acquireSessionWriteLock,
1416
drainSessionFileWriteLockStateForTest,
1517
} from "./session-write-lock-runtime.js";
1618

19+
const CLEANUP_SIGNALS = ["SIGINT", "SIGTERM", "SIGQUIT", "SIGABRT"] as const;
20+
21+
function addedSignalListener(
22+
signal: (typeof CLEANUP_SIGNALS)[number],
23+
before: Set<(...args: unknown[]) => void>,
24+
): (() => void) | undefined {
25+
return process
26+
.listeners(signal)
27+
.find((listener) => !before.has(listener as (...args: unknown[]) => void)) as
28+
| (() => void)
29+
| undefined;
30+
}
31+
1732
describe("Plugin SDK session write-lock adapter", () => {
1833
let root = "";
1934

@@ -40,16 +55,131 @@ describe("Plugin SDK session write-lock adapter", () => {
4055
await expect(fs.access(`${sessionFile}.lock`)).rejects.toMatchObject({ code: "ENOENT" });
4156
});
4257

43-
it("synchronously releases file sidecars on termination signals", async () => {
44-
const sessionFile = path.join(root, "session.jsonl");
58+
for (const signal of CLEANUP_SIGNALS) {
59+
it(`synchronously releases sidecars for ${signal} without removing peer listeners`, async () => {
60+
const sessionFile = path.join(root, `${signal}.jsonl`);
61+
const peer = () => {};
62+
process.on(signal, peer);
63+
const before = new Set(process.listeners(signal) as Array<(...args: unknown[]) => void>);
64+
const kill = vi.spyOn(process, "kill").mockReturnValue(true);
65+
try {
66+
await acquireSessionWriteLock({ sessionFile, timeoutMs: 500 });
67+
const cleanup = addedSignalListener(signal, before);
68+
expect(cleanup).toBeDefined();
69+
70+
cleanup?.();
71+
72+
await expect(fs.access(`${sessionFile}.lock`)).rejects.toMatchObject({ code: "ENOENT" });
73+
await drainSessionFileWriteLockStateForTest();
74+
expect(new Set(process.listeners(signal))).toEqual(before);
75+
expect(kill).not.toHaveBeenCalled();
76+
} finally {
77+
kill.mockRestore();
78+
process.off(signal, peer);
79+
}
80+
});
81+
}
82+
83+
it("does not accumulate cleanup listeners across drain cycles", async () => {
84+
const prime = await acquireSessionWriteLock({
85+
sessionFile: path.join(root, "listener-prime.jsonl"),
86+
timeoutMs: 500,
87+
});
88+
await prime.release();
89+
await drainSessionFileWriteLockStateForTest();
90+
const signalCounts = CLEANUP_SIGNALS.map((signal) => process.listenerCount(signal));
91+
const exitCount = process.listenerCount("exit");
92+
93+
for (let cycle = 0; cycle < 2; cycle += 1) {
94+
const lock = await acquireSessionWriteLock({
95+
sessionFile: path.join(root, `listener-${cycle}.jsonl`),
96+
timeoutMs: 500,
97+
});
98+
await lock.release();
99+
await drainSessionFileWriteLockStateForTest();
100+
}
101+
102+
expect(CLEANUP_SIGNALS.map((signal) => process.listenerCount(signal))).toEqual(signalCounts);
103+
expect(process.listenerCount("exit")).toBe(exitCount);
104+
});
105+
106+
it("reraises a sole termination signal after synchronous cleanup", async () => {
107+
const signal = "SIGTERM";
108+
const before = new Set(process.listeners(signal) as Array<(...args: unknown[]) => void>);
109+
const sessionFile = path.join(root, "sole-signal.jsonl");
45110
await acquireSessionWriteLock({ sessionFile, timeoutMs: 500 });
46-
const keepAlive = () => {};
47-
process.on("SIGTERM", keepAlive);
111+
const cleanup = addedSignalListener(signal, before);
112+
const listenerCount = vi.spyOn(process, "listenerCount").mockReturnValue(1);
113+
const kill = vi.spyOn(process, "kill").mockReturnValue(true);
48114
try {
49-
process.emit("SIGTERM");
115+
cleanup?.();
116+
50117
await expect(fs.access(`${sessionFile}.lock`)).rejects.toMatchObject({ code: "ENOENT" });
118+
expect(kill).toHaveBeenCalledWith(process.pid, signal);
51119
} finally {
52-
process.off("SIGTERM", keepAlive);
120+
listenerCount.mockRestore();
121+
kill.mockRestore();
122+
}
123+
});
124+
125+
it("removes sidecars during real process exit", async () => {
126+
const sessionFile = path.join(root, "process-exit.jsonl");
127+
const runtimeUrl = pathToFileURL(
128+
path.resolve("src/plugin-sdk/session-write-lock-runtime.ts"),
129+
).href;
130+
const script = `
131+
import fs from "node:fs/promises";
132+
import { acquireSessionWriteLock } from ${JSON.stringify(runtimeUrl)};
133+
const sessionFile = ${JSON.stringify(sessionFile)};
134+
await acquireSessionWriteLock({ sessionFile, timeoutMs: 500 });
135+
await fs.access(sessionFile + ".lock");
136+
process.exit(0);
137+
`;
138+
const result = spawnSync(
139+
process.execPath,
140+
["--import", "tsx", "--input-type=module", "-e", script],
141+
{ encoding: "utf8", timeout: 10_000 },
142+
);
143+
144+
expect(result.error).toBeUndefined();
145+
expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
146+
await expect(fs.access(`${sessionFile}.lock`)).rejects.toMatchObject({ code: "ENOENT" });
147+
});
148+
149+
it("watchdog expiry releases only the lock it owns", async () => {
150+
vi.useFakeTimers();
151+
vi.stubEnv("VITEST", "false");
152+
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
153+
const sessionFile = path.join(root, "watchdog.jsonl");
154+
try {
155+
const expired = await acquireSessionWriteLock({ sessionFile, timeoutMs: 500, maxHoldMs: 1 });
156+
await vi.advanceTimersByTimeAsync(60_001);
157+
vi.useRealTimers();
158+
await expect
159+
.poll(
160+
async () => {
161+
try {
162+
await fs.access(`${sessionFile}.lock`);
163+
return false;
164+
} catch {
165+
return true;
166+
}
167+
},
168+
{ timeout: 1_000 },
169+
)
170+
.toBe(true);
171+
expect(warn).toHaveBeenCalledWith(
172+
expect.stringContaining("[session-write-lock] releasing lock held for"),
173+
);
174+
175+
const successor = await acquireSessionWriteLock({ sessionFile, timeoutMs: 500 });
176+
await expired.release();
177+
await expect(fs.access(`${sessionFile}.lock`)).resolves.toBeUndefined();
178+
await successor.release();
179+
} finally {
180+
vi.useRealTimers();
181+
vi.unstubAllEnvs();
182+
warn.mockRestore();
53183
}
54184
});
55185

@@ -108,18 +238,40 @@ describe("Plugin SDK session write-lock adapter", () => {
108238
it("cancels contended infinite admission without affecting the owner", async () => {
109239
const sessionFile = path.join(root, "session.jsonl");
110240
const held = await acquireSessionWriteLock({ sessionFile, timeoutMs: 500 });
241+
const lockPath = `${sessionFile}.lock`;
242+
const originalReadFile = fs.readFile.bind(fs);
243+
let observedContention: (() => void) | undefined;
244+
const contention = new Promise<void>((resolve) => {
245+
observedContention = resolve;
246+
});
247+
const readFile = vi.spyOn(fs, "readFile").mockImplementation((async (file, options) => {
248+
if (file === lockPath) {
249+
observedContention?.();
250+
}
251+
return await originalReadFile(file, options as never);
252+
}) as typeof fs.readFile);
111253
const abort = new AbortController();
112254
const reason = new Error("stop requested");
113-
const pending = acquireSessionWriteLock({
114-
sessionFile,
115-
timeoutMs: Number.POSITIVE_INFINITY,
116-
signal: abort.signal,
117-
});
118-
abort.abort(reason);
255+
try {
256+
const pending = acquireSessionWriteLock({
257+
sessionFile,
258+
timeoutMs: Number.POSITIVE_INFINITY,
259+
signal: abort.signal,
260+
});
261+
const rejected = expect(pending).rejects.toBe(reason);
262+
await contention;
263+
abort.abort(reason);
119264

120-
await expect(pending).rejects.toBe(reason);
121-
await expect(fs.access(`${sessionFile}.lock`)).resolves.toBeUndefined();
122-
await held.release();
265+
await expect(fs.access(lockPath)).resolves.toBeUndefined();
266+
await held.release();
267+
await rejected;
268+
const successor = await acquireSessionWriteLock({ sessionFile, timeoutMs: 500 });
269+
await successor.release();
270+
await expect(fs.access(lockPath)).rejects.toMatchObject({ code: "ENOENT" });
271+
} finally {
272+
readFile.mockRestore();
273+
await held.release();
274+
}
123275
});
124276

125277
it("reclaims a definitely dead file owner", async () => {
@@ -164,6 +316,31 @@ describe("Plugin SDK session write-lock adapter", () => {
164316
await lock.release();
165317
});
166318

319+
it.runIf(process.platform === "linux")(
320+
"emits process starttime and reclaims a recycled-pid sidecar",
321+
async () => {
322+
const starttime = readSessionLockProcessStartTime(process.pid);
323+
expect(starttime).not.toBeNull();
324+
const sessionFile = path.join(root, "recycled-pid.jsonl");
325+
await fs.writeFile(
326+
`${sessionFile}.lock`,
327+
JSON.stringify({
328+
pid: process.pid,
329+
starttime: (starttime ?? 0) + 1,
330+
createdAt: new Date().toISOString(),
331+
}),
332+
);
333+
334+
const lock = await acquireSessionWriteLock({ sessionFile, timeoutMs: 500 });
335+
const payload = JSON.parse(await fs.readFile(`${sessionFile}.lock`, "utf8")) as {
336+
pid: number;
337+
starttime: number;
338+
};
339+
expect(payload).toMatchObject({ pid: process.pid, starttime });
340+
await lock.release();
341+
},
342+
);
343+
167344
it("reports an old live OpenClaw owner without removing it", async () => {
168345
const owner = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)", "openclaw"], {
169346
stdio: "ignore",

‎src/plugin-sdk/session-write-lock-runtime.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,12 @@ async function acquireFileArtifactLock(
205205
shouldRemoveStaleLock: async ({ lockPath: contenderPath, payload }) =>
206206
(await inspectArtifact(contenderPath, payload, Date.now())).removable,
207207
});
208+
// The signal can fire while fs-safe owns its retry loop. Never return a
209+
// newly acquired sidecar after the caller has cancelled admission.
210+
if (params.signal?.aborted) {
211+
await lock.release().catch(() => undefined);
212+
throwIfAborted(params.signal);
213+
}
208214
return { release: () => lock.release() };
209215
} catch (error) {
210216
throwIfAborted(params.signal);

0 commit comments

Comments
 (0)