Skip to content

Commit fe790ab

Browse files
VACIncvincentkoc
andauthored
fix(doctor): keep repaired session rows readable (#117207)
* fix: keep repaired session delivery rows readable * fix(doctor): settle session entry rewrites --------- Co-authored-by: VACInc <[email protected]> Co-authored-by: Vincent Koc <[email protected]>
1 parent ad3e36e commit fe790ab

5 files changed

Lines changed: 154 additions & 32 deletions

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

Lines changed: 60 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import fs from "node:fs";
22
import path from "node:path";
33
import { afterEach, describe, expect, it } from "vitest";
44
import { createTempDirTracker } from "../../test/helpers/temp-dir.js";
5+
import { listSessionEntries } from "../config/sessions/session-accessor.js";
56
import {
67
closeOpenClawAgentDatabasesForTest,
78
openOpenClawAgentDatabase,
@@ -27,6 +28,9 @@ function insertSessionRow(
2728
"INSERT INTO session_nodes (session_key, current_session_id, entry_json, updated_at) VALUES (?, ?, ?, ?)",
2829
)
2930
.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);
3034
const legacyContext = entry.deliveryContext as Record<string, unknown> | undefined;
3135
database.db
3236
.prepare(
@@ -58,6 +62,14 @@ function readEntryJson(env: NodeJS.ProcessEnv, sessionKey: string): string {
5862
return row.entry_json;
5963
}
6064

65+
function readEntryValidity(env: NodeJS.ProcessEnv, sessionKey: string): number {
66+
const database = openOpenClawAgentDatabase({ agentId: "main", env });
67+
const row = database.db
68+
.prepare("SELECT entry_valid FROM session_nodes WHERE session_key = ?")
69+
.get(sessionKey) as { entry_valid: number };
70+
return row.entry_valid;
71+
}
72+
6173
describe("doctor canonical session delivery state", () => {
6274
it("warns and skips an unmigrated agent database", () => {
6375
const stateDir = fs.realpathSync(tempDirs.make("openclaw-delivery-legacy-schema-"));
@@ -127,6 +139,37 @@ describe("doctor canonical session delivery state", () => {
127139
}
128140
});
129141

142+
it("keeps rewritten delivery rows valid for normal session reads", () => {
143+
const stateDir = fs.realpathSync(tempDirs.make("openclaw-delivery-validity-"));
144+
const env = { ...process.env, OPENCLAW_STATE_DIR: stateDir };
145+
const sessionKey = "agent:main:delivery-validity";
146+
insertSessionRow(env, sessionKey, {
147+
sessionId: "delivery-validity-session",
148+
updatedAt: 10,
149+
deliveryContext: { channel: "telegram", to: "recipient" },
150+
});
151+
const database = openOpenClawAgentDatabase({ agentId: "main", env });
152+
database.db
153+
.prepare("UPDATE session_nodes SET entry_valid = 1 WHERE session_key = ?")
154+
.run(sessionKey);
155+
156+
expect(repairCanonicalSessionDeliveryStates({ apply: true, cfg: {}, env })).toEqual({
157+
found: 1,
158+
repaired: 1,
159+
scannedStores: 1,
160+
});
161+
expect(readEntryValidity(env, sessionKey)).toBe(1);
162+
closeOpenClawAgentDatabasesForTest();
163+
expect(listSessionEntries({ agentId: "main", env })).toMatchObject([
164+
{ sessionKey, entry: { sessionId: "delivery-validity-session", updatedAt: 10 } },
165+
]);
166+
expect(repairCanonicalSessionDeliveryStates({ apply: true, cfg: {}, env })).toEqual({
167+
found: 0,
168+
repaired: 0,
169+
scannedStores: 1,
170+
});
171+
});
172+
130173
it("preserves shipped last-route precedence over stale explicit context", () => {
131174
const stateDir = fs.realpathSync(tempDirs.make("openclaw-delivery-precedence-"));
132175
const env = { ...process.env, OPENCLAW_STATE_DIR: stateDir };
@@ -261,18 +304,28 @@ describe("doctor canonical session delivery state", () => {
261304
updatedAt: 10,
262305
deliveryContext: { channel: "telegram", to: "-1001" },
263306
});
264-
openOpenClawAgentDatabase({ agentId: "main", env })
265-
.db.prepare(
266-
"INSERT INTO session_nodes (session_key, current_session_id, entry_json, updated_at) VALUES (?, ?, ?, ?)",
267-
)
268-
.run("agent:main:invalid", "invalid-session", "null", 20);
307+
const database = openOpenClawAgentDatabase({ agentId: "main", env });
308+
const insertInvalid = database.db.prepare(
309+
"INSERT INTO session_nodes (session_key, current_session_id, entry_json, updated_at) VALUES (?, ?, ?, ?)",
310+
);
311+
insertInvalid.run("agent:main:invalid", "invalid-session", "null", 20);
312+
const invalidObjectJson = JSON.stringify({
313+
deliveryContext: { channel: "telegram", to: "recipient" },
314+
});
315+
insertInvalid.run("agent:main:invalid-object", "invalid-object-session", invalidObjectJson, 30);
269316

270317
expect(repairCanonicalSessionDeliveryStates({ apply: true, cfg: {}, env })).toEqual({
271318
found: 1,
272319
repaired: 1,
273320
scannedStores: 1,
274321
});
275322
expect(readEntryJson(env, "agent:main:invalid")).toBe("null");
323+
expect(readEntryJson(env, "agent:main:invalid-object")).toBe(invalidObjectJson);
324+
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+
);
276329
});
277330

278331
it("migrates a copied realistic store without touching the source or canonical row bytes", () => {
@@ -351,6 +404,8 @@ describe("doctor canonical session delivery state", () => {
351404
repaired: 3,
352405
scannedStores: 1,
353406
});
407+
closeOpenClawAgentDatabasesForTest();
408+
expect(listSessionEntries({ agentId: "main", env: copiedEnv })).toHaveLength(4);
354409
expect(repairCanonicalSessionDeliveryStates({ apply: true, cfg: {}, env: copiedEnv })).toEqual({
355410
found: 0,
356411
repaired: 0,

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

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import fs from "node:fs";
22
import type { DatabaseSync } from "node:sqlite";
3+
import { parseSqliteSessionEntryRecord } from "../config/sessions/session-entry-json.js";
34
import { resolveAllAgentSessionStoreCandidateTargetsSync } from "../config/sessions/targets.js";
45
import type { SessionEntry } from "../config/sessions/types.js";
56
import type { OpenClawConfig } from "../config/types.openclaw.js";
@@ -17,6 +18,10 @@ import {
1718
sessionDeliveryChannel,
1819
} from "../utils/delivery-context.shared.js";
1920
import { runDoctorAgentDatabaseOperation } from "./doctor-agent-database-operation.js";
21+
import {
22+
type DoctorSessionEntryRow,
23+
writeValidatedDoctorSessionEntryJson,
24+
} from "./doctor-session-entry-rewrite.js";
2025
import { resolveTargetSqlitePath } from "./doctor-session-sqlite-readers.js";
2126

2227
export type SessionDeliveryStateRepairReport = {
@@ -30,7 +35,7 @@ type DeliveryRewrite = {
3035
channel: string | null;
3136
currentSessionId: string;
3237
entryJson: string;
33-
sessionKey: string;
38+
row: DoctorSessionEntryRow;
3439
};
3540

3641
/** Scan or rewrite legacy delivery fields inside existing session row JSON. */
@@ -95,30 +100,28 @@ function collectDeliveryRewrites(database: DatabaseSync): DeliveryRewrite[] {
95100
const db = getNodeSqliteKysely<OpenClawAgentKyselyDatabase>(database);
96101
const rows = executeSqliteQuerySync(
97102
database,
98-
db.selectFrom("session_nodes").select(["session_key", "current_session_id", "entry_json"]),
103+
db
104+
.selectFrom("session_nodes")
105+
.select(["session_key", "current_session_id", "entry_json", "updated_at"]),
99106
).rows;
100107
return rows.flatMap((row) => {
101-
let parsed: unknown;
102-
try {
103-
parsed = JSON.parse(row.entry_json);
104-
} catch {
105-
return [];
106-
}
107-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
108+
const parsed = parseSqliteSessionEntryRecord(row);
109+
if (!parsed) {
108110
return [];
109111
}
110112
const entry = parsed as SessionEntry;
111113
const normalizedEntry = normalizeLegacySessionEntryDelivery(entry);
112114
const entryJson = JSON.stringify(normalizedEntry);
113-
return entryJson === row.entry_json
115+
return entryJson === row.entry_json ||
116+
!parseSqliteSessionEntryRecord({ ...row, entry_json: entryJson })
114117
? []
115118
: [
116119
{
117120
accountId: deliveryContextFromSession(normalizedEntry)?.accountId ?? null,
118121
channel: sessionDeliveryChannel(normalizedEntry) ?? null,
119122
currentSessionId: row.current_session_id,
120123
entryJson,
121-
sessionKey: row.session_key,
124+
row,
122125
},
123126
];
124127
});
@@ -128,13 +131,7 @@ function applyDeliveryRewrites(database: DatabaseSync): number {
128131
const db = getNodeSqliteKysely<OpenClawAgentKyselyDatabase>(database);
129132
const rewrites = collectDeliveryRewrites(database);
130133
for (const rewrite of rewrites) {
131-
executeSqliteQuerySync(
132-
database,
133-
db
134-
.updateTable("session_nodes")
135-
.set({ entry_json: rewrite.entryJson })
136-
.where("session_key", "=", rewrite.sessionKey),
137-
);
134+
writeValidatedDoctorSessionEntryJson(database, rewrite.row, rewrite.entryJson);
138135
executeSqliteQuerySync(
139136
database,
140137
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)