Skip to content

Commit 625dd5b

Browse files
committed
fix(plugin-state): distinguish fresh stores from damaged schemas
1 parent 1e1d800 commit 625dd5b

2 files changed

Lines changed: 82 additions & 20 deletions

File tree

‎src/plugin-state/plugin-state-store.fresh-store.test.ts‎

Lines changed: 60 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
// Fresh-store reads: a state DB created before the first plugin-state write has no
1+
// Fresh-store reads: a startup-checkpoint DB created before the first plugin-state write has no
22
// plugin_state_entries table; read-only paths must report empty, not error (#117249).
3-
import { mkdirSync } from "node:fs";
4-
import path from "node:path";
53
import { DatabaseSync } from "node:sqlite";
64
import { afterEach, describe, expect, it } from "vitest";
5+
import { withOpenClawStateStartupMigrationCheckpointDatabase } from "../state/openclaw-state-db.js";
76
import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths.js";
87
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
98
import {
@@ -12,21 +11,37 @@ import {
1211
pluginStateEntriesInKeyRange,
1312
resetPluginStateStoreForTests,
1413
} from "./plugin-state-store.js";
14+
import { PluginStateStoreError } from "./plugin-state-store.types.js";
1515

1616
afterEach(() => {
1717
resetPluginStateStoreForTests({ closeDatabase: false });
1818
});
1919

20+
async function expectPluginStateReadFailure(
21+
promise: Promise<unknown>,
22+
expected: { operation: "entries" | "lookup"; path: string },
23+
): Promise<void> {
24+
let storeError: unknown;
25+
try {
26+
await promise;
27+
} catch (error) {
28+
storeError = error;
29+
}
30+
expect(storeError).toBeInstanceOf(PluginStateStoreError);
31+
expect(storeError).toMatchObject({
32+
code: "PLUGIN_STATE_READ_FAILED",
33+
operation: expected.operation,
34+
path: expected.path,
35+
});
36+
}
37+
2038
describe("plugin state fresh-store reads", () => {
2139
it("treats an existing state database without the lazy plugin-state table as empty", async () => {
2240
await withOpenClawTestState(
2341
{ label: "plugin-state-read-only-table-missing", applyEnv: false },
2442
async (state) => {
2543
const databasePath = resolveOpenClawStateSqlitePath(state.env);
26-
mkdirSync(path.dirname(databasePath), { recursive: true });
27-
const database = new DatabaseSync(databasePath);
28-
database.exec("CREATE TABLE unrelated_state (id INTEGER PRIMARY KEY)");
29-
database.close();
44+
withOpenClawStateStartupMigrationCheckpointDatabase(() => undefined, { env: state.env });
3045

3146
const store = createPluginStateKeyedStore("discord", {
3247
namespace: "read-only-table-missing",
@@ -49,14 +64,45 @@ describe("plugin state fresh-store reads", () => {
4964
expect(countPluginStateLiveEntries("discord", state.env)).toBe(0);
5065

5166
const verify = new DatabaseSync(databasePath, { readOnly: true });
52-
expect(
53-
verify
54-
.prepare(
55-
"SELECT name FROM sqlite_schema WHERE type = 'table' AND name = 'plugin_state_entries'",
56-
)
57-
.get(),
58-
).toBeUndefined();
67+
const tables = verify
68+
.prepare("SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name")
69+
.all();
5970
verify.close();
71+
expect(tables).toEqual([{ name: "schema_meta" }, { name: "state_leases" }]);
72+
},
73+
);
74+
});
75+
76+
it("rejects a missing plugin-state table after another state table has been initialized", async () => {
77+
await withOpenClawTestState(
78+
{ label: "plugin-state-read-only-table-damaged", applyEnv: false },
79+
async (state) => {
80+
const databasePath = resolveOpenClawStateSqlitePath(state.env);
81+
withOpenClawStateStartupMigrationCheckpointDatabase(() => undefined, { env: state.env });
82+
const database = new DatabaseSync(databasePath);
83+
database.exec(`
84+
CREATE TABLE config_machine_state (
85+
state_key TEXT NOT NULL PRIMARY KEY,
86+
value_json TEXT NOT NULL,
87+
updated_at_ms INTEGER NOT NULL
88+
) STRICT
89+
`);
90+
database.close();
91+
92+
const store = createPluginStateKeyedStore("discord", {
93+
namespace: "read-only-table-damaged",
94+
maxEntries: 10,
95+
env: state.env,
96+
});
97+
98+
await expectPluginStateReadFailure(store.lookup("k"), {
99+
operation: "lookup",
100+
path: databasePath,
101+
});
102+
await expectPluginStateReadFailure(store.entries(), {
103+
operation: "entries",
104+
path: databasePath,
105+
});
60106
},
61107
);
62108
});

‎src/plugin-state/plugin-state-store.sqlite.ts‎

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,16 @@ function isMissingPluginStateTableError(error: unknown): boolean {
407407
);
408408
}
409409

410+
function hasStateTablesBeyondStartupCheckpoint(db: DatabaseSync): boolean {
411+
return (
412+
/* sqlite-allow-raw -- Read-only startup-checkpoint schema discriminator. */ db
413+
.prepare(
414+
"SELECT 1 FROM main.sqlite_schema WHERE type = 'table' AND name NOT IN ('schema_meta', 'state_leases') LIMIT 1",
415+
)
416+
.get() !== undefined
417+
);
418+
}
419+
410420
/** Read plugin state without joining the shared writable database lifecycle. */
411421
function withPluginStateDatabaseReadOnly<T>(
412422
operationName: PluginStateStoreOperation,
@@ -418,7 +428,18 @@ function withPluginStateDatabaseReadOnly<T>(
418428
try {
419429
return withExistingOpenClawStateDatabaseReadOnly(({ db, path }) => {
420430
operationStarted = true;
421-
return operation({ db, path });
431+
try {
432+
return operation({ db, path });
433+
} catch (error) {
434+
if (isMissingPluginStateTableError(error)) {
435+
// The lease bootstrap creates exactly schema_meta + state_leases before the first write;
436+
// any other table means the missing plugin-state table is damage, not fresh state.
437+
if (!hasStateTablesBeyondStartupCheckpoint(db)) {
438+
return undefined;
439+
}
440+
}
441+
throw error;
442+
}
422443
}, options);
423444
} catch (error) {
424445
if (!operationStarted) {
@@ -430,11 +451,6 @@ function withPluginStateDatabaseReadOnly<T>(
430451
pathname,
431452
);
432453
}
433-
if (isMissingPluginStateTableError(error)) {
434-
// Startup leases create the shared file before the first plugin-state write.
435-
// Read-only callers cannot ensure the lazy table, so its absence means no data yet.
436-
return undefined;
437-
}
438454
throw error;
439455
}
440456
}

0 commit comments

Comments
 (0)