Skip to content

Commit daa1b8d

Browse files
committed
fix(doctor): settle session entry rewrites
1 parent 40a8e30 commit daa1b8d

5 files changed

Lines changed: 95 additions & 27 deletions

‎src/commands/doctor-session-delivery-state.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ function insertSessionRow(
2828
"INSERT INTO session_nodes (session_key, current_session_id, entry_json, updated_at) VALUES (?, ?, ?, ?)",
2929
)
3030
.run(sessionKey, String(entry.sessionId), JSON.stringify(entry), Number(entry.updatedAt));
31+
database.db
32+
.prepare("UPDATE session_nodes SET entry_valid = 1 WHERE session_key = ?")
33+
.run(sessionKey);
3134
const legacyContext = entry.deliveryContext as Record<string, unknown> | undefined;
3235
database.db
3336
.prepare(
@@ -319,6 +322,10 @@ describe("doctor canonical session delivery state", () => {
319322
expect(readEntryJson(env, "agent:main:invalid")).toBe("null");
320323
expect(readEntryJson(env, "agent:main:invalid-object")).toBe(invalidObjectJson);
321324
expect(readEntryValidity(env, "agent:main:invalid-object")).toBe(0);
325+
closeOpenClawAgentDatabasesForTest();
326+
expect(() => listSessionEntries({ agentId: "main", env })).toThrow(
327+
/invalid persisted session row requires repair/u,
328+
);
322329
});
323330

324331
it("migrates a copied realistic store without touching the source or canonical row bytes", () => {
@@ -397,6 +404,8 @@ describe("doctor canonical session delivery state", () => {
397404
repaired: 3,
398405
scannedStores: 1,
399406
});
407+
closeOpenClawAgentDatabasesForTest();
408+
expect(listSessionEntries({ agentId: "main", env: copiedEnv })).toHaveLength(4);
400409
expect(repairCanonicalSessionDeliveryStates({ apply: true, cfg: {}, env: copiedEnv })).toEqual({
401410
found: 0,
402411
repaired: 0,

‎src/commands/doctor-session-delivery-state.ts‎

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ import {
1818
sessionDeliveryChannel,
1919
} from "../utils/delivery-context.shared.js";
2020
import { runDoctorAgentDatabaseOperation } from "./doctor-agent-database-operation.js";
21+
import {
22+
type DoctorSessionEntryRow,
23+
writeValidatedDoctorSessionEntryJson,
24+
} from "./doctor-session-entry-rewrite.js";
2125
import { resolveTargetSqlitePath } from "./doctor-session-sqlite-readers.js";
2226

2327
export type SessionDeliveryStateRepairReport = {
@@ -31,7 +35,7 @@ type DeliveryRewrite = {
3135
channel: string | null;
3236
currentSessionId: string;
3337
entryJson: string;
34-
sessionKey: string;
38+
row: DoctorSessionEntryRow;
3539
};
3640

3741
/** Scan or rewrite legacy delivery fields inside existing session row JSON. */
@@ -117,7 +121,7 @@ function collectDeliveryRewrites(database: DatabaseSync): DeliveryRewrite[] {
117121
channel: sessionDeliveryChannel(normalizedEntry) ?? null,
118122
currentSessionId: row.current_session_id,
119123
entryJson,
120-
sessionKey: row.session_key,
124+
row,
121125
},
122126
];
123127
});
@@ -127,22 +131,7 @@ function applyDeliveryRewrites(database: DatabaseSync): number {
127131
const db = getNodeSqliteKysely<OpenClawAgentKyselyDatabase>(database);
128132
const rewrites = collectDeliveryRewrites(database);
129133
for (const rewrite of rewrites) {
130-
executeSqliteQuerySync(
131-
database,
132-
db
133-
.updateTable("session_nodes")
134-
.set({ entry_json: rewrite.entryJson })
135-
.where("session_key", "=", rewrite.sessionKey),
136-
);
137-
// Updating entry_json resets the validity projection to pending. Settle the proven-valid
138-
// rewrite in a second statement so strict runtime readers can consume doctor's output.
139-
executeSqliteQuerySync(
140-
database,
141-
db
142-
.updateTable("session_nodes")
143-
.set({ entry_valid: 1 })
144-
.where("session_key", "=", rewrite.sessionKey),
145-
);
134+
writeValidatedDoctorSessionEntryJson(database, rewrite.row, rewrite.entryJson);
146135
executeSqliteQuerySync(
147136
database,
148137
db
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import type { DatabaseSync } from "node:sqlite";
2+
import { parseSqliteSessionEntryRecord } from "../config/sessions/session-entry-json.js";
3+
import { executeSqliteQuerySync, getNodeSqliteKysely } from "../infra/kysely-sync.js";
4+
import type { DB as OpenClawAgentKyselyDatabase } from "../state/openclaw-agent-db.generated.js";
5+
6+
export type DoctorSessionEntryRow = {
7+
current_session_id: string;
8+
entry_json: string;
9+
session_key: string;
10+
updated_at: number;
11+
};
12+
13+
/** Persist a doctor-proven entry rewrite and settle the schema-owned validity projection. */
14+
export function writeValidatedDoctorSessionEntryJson(
15+
database: DatabaseSync,
16+
row: DoctorSessionEntryRow,
17+
entryJson: string,
18+
): void {
19+
if (!parseSqliteSessionEntryRecord({ ...row, entry_json: entryJson })) {
20+
throw new Error(`Refusing invalid SQLite session entry rewrite for ${row.session_key}`);
21+
}
22+
const db = getNodeSqliteKysely<OpenClawAgentKyselyDatabase>(database);
23+
executeSqliteQuerySync(
24+
database,
25+
db
26+
.updateTable("session_nodes")
27+
.set({ entry_json: entryJson })
28+
.where("session_key", "=", row.session_key),
29+
);
30+
// The entry_json trigger marks every rewrite pending, including a value already validated
31+
// above. Settle it separately so the next strict reader does not reject doctor's output.
32+
executeSqliteQuerySync(
33+
database,
34+
db
35+
.updateTable("session_nodes")
36+
.set({ entry_valid: 1 })
37+
.where("session_key", "=", row.session_key),
38+
);
39+
}

‎src/commands/doctor-session-incognito-key-repair.test.ts‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import fs from "node:fs";
22
import { afterEach, describe, expect, it } from "vitest";
33
import { createTempDirTracker } from "../../test/helpers/temp-dir.js";
4+
import { listSessionEntries } from "../config/sessions/session-accessor.js";
45
import {
56
closeOpenClawAgentDatabasesForTest,
67
openOpenClawAgentDatabase,
@@ -38,6 +39,7 @@ describe("doctor reserved incognito session key repair", () => {
3839
try {
3940
const entryJson = JSON.stringify({
4041
sessionId: "session-old",
42+
updatedAt: 1,
4143
parentSessionKey: oldKey,
4244
spawnedBy: oldKey,
4345
completionOwnerSessionKey: oldKey,
@@ -81,10 +83,22 @@ describe("doctor reserved incognito session key repair", () => {
8183
"INSERT INTO session_nodes (session_key, current_session_id, entry_json, updated_at, parent_session_key, spawned_by) VALUES ('agent:work:dashboard:regular', 'session-work', ?, 1, ?, ?)",
8284
)
8385
.run(
84-
JSON.stringify({ sessionId: "session-work", completionOwnerSessionKey: oldKey }),
86+
JSON.stringify({
87+
sessionId: "session-work",
88+
updatedAt: 1,
89+
parentSessionKey: oldKey,
90+
spawnedBy: oldKey,
91+
completionOwnerSessionKey: oldKey,
92+
}),
8593
oldKey,
8694
oldKey,
8795
);
96+
database.db
97+
.prepare("UPDATE session_nodes SET entry_valid = 1 WHERE session_key = ?")
98+
.run(oldKey);
99+
secondaryDatabase.db
100+
.prepare("UPDATE session_nodes SET entry_valid = 1 WHERE session_key = ?")
101+
.run("agent:work:dashboard:regular");
88102
secondaryDatabase.db
89103
.prepare(
90104
"INSERT INTO session_windows (session_id, session_key, session_scope, created_at, updated_at, parent_session_key, spawned_by) VALUES ('session-work', 'agent:work:dashboard:regular', 'conversation', 1, 1, ?, ?)",
@@ -206,6 +220,26 @@ describe("doctor reserved incognito session key repair", () => {
206220
systemPromptReport: { sessionKey: newKey },
207221
pluginExtensions: { test: { label: oldKey } },
208222
});
223+
expect(
224+
database.db
225+
.prepare("SELECT entry_valid FROM session_nodes WHERE session_key = ?")
226+
.get(newKey),
227+
).toEqual({ entry_valid: 1 });
228+
expect(
229+
secondaryDatabase.db
230+
.prepare("SELECT entry_valid FROM session_nodes WHERE session_key = ?")
231+
.get("agent:work:dashboard:regular"),
232+
).toEqual({ entry_valid: 1 });
233+
closeOpenClawAgentDatabasesForTest();
234+
expect(listSessionEntries({ agentId: "main", env })).toMatchObject([
235+
{ sessionKey: newKey, entry: { sessionId: "session-old", updatedAt: 1 } },
236+
]);
237+
expect(listSessionEntries({ agentId: "work", env })).toMatchObject([
238+
{
239+
sessionKey: "agent:work:dashboard:regular",
240+
entry: { sessionId: "session-work", updatedAt: 1 },
241+
},
242+
]);
209243
expect(repairReservedIncognitoSessionKeys({ apply: true, cfg: {}, env })).toEqual({
210244
found: 0,
211245
repaired: 0,

‎src/commands/doctor-session-incognito-key-repair.ts‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
runOpenClawStateWriteTransaction,
1717
} from "../state/openclaw-state-db.js";
1818
import { runDoctorAgentDatabaseOperation } from "./doctor-agent-database-operation.js";
19+
import { writeValidatedDoctorSessionEntryJson } from "./doctor-session-entry-rewrite.js";
1920
import {
2021
collectSharedStateSessionKeys,
2122
deleteRepairJournal,
@@ -357,7 +358,9 @@ function rewriteSessionEntryJsonReferences(
357358
const db = getNodeSqliteKysely<OpenClawAgentKyselyDatabase>(database);
358359
const rows = executeSqliteQuerySync(
359360
database,
360-
db.selectFrom("session_nodes").select(["session_key", "entry_json"]),
361+
db
362+
.selectFrom("session_nodes")
363+
.select(["session_key", "current_session_id", "entry_json", "updated_at"]),
361364
).rows;
362365
for (const row of rows) {
363366
let parsed: unknown;
@@ -371,13 +374,7 @@ function rewriteSessionEntryJsonReferences(
371374
if (entryJson === row.entry_json) {
372375
continue;
373376
}
374-
executeSqliteQuerySync(
375-
database,
376-
db
377-
.updateTable("session_nodes")
378-
.set({ entry_json: entryJson })
379-
.where("session_key", "=", row.session_key),
380-
);
377+
writeValidatedDoctorSessionEntryJson(database, row, entryJson);
381378
}
382379
}
383380

0 commit comments

Comments
 (0)