Skip to content

Commit 02419ed

Browse files
authored
fix(plugin-state): treat missing plugin-state table as empty on read-only fresh stores (#117257)
* fix(plugin-state): treat missing plugin-state table as empty on read-only fresh stores Startup leases create state/openclaw.sqlite before the first plugin-state write, so legacy-state migration detection read the file through a read-only connection and failed on the missing plugin_state_entries table, blocking fresh-state-dir gateway boots from reaching ready. Fixes #117249 * test(plugin-state): split fresh-store read coverage into focused file * fix(plugin-state): distinguish fresh stores from damaged schemas
1 parent 0991fad commit 02419ed

3 files changed

Lines changed: 189 additions & 1 deletion

File tree

‎src/infra/state-migrations.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,14 @@ import { readAcpSessionMetaForEntry } from "../acp/runtime/session-meta.js";
88
import type { OpenClawConfig } from "../config/config.js";
99
import { loadNodeHostConfig } from "../node-host/config.js";
1010
import { readChannelPairingStateSnapshot } from "../pairing/pairing-store-sqlite.test-helpers.js";
11+
import type { PluginDoctorStateMigrationContext } from "../plugins/doctor-contract-registry.js";
1112
import type { DB as OpenClawStateKyselyDatabase } from "../state/openclaw-state-db.generated.js";
1213
import {
1314
closeOpenClawStateDatabaseForTest,
1415
openOpenClawStateDatabase,
1516
OPENCLAW_STATE_SCHEMA_VERSION,
1617
} from "../state/openclaw-state-db.js";
18+
import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths.js";
1719
import { createTrackedTempDirs } from "../test-utils/tracked-temp-dirs.js";
1820
import { acquireGatewayLock } from "./gateway-lock.js";
1921
import {
@@ -29,6 +31,7 @@ import {
2931
readPersistedVapidKeyPair,
3032
} from "./push-web-store.js";
3133
import { readRestartSentinel } from "./restart-sentinel.js";
34+
import { acquireStartupMigrationLease } from "./startup-migration-checkpoint.js";
3235
import {
3336
autoMigrateLegacyState,
3437
autoMigrateLegacyPluginDoctorState,
@@ -749,6 +752,53 @@ describe("state migrations", () => {
749752
}
750753
});
751754

755+
it("detects no plugin-state migration warnings after the startup lease creates fresh state", async () => {
756+
const root = await createTempDir();
757+
const stateDir = path.join(root, ".openclaw");
758+
const env = createEnv(stateDir);
759+
const detectLegacyState = vi.fn(async ({ context }: { context: unknown }) => {
760+
const pluginState = (context as PluginDoctorStateMigrationContext).openPluginStateKeyedStore({
761+
namespace: "fresh-start-detection",
762+
maxEntries: 10,
763+
});
764+
await expect(pluginState.lookup("legacy")).resolves.toBeUndefined();
765+
await expect(pluginState.entries()).resolves.toEqual([]);
766+
return null;
767+
});
768+
pluginDoctorStateMigrationEntries.entries = [
769+
{
770+
pluginId: "fixture",
771+
migration: {
772+
id: "fixture-fresh-start-plugin-state",
773+
label: "Fixture fresh-start plugin state",
774+
detectLegacyState,
775+
migrateLegacyState: vi.fn(() => ({ changes: [], warnings: [] })),
776+
},
777+
},
778+
];
779+
780+
const lease = acquireStartupMigrationLease({ env, owner: "fresh-start-test" });
781+
try {
782+
const databasePath = resolveOpenClawStateSqlitePath(env);
783+
const database = new DatabaseSync(databasePath, { readOnly: true });
784+
expect(
785+
database.prepare("SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name").all(),
786+
).toEqual([{ name: "schema_meta" }, { name: "state_leases" }]);
787+
database.close();
788+
789+
const detected = await detectLegacyStateMigrations({
790+
cfg: createConfig(),
791+
env,
792+
homedir: () => root,
793+
});
794+
795+
expect(detectLegacyState).toHaveBeenCalledOnce();
796+
expect(detected.warnings).toEqual([]);
797+
} finally {
798+
lease.release();
799+
}
800+
});
801+
752802
it("uses the requested environment for plugin migration refresh and writes", async () => {
753803
const root = await createTempDir();
754804
const stateDir = path.join(root, "custom-state");
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
// Fresh-store reads: a startup-checkpoint DB created before the first plugin-state write has no
2+
// plugin_state_entries table; read-only paths must report empty, not error (#117249).
3+
import { DatabaseSync } from "node:sqlite";
4+
import { afterEach, describe, expect, it } from "vitest";
5+
import { withOpenClawStateStartupMigrationCheckpointDatabase } from "../state/openclaw-state-db.js";
6+
import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths.js";
7+
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
8+
import {
9+
countPluginStateLiveEntries,
10+
createPluginStateKeyedStore,
11+
pluginStateEntriesInKeyRange,
12+
resetPluginStateStoreForTests,
13+
} from "./plugin-state-store.js";
14+
import { PluginStateStoreError } from "./plugin-state-store.types.js";
15+
16+
afterEach(() => {
17+
resetPluginStateStoreForTests({ closeDatabase: false });
18+
});
19+
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+
38+
describe("plugin state fresh-store reads", () => {
39+
it("treats an existing state database without the lazy plugin-state table as empty", async () => {
40+
await withOpenClawTestState(
41+
{ label: "plugin-state-read-only-table-missing", applyEnv: false },
42+
async (state) => {
43+
const databasePath = resolveOpenClawStateSqlitePath(state.env);
44+
withOpenClawStateStartupMigrationCheckpointDatabase(() => undefined, { env: state.env });
45+
46+
const store = createPluginStateKeyedStore("discord", {
47+
namespace: "read-only-table-missing",
48+
maxEntries: 10,
49+
env: state.env,
50+
});
51+
52+
await expect(store.lookup("k")).resolves.toBeUndefined();
53+
await expect(store.entries()).resolves.toEqual([]);
54+
expect(
55+
pluginStateEntriesInKeyRange({
56+
pluginId: "discord",
57+
namespace: "read-only-table-missing",
58+
keyStartInclusive: "a",
59+
keyEndExclusive: "z",
60+
limit: 1,
61+
env: state.env,
62+
}),
63+
).toEqual([]);
64+
expect(countPluginStateLiveEntries("discord", state.env)).toBe(0);
65+
66+
const verify = new DatabaseSync(databasePath, { readOnly: true });
67+
const tables = verify
68+
.prepare("SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name")
69+
.all();
70+
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+
});
106+
},
107+
);
108+
});
109+
});

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

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,24 @@ function openPluginStateDatabase(
399399
}
400400
}
401401

402+
function isMissingPluginStateTableError(error: unknown): boolean {
403+
return (
404+
error instanceof Error &&
405+
(error as NodeJS.ErrnoException).code === "ERR_SQLITE_ERROR" &&
406+
error.message === "no such table: plugin_state_entries"
407+
);
408+
}
409+
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+
402420
/** Read plugin state without joining the shared writable database lifecycle. */
403421
function withPluginStateDatabaseReadOnly<T>(
404422
operationName: PluginStateStoreOperation,
@@ -410,7 +428,18 @@ function withPluginStateDatabaseReadOnly<T>(
410428
try {
411429
return withExistingOpenClawStateDatabaseReadOnly(({ db, path }) => {
412430
operationStarted = true;
413-
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+
}
414443
}, options);
415444
} catch (error) {
416445
if (!operationStarted) {

0 commit comments

Comments
 (0)