Skip to content

Commit 6a461c3

Browse files
committed
fix(gateway): preserve oversized history responsiveness
1 parent a9d3056 commit 6a461c3

5 files changed

Lines changed: 246 additions & 17 deletions

‎src/config/sessions/session-accessor.sqlite-history-events.test.ts‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,72 @@ describe("SQLite transcript history events", () => {
233233
expect(page.events.map(({ seq }) => seq)).toEqual([3]);
234234
});
235235

236+
it("does not read an inactive boundary between active sequence bounds", async () => {
237+
await persistSessionTranscriptTurn(scope, {
238+
messages: [{ eventId: "seed", parentId: null, message: { role: "user", content: "seed" } }],
239+
touchSessionEntry: false,
240+
});
241+
const database = openOpenClawAgentDatabase({ agentId: scope.agentId, env: scope.env });
242+
const boundaryEvents = [
243+
{
244+
seq: 2,
245+
id: "active-boundary-2",
246+
eventJson: JSON.stringify({
247+
type: "compaction",
248+
id: "active-boundary-2",
249+
parentId: "seed",
250+
timestamp: "2026-08-15T00:00:01.000Z",
251+
summary: "active",
252+
}),
253+
activePosition: 1,
254+
},
255+
{ seq: 3, id: "inactive-boundary", eventJson: "{", activePosition: undefined },
256+
{
257+
seq: 4,
258+
id: "active-boundary-4",
259+
eventJson: JSON.stringify({
260+
type: "compaction",
261+
id: "active-boundary-4",
262+
parentId: "active-boundary-2",
263+
timestamp: "2026-08-15T00:00:02.000Z",
264+
summary: "active",
265+
}),
266+
activePosition: 2,
267+
},
268+
];
269+
const insertEvent = database.db.prepare(
270+
"INSERT INTO transcript_events (session_id, seq, event_json, created_at) VALUES (?, ?, ?, ?)",
271+
);
272+
const insertIdentity = database.db.prepare(
273+
`INSERT INTO transcript_event_identities
274+
(session_id, event_id, seq, event_type, parent_id, message_idempotency_key, created_at)
275+
VALUES (?, ?, ?, 'compaction', NULL, NULL, ?)`,
276+
);
277+
const insertActive = database.db.prepare(
278+
`INSERT INTO session_transcript_active_events
279+
(session_id, active_position, event_seq, message_position)
280+
VALUES (?, ?, ?, NULL)`,
281+
);
282+
for (const event of boundaryEvents) {
283+
insertEvent.run(scope.sessionId, event.seq, event.eventJson, event.seq);
284+
insertIdentity.run(scope.sessionId, event.id, event.seq, event.seq);
285+
if (event.activePosition !== undefined) {
286+
insertActive.run(scope.sessionId, event.activePosition, event.seq);
287+
}
288+
}
289+
database.db
290+
.prepare(
291+
`UPDATE session_transcript_index_state
292+
SET indexed_seq = 4, leaf_event_id = 'active-boundary-4', active_event_count = 3
293+
WHERE session_id = ?`,
294+
)
295+
.run(scope.sessionId);
296+
297+
const events = readSessionTranscriptHistoryEvents(scope);
298+
299+
expect(events.map(historyEventId)).toEqual(["seed", "active-boundary-2", "active-boundary-4"]);
300+
});
301+
236302
it("bounds metadata bindings when the raw history window exceeds SQLite's limit", async () => {
237303
await persistSessionTranscriptTurn(scope, {
238304
messages: [{ eventId: "seed", parentId: null, message: { role: "user", content: "seed" } }],

‎src/config/sessions/session-accessor.sqlite-history-events.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -136,14 +136,19 @@ function readBoundaryEvents(
136136
executeSqliteQuerySync(
137137
projection.database.db,
138138
db
139-
.selectFrom("transcript_event_identities as identity")
139+
.selectFrom("session_transcript_active_events as active")
140+
.innerJoin("transcript_event_identities as identity", (join) =>
141+
join
142+
.onRef("identity.session_id", "=", "active.session_id")
143+
.onRef("identity.seq", "=", "active.event_seq"),
144+
)
140145
.innerJoin("transcript_events as event", (join) =>
141146
join
142-
.onRef("event.session_id", "=", "identity.session_id")
143-
.onRef("event.seq", "=", "identity.seq"),
147+
.onRef("event.session_id", "=", "active.session_id")
148+
.onRef("event.seq", "=", "active.event_seq"),
144149
)
145150
.select(["event.seq", "event.event_json"])
146-
.where("identity.session_id", "=", projection.resolved.sessionId)
151+
.where("active.session_id", "=", projection.resolved.sessionId)
147152
.where("identity.event_type", "in", ["compaction", "reset"])
148153
.where("identity.seq", ">=", firstSeq)
149154
.where("identity.seq", "<=", lastSeq),

‎src/gateway/cli-session-history.claude-snapshot.ts‎

Lines changed: 121 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,62 @@
11
import fs from "node:fs";
22
import readline from "node:readline";
33
import { setImmediate as yieldToEventLoop } from "node:timers/promises";
4+
import { Worker } from "node:worker_threads";
5+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
46
import type { CliSessionReseedReceipt } from "../config/sessions.js";
57
import { normalizeCliSessionReseedReceipt } from "../config/sessions/cli-session-binding.js";
68
import {
79
appendCoalescedClaudeCliToolMessage,
810
createClaudeReseedImportState,
911
decodeClaudeCliProjectEntry,
12+
type ClaudeCliProjectEntry,
1013
parseClaudeCliHistoryEntry,
1114
redactClaudeCliHistoryMessage,
1215
resolveClaudeCliSessionFilePath,
1316
} from "./cli-session-history.claude.js";
1417

1518
const YIELD_BYTES = 256 * 1024;
19+
const OFFTHREAD_JSONL_LINE_CHARS = 1024 * 1024;
20+
const OVERSIZED_HISTORY_PLACEHOLDER =
21+
"[Claude CLI history record omitted from context because it exceeded 1 MiB.]";
22+
const OVERSIZED_ENTRY_WORKER_SOURCE = `
23+
const { parentPort, workerData } = require("node:worker_threads");
24+
const boundedString = (value, max) =>
25+
typeof value === "string" && value.length <= max ? value : undefined;
26+
try {
27+
const entry = JSON.parse(workerData);
28+
const type = entry?.type;
29+
const message = entry?.message;
30+
if ((type !== "user" && type !== "assistant") || !message || message.role !== type) {
31+
parentPort.postMessage(null);
32+
} else {
33+
const rawUsage = message.usage;
34+
const usage = rawUsage && typeof rawUsage === "object"
35+
? Object.fromEntries(
36+
["input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"]
37+
.flatMap((key) => Number.isFinite(rawUsage[key]) ? [[key, rawUsage[key]]] : []),
38+
)
39+
: undefined;
40+
parentPort.postMessage({
41+
type,
42+
timestamp: boundedString(entry.timestamp, 128),
43+
uuid: boundedString(entry.uuid, 1_024),
44+
isSidechain: entry.isSidechain === true,
45+
isMeta: entry.isMeta === true,
46+
isCompactSummary: entry.isCompactSummary === true,
47+
message: {
48+
role: type,
49+
content: ${JSON.stringify(OVERSIZED_HISTORY_PLACEHOLDER)},
50+
model: boundedString(message.model, 256),
51+
stop_reason: boundedString(message.stop_reason, 128),
52+
usage,
53+
},
54+
});
55+
}
56+
} catch {
57+
parentPort.postMessage(null);
58+
}
59+
`;
1660
type Message = Record<string, unknown>;
1761
type HistoryParams = {
1862
cliSessionId: string;
@@ -22,6 +66,63 @@ type HistoryParams = {
2266
};
2367
let snapshotCache: { key: string; pending: Promise<readonly Message[]> } | undefined;
2468

69+
function normalizeOversizedEntry(value: unknown): ClaudeCliProjectEntry | null {
70+
if (!isRecord(value) || (value.type !== "user" && value.type !== "assistant")) {
71+
return null;
72+
}
73+
const message = value.message;
74+
if (!isRecord(message) || message.role !== value.type) {
75+
return null;
76+
}
77+
const usage = isRecord(message.usage) ? message.usage : undefined;
78+
return {
79+
type: value.type,
80+
...(typeof value.timestamp === "string" ? { timestamp: value.timestamp } : {}),
81+
...(typeof value.uuid === "string" ? { uuid: value.uuid } : {}),
82+
...(value.isSidechain === true ? { isSidechain: true } : {}),
83+
...(value.isMeta === true ? { isMeta: true } : {}),
84+
...(value.isCompactSummary === true ? { isCompactSummary: true } : {}),
85+
message: {
86+
role: value.type,
87+
content: OVERSIZED_HISTORY_PLACEHOLDER,
88+
...(typeof message.model === "string" ? { model: message.model } : {}),
89+
...(typeof message.stop_reason === "string" ? { stop_reason: message.stop_reason } : {}),
90+
...(usage
91+
? {
92+
usage: {
93+
input_tokens: usage.input_tokens,
94+
output_tokens: usage.output_tokens,
95+
cache_read_input_tokens: usage.cache_read_input_tokens,
96+
cache_creation_input_tokens: usage.cache_creation_input_tokens,
97+
},
98+
}
99+
: {}),
100+
},
101+
};
102+
}
103+
104+
async function decodeOversizedClaudeEntry(line: string): Promise<ClaudeCliProjectEntry | null> {
105+
let worker: Worker;
106+
try {
107+
worker = new Worker(OVERSIZED_ENTRY_WORKER_SOURCE, { eval: true, workerData: line });
108+
} catch {
109+
return null;
110+
}
111+
return await new Promise((resolve) => {
112+
let settled = false;
113+
const finish = (value: unknown) => {
114+
if (settled) {
115+
return;
116+
}
117+
settled = true;
118+
resolve(normalizeOversizedEntry(value));
119+
};
120+
worker.once("message", finish);
121+
worker.once("error", () => finish(null));
122+
worker.once("exit", () => finish(null));
123+
});
124+
}
125+
25126
function fingerprint(stats: fs.Stats): string {
26127
return [stats.dev, stats.ino, stats.size, stats.mtimeMs, stats.ctimeMs].join(":");
27128
}
@@ -62,17 +163,30 @@ async function parseSnapshot(filePath: string, params: HistoryParams): Promise<r
62163
let lineNumber = 0;
63164
for await (const line of lines) {
64165
lineNumber += 1;
65-
bytesSinceYield += Buffer.byteLength(line, "utf8") + 1;
66-
if (bytesSinceYield >= YIELD_BYTES) {
166+
const oversized = line.length > OFFTHREAD_JSONL_LINE_CHARS;
167+
if (oversized) {
67168
bytesSinceYield = 0;
68-
await yieldToEventLoop();
69-
}
70-
if (!line.trim()) {
71-
continue;
169+
} else {
170+
bytesSinceYield += Buffer.byteLength(line, "utf8") + 1;
171+
if (bytesSinceYield >= YIELD_BYTES) {
172+
bytesSinceYield = 0;
173+
await yieldToEventLoop();
174+
}
175+
if (!line.trim()) {
176+
continue;
177+
}
72178
}
73179
try {
180+
// Keep large valid user/assistant records visible through a bounded projection;
181+
// unsupported external records are still ignored, but JSON.parse runs off-loop.
182+
const entry = oversized
183+
? await decodeOversizedClaudeEntry(line)
184+
: decodeClaudeCliProjectEntry(line);
185+
if (!entry) {
186+
continue;
187+
}
74188
const message = parseClaudeCliHistoryEntry(
75-
decodeClaudeCliProjectEntry(line),
189+
entry,
76190
params.cliSessionId,
77191
lineNumber,
78192
toolNames,

‎src/gateway/cli-session-history.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,53 @@ describe("cli session history", () => {
320320
});
321321
});
322322

323+
it("projects oversized Claude messages after off-thread parsing", async () => {
324+
await withClaudeProjectsDir(async ({ homeDir, sessionId, filePath }) => {
325+
const oversizedRecord = JSON.stringify({
326+
type: "user",
327+
uuid: "oversized-user",
328+
timestamp: "2026-03-26T16:29:54.700Z",
329+
message: { role: "user", content: "q".repeat(2 * 1024 * 1024) },
330+
});
331+
await fs.writeFile(
332+
filePath,
333+
`${oversizedRecord}\n${createClaudeTextHistoryLines([
334+
{ role: "user", uuid: "visible-after-oversized", content: "visible" },
335+
])}`,
336+
"utf8",
337+
);
338+
const parseSpy = vi.spyOn(JSON, "parse");
339+
try {
340+
const messages = await readChatHistoryCliSessionImportSnapshot({
341+
entry: {
342+
sessionId: "openclaw-session",
343+
updatedAt: Date.now(),
344+
cliSessionBindings: { "claude-cli": { sessionId } },
345+
},
346+
provider: "claude-cli",
347+
localMessages: [],
348+
homeDir,
349+
});
350+
351+
expect(messages).toHaveLength(2);
352+
expectFields(readRecord(messages[0])["__openclaw"], {
353+
externalId: "oversized-user",
354+
});
355+
expect(readRecord(messages[0]).content).toContain("exceeded 1 MiB");
356+
expectFields(readRecord(messages[1])["__openclaw"], {
357+
externalId: "visible-after-oversized",
358+
});
359+
expect(
360+
parseSpy.mock.calls.some(
361+
([source]) => typeof source === "string" && source.length === oversizedRecord.length,
362+
),
363+
).toBe(false);
364+
} finally {
365+
parseSpy.mockRestore();
366+
}
367+
});
368+
});
369+
323370
it("preserves Date.parse semantics for numeric-looking Claude timestamps", async () => {
324371
await withClaudeProjectsDir(async ({ homeDir, sessionId, filePath }) => {
325372
await fs.writeFile(

‎src/gateway/server.chat.gateway-server-chat-b.test.ts‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4846,16 +4846,13 @@ describe("gateway server chat", () => {
48464846
const homeDir = path.join(sessionDir, "home");
48474847
const claudeProjectsDir = path.join(homeDir, ".claude", "projects", "workspace");
48484848
const secret = "sk-abcdef1234567890-large-snapshot";
4849-
const ignoredLine = JSON.stringify({
4849+
const oversizedIgnoredLine = JSON.stringify({
48504850
type: "queue-operation",
48514851
operation: "enqueue",
48524852
sessionId: cliSessionId,
4853-
content: "q".repeat(2_048),
4853+
content: "q".repeat(34 * 1024 * 1024),
48544854
});
4855-
const ignoredBlock = `${ignoredLine}\n`.repeat(
4856-
Math.ceil((34 * 1024 * 1024) / (Buffer.byteLength(ignoredLine, "utf8") + 1)),
4857-
);
4858-
const jsonl = `${ignoredBlock}${[
4855+
const jsonl = `${oversizedIgnoredLine}\n${[
48594856
JSON.stringify({
48604857
type: "user",
48614858
uuid: "large-snapshot-user",

0 commit comments

Comments
 (0)