1+ import { spawnSync } from "node:child_process" ;
12import fs from "node:fs" ;
23import path from "node:path" ;
34import type { DatabaseSync } from "node:sqlite" ;
45import { Worker } from "node:worker_threads" ;
56import { afterEach , describe , expect , it , vi } from "vitest" ;
67import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js" ;
78import { 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
1016const workers : Worker [ ] = [ ] ;
1117const 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+
2466function 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+
59138describe ( "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+ / S Q L i t e r e a d - o n l y w o r k e r .* E N O E N T / 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+ / S Q L i t e r e a d - o n l y w o r k e r .* E N O E N T / 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