Skip to content

Commit d83511b

Browse files
committed
fix(sessions): guard malformed maintenance rows
1 parent 093fb75 commit d83511b

4 files changed

Lines changed: 89 additions & 49 deletions

File tree

‎src/config/sessions/session-accessor.conformance.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1323,6 +1323,33 @@ describe("sqlite session normalization", () => {
13231323
).toEqual({ entry_valid: 0 });
13241324
});
13251325

1326+
it("writes a valid session beside an unrelated malformed legacy row", async () => {
1327+
const env = { ...process.env, OPENCLAW_STATE_DIR: paths.stateDir };
1328+
const database = openOpenClawAgentDatabase({ agentId: "main", env, path: paths.sqlitePath });
1329+
database.db
1330+
.prepare(
1331+
"INSERT INTO session_nodes (session_key, current_session_id, entry_json, entry_valid, updated_at) VALUES (?, ?, ?, -1, ?)",
1332+
)
1333+
.run("agent:main:malformed", "malformed-session", "{ malformed", 0);
1334+
1335+
await expect(
1336+
replaceSessionEntry(
1337+
{
1338+
agentId: "main",
1339+
env,
1340+
sessionKey: "agent:main:valid",
1341+
storePath: paths.sqlitePath,
1342+
},
1343+
{ sessionId: "valid-session", updatedAt: Date.now() },
1344+
),
1345+
).resolves.toMatchObject({ sessionId: "valid-session" });
1346+
expect(
1347+
database.db
1348+
.prepare("SELECT entry_json FROM session_nodes WHERE session_key = ?")
1349+
.get("agent:main:malformed"),
1350+
).toEqual({ entry_json: "{ malformed" });
1351+
});
1352+
13261353
it("exposes same-key rollover lineage when a killed session is replaced", async () => {
13271354
const env = { ...process.env, OPENCLAW_STATE_DIR: paths.stateDir };
13281355
const sessionKey = "agent:main:telegram:group:-1003774691294:topic:29020";

‎src/config/sessions/session-accessor.sqlite-maintenance.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,12 @@ function hasStaleSqliteSessionEntryCandidate(
7979
.select(["entry_json", "session_key"])
8080
.where("updated_at", "<", cutoffMs)
8181
.where(
82-
/* kysely-allow-raw: archivedAt lives inside the canonical JSON entry, not a SQL column. */
83-
sql<boolean>`json_extract(entry_json, '$.archivedAt') IS NULL`,
82+
/* kysely-allow-raw: archivedAt lives inside the canonical JSON entry, not a SQL column.
83+
* The CASE guard keeps malformed legacy bytes from aborting unrelated session writes. */
84+
sql<boolean>`CASE
85+
WHEN json_valid(entry_json) THEN json_extract(entry_json, '$.archivedAt') IS NULL
86+
ELSE 0
87+
END`,
8488
)
8589
.orderBy("updated_at", "asc"),
8690
).rows;

‎src/config/sessions/store-maintenance-total-cap.test.ts‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { describe, expect, it } from "vitest";
1+
import { describe, expect, it, vi } from "vitest";
2+
import { applyFileBackedSessionStoreMaintenance } from "./store-maintenance-operations.js";
23
import { capEntryCount, getActiveSessionMaintenanceWarning } from "./store-maintenance.js";
34
import type { SessionEntry } from "./types.js";
45

@@ -12,6 +13,14 @@ function makeStore(entries: Array<[string, SessionEntry]>): Record<string, Sessi
1213
return Object.fromEntries(entries);
1314
}
1415

16+
function createMaintenanceArtifacts() {
17+
return {
18+
archiveRemovedSessionTranscripts: async () => new Set<string>(),
19+
removeRemovedSessionTrajectoryArtifacts: async () => {},
20+
cleanupArchivedSessionTranscripts: async () => {},
21+
};
22+
}
23+
1524
describe("session maintenance total entry cap", () => {
1625
it("counts archived sessions toward the cap without evicting them", () => {
1726
const now = Date.now();
@@ -77,4 +86,50 @@ describe("session maintenance total entry cap", () => {
7786
}),
7887
).toMatchObject({ wouldCap: true, wouldPrune: false });
7988
});
89+
90+
it("uses enforcement preservation when predicting active-session eviction", async () => {
91+
const now = Date.now();
92+
const storePath = "/tmp/openclaw-sessions/warn-enforce-parity.json";
93+
const makePressureStore = () =>
94+
makeStore([
95+
["archived", { ...makeEntry(now - 2), archivedAt: now }],
96+
["active", makeEntry(now - 1)],
97+
["recent", makeEntry(now)],
98+
]);
99+
const maintenanceConfig = {
100+
mode: "warn" as const,
101+
pruneAfterMs: 30 * DAY_MS,
102+
maxEntries: 2,
103+
modelRunPruneAfterMs: DAY_MS,
104+
resetArchiveRetentionMs: null,
105+
maxDiskBytes: null,
106+
highWaterBytes: null,
107+
};
108+
const onWarn = vi.fn();
109+
110+
await applyFileBackedSessionStoreMaintenance({
111+
storePath,
112+
store: makePressureStore(),
113+
activeSessionKey: "active",
114+
maintenanceConfig,
115+
onWarn,
116+
log: { warn: () => {}, info: () => {} },
117+
artifacts: createMaintenanceArtifacts(),
118+
});
119+
120+
const enforcedStore = makePressureStore();
121+
await applyFileBackedSessionStoreMaintenance({
122+
storePath,
123+
store: enforcedStore,
124+
activeSessionKey: "active",
125+
maintenanceConfig: { ...maintenanceConfig, mode: "enforce" },
126+
log: { warn: () => {}, info: () => {} },
127+
artifacts: createMaintenanceArtifacts(),
128+
});
129+
130+
expect(onWarn).not.toHaveBeenCalled();
131+
expect(enforcedStore).toHaveProperty("archived");
132+
expect(enforcedStore).toHaveProperty("active");
133+
expect(enforcedStore.recent).toBeUndefined();
134+
});
80135
});

