Skip to content

Commit 0771787

Browse files
authored
fix(state): repair mis-stamped v17 agent databases (#122171)
* fix(state): repair mis-stamped v17 agent databases * refactor(state): keep lease repair helpers internal
1 parent 2d0c30f commit 0771787

3 files changed

Lines changed: 320 additions & 14 deletions

File tree

Lines changed: 274 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,274 @@
1+
import { afterEach, describe, expect, it } from "vitest";
2+
import { cleanupTempDirs, makeTempDir } from "../../test/helpers/temp-dir.js";
3+
import { openNodeSqliteDatabase } from "../infra/node-sqlite.js";
4+
import { migrateLegacyMediaPersistence } from "../infra/state-migrations.media-persistence.js";
5+
import { withOpenClawAgentDatabaseReadOnly } from "./openclaw-agent-db-readonly.js";
6+
import {
7+
closeOpenClawAgentDatabasesForTest,
8+
migrateOpenClawAgentDatabaseForMaintenance,
9+
OPENCLAW_AGENT_SCHEMA_VERSION,
10+
openOpenClawAgentDatabase,
11+
} from "./openclaw-agent-db.js";
12+
import { closeOpenClawStateDatabaseForTest } from "./openclaw-state-db.js";
13+
14+
const tempDirs: string[] = [];
15+
16+
function createCurrentAgentDatabase(): { databasePath: string; env: NodeJS.ProcessEnv } {
17+
const stateDir = makeTempDir(tempDirs, "agent-db-retired-lease-");
18+
const env = { OPENCLAW_STATE_DIR: stateDir };
19+
const databasePath = openOpenClawAgentDatabase({ agentId: "worker-1", env }).path;
20+
closeOpenClawAgentDatabasesForTest();
21+
closeOpenClawStateDatabaseForTest();
22+
return { databasePath, env };
23+
}
24+
25+
function installRetiredLeaseSchema(databasePath: string): void {
26+
const database = openNodeSqliteDatabase(databasePath);
27+
try {
28+
database.exec(`
29+
CREATE TABLE state_leases (
30+
scope TEXT NOT NULL,
31+
lease_key TEXT NOT NULL,
32+
owner TEXT NOT NULL,
33+
expires_at INTEGER,
34+
heartbeat_at INTEGER,
35+
payload_json TEXT,
36+
created_at INTEGER NOT NULL,
37+
updated_at INTEGER NOT NULL,
38+
PRIMARY KEY (scope, lease_key)
39+
) STRICT;
40+
CREATE INDEX idx_agent_state_leases_expiry
41+
ON state_leases(expires_at, scope, lease_key)
42+
WHERE expires_at IS NOT NULL;
43+
CREATE INDEX idx_agent_state_leases_owner
44+
ON state_leases(owner, updated_at DESC);
45+
INSERT INTO state_leases (
46+
scope, lease_key, owner, expires_at, heartbeat_at, payload_json, created_at, updated_at
47+
) VALUES ('retired', 'orphan', 'nobody', NULL, NULL, NULL, 1, 1);
48+
ANALYZE state_leases;
49+
`);
50+
} finally {
51+
database.close();
52+
}
53+
}
54+
55+
function readPrimarySchemaMetadata(databasePath: string): unknown {
56+
const database = openNodeSqliteDatabase(databasePath, { readOnly: true });
57+
try {
58+
return database.prepare("SELECT * FROM schema_meta WHERE meta_key = 'primary'").get();
59+
} finally {
60+
database.close();
61+
}
62+
}
63+
64+
afterEach(() => {
65+
closeOpenClawAgentDatabasesForTest();
66+
closeOpenClawStateDatabaseForTest();
67+
cleanupTempDirs(tempDirs);
68+
});
69+
70+
describe("retired agent state lease repair", () => {
71+
it("repairs a mis-stamped v17 database while preserving auth and ownership", () => {
72+
const { databasePath, env } = createCurrentAgentDatabase();
73+
installRetiredLeaseSchema(databasePath);
74+
const beforeMetadata = readPrimarySchemaMetadata(databasePath);
75+
const database = openNodeSqliteDatabase(databasePath);
76+
try {
77+
database
78+
.prepare(
79+
"INSERT INTO auth_profile_state (state_key, state_json, updated_at) VALUES (?, ?, ?)",
80+
)
81+
.run("last-good", '{"profile":"primary"}', 10);
82+
database
83+
.prepare(
84+
"INSERT INTO auth_profile_store (store_key, store_json, updated_at) VALUES (?, ?, ?)",
85+
)
86+
.run("primary", '{"profiles":{"primary":{"provider":"openai"}}}', 10);
87+
} finally {
88+
database.close();
89+
}
90+
91+
expect(migrateLegacyMediaPersistence({ env }).warnings).toEqual([]);
92+
expect(migrateLegacyMediaPersistence({ env }).warnings).toEqual([]);
93+
94+
const repaired = openNodeSqliteDatabase(databasePath, { readOnly: true });
95+
try {
96+
expect(repaired.prepare("PRAGMA user_version").get()).toEqual({
97+
user_version: OPENCLAW_AGENT_SCHEMA_VERSION,
98+
});
99+
expect(
100+
repaired.prepare("SELECT * FROM schema_meta WHERE meta_key = 'primary'").get(),
101+
).toEqual(beforeMetadata);
102+
expect(
103+
repaired
104+
.prepare("SELECT state_json FROM auth_profile_state WHERE state_key = 'last-good'")
105+
.get(),
106+
).toEqual({ state_json: '{"profile":"primary"}' });
107+
expect(
108+
repaired
109+
.prepare("SELECT store_json FROM auth_profile_store WHERE store_key = 'primary'")
110+
.get(),
111+
).toEqual({ store_json: '{"profiles":{"primary":{"provider":"openai"}}}' });
112+
expect(
113+
repaired
114+
.prepare(
115+
`SELECT type, name FROM sqlite_schema
116+
WHERE name IN (
117+
'state_leases',
118+
'idx_agent_state_leases_expiry',
119+
'idx_agent_state_leases_owner'
120+
)`,
121+
)
122+
.all(),
123+
).toEqual([]);
124+
expect(
125+
repaired.prepare("SELECT tbl, idx FROM sqlite_stat1 WHERE tbl = 'state_leases'").all(),
126+
).toEqual([]);
127+
expect(repaired.prepare("PRAGMA integrity_check").get()).toEqual({ integrity_check: "ok" });
128+
expect(repaired.prepare("PRAGMA foreign_key_check").all()).toEqual([]);
129+
} finally {
130+
repaired.close();
131+
}
132+
});
133+
134+
it("leaves a clean v17 database unchanged", () => {
135+
const { databasePath } = createCurrentAgentDatabase();
136+
const beforeMetadata = readPrimarySchemaMetadata(databasePath);
137+
const before = openNodeSqliteDatabase(databasePath, { readOnly: true });
138+
const beforeSchemaVersion = before.prepare("PRAGMA schema_version").get();
139+
before.close();
140+
141+
migrateOpenClawAgentDatabaseForMaintenance({
142+
agentId: "worker-1",
143+
pathname: databasePath,
144+
});
145+
146+
const after = openNodeSqliteDatabase(databasePath, { readOnly: true });
147+
try {
148+
expect(after.prepare("PRAGMA user_version").get()).toEqual({
149+
user_version: OPENCLAW_AGENT_SCHEMA_VERSION,
150+
});
151+
expect(after.prepare("SELECT * FROM schema_meta WHERE meta_key = 'primary'").get()).toEqual(
152+
beforeMetadata,
153+
);
154+
expect(after.prepare("PRAGMA schema_version").get()).toEqual(beforeSchemaVersion);
155+
expect(
156+
after.prepare("SELECT name FROM sqlite_schema WHERE name = 'state_leases'").get(),
157+
).toBeUndefined();
158+
} finally {
159+
after.close();
160+
}
161+
});
162+
163+
it("rejects a foreign state_leases structure without changing it", () => {
164+
const { databasePath } = createCurrentAgentDatabase();
165+
const beforeMetadata = readPrimarySchemaMetadata(databasePath);
166+
const database = openNodeSqliteDatabase(databasePath);
167+
try {
168+
database.exec(`
169+
CREATE TABLE state_leases (
170+
foreign_id TEXT NOT NULL PRIMARY KEY,
171+
foreign_payload TEXT NOT NULL
172+
) STRICT;
173+
INSERT INTO state_leases VALUES ('foreign', 'preserve-me');
174+
`);
175+
} finally {
176+
database.close();
177+
}
178+
179+
expect(() =>
180+
migrateOpenClawAgentDatabaseForMaintenance({
181+
agentId: "worker-1",
182+
pathname: databasePath,
183+
}),
184+
).toThrow(/state_leases.*noncanonical|column definitions differ for state_leases/iu);
185+
186+
const after = openNodeSqliteDatabase(databasePath, { readOnly: true });
187+
try {
188+
expect(after.prepare("SELECT * FROM state_leases").all()).toEqual([
189+
{ foreign_id: "foreign", foreign_payload: "preserve-me" },
190+
]);
191+
expect(after.prepare("SELECT * FROM schema_meta WHERE meta_key = 'primary'").get()).toEqual(
192+
beforeMetadata,
193+
);
194+
expect(after.prepare("PRAGMA user_version").get()).toEqual({
195+
user_version: OPENCLAW_AGENT_SCHEMA_VERSION,
196+
});
197+
} finally {
198+
after.close();
199+
}
200+
});
201+
202+
it("rolls back the lease drop when canonical validation fails", () => {
203+
const { databasePath } = createCurrentAgentDatabase();
204+
installRetiredLeaseSchema(databasePath);
205+
const beforeMetadata = readPrimarySchemaMetadata(databasePath);
206+
const database = openNodeSqliteDatabase(databasePath);
207+
try {
208+
database.exec(`
209+
DROP TABLE session_key_contract;
210+
CREATE VIEW session_key_contract AS SELECT 1 AS id, 'main' AS main_key, 0 AS updated_at;
211+
`);
212+
} finally {
213+
database.close();
214+
}
215+
216+
expect(() =>
217+
migrateOpenClawAgentDatabaseForMaintenance({
218+
agentId: "worker-1",
219+
pathname: databasePath,
220+
}),
221+
).toThrow(/session_key_contract/iu);
222+
223+
const after = openNodeSqliteDatabase(databasePath, { readOnly: true });
224+
try {
225+
expect(after.prepare("SELECT scope, lease_key FROM state_leases").all()).toEqual([
226+
{ lease_key: "orphan", scope: "retired" },
227+
]);
228+
expect(
229+
after
230+
.prepare(
231+
`SELECT name FROM sqlite_schema
232+
WHERE type = 'index' AND name LIKE 'idx_agent_state_leases_%'
233+
ORDER BY name`,
234+
)
235+
.all(),
236+
).toEqual([
237+
{ name: "idx_agent_state_leases_expiry" },
238+
{ name: "idx_agent_state_leases_owner" },
239+
]);
240+
expect(after.prepare("SELECT * FROM schema_meta WHERE meta_key = 'primary'").get()).toEqual(
241+
beforeMetadata,
242+
);
243+
expect(after.prepare("PRAGMA user_version").get()).toEqual({
244+
user_version: OPENCLAW_AGENT_SCHEMA_VERSION,
245+
});
246+
} finally {
247+
after.close();
248+
}
249+
});
250+
251+
it("repairs the same canonical drift through the writable schema owner", () => {
252+
const { databasePath, env } = createCurrentAgentDatabase();
253+
installRetiredLeaseSchema(databasePath);
254+
expect(
255+
withOpenClawAgentDatabaseReadOnly(
256+
({ db }) => db.prepare("SELECT COUNT(*) AS count FROM state_leases").get(),
257+
{ agentId: "worker-1", env },
258+
),
259+
).toEqual({ found: true, value: { count: 1 } });
260+
const beforeWritableOpen = openNodeSqliteDatabase(databasePath, { readOnly: true });
261+
expect(
262+
beforeWritableOpen
263+
.prepare("SELECT name FROM sqlite_schema WHERE name = 'state_leases'")
264+
.get(),
265+
).toEqual({ name: "state_leases" });
266+
beforeWritableOpen.close();
267+
268+
const repaired = openOpenClawAgentDatabase({ agentId: "worker-1", env });
269+
270+
expect(
271+
repaired.db.prepare("SELECT name FROM sqlite_schema WHERE name = 'state_leases'").get(),
272+
).toBeUndefined();
273+
});
274+
});

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,12 @@ const AGENT_SCHEMA_COMPATIBILITY = {
6565
],
6666
} satisfies SqliteSchemaCompatibility;
6767

