Skip to content

Commit 5248c2f

Browse files
authored
fix(sqlite): isolate read-only snapshot preparation to stop WAL lock drops (#127855)
Runs prepareSqliteReadOnlyLocation[Sync] in a short-lived child process so POSIX close() can no longer drop the gateway's WAL locks (the #125744 producer), and adds a Linux WAL sidecar split-brain tripwire that invalidates and evicts a connection whose -wal/-shm fds no longer match the on-disk sidecars. Regression net: F_GETLK lock-survival test plus platform-agnostic smoke/error tests.
1 parent c719971 commit 5248c2f

12 files changed

Lines changed: 657 additions & 45 deletions

‎config/knip.config.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,8 @@ const rootEntries = [
157157
// Loaded by URL from the SQLite lifecycle archive owner.
158158
"src/config/sessions/session-accessor.sqlite-archive.worker.ts!",
159159
"src/state/openclaw-database-verify.worker.ts!",
160+
// Spawned by path from sqlite-readonly-location.ts to isolate raw-fd snapshot preparation.
161+
"src/infra/sqlite-readonly-location.worker.ts!",
160162
// Loaded by URL from tailscale.ts to outlive abrupt Gateway process exit.
161163
"src/infra/tailscale-route-owner.worker.ts!",
162164
"src/agents/model-provider-auth.worker.ts!",

‎src/infra/sqlite-readonly-location.test.ts‎

Lines changed: 150 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
1+
import { spawnSync } from "node:child_process";
12
import fs from "node:fs";
23
import path from "node:path";
34
import type { DatabaseSync } from "node:sqlite";
45
import { Worker } from "node:worker_threads";
56
import { afterEach, describe, expect, it, vi } from "vitest";
67
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
78
import { requireNodeSqlite } from "./node-sqlite.js";
8-
import { prepareSqliteReadOnlyLocation } from "./sqlite-readonly-location.js";
9+
import {
10+
prepareSqliteReadOnlyLocation,
11+
prepareSqliteReadOnlyLocationInProcess,
12+
prepareSqliteReadOnlyLocationSync,
13+
prepareSqliteReadOnlyLocationSyncInProcess,
14+
} from "./sqlite-readonly-location.js";
915

1016
const workers: Worker[] = [];
1117
const tempDirs = useAutoCleanupTempDirTracker((cleanup) => {
@@ -21,6 +27,42 @@ function createTempDatabasePath(): string {
2127
return path.join(tempDir, "state.sqlite");
2228
}
2329

30+
async function expectPublicSnapshot(
31+
prepare: (
32+
pathname: string,
33+
) =>
34+
| { cleanup: () => boolean; location: string }
35+
| Promise<{ cleanup: () => boolean; location: string }>,
36+
): Promise<void> {
37+
const sqlite = requireNodeSqlite();
38+
const databasePath = createTempDatabasePath();
39+
const writer = new sqlite.DatabaseSync(databasePath);
40+
let cleanup: (() => boolean) | undefined;
41+
try {
42+
writer.exec(`
43+
PRAGMA journal_mode = WAL;
44+
PRAGMA wal_autocheckpoint = 0;
45+
CREATE TABLE probe (value TEXT NOT NULL);
46+
INSERT INTO probe VALUES ('from-wal');
47+
`);
48+
expect(fs.existsSync(`${databasePath}-wal`)).toBe(true);
49+
50+
const prepared = await prepare(databasePath);
51+
cleanup = prepared.cleanup;
52+
const snapshot = new sqlite.DatabaseSync(prepared.location, { readOnly: true });
53+
try {
54+
expect(snapshot.prepare("SELECT value FROM probe").all()).toEqual([{ value: "from-wal" }]);
55+
} finally {
56+
snapshot.close();
57+
}
58+
expect(prepared.cleanup()).toBe(true);
59+
cleanup = undefined;
60+
} finally {
61+
cleanup?.();
62+
writer.close();
63+
}
64+
}
65+
2466
function readFamily(pathname: string): Map<string, Buffer> {
2567
const family = new Map<string, Buffer>();
2668
for (const suffix of ["", "-journal", "-shm", "-wal"]) {
@@ -56,7 +98,105 @@ function waitForWorkerMessage(worker: Worker, expected: string): Promise<void> {
5698
});
5799
}
58100

101+
type PosixLock = {
102+
length: number;
103+
pid: number;
104+
start: number;
105+
type: string;
106+
};
107+
108+
function readMainDatabasePosixLocks(pathname: string): PosixLock[] {
109+
const result = spawnSync(
110+
"python3",
111+
[
112+
"-c",
113+
`
114+
import fcntl, json, os, struct, sys
115+
layout = struct.Struct("hhqqi4x")
116+
request = layout.pack(fcntl.F_WRLCK, os.SEEK_SET, 1073741826, 510, 0)
117+
with open(sys.argv[1], "rb") as database:
118+
result = layout.unpack(fcntl.fcntl(database.fileno(), fcntl.F_GETLK, request))
119+
lock_type, _, start, length, pid = result
120+
locks = [] if lock_type == fcntl.F_UNLCK else [{
121+
"length": length,
122+
"pid": pid,
123+
"start": start,
124+
"type": "read" if lock_type == fcntl.F_RDLCK else "write",
125+
}]
126+
print(json.dumps(locks))
127+
`,
128+
pathname,
129+
],
130+
{ encoding: "utf8" },
131+
);
132+
if (result.status !== 0) {
133+
throw new Error(result.stderr || "POSIX lock probe failed");
134+
}
135+
return JSON.parse(result.stdout) as PosixLock[];
136+
}
137+
59138
describe("prepareSqliteReadOnlyLocation", () => {
139+
it("prepares a readable WAL snapshot through the async public entry point", async () => {
140+
await expectPublicSnapshot(prepareSqliteReadOnlyLocation);
141+
});
142+
143+
it("prepares a readable WAL snapshot through the sync public entry point", async () => {
144+
await expectPublicSnapshot(prepareSqliteReadOnlyLocationSync);
145+
});
146+
147+
it("propagates async public entry point failures", async () => {
148+
const missingPath = path.join(tempDirs.make("openclaw-sqlite-readonly-missing-"), "missing.db");
149+
await expect(prepareSqliteReadOnlyLocation(missingPath)).rejects.toThrow(
150+
/SQLite read-only worker .*ENOENT/u,
151+
);
152+
});
153+
154+
it("propagates sync public entry point failures", () => {
155+
const missingPath = path.join(tempDirs.make("openclaw-sqlite-readonly-missing-"), "missing.db");
156+
expect(() => prepareSqliteReadOnlyLocationSync(missingPath)).toThrow(
157+
/SQLite read-only worker .*ENOENT/u,
158+
);
159+
});
160+
161+
it.runIf(process.platform === "linux")(
162+
"keeps a live WAL connection's POSIX locks in the owning process",
163+
async () => {
164+
const sqlite = requireNodeSqlite();
165+
const databasePath = createTempDatabasePath();
166+
const writer = new sqlite.DatabaseSync(databasePath);
167+
writer.exec(`
168+
PRAGMA journal_mode = WAL;
169+
CREATE TABLE writes (id INTEGER PRIMARY KEY);
170+
INSERT INTO writes DEFAULT VALUES;
171+
`);
172+
const locksBefore = readMainDatabasePosixLocks(databasePath);
173+
const cleanups: Array<() => boolean> = [];
174+
try {
175+
expect(locksBefore).toHaveLength(1);
176+
177+
const preparedAsync = await prepareSqliteReadOnlyLocation(databasePath);
178+
cleanups.push(preparedAsync.cleanup);
179+
expect(readMainDatabasePosixLocks(databasePath)).toEqual(locksBefore);
180+
expect(preparedAsync.cleanup()).toBe(true);
181+
182+
const preparedSync = prepareSqliteReadOnlyLocationSync(databasePath);
183+
cleanups.push(preparedSync.cleanup);
184+
expect(readMainDatabasePosixLocks(databasePath)).toEqual(locksBefore);
185+
expect(preparedSync.cleanup()).toBe(true);
186+
187+
const characterized = prepareSqliteReadOnlyLocationSyncInProcess(databasePath);
188+
cleanups.push(characterized.cleanup);
189+
expect(readMainDatabasePosixLocks(databasePath)).toEqual([]);
190+
expect(characterized.cleanup()).toBe(true);
191+
} finally {
192+
for (const cleanup of cleanups) {
193+
cleanup();
194+
}
195+
writer.close();
196+
}
197+
},
198+
);
199+
60200
it("retries a same-size WAL reset instead of accepting an impossible pair", async () => {
61201
const sqlite = requireNodeSqlite();
62202
const livePath = createTempDatabasePath();
@@ -92,7 +232,7 @@ describe("prepareSqliteReadOnlyLocation", () => {
92232
}
93233
});
94234

95-
const prepared = await prepareSqliteReadOnlyLocation(databasePath);
235+
const prepared = await prepareSqliteReadOnlyLocationInProcess(databasePath);
96236
expect(injected).toBe(true);
97237
expect(fs.statSync(`${databasePath}-wal`).size).toBe(walSizeBeforeReset);
98238
const snapshot = new sqlite.DatabaseSync(prepared.location, { readOnly: true });
@@ -152,7 +292,7 @@ describe("prepareSqliteReadOnlyLocation", () => {
152292
try {
153293
await waitForWorkerMessage(worker, "ready");
154294

155-
const prepared = await prepareSqliteReadOnlyLocation(databasePath);
295+
const prepared = await prepareSqliteReadOnlyLocationInProcess(databasePath);
156296
const snapshot = new sqlite.DatabaseSync(prepared.location, { readOnly: true });
157297
expect(snapshot.prepare("PRAGMA integrity_check").get()).toEqual({ integrity_check: "ok" });
158298
expect(snapshot.prepare("SELECT COUNT(*) AS count FROM payload").get()).toEqual({ count: 1 });
@@ -196,7 +336,7 @@ describe("prepareSqliteReadOnlyLocation", () => {
196336
return statSync(pathname, options as never);
197337
}) as typeof fs.statSync);
198338

199-
const prepared = await prepareSqliteReadOnlyLocation(databasePath);
339+
const prepared = await prepareSqliteReadOnlyLocationInProcess(databasePath);
200340
const snapshot = new sqlite.DatabaseSync(prepared.location, { readOnly: true });
201341
expect(snapshot.prepare("SELECT value FROM probe").all()).toEqual([{ value: "ok" }]);
202342
snapshot.close();
@@ -249,7 +389,7 @@ describe("prepareSqliteReadOnlyLocation", () => {
249389
try {
250390
await waitForWorkerMessage(worker, "ready");
251391

252-
const prepared = await prepareSqliteReadOnlyLocation(databasePath);
392+
const prepared = await prepareSqliteReadOnlyLocationInProcess(databasePath);
253393
const snapshot = new sqlite.DatabaseSync(prepared.location, { readOnly: true });
254394
const values = snapshot
255395
.prepare("SELECT value FROM pair ORDER BY name")
@@ -290,7 +430,7 @@ describe("prepareSqliteReadOnlyLocation", () => {
290430
}
291431
});
292432

293-
const prepared = await prepareSqliteReadOnlyLocation(databasePath);
433+
const prepared = await prepareSqliteReadOnlyLocationInProcess(databasePath);
294434
expect(injected).toBe(true);
295435
expect(path.resolve(prepared.location)).not.toBe(path.resolve(databasePath));
296436
const snapshot = new sqlite.DatabaseSync(prepared.location, { readOnly: true });
@@ -316,7 +456,7 @@ describe("prepareSqliteReadOnlyLocation", () => {
316456
const symlinkPath = path.join(path.dirname(databasePath), "state-link.sqlite");
317457
fs.symlinkSync(path.basename(databasePath), symlinkPath);
318458

319-
const prepared = await prepareSqliteReadOnlyLocation(symlinkPath);
459+
const prepared = await prepareSqliteReadOnlyLocationInProcess(symlinkPath);
320460
const snapshot = new sqlite.DatabaseSync(prepared.location, { readOnly: true });
321461
expect(snapshot.prepare("SELECT value FROM probe").all()).toEqual([{ value: "from-wal" }]);
322462
snapshot.close();
@@ -346,7 +486,7 @@ describe("prepareSqliteReadOnlyLocation", () => {
346486
return statSync(pathname, options as never);
347487
}) as typeof fs.statSync);
348488

349-
const prepared = await prepareSqliteReadOnlyLocation(databasePath);
489+
const prepared = await prepareSqliteReadOnlyLocationInProcess(databasePath);
350490
expect(injected).toBe(true);
351491
const snapshot = new sqlite.DatabaseSync(prepared.location, { readOnly: true });
352492
expect(snapshot.prepare("SELECT value FROM probe").all()).toEqual([{ value: "ok" }]);
@@ -360,7 +500,7 @@ describe("prepareSqliteReadOnlyLocation", () => {
360500
const seed = new sqlite.DatabaseSync(databasePath);
361501
seed.exec("CREATE TABLE probe (value TEXT);");
362502
seed.close();
363-
const prepared = await prepareSqliteReadOnlyLocation(databasePath);
503+
const prepared = await prepareSqliteReadOnlyLocationInProcess(databasePath);
364504
const privateDirectory = path.dirname(prepared.location);
365505
const rmSync = fs.rmSync.bind(fs);
366506
let failRemoval = true;
@@ -397,7 +537,7 @@ describe("prepareSqliteReadOnlyLocation", () => {
397537
const beforeMain = fs.readFileSync(databasePath);
398538
const beforeEntries = fs.readdirSync(path.dirname(databasePath)).toSorted();
399539

400-
const prepared = await prepareSqliteReadOnlyLocation(databasePath);
540+
const prepared = await prepareSqliteReadOnlyLocationInProcess(databasePath);
401541
const snapshot = new sqlite.DatabaseSync(prepared.location, { readOnly: true });
402542
expect(snapshot.prepare("SELECT value FROM probe").all()).toEqual([{ value: "committed" }]);
403543
snapshot.close();

0 commit comments

Comments
 (0)