Skip to content

Commit 6b32438

Browse files
authored
fix(sqlite): clear statement cache on database close (#115321)
Co-authored-by: VACInc <[email protected]>
1 parent fb8e1aa commit 6b32438

4 files changed

Lines changed: 130 additions & 20 deletions

File tree

‎src/infra/kysely-sync.test.ts‎

Lines changed: 104 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -375,16 +375,89 @@ describe("kysely sync helpers", () => {
375375
expect(prepares.calls()).toBe(2);
376376
});
377377

378+
it("preserves close return values and double-close errors", () => {
379+
const baseline = new DatabaseSync(":memory:");
380+
expect(baseline.close()).toBeUndefined();
381+
const baselineError = captureError(() => baseline.close());
382+
383+
const cached = new DatabaseSync(":memory:");
384+
enableNodeSqliteKyselyStatementCache(cached);
385+
expect(cached.close()).toBeUndefined();
386+
expect(errorShape(captureError(() => cached.close()))).toEqual(errorShape(baselineError));
387+
});
388+
389+
it("preserves close errors when invalidation is installed after the handle closes", () => {
390+
const baseline = new DatabaseSync(":memory:");
391+
baseline.close();
392+
const baselineError = captureError(() => baseline.close());
393+
394+
const cached = new DatabaseSync(":memory:");
395+
cached.close();
396+
enableNodeSqliteKyselyStatementCache(cached);
397+
expect(errorShape(captureError(() => cached.close()))).toEqual(errorShape(baselineError));
398+
});
399+
400+
it("clears cached statements before propagating a close failure", () => {
401+
const cached = new DatabaseSync(":memory:");
402+
cached.exec("create table items (id integer primary key, name text not null)");
403+
cached.exec("insert into items (id, name) values (1, 'Ada')");
404+
const closeError = new Error("synthetic close failure");
405+
Object.defineProperty(cached, "close", {
406+
configurable: true,
407+
writable: true,
408+
value(): never {
409+
throw closeError;
410+
},
411+
});
412+
const db = getNodeSqliteKysely<SyncHelperTestDatabase>(cached);
413+
const select = db.selectFrom("items").selectAll();
414+
const prepares = countPrepares(cached);
415+
416+
try {
417+
expect(executeSqliteQuerySync(cached, select).rows).toEqual([{ id: 1, name: "Ada" }]);
418+
expect(executeSqliteQuerySync(cached, select).rows).toEqual([{ id: 1, name: "Ada" }]);
419+
expect(executeSqliteQuerySync(cached, select).rows).toEqual([{ id: 1, name: "Ada" }]);
420+
expect(prepares.calls()).toBe(2);
421+
422+
expect(() => cached.close()).toThrow(closeError);
423+
expect(executeSqliteQuerySync(cached, select).rows).toEqual([{ id: 1, name: "Ada" }]);
424+
expect(prepares.calls()).toBe(3);
425+
} finally {
426+
clearNodeSqliteKyselyCacheForDatabase(cached);
427+
delete (cached as { close?: DatabaseSync["close"] }).close;
428+
cached.close();
429+
}
430+
});
431+
378432
it("allows databases and prepared statements to collect after lifecycle clearing", () => {
379-
expect(runRetentionScenario({ clearBeforeDrop: true })).toEqual({
433+
expect(runRetentionScenario({ cleanup: "clear-and-close" })).toEqual({
380434
databaseCollected: true,
381435
statementsCollected: 2,
382436
statementCount: 2,
383437
});
384438
});
385439

440+
it("allows databases and prepared statements to collect after close", () => {
441+
expect(runRetentionScenario({ cleanup: "close" })).toEqual({
442+
databaseCollected: true,
443+
statementsCollected: 2,
444+
statementCount: 2,
445+
});
446+
});
447+
448+
it.skipIf(typeof DatabaseSync.prototype[Symbol.dispose] !== "function")(
449+
"allows databases and prepared statements to collect after disposal",
450+
() => {
451+
expect(runRetentionScenario({ cleanup: "dispose" })).toEqual({
452+
databaseCollected: true,
453+
statementsCollected: 2,
454+
statementCount: 2,
455+
});
456+
},
457+
);
458+
386459
it("retains a cached database when lifecycle clearing is skipped", () => {
387-
expect(runRetentionScenario({ clearBeforeDrop: false })).toEqual({
460+
expect(runRetentionScenario({ cleanup: "drop" })).toEqual({
388461
databaseCollected: false,
389462
statementsCollected: 1,
390463
statementCount: 2,
@@ -432,18 +505,42 @@ function countPrepares(database: DatabaseSync): { calls: () => number } {
432505
return { calls: () => calls };
433506
}
434507

435-
function runRetentionScenario(options: { clearBeforeDrop: boolean }): {
508+
function captureError(operation: () => void): unknown {
509+
try {
510+
operation();
511+
} catch (error) {
512+
return error;
513+
}
514+
throw new Error("expected operation to throw");
515+
}
516+
517+
function errorShape(error: unknown): { code: string | undefined; message: string; name: string } {
518+
expect(error).toBeInstanceOf(Error);
519+
const sqliteError = error as Error & { code?: string };
520+
return {
521+
code: sqliteError.code,
522+
message: sqliteError.message,
523+
name: sqliteError.name,
524+
};
525+
}
526+
527+
function runRetentionScenario(options: {
528+
cleanup: "clear-and-close" | "close" | "dispose" | "drop";
529+
}): {
436530
databaseCollected: boolean;
437531
statementsCollected: number;
438532
statementCount: number;
439533
} {
440534
const moduleUrl = new URL("./kysely-sync.ts", import.meta.url).href;
441-
const cleanup = options.clearBeforeDrop
442-
? `
535+
const cleanup = {
536+
"clear-and-close": `
443537
clearNodeSqliteKyselyCacheForDatabase(database);
444538
database.close();
445-
`
446-
: "";
539+
`,
540+
close: "database.close();",
541+
dispose: "database[Symbol.dispose]();",
542+
drop: "",
543+
}[options.cleanup];
447544
const script = `
448545
import { DatabaseSync } from "node:sqlite";
449546
import {

‎src/infra/kysely-sync.ts‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ import { InsertQueryNode, Kysely as KyselyInstance, SqliteDialect } from "kysely
77
// going through Kysely's async driver path.
88

99
const kyselyByDatabase = new WeakMap<DatabaseSync, Kysely<unknown>>();
10-
// Cached statements retain their database. Every enabled owner must clear before
11-
// close or drop; this required lifecycle pairing is not enforced automatically.
10+
// Cached statements retain their database. Per-instance lifecycle wrappers clear
11+
// both caches before the native database handle closes.
1212
const statementCacheSymbol = Symbol("openclaw.kyselySyncStatementCache");
1313
const statementInvalidationSymbol = Symbol("openclaw.kyselySyncStatementInvalidation");
1414
const statementCacheEnabledSymbol = Symbol("openclaw.kyselySyncStatementCacheEnabled");
@@ -88,6 +88,28 @@ function installStatementInvalidation(owner: StatementCacheOwner): void {
8888
},
8989
});
9090
}
91+
if (typeof owner.close === "function") {
92+
const close = owner.close.bind(owner);
93+
Object.defineProperty(owner, "close", {
94+
configurable: true,
95+
writable: true,
96+
value(this: StatementCacheOwner): void {
97+
clearNodeSqliteKyselyCacheForDatabase(this);
98+
return close();
99+
},
100+
});
101+
}
102+
if (typeof owner[Symbol.dispose] === "function") {
103+
const dispose = owner[Symbol.dispose].bind(owner);
104+
Object.defineProperty(owner, Symbol.dispose, {
105+
configurable: true,
106+
writable: true,
107+
value(this: StatementCacheOwner): void {
108+
clearNodeSqliteKyselyCacheForDatabase(this);
109+
return dispose();
110+
},
111+
});
112+
}
91113
Object.defineProperty(owner, statementInvalidationSymbol, {
92114
configurable: true,
93115
value: true,
@@ -259,7 +281,7 @@ export function executeSqliteQueryTakeFirstSync<Row>(
259281
return executeSqliteQuerySync<Row>(db, query).rows[0];
260282
}
261283

262-
/** Drop cached Kysely state for a DatabaseSync before close/test reset. */
284+
/** Drop cached Kysely state for a DatabaseSync. */
263285
export function clearNodeSqliteKyselyCacheForDatabase(db: DatabaseSync): void {
264286
// Delete the database-owned cache before close so statements release their
265287
// native database backreferences instead of recreating the WeakMap leak.

‎src/state/openclaw-agent-db.ts‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,7 @@
22
import { existsSync } from "node:fs";
33
import path from "node:path";
44
import type { DatabaseSync } from "node:sqlite";
5-
import {
6-
clearNodeSqliteKyselyCacheForDatabase,
7-
enableNodeSqliteKyselyStatementCache,
8-
} from "../infra/kysely-sync.js";
5+
import { enableNodeSqliteKyselyStatementCache } from "../infra/kysely-sync.js";
96
import { openNodeSqliteDatabase } from "../infra/node-sqlite.js";
107
import type { SqliteFileGeneration } from "../infra/sqlite-file-generation.js";
118
import {
@@ -343,7 +340,6 @@ export function openOpenClawAgentDatabase(
343340
return maintenance;
344341
} catch (err) {
345342
maintenance?.close();
346-
clearNodeSqliteKyselyCacheForDatabase(db);
347343
db.close();
348344
if (
349345
err instanceof Error &&
@@ -487,7 +483,6 @@ function closeCachedOpenClawAgentDatabase(
487483
// Eviction must stay cheap: PASSIVE skips waiting on concurrent readers,
488484
// whose drained TRUNCATE checkpoints blocked the event loop for seconds.
489485
database.walMaintenance.close(options.eviction ? { checkpointMode: "PASSIVE" } : undefined);
490-
clearNodeSqliteKyselyCacheForDatabase(database.db);
491486
if (database.db.isOpen) {
492487
database.db.close();
493488
}

‎src/state/openclaw-state-db.ts‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,6 @@ const terminalOpenLatch = createSqliteTerminalOpenLatch({
107107
return;
108108
}
109109
cached.walMaintenance.close();
110-
clearNodeSqliteKyselyCacheForDatabase(cached.db);
111110
if (cached.db.isOpen) {
112111
cached.db.close();
113112
}
@@ -583,7 +582,6 @@ export function openOpenClawStateDatabase(
583582
return maintenance;
584583
} catch (err) {
585584
maintenance?.close();
586-
clearNodeSqliteKyselyCacheForDatabase(db);
587585
db.close();
588586
if (
589587
err instanceof Error &&
@@ -647,7 +645,6 @@ export function closeOpenClawStateDatabaseByPath(pathname: string): boolean {
647645
return false;
648646
}
649647
database.walMaintenance.close();
650-
clearNodeSqliteKyselyCacheForDatabase(database.db);
651648
if (database.db.isOpen) {
652649
database.db.close();
653650
}
@@ -659,7 +656,6 @@ export function closeOpenClawStateDatabaseByPath(pathname: string): boolean {
659656
export function closeOpenClawStateDatabase(): void {
660657
for (const database of cachedDatabases.values()) {
661658
database.walMaintenance.close();
662-
clearNodeSqliteKyselyCacheForDatabase(database.db);
663659
if (database.db.isOpen) {
664660
database.db.close();
665661
}

0 commit comments

Comments
 (0)