68+
function hasRetiredAgentStateLeaseSchema(database: DatabaseSync): boolean {
69+
return Boolean(
70+
database.prepare("SELECT 1 FROM main.sqlite_schema WHERE name = 'state_leases'").get(),
71+
);
72+
}
73+
6874
export function assertOpenClawAgentSchemaContains(
6975
database: DatabaseSync,
7076
pathname: string,
@@ -90,6 +96,11 @@ export function assertOpenClawAgentCurrentRuntimeSchema(
9096
`OpenClaw agent database ${options.pathname} metadata schema version ${metadata.schemaVersion ?? "invalid"} does not match ${OPENCLAW_AGENT_SCHEMA_VERSION}; run openclaw doctor --fix before using it.`,
9197
);
9298
}
99+
if (hasRetiredAgentStateLeaseSchema(database)) {
100+
throw new Error(
101+
`OpenClaw agent database ${options.pathname} retains retired state_leases storage; run openclaw doctor --fix before using it.`,
102+
);
103+
}
93104
assertOpenClawAgentSchemaContains(database, options.pathname, OPENCLAW_AGENT_SCHEMA_SQL);
94105
}
95106

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

Lines changed: 35 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
verifyAndRepairCanonicalSqliteIndexes,
1515
} from "../infra/sqlite-index-schema.js";
1616
import { assertSqliteIntegrity } from "../infra/sqlite-integrity.js";
17+
import { assertSqliteSchemaContains } from "../infra/sqlite-schema-contract.js";
1718
import { migrateSqliteSchemaToStrictInTransaction } from "../infra/sqlite-strict.js";
1819
import { runSqliteImmediateTransactionSync } from "../infra/sqlite-transaction.js";
1920
import { readSqliteUserVersion } from "../infra/sqlite-user-version.js";
@@ -292,21 +293,37 @@ function migrateOpenClawAgentSchema(db: DatabaseSync): void {
292293
backfillTranscriptMutationWatermarks(db);
293294
}
294295

