Skip to content

Commit cf2af03

Browse files
authored
fix(sqlite): validate agent state before schema setup (#105179)
1 parent f84b6f6 commit cf2af03

2 files changed

Lines changed: 109 additions & 0 deletions

File tree

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

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
closeOpenClawAgentDatabaseByPath,
1919
closeOpenClawAgentDatabasesForTest,
2020
disposeOpenClawAgentDatabaseByPath,
21+
ensureOpenClawAgentDatabaseSchema,
2122
inspectOpenClawAgentDatabaseOwner,
2223
listOpenClawRegisteredAgentDatabases,
2324
OPENCLAW_AGENT_SCHEMA_VERSION,
@@ -156,6 +157,34 @@ function seedVersion1MemoryAgentDatabase(
156157
}
157158
}
158159

160+
function createUnsafeIndexDrift(databasePath: string): void {
161+
const { DatabaseSync } = requireNodeSqlite();
162+
const database = new DatabaseSync(databasePath);
163+
try {
164+
database.exec(`
165+
CREATE TABLE unsafe_index_records (
166+
id INTEGER PRIMARY KEY,
167+
indexed_value TEXT NOT NULL,
168+
alternate_value TEXT NOT NULL
169+
);
170+
CREATE INDEX unsafe_index_records_value ON unsafe_index_records(indexed_value);
171+
INSERT INTO unsafe_index_records (indexed_value, alternate_value)
172+
VALUES ('alpha', 'zeta'), ('beta', 'eta'), ('gamma', 'theta');
173+
`);
174+
database.enableDefensive?.(false);
175+
database.exec("PRAGMA writable_schema = ON;");
176+
database
177+
.prepare(
178+
"UPDATE sqlite_schema SET sql = 'CREATE INDEX unsafe_index_records_value ON unsafe_index_records(alternate_value)' WHERE name = 'unsafe_index_records_value'",
179+
)
180+
.run();
181+
const schemaVersion = readSqliteNumberPragma(database, "schema_version");
182+
database.exec(`PRAGMA writable_schema = OFF; PRAGMA schema_version = ${schemaVersion + 1};`);
183+
} finally {
184+
database.close();
185+
}
186+
}
187+
159188
type AgentSchemaOpenerResult = { agentId: string; ok: boolean; error?: string };
160189

161190
function launchAgentSchemaOpener(params: {
@@ -1354,6 +1383,73 @@ describe("openclaw agent database", () => {
13541383
"size",
13551384
]);
13561385
});
1386+
1387+
it("rejects stale secondary indexes before writable initialization", () => {
1388+
const stateDir = createTempStateDir();
1389+
const env = { OPENCLAW_STATE_DIR: stateDir };
1390+
const created = openOpenClawAgentDatabase({ agentId: "worker-1", env });
1391+
const databasePath = created.path;
1392+
closeOpenClawAgentDatabasesForTest();
1393+
closeOpenClawStateDatabaseForTest();
1394+
createUnsafeIndexDrift(databasePath);
1395+
1396+
const { DatabaseSync } = requireNodeSqlite();
1397+
const before = new DatabaseSync(databasePath, { readOnly: true });
1398+
let metadataBefore: unknown;
1399+
try {
1400+
expect(before.prepare("PRAGMA quick_check").get()).toEqual({ quick_check: "ok" });
1401+
expect(before.prepare("PRAGMA integrity_check").all()).toEqual(
1402+
expect.arrayContaining([
1403+
expect.objectContaining({
1404+
integrity_check: expect.stringMatching(/missing from index unsafe_index_records_value/),
1405+
}),
1406+
]),
1407+
);
1408+
metadataBefore = before
1409+
.prepare(
1410+
"SELECT schema_version, updated_at FROM schema_meta WHERE meta_key = 'primary' LIMIT 1",
1411+
)
1412+
.get();
1413+
} finally {
1414+
before.close();
1415+
}
1416+
1417+
expect(() => openOpenClawAgentDatabase({ agentId: "worker-1", env })).toThrow(
1418+
/integrity_check failed.*missing from index unsafe_index_records_value/iu,
1419+
);
1420+
const independentlyManaged = new DatabaseSync(databasePath);
1421+
try {
1422+
expect(() =>
1423+
ensureOpenClawAgentDatabaseSchema(independentlyManaged, {
1424+
agentId: "worker-1",
1425+
env,
1426+
}),
1427+
).toThrow(/integrity_check failed.*missing from index unsafe_index_records_value/iu);
1428+
} finally {
1429+
independentlyManaged.close();
1430+
}
1431+
1432+
const after = new DatabaseSync(databasePath, { readOnly: true });
1433+
try {
1434+
expect(
1435+
after
1436+
.prepare(
1437+
"SELECT schema_version, updated_at FROM schema_meta WHERE meta_key = 'primary' LIMIT 1",
1438+
)
1439+
.get(),
1440+
).toEqual(metadataBefore);
1441+
expect(after.prepare("PRAGMA integrity_check").all()).toEqual(
1442+
expect.arrayContaining([
1443+
expect.objectContaining({
1444+
integrity_check: expect.stringMatching(/missing from index unsafe_index_records_value/),
1445+
}),
1446+
]),
1447+
);
1448+
} finally {
1449+
after.close();
1450+
}
1451+
});
1452+
13571453
it("refuses to open newer per-agent schema versions", () => {
13581454
const stateDir = createTempStateDir();
13591455
const databasePath = path.join(

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
} from "../infra/kysely-sync.js";
1111
import { requireNodeSqlite } from "../infra/node-sqlite.js";
1212
import { resolveSqliteDatabaseFilePaths } from "../infra/sqlite-files.js";
13+
import { assertSqliteIntegrity } from "../infra/sqlite-integrity.js";
1314
import {
1415
runSqliteImmediateTransactionSync,
1516
type SqliteTransactionOptions,
@@ -608,6 +609,7 @@ export function ensureOpenClawAgentDatabaseSchema(
608609
const databaseOptions = { ...options, agentId };
609610
const pathname = resolveOpenClawAgentSqlitePath(databaseOptions);
610611
ensureOpenClawAgentDatabasePermissions(pathname, databaseOptions);
612+
assertAgentDatabaseIntegrityBeforeMutation(db, pathname);
611613
configureSqlitePreSchemaPragmas(db, {
612614
busyTimeoutMs: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS,
613615
});
@@ -803,6 +805,16 @@ export function inspectOpenClawAgentDatabaseOwner(
803805
}
804806
}
805807

808+
function assertAgentDatabaseIntegrityBeforeMutation(
809+
database: DatabaseSync,
810+
pathname: string,
811+
): void {
812+
database.exec(`PRAGMA busy_timeout = ${OPENCLAW_SQLITE_BUSY_TIMEOUT_MS};`);
813+
// Writable open permits interrupted journal recovery. Schema and connection
814+
// setup must wait until full table/index consistency is proven afterward.
815+
assertSqliteIntegrity(database, pathname);
816+
}
817+
806818
/** Open or return a cached per-agent database after schema and owner validation. */
807819
export function openOpenClawAgentDatabase(
808820
options: OpenClawAgentDatabaseOptions,
@@ -833,6 +845,7 @@ export function openOpenClawAgentDatabase(
833845
const walMaintenance = (() => {
834846
let maintenance: SqliteWalMaintenance | undefined;
835847
try {
848+
assertAgentDatabaseIntegrityBeforeMutation(db, pathname);
836849
configureSqlitePreSchemaPragmas(db, {
837850
busyTimeoutMs: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS,
838851
});

0 commit comments

Comments
 (0)