Skip to content

Commit 4ea758d

Browse files
authored
fix(sqlite): keep plugin index reads read-only (#106103)
1 parent 24ad248 commit 4ea758d

4 files changed

Lines changed: 130 additions & 39 deletions

File tree

‎src/plugins/installed-plugin-index-record-reader.ts‎

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import path from "node:path";
44
import { isRecord } from "@openclaw/normalization-core/record-coerce";
55
import type { PluginInstallRecord } from "../config/types.plugins.js";
66
import { tryReadJsonSync } from "../infra/json-files.js";
7-
import { openOpenClawStateDatabase } from "../state/openclaw-state-db.js";
7+
import { withOpenClawStateDatabaseReadOnly } from "../state/openclaw-state-db-readonly.js";
88
import { resolveDefaultPluginNpmDir, validatePluginId } from "./install-paths.js";
99
import {
1010
getInstalledPluginIndexInstallRecordsCache,
@@ -269,25 +269,24 @@ function readPersistedInstalledPluginIndexForRecords(
269269
return tryReadJsonSync(options.filePath);
270270
}
271271
try {
272-
const database = openOpenClawStateDatabase(
273-
resolveInstalledPluginIndexStateDatabaseOptions(options),
274-
);
275-
const row = database.db
276-
.prepare(
277-
`
278-
SELECT install_records_json, plugins_json
279-
FROM installed_plugin_index
280-
WHERE index_key = ?
281-
`,
282-
)
283-
.get("installed-plugin-index") as InstalledPluginIndexRecordRow | undefined;
284-
if (!row) {
285-
return null;
286-
}
287-
return {
288-
installRecords: parseJsonColumn(row.install_records_json),
289-
plugins: parseJsonColumn(row.plugins_json),
290-
};
272+
return withOpenClawStateDatabaseReadOnly(({ db }) => {
273+
const row = db
274+
.prepare(
275+
`
276+
SELECT install_records_json, plugins_json
277+
FROM installed_plugin_index
278+
WHERE index_key = ?
279+
`,
280+
)
281+
.get("installed-plugin-index") as InstalledPluginIndexRecordRow | undefined;
282+
if (!row) {
283+
return null;
284+
}
285+
return {
286+
installRecords: parseJsonColumn(row.install_records_json),
287+
plugins: parseJsonColumn(row.plugins_json),
288+
};
289+
}, resolveInstalledPluginIndexStateDatabaseOptions(options));
291290
} catch {
292291
return null;
293292
}

‎src/plugins/installed-plugin-index-store.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@
22
import fs from "node:fs";
33
import path from "node:path";
44
import { afterEach, describe, expect, it } from "vitest";
5+
import { requireNodeSqlite } from "../infra/node-sqlite.js";
56
import {
67
closeOpenClawStateDatabaseForTest,
78
runOpenClawStateWriteTransaction,
89
} from "../state/openclaw-state-db.js";
910
import type { PluginCandidate } from "./discovery.js";
11+
import { readPersistedInstalledPluginIndexInstallRecords } from "./installed-plugin-index-records.js";
1012
import {
1113
inspectPersistedInstalledPluginIndex,
1214
readPersistedInstalledPluginIndex,
@@ -228,6 +230,43 @@ describe("installed plugin index persistence", () => {
228230
expectPluginFields(persisted, "demo", { packageBuild: { bundledDist: false } });
229231
});
230232

233+
it("does not repair shared state schema while reading the index", async () => {
234+
const stateDir = makeTempDir();
235+
const filePath = resolveInstalledPluginIndexStorePath({ stateDir });
236+
await writePersistedInstalledPluginIndex(createIndex(), { stateDir });
237+
closeOpenClawStateDatabaseForTest();
238+
239+
const sqlite = requireNodeSqlite();
240+
const mutate = new sqlite.DatabaseSync(filePath);
241+
mutate.exec("DROP INDEX idx_operator_approvals_resolution_ref;");
242+
mutate.close();
243+
244+
const expectCanonicalIndexMissing = () => {
245+
const verify = new sqlite.DatabaseSync(filePath, { readOnly: true });
246+
try {
247+
expect(
248+
verify
249+
.prepare(
250+
"SELECT 1 FROM sqlite_schema WHERE type = 'index' AND name = 'idx_operator_approvals_resolution_ref'",
251+
)
252+
.get(),
253+
).toBeUndefined();
254+
} finally {
255+
verify.close();
256+
}
257+
};
258+
259+
await expect(readPersistedInstalledPluginIndex({ stateDir })).resolves.toMatchObject({
260+
version: 1,
261+
});
262+
expectCanonicalIndexMissing();
263+
264+
await expect(readPersistedInstalledPluginIndexInstallRecords({ stateDir })).resolves.toEqual(
265+
{},
266+
);
267+
expectCanonicalIndexMissing();
268+
});
269+
231270
it("preserves startup config paths across persisted index roundtrips", async () => {
232271
const stateDir = makeTempDir();
233272
const index = createIndex({

‎src/plugins/installed-plugin-index-store.ts‎

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,8 @@
22
import { existsSync, readFileSync } from "node:fs";
33
import { z } from "zod";
44
import { isBlockedObjectKey } from "../infra/prototype-keys.js";
5-
import {
6-
openOpenClawStateDatabase,
7-
runOpenClawStateWriteTransaction,
8-
} from "../state/openclaw-state-db.js";
5+
import { withOpenClawStateDatabaseReadOnly } from "../state/openclaw-state-db-readonly.js";
6+
import { runOpenClawStateWriteTransaction } from "../state/openclaw-state-db.js";
97
import { safeParseWithSchema } from "../utils/zod-parse.js";
108
import { resolveCompatibilityHostVersion } from "../version.js";
119
import { normalizePluginsConfig, resolveEffectiveEnableState } from "./config-state.js";
@@ -294,21 +292,20 @@ function readPersistedInstalledPluginIndexFromSqlite(
294292
return null;
295293
}
296294
try {
297-
const database = openOpenClawStateDatabase(
298-
resolveInstalledPluginIndexStateDatabaseOptions(options),
299-
);
300-
const row = database.db
301-
.prepare(
302-
`
303-
SELECT version, warning, host_contract_version, compat_registry_version,
304-
migration_version, policy_hash, generated_at_ms, refresh_reason,
305-
install_records_json, plugins_json, diagnostics_json
306-
FROM installed_plugin_index
307-
WHERE index_key = ?
308-
`,
309-
)
310-
.get(INSTALLED_PLUGIN_INDEX_SQLITE_KEY) as InstalledPluginIndexSqliteRow | undefined;
311-
return parseInstalledPluginIndexSqliteRow(row);
295+
return withOpenClawStateDatabaseReadOnly(({ db }) => {
296+
const row = db
297+
.prepare(
298+
`
299+
SELECT version, warning, host_contract_version, compat_registry_version,
300+
migration_version, policy_hash, generated_at_ms, refresh_reason,
301+
install_records_json, plugins_json, diagnostics_json
302+
FROM installed_plugin_index
303+
WHERE index_key = ?
304+
`,
305+
)
306+
.get(INSTALLED_PLUGIN_INDEX_SQLITE_KEY) as InstalledPluginIndexSqliteRow | undefined;
307+
return parseInstalledPluginIndexSqliteRow(row);
308+
}, resolveInstalledPluginIndexStateDatabaseOptions(options));
312309
} catch {
313310
return null;
314311
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import path from "node:path";
2+
import type { DatabaseSync } from "node:sqlite";
3+
import { clearNodeSqliteKyselyCacheForDatabase } from "../infra/kysely-sync.js";
4+
import { requireNodeSqlite } from "../infra/node-sqlite.js";
5+
import {
6+
createNewerSqliteSchemaVersionError,
7+
readSqliteUserVersion,
8+
} from "../infra/sqlite-user-version.js";
9+
import {
10+
OPENCLAW_SQLITE_BUSY_TIMEOUT_MS,
11+
OPENCLAW_STATE_SCHEMA_VERSION,
12+
type OpenClawStateDatabaseOptions,
13+
} from "./openclaw-state-db.js";
14+
import { resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths.js";
15+
16+
type OpenClawStateReadOnlyDatabase = {
17+
db: DatabaseSync;
18+
path: string;
19+
};
20+
21+
function assertSupportedSchemaVersion(db: DatabaseSync, pathname: string): void {
22+
const userVersion = readSqliteUserVersion(db);
23+
if (userVersion > OPENCLAW_STATE_SCHEMA_VERSION) {
24+
throw createNewerSqliteSchemaVersionError(
25+
"OpenClaw state database",
26+
pathname,
27+
userVersion,
28+
OPENCLAW_STATE_SCHEMA_VERSION,
29+
);
30+
}
31+
}
32+
33+
/**
34+
* Read shared state without joining the writable lifecycle.
35+
*
36+
* CLI metadata reads can overlap a live Gateway. Keep them off schema repair,
37+
* journal-mode setup, checkpoints, and permission mutation owned by writers.
38+
*/
39+
export function withOpenClawStateDatabaseReadOnly<T>(
40+
operation: (database: OpenClawStateReadOnlyDatabase) => T,
41+
options: OpenClawStateDatabaseOptions = {},
42+
): T {
43+
const pathname = path.resolve(
44+
options.path ?? resolveOpenClawStateSqlitePath(options.env ?? process.env),
45+
);
46+
const sqlite = requireNodeSqlite();
47+
const db = new sqlite.DatabaseSync(pathname, { readOnly: true });
48+
try {
49+
db.exec(`PRAGMA busy_timeout = ${OPENCLAW_SQLITE_BUSY_TIMEOUT_MS};`);
50+
assertSupportedSchemaVersion(db, pathname);
51+
return operation({ db, path: pathname });
52+
} finally {
53+
clearNodeSqliteKyselyCacheForDatabase(db);
54+
db.close();
55+
}
56+
}

0 commit comments

Comments
 (0)