‎src/config/sessions/store.pruning.test.ts‎

Lines changed: 0 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -417,52 +417,6 @@ describe("applyFileBackedSessionStoreMaintenance", () => {
417417
expect(store["dashboard-2"]).toBeUndefined();
418418
});
419419

420-
it("uses enforcement preservation when predicting active-session eviction", async () => {
421-
const now = Date.now();
422-
const storePath = "/tmp/openclaw-sessions/warn-enforce-parity.json";
423-
const makePressureStore = () =>
424-
makeStore([
425-
["archived", { ...makeEntry(now - 2), archivedAt: now }],
426-
["active", makeEntry(now - 1)],
427-
["recent", makeEntry(now)],
428-
]);
429-
const maintenanceConfig = {
430-
mode: "warn" as const,
431-
pruneAfterMs: 30 * DAY_MS,
432-
maxEntries: 2,
433-
modelRunPruneAfterMs: DAY_MS,
434-
resetArchiveRetentionMs: null,
435-
maxDiskBytes: null,
436-
highWaterBytes: null,
437-
};
438-
const onWarn = vi.fn();
439-
440-
await applyFileBackedSessionStoreMaintenance({
441-
storePath,
442-
store: makePressureStore(),
443-
activeSessionKey: "active",
444-
maintenanceConfig,
445-
onWarn,
446-
log: { warn: () => {}, info: () => {} },
447-
artifacts: createMaintenanceArtifacts(),
448-
});
449-
450-
const enforcedStore = makePressureStore();
451-
await applyFileBackedSessionStoreMaintenance({
452-
storePath,
453-
store: enforcedStore,
454-
activeSessionKey: "active",
455-
maintenanceConfig: { ...maintenanceConfig, mode: "enforce" },
456-
log: { warn: () => {}, info: () => {} },
457-
artifacts: createMaintenanceArtifacts(),
458-
});
459-
460-
expect(onWarn).not.toHaveBeenCalled();
461-
expect(enforcedStore).toHaveProperty("archived");
462-
expect(enforcedStore).toHaveProperty("active");
463-
expect(enforcedStore.recent).toBeUndefined();
464-
});
465-
466420
it.each([
467421
{
468422
name: "preserves every active admission instead of only the writer session",

0 commit comments

Comments
 (0)