Skip to content

Commit 592253f

Browse files
EthDingobviyus
andauthored
fix(state): let doctor repair legacy v17 agent databases (#134208)
Fixes #134163. Repair the v17 additive session schema inside the canonical-index savepoint before strict validation. Preserve rollback for unrelated schema drift and cover the distributed Doctor path. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 64d5fab commit 592253f

3 files changed

Lines changed: 194 additions & 7 deletions

File tree

‎src/commands/doctor-config-preflight.process.test.ts‎

Lines changed: 97 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,10 @@ import { resolveGatewayLockDir } from "../config/paths.js";
1212
import type { OpenClawConfig } from "../config/types.openclaw.js";
1313
import { hasActiveStartupMigrationLease } from "../infra/startup-migration-checkpoint.js";
1414
import { getFileLockProcessStartTime } from "../shared/pid-alive.js";
15-
import { ensureOpenClawAgentDatabaseSchema } from "../state/openclaw-agent-db.js";
15+
import {
16+
ensureOpenClawAgentDatabaseSchema,
17+
OPENCLAW_AGENT_SCHEMA_VERSION,
18+
} from "../state/openclaw-agent-db.js";
1619

1720
const STARTUP_REFUSAL =
1821
"OpenClaw startup migrations did not complete cleanly; refusing to report the gateway ready.";
@@ -160,7 +163,100 @@ function seedOwnerlessSchemaOnlyAgentDatabase(stateDir: string): string {
160163
return databasePath;
161164
}
162165

166+
function seedV17AdditiveRepairDatabase(stateDir: string): string {
167+
const databasePath = path.join(stateDir, "agents", "main", "agent", "openclaw-agent.sqlite");
168+
fs.mkdirSync(path.dirname(databasePath), { recursive: true });
169+
const database = new DatabaseSync(databasePath);
170+
try {
171+
ensureOpenClawAgentDatabaseSchema(database, {
172+
agentId: "main",
173+
env: { ...process.env, OPENCLAW_STATE_DIR: stateDir },
174+
path: databasePath,
175+
register: false,
176+
});
177+
database.exec(`
178+
DROP TABLE session_participants;
179+
DROP TRIGGER session_conversations_route_context_invalidate_after_update;
180+
ALTER TABLE session_conversations DROP COLUMN route_context_json;
181+
DROP INDEX idx_agent_transcript_event_identity_sequence;
182+
PRAGMA user_version = 17;
183+
UPDATE schema_meta SET schema_version = 17;
184+
`);
185+
} finally {
186+
database.close();
187+
}
188+
return databasePath;
189+
}
190+
163191
describe("doctor invalid config process exit", () => {
192+
it("repairs the v17 additive schema through doctor --fix", () => {
193+
const root = fs.realpathSync(tempDirs.make("openclaw-doctor-v17-additive-"));
194+
const stateDir = path.join(root, "state");
195+
const configPath = path.join(stateDir, "openclaw.json");
196+
fs.mkdirSync(path.join(stateDir, "agents", "main", "sessions"), { recursive: true });
197+
fs.writeFileSync(configPath, "{}\n");
198+
const databasePath = seedV17AdditiveRepairDatabase(stateDir);
199+
const runtimeRoot = createSourceRuntime(root);
200+
const env: NodeJS.ProcessEnv = {
201+
...process.env,
202+
OPENCLAW_CONFIG_PATH: configPath,
203+
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
204+
OPENCLAW_STATE_DIR: stateDir,
205+
OPENCLAW_TEST_FAST: "1",
206+
NO_COLOR: "1",
207+
};
208+
const args = [
209+
path.join(runtimeRoot, "src", "entry.ts"),
210+
"doctor",
211+
"--fix",
212+
"--non-interactive",
213+
"--yes",
214+
"--no-workspace-suggestions",
215+
];
216+
217+
const first = runSourceRuntime(runtimeRoot, env, args, 60_000);
218+
expect(first.error, first.stderr).toBeUndefined();
219+
expect(first.status, first.stderr).toBe(0);
220+
expect(`${first.stdout}\n${first.stderr}`).toContain("v17 -> v19");
221+
222+
const repaired = new DatabaseSync(databasePath, { readOnly: true });
223+
try {
224+
expect(repaired.prepare("PRAGMA user_version").get()?.user_version).toBe(
225+
OPENCLAW_AGENT_SCHEMA_VERSION,
226+
);
227+
expect(
228+
repaired
229+
.prepare(
230+
"SELECT name FROM pragma_table_info('session_conversations') WHERE name = 'route_context_json'",
231+
)
232+
.get()?.name,
233+
).toBe("route_context_json");
234+
expect(
235+
repaired
236+
.prepare(
237+
"SELECT name FROM sqlite_schema WHERE type = 'trigger' AND name = 'session_conversations_route_context_invalidate_after_update'",
238+
)
239+
.get()?.name,
240+
).toBe("session_conversations_route_context_invalidate_after_update");
241+
expect(
242+
repaired
243+
.prepare(
244+
"SELECT name FROM sqlite_schema WHERE type = 'index' AND name = 'idx_agent_transcript_event_identity_sequence'",
245+
)
246+
.get()?.name,
247+
).toBe("idx_agent_transcript_event_identity_sequence");
248+
} finally {
249+
repaired.close();
250+
}
251+
252+
const second = runSourceRuntime(runtimeRoot, env, args, 60_000);
253+
expect(second.error, second.stderr).toBeUndefined();
254+
expect(second.status, second.stderr).toBe(0);
255+
expect(`${second.stdout}\n${second.stderr}`).not.toMatch(
256+
/Skipped agent database migration|Upgraded agent database schema/u,
257+
);
258+
});
259+
164260
it("keeps Doctor UI checks inside the source runtime fixture", () => {
165261
const root = fs.realpathSync(tempDirs.make("openclaw-doctor-runtime-owner-"));
166262
const runtimeRoot = createSourceRuntime(root);

‎src/infra/state-migrations.media-persistence.additive-schema.test.ts‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,31 @@ import { migrateLegacyMediaPersistence } from "./state-migrations.media-persiste
1111

1212
const tempDirs: string[] = [];
1313

14+
function createV17AdditiveFixture(options: { schemaDrift?: "missing-cache-table" } = {}) {
15+
const stateDir = makeTempDir(tempDirs, "media-persistence-v17-additive-");
16+
const env = { OPENCLAW_STATE_DIR: stateDir };
17+
const opened = openOpenClawAgentDatabase({ agentId: "main", env });
18+
const databasePath = opened.path;
19+
closeOpenClawAgentDatabasesForTest();
20+
closeOpenClawStateDatabaseForTest();
21+
22+
const { DatabaseSync } = requireNodeSqlite();
23+
const database = new DatabaseSync(databasePath);
24+
database.exec(`
25+
DROP TABLE session_participants;
26+
DROP TRIGGER session_conversations_route_context_invalidate_after_update;
27+
ALTER TABLE session_conversations DROP COLUMN route_context_json;
28+
DROP INDEX idx_agent_transcript_event_identity_sequence;
29+
PRAGMA user_version = 17;
30+
UPDATE schema_meta SET schema_version = 17;
31+
`);
32+
if (options.schemaDrift === "missing-cache-table") {
33+
database.exec("DROP TABLE cache_entries;");
34+
}
35+
database.close();
36+
return { databasePath, env };
37+
}
38+
1439
describe("legacy media persistence additive schema repair", () => {
1540
afterEach(() => {
1641
closeOpenClawAgentDatabasesForTest();
@@ -68,4 +93,70 @@ describe("legacy media persistence additive schema repair", () => {
6893
repaired.close();
6994
}
7095
});
96+
97+
it("repairs v17 additive session schema before canonical index validation", async () => {
98+
const { databasePath, env } = createV17AdditiveFixture();
99+
const { DatabaseSync } = requireNodeSqlite();
100+
const result = await migrateLegacyMediaPersistence({ env });
101+
expect(result.warnings).toEqual([]);
102+
const repaired = new DatabaseSync(databasePath, { readOnly: true });
103+
try {
104+
expect(repaired.prepare("PRAGMA user_version").get()).toEqual({
105+
user_version: OPENCLAW_AGENT_SCHEMA_VERSION,
106+
});
107+
expect(
108+
repaired
109+
.prepare(
110+
"SELECT name FROM pragma_table_info('session_conversations') WHERE name = 'route_context_json'",
111+
)
112+
.get(),
113+
).toEqual({ name: "route_context_json" });
114+
expect(
115+
repaired
116+
.prepare(
117+
"SELECT name FROM sqlite_schema WHERE type = 'trigger' AND name = 'session_conversations_route_context_invalidate_after_update'",
118+
)
119+
.get(),
120+
).toEqual({ name: "session_conversations_route_context_invalidate_after_update" });
121+
expect(
122+
repaired
123+
.prepare(
124+
"SELECT name FROM sqlite_schema WHERE type = 'index' AND name = 'idx_agent_transcript_event_identity_sequence'",
125+
)
126+
.get(),
127+
).toEqual({ name: "idx_agent_transcript_event_identity_sequence" });
128+
} finally {
129+
repaired.close();
130+
}
131+
});
132+
133+
it("keeps non-additive v17 schema drift rejected during index repair", async () => {
134+
const { databasePath, env } = createV17AdditiveFixture({
135+
schemaDrift: "missing-cache-table",
136+
});
137+
const { DatabaseSync } = requireNodeSqlite();
138+
const result = await migrateLegacyMediaPersistence({ env });
139+
expect(result.warnings).toHaveLength(1);
140+
expect(result.warnings[0]).toMatch(/missing table cache_entries/);
141+
const rejected = new DatabaseSync(databasePath, { readOnly: true });
142+
try {
143+
expect(rejected.prepare("PRAGMA user_version").get()).toEqual({ user_version: 17 });
144+
expect(
145+
rejected
146+
.prepare(
147+
"SELECT name FROM pragma_table_info('session_conversations') WHERE name = 'route_context_json'",
148+
)
149+
.get(),
150+
).toBeUndefined();
151+
expect(
152+
rejected
153+
.prepare(
154+
"SELECT name FROM sqlite_schema WHERE type = 'index' AND name = 'idx_agent_transcript_event_identity_sequence'",
155+
)
156+
.get(),
157+
).toBeUndefined();
158+
} finally {
159+
rejected.close();
160+
}
161+
});
71162
});

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

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -536,13 +536,11 @@ export function assertAgentDatabaseIntegrityBeforeMutation(
536536
validateAfterRepair: () =>
537537
assertOpenClawAgentCurrentRuntimeSchema(database, { agentId, pathname }),
538538
});
539+
assertOpenClawAgentCurrentRuntimeSchema(database, { agentId, pathname });
539540
} else {
540541
// Every physical open proves the full file before schema mutation or exposure.
541542
assertSqliteIntegrity(database, pathname);
542543
}
543-
if (userVersion === OPENCLAW_AGENT_SCHEMA_VERSION && !hasPendingCurrentVersionMigration) {
544-
assertOpenClawAgentCurrentRuntimeSchema(database, { agentId, pathname });
545-
}
546544
return hasPendingCurrentVersionMigration;
547545
}
548546

@@ -714,15 +712,17 @@ export function ensureOpenClawAgentDatabaseSchema(
714712
if (readSqliteUserVersion(db) === AGENT_MEDIA_SCHEMA_VERSION) {
715713
maintenanceAuthority.assertAgentDatabaseMaintenanceAuthority();
716714
const legacySql = withLegacySessionParticipantsSchema(OPENCLAW_AGENT_SCHEMA_SQL);
717-
// Keep canonical index recovery reachable before rebuilding the v17 identity table.
718715
verifyAndRepairCanonicalSqliteIndexes(db, pathname, legacySql, {
719716
allowMissingColumns: true,
720-
validateAfterRepair: () =>
717+
validateAfterRepair: () => {
718+
// Share the savepoint so schema drift rolls back additive and index repairs together.
719+
ensureSessionAdditiveColumns(db);
721720
assertAgentSchemaVersion(
722721
db,
723722
{ agentId, pathname, version: AGENT_MEDIA_SCHEMA_VERSION },
724723
legacySql,
725-
),
724+
);
725+
},
726726
});
727727
}
728728
assertAgentDatabaseIntegrityBeforeMutation(db, agentId, pathname);

0 commit comments

Comments
 (0)