296+
const RETIRED_AGENT_STATE_LEASE_SCHEMA_SQL = `
297+
CREATE TABLE state_leases (
298+
scope TEXT NOT NULL,
299+
lease_key TEXT NOT NULL,
300+
owner TEXT NOT NULL,
301+
expires_at INTEGER,
302+
heartbeat_at INTEGER,
303+
payload_json TEXT,
304+
created_at INTEGER NOT NULL,
305+
updated_at INTEGER NOT NULL,
306+
PRIMARY KEY (scope, lease_key)
307+
) STRICT;
308+
`;
309+
310+
function hasRetiredAgentStateLeaseSchema(db: DatabaseSync): boolean {
311+
return Boolean(db.prepare("SELECT 1 FROM main.sqlite_schema WHERE name = 'state_leases'").get());
312+
}
313+
295314
function migrateRetiredAgentStateLeaseSchema(
296315
db: DatabaseSync,
297-
previousVersion: number,
316+
pathname: string,
298317
targetVersion: number,
299318
): void {
300-
if (previousVersion >= 17 || targetVersion < 17) {
319+
if (targetVersion < 17 || !hasRetiredAgentStateLeaseSchema(db)) {
301320
return;
302321
}
303322
// The 2026-08-10 tenant audit found no agent-DB lease writers after #121113;
304323
// #121615 removed the unreachable routing arm, so v17 retires this table.
305-
db.exec(`
306-
DROP INDEX IF EXISTS idx_agent_state_leases_owner;
307-
DROP INDEX IF EXISTS idx_agent_state_leases_expiry;
308-
DROP TABLE IF EXISTS state_leases;
309-
`);
324+
assertSqliteSchemaContains(db, pathname, RETIRED_AGENT_STATE_LEASE_SCHEMA_SQL);
325+
// DROP TABLE also removes the retired indexes and sqlite_stat rows atomically.
326+
db.exec("DROP TABLE state_leases;");
310327
}
311328

312329
/** Backfill one generation token without copying or rewriting transcript rows. */
@@ -555,9 +572,13 @@ export function assertAgentDatabaseIntegrityBeforeMutation(
555572
const hasPendingSessionContractMigration =
556573
userVersion === OPENCLAW_AGENT_SCHEMA_VERSION &&
557574
hasPendingSessionKeyContractSchemaMigration(database);
558-
const hasPendingAdditiveMigration =
559-
hasPendingMemoryMigration || hasPendingSessionContractMigration;
560-
if (userVersion === OPENCLAW_AGENT_SCHEMA_VERSION && !hasPendingAdditiveMigration) {
575+
const hasPendingRetiredLeaseMigration =
576+
userVersion === OPENCLAW_AGENT_SCHEMA_VERSION && hasRetiredAgentStateLeaseSchema(database);
577+
const hasPendingCurrentVersionMigration =
578+
hasPendingMemoryMigration ||
579+
hasPendingSessionContractMigration ||
580+
hasPendingRetiredLeaseMigration;
581+
if (userVersion === OPENCLAW_AGENT_SCHEMA_VERSION && !hasPendingCurrentVersionMigration) {
561582
verifyAndRepairCanonicalSqliteIndexes(database, pathname, OPENCLAW_AGENT_SCHEMA_SQL, {
562583
allowMissingColumns: true,
563584
validateAfterRepair: () =>
@@ -567,9 +588,9 @@ export function assertAgentDatabaseIntegrityBeforeMutation(
567588
// Every physical open proves the full file before schema mutation or exposure.
568589
assertSqliteIntegrity(database, pathname);
569590
}
570-
// Current-version additive surfaces are installed atomically by ensureAgentSchema below.
571-
// Validating them here would make the same-version repair path unreachable after an update.
572-
if (userVersion === OPENCLAW_AGENT_SCHEMA_VERSION && !hasPendingAdditiveMigration) {
591+
// Current-version convergence runs atomically in ensureAgentSchema below.
592+
// Validating here would make same-version repair unreachable after an update.
593+
if (userVersion === OPENCLAW_AGENT_SCHEMA_VERSION && !hasPendingCurrentVersionMigration) {
573594
assertOpenClawAgentCurrentRuntimeSchema(database, { agentId, pathname });
574595
}
575596
}
@@ -613,6 +634,7 @@ function ensureAgentSchema(
613634
`OpenClaw agent database ${pathname} uses schema version ${previousVersion}; expected at most ${targetVersion} for this migration.`,
614635
);
615636
}
637+
migrateRetiredAgentStateLeaseSchema(db, pathname, targetVersion);
616638
if (previousVersion === targetVersion) {
617639
ensureSessionEntryValidityProjection(db);
618640
ensureSessionKeyContractSchemaInTransaction(db);
@@ -640,7 +662,6 @@ function ensureAgentSchema(
640662
dropLegacyRuntimeJournalSchemas(db);
641663
migrateMemoryIndexSourcesIdentity(db);
642664
migrateOpenClawAgentSchema(db);
643-
migrateRetiredAgentStateLeaseSchema(db, previousVersion, targetVersion);
644665
migrateConversationDeliveryTargetColumn(db);
645666
backfillOpenClawAgentSchema(db, previousVersion);
646667
// Remove after 2026-10-01: drop the pre-v11 conversation backfill once schema 11 is the support floor.

0 commit comments

Comments
 (0)