Skip to content

Commit c09f136

Browse files
authored
fix: reduce memory spikes when preparing long session histories (#133753)
* fix(sessions): project model history before hydration * fix(sessions): follow canonical transcript identity reader * fix(sessions): type projection column references
1 parent dc12bbd commit c09f136

28 files changed

Lines changed: 1421 additions & 160 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ extensions/codex/src/app-server/sandbox-exec-server/processes.ts 1
223223
extensions/codex/src/app-server/sandbox-guard.ts 2
224224
extensions/codex/src/app-server/scheduled-app-authority.ts 5
225225
extensions/codex/src/app-server/session-binding.ts 4
226-
extensions/codex/src/app-server/session-history.ts 6
226+
extensions/codex/src/app-server/session-history.ts 4
227227
extensions/codex/src/app-server/settled-turn-context.ts 3
228228
extensions/codex/src/app-server/shared-client.ts 4
229229
extensions/codex/src/app-server/side-question.ts 8
@@ -1967,7 +1967,7 @@ src/agents/session-placement-admission.ts 1
19671967
src/agents/session-raw-append-message.ts 2
19681968
src/agents/session-suspension.ts 1
19691969
src/agents/session-tool-result-guard.ts 24
1970-
src/agents/session-transcript-repair.ts 15
1970+
src/agents/session-transcript-repair.ts 14
19711971
src/agents/sessions/agent-session-base.ts 3
19721972
src/agents/sessions/agent-session-extensions.ts 1
19731973
src/agents/sessions/agent-session-inspection.ts 2
@@ -2700,7 +2700,6 @@ src/config/sessions/session-sqlite-target.ts 3
27002700
src/config/sessions/session-store-config.ts 2
27012701
src/config/sessions/session-suggestion-store.ts 4
27022702
src/config/sessions/session-transcript-projection-rebuild.ts 6
2703-
src/config/sessions/session-transcript-read-fence.ts 1
27042703
src/config/sessions/session-transcript-reconcile.worker.ts 1
27052704
src/config/sessions/session-transcript-search.ts 1
27062705
src/config/sessions/skill-prompt-blobs.ts 5

‎docs/plugins/hooks.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -781,6 +781,8 @@ restrictions intersect. A nested ordinary `before_prompt_build` dispatch on
781781
the same runner is skipped while its outer dispatch is active; other hook
782782
families and independent turns remain available.
783783

784+
Message-consuming prompt hooks receive a detached model-context snapshot. Mutating nested messages does not change the caller's history, including when a handler retains its input after returning. Registrations within one dispatch share that snapshot in priority order; prepare, ordinary prompt-build, authorized enrichment, and subsequent prompt rebuilds receive separate snapshots. Storage-only native prompt text and tool-result details are excluded from these snapshots.
785+
784786
### Authorized prompt enrichment
785787

786788
Register `before_prompt_build` with `requiresToolAuthority: true` when a plugin

‎docs/reference/session-management-compaction.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,8 @@ Notable entry types:
186186

187187
History readers keep the latest reset window across later compactions: explicitly retained reset messages and messages after that reset remain visible, but older messages and compaction summaries do not reappear. Model context follows the latest reset or compaction instead, so compaction can summarize the current conversation without reopening its earlier history.
188188

189+
Model-only callers can use `SessionManager.openModelContext()` to create a detached, non-persisting view. The reader selects payloads in SQLite and retains lightweight navigation outside the model window, without introducing a history size cutoff. Storage-only native prompt text and tool-result details stay out of that view; mirror identity, sender and media facts, tool content, and valid provider replay state remain available. Native fork verification, replay, exports, and doctor operations continue to use full-fidelity evidence readers.
190+
189191
OpenClaw intentionally does not "fix up" transcripts; the Gateway uses `SessionManager` to read/write them.
190192

191193
## Context windows vs tracked tokens

‎docs/tools/self-learning.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -212,8 +212,10 @@ Experience review adds one bounded model run on the configured provider only
212212
after a substantial turn, not after every message. The review can make more
213213
than one provider request while it inspects or drafts its single proposal.
214214

215-
The review forks the foreground transcript in memory and appends one small user
216-
message. It uses a private detached session identity while preserving the
215+
The review creates a detached view of the foreground model context and appends
216+
one small user message. Storage-only native prompt payloads stay in the original
217+
transcript, whose stored bytes the review does not change. It uses a private
218+
detached session identity while preserving the
217219
foreground provider, model, auth profile, bootstrap context, skills prompt, tool
218220
schemas, and prompt-cache affinity. The provider can reuse the finished turn's
219221
cached request prefix without making the review part of the foreground session.

‎extensions/codex/src/app-server/attempt-context.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,11 @@ export async function readMirroredSessionHistoryMessages(params: {
9090
admission?: TranscriptTurnAdmission;
9191
}): Promise<AgentMessage[] | undefined> {
9292
const { admission, ...target } = params;
93-
const messages = await readCodexMirroredSessionHistoryMessages(target, admission);
93+
const messages = await readCodexMirroredSessionHistoryMessages(
94+
target,
95+
admission,
96+
"model-context",
97+
);
9498
if (!messages) {
9599
embeddedAgentLog.warn("failed to read mirrored session history for codex harness hooks", {
96100
sessionFile: params.sessionFile,

‎extensions/codex/src/app-server/run-attempt-prompt.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ export async function prepareCodexAttemptPrompt(context: CodexAttemptContext) {
198198
return promptState.developerInstructions;
199199
},
200200
},
201-
messages: structuredClone(historyState.messages),
201+
messages: historyState.messages,
202202
ctx: hookContext,
203203
bootstrapContextRunKind: params.bootstrapContextRunKind,
204204
toolAuthority: {

‎extensions/codex/src/app-server/run-attempt.test.ts‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3044,6 +3044,101 @@ describe("runCodexAppServerAttempt", () => {
30443044
expect(JSON.stringify(result.messagesSnapshot)).not.toContain("tool_search");
30453045
expect(JSON.stringify(result.messagesSnapshot)).not.toContain("function_call_output");
30463046
});
3047+
it.each(["none", "heartbeat", "ordinary", "authorized"])(
3048+
"keeps private native history out of prompt acquisition and clones (%s)",
3049+
async (kind) => {
3050+
const marker = "synthetic-native-payload:";
3051+
const privateText = marker + "x".repeat(1024 * 1024);
3052+
const hook = vi.fn(() => ({ prependContext: "hook context" }));
3053+
initializeGlobalHookRunner(
3054+
createMockPluginRegistry(
3055+
kind === "none"
3056+
? []
3057+
: [
3058+
{
3059+
hookName:
3060+
kind === "heartbeat" ? "heartbeat_prompt_contribution" : "before_prompt_build",
3061+
...(kind === "authorized" ? { requiresToolAuthority: true as const } : {}),
3062+
handler: hook,
3063+
},
3064+
],
3065+
),
3066+
);
3067+
const { sessionFile, workspaceDir } = createRunPaths();
3068+
const params = createParams(sessionFile, workspaceDir);
3069+
await attachSqliteSessionTarget(params, path.join(tempDir, "memory.sqlite"), "session-1");
3070+
await appendSqliteHistoryMessage(params, {
3071+
...userMessage("previous visible request", 1),
3072+
__openclaw: { upstreamUserText: privateText },
3073+
} as ReturnType<typeof userMessage>);
3074+
const originalParse = JSON.parse;
3075+
let privateParseBytes = 0;
3076+
const parseSpy = vi.spyOn(JSON, "parse").mockImplementation((text, reviver) => {
3077+
if (typeof text === "string" && text.includes(marker)) {
3078+
privateParseBytes += text.length;
3079+
}
3080+
return originalParse(text, reviver);
3081+
});
3082+
const originalClone = structuredClone;
3083+
let historyClones = 0;
3084+
let privateCloneBytes = 0;
3085+
const cloneSpy = vi
3086+
.spyOn(globalThis, "structuredClone")
3087+
.mockImplementation((value, options) => {
3088+
const seen = new WeakSet<object>();
3089+
const visit = (node: unknown): void => {
3090+
if (typeof node === "string" && node.startsWith(marker)) {
3091+
privateCloneBytes += node.length;
3092+
}
3093+
if (!node || typeof node !== "object" || seen.has(node)) {
3094+
return;
3095+
}
3096+
seen.add(node);
3097+
if (
3098+
"role" in node &&
3099+
node.role === "user" &&
3100+
"content" in node &&
3101+
Array.isArray(node.content) &&
3102+
node.content[0]?.text === "previous visible request"
3103+
) {
3104+
historyClones += 1;
3105+
}
3106+
for (const child of Object.values(node)) {
3107+
visit(child);
3108+
}
3109+
};
3110+
visit(value);
3111+
return originalClone(value, options);
3112+
});
3113+
try {
3114+
const harness = createStartedThreadHarness();
3115+
if (kind === "heartbeat") {
3116+
params.trigger = "heartbeat";
3117+
}
3118+
if (kind === "authorized") {
3119+
params.toolAuthorityFingerprint = "synthetic-authority";
3120+
}
3121+
const run = runCodexAppServerAttempt(params);
3122+
await harness.waitForMethod("turn/start");
3123+
await harness.completeTurn({ threadId: "thread-1", turnId: "turn-1" });
3124+
await run;
3125+
expect(privateParseBytes).toBe(0);
3126+
expect(privateCloneBytes).toBe(0);
3127+
if (kind === "none" || kind === "heartbeat") {
3128+
expect(historyClones).toBe(0);
3129+
} else {
3130+
expect(historyClones).toBeGreaterThan(0);
3131+
}
3132+
if (kind !== "none") {
3133+
expect(hook).toHaveBeenCalled();
3134+
}
3135+
} finally {
3136+
parseSpy.mockRestore();
3137+
cloneSpy.mockRestore();
3138+
}
3139+
},
3140+
);
3141+
30473142
it("applies before_prompt_build to Codex developer instructions and turn input", async () => {
30483143
const llmInput = vi.fn();
30493144
const beforePromptBuild = vi.fn(async () => ({

‎extensions/codex/src/app-server/session-history.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Codex tests cover mirrored session-history branch selection.
2+
import { createHash } from "node:crypto";
23
import fs from "node:fs/promises";
34
import os from "node:os";
45
import path from "node:path";
@@ -7,6 +8,7 @@ import { upsertSessionEntry } from "openclaw/plugin-sdk/session-store-runtime";
78
import { appendSessionTranscriptMessageByIdentity } from "openclaw/plugin-sdk/session-transcript-runtime";
89
import { afterEach, describe, expect, it } from "vitest";
910
import { readCodexMirroredSessionHistoryMessages } from "./session-history.js";
11+
import { readMirrorIdentity, readUpstreamUserText } from "./upstream-prompt-provenance.js";
1012

1113
const tempDirs: string[] = [];
1214

@@ -130,6 +132,44 @@ async function writeSqliteSession(params: { storedSessionFile?: string } = {}):
130132
}
131133

132134
describe("readCodexMirroredSessionHistoryMessages", () => {
135+
it("preserves native prompt evidence across explicit model-only reads", async () => {
136+
const { marker, sessionTarget } = await writeSqliteSession();
137+
const upstreamUserText = "synthetic-native-prompt:" + "x".repeat(1024 * 1024);
138+
const message = {
139+
role: "user" as const,
140+
content: "native visible",
141+
timestamp: 3,
142+
__openclaw: {
143+
upstreamUserText,
144+
mirrorIdentity: "synthetic-native-turn",
145+
mirrorOrigin: "codex",
146+
turnTainted: true,
147+
},
148+
};
149+
await appendSessionTranscriptMessageByIdentity({ ...sessionTarget, message });
150+
const target = { ...sessionTarget, sessionTarget, sessionFile: marker };
151+
const hash = (text: string | undefined) =>
152+
createHash("sha256")
153+
.update(text ?? "")
154+
.digest("hex");
155+
const before = (await readCodexMirroredSessionHistoryMessages(target))!.at(-1)!;
156+
expect(hash(readUpstreamUserText(before))).toBe(hash(upstreamUserText));
157+
const model = (await readCodexMirroredSessionHistoryMessages(
158+
target,
159+
undefined,
160+
"model-context",
161+
))!.at(-1)!;
162+
expect(readUpstreamUserText(model)).toBeUndefined();
163+
expect(readMirrorIdentity(model)).toBe("synthetic-native-turn");
164+
expect(model).toMatchObject({
165+
content: "native visible",
166+
timestamp: 3,
167+
__openclaw: { mirrorOrigin: "codex", turnTainted: true },
168+
});
169+
const after = (await readCodexMirroredSessionHistoryMessages(target))!.at(-1)!;
170+
expect(hash(readUpstreamUserText(after))).toBe(hash(upstreamUserText));
171+
expect(readMirrorIdentity(after)).toBe("synthetic-native-turn");
172+
});
133173
it("treats a missing mirrored session file as empty history", async () => {
134174
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-codex-session-history-"));
135175
tempDirs.push(dir);

‎extensions/codex/src/app-server/session-history.ts‎

Lines changed: 34 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
buildSessionContext,
1010
migrateSessionEntries,
1111
parseSessionEntries,
12+
SessionManager,
1213
} from "openclaw/plugin-sdk/agent-sessions";
1314
import { readCodexSessionTranscriptEventsBeforeAdmission } from "openclaw/plugin-sdk/codex-session-transcript-runtime";
1415
import {
@@ -40,9 +41,20 @@ export type CodexMirroredSessionHistoryTarget = {
4041
export async function readCodexMirroredSessionHistoryMessages(
4142
target: CodexMirroredSessionHistoryTarget,
4243
admission?: TranscriptTurnAdmission,
44+
view: "native-evidence" | "model-context" = "native-evidence",
4345
): Promise<AgentMessage[] | undefined> {
4446
try {
45-
const entries = await readCodexMirroredSessionEntries(target, admission);
47+
const loaded = await readCodexMirroredSessionEntries(target, admission, view);
48+
if (!Array.isArray(loaded)) {
49+
if (loaded.getHeader()?.id !== target.sessionId) {
50+
return [];
51+
}
52+
return sanitizeCodexHistoryImagePayloads(
53+
loaded.buildSessionContext().messages,
54+
"codex mirrored model context",
55+
);
56+
}
57+
const entries = loaded;
4658
if (entries.length === 0) {
4759
return [];
4860
}
@@ -87,8 +99,19 @@ export async function readCodexMirroredSessionHistoryMessages(
8799

88100
async function readCodexMirroredSessionEntries(
89101
target: CodexMirroredSessionHistoryTarget,
90-
admission?: TranscriptTurnAdmission,
91-
): Promise<SessionEntry[]> {
102+
admission: TranscriptTurnAdmission | undefined,
103+
view: "native-evidence" | "model-context",
104+
): Promise<SessionEntry[] | SessionManager> {
105+
const readTarget = async (
106+
transcriptTarget: Required<
107+
Pick<SessionTranscriptTargetParams, "agentId" | "sessionId" | "sessionKey" | "storePath">
108+
>,
109+
) =>
110+
view === "model-context"
111+
? SessionManager.openModelContext(transcriptTarget, { admission })
112+
: ((await (admission
113+
? readCodexSessionTranscriptEventsBeforeAdmission(transcriptTarget, admission)
114+
: readSessionTranscriptEvents(transcriptTarget))) as SessionEntry[]);
92115
if (target.sessionTarget) {
93116
const { agentId, sessionId, sessionKey, storePath } = target.sessionTarget;
94117
if (
@@ -108,9 +131,7 @@ async function readCodexMirroredSessionEntries(
108131
sessionKey,
109132
storePath,
110133
};
111-
return (await (admission
112-
? readCodexSessionTranscriptEventsBeforeAdmission(transcriptTarget, admission)
113-
: readSessionTranscriptEvents(transcriptTarget))) as SessionEntry[];
134+
return readTarget(transcriptTarget);
114135
}
115136
const sqliteMarker = parseSqliteSessionFileMarker(target.sessionFile);
116137
if (sqliteMarker) {
@@ -130,9 +151,7 @@ async function readCodexMirroredSessionEntries(
130151
sessionKey,
131152
storePath: sqliteMarker.storePath,
132153
};
133-
return (await (admission
134-
? readCodexSessionTranscriptEventsBeforeAdmission(transcriptTarget, admission)
135-
: readSessionTranscriptEvents(transcriptTarget))) as SessionEntry[];
154+
return readTarget(transcriptTarget);
136155
}
137156
if (admission) {
138157
if (
@@ -142,15 +161,12 @@ async function readCodexMirroredSessionEntries(
142161
) {
143162
return [];
144163
}
145-
return (await readCodexSessionTranscriptEventsBeforeAdmission(
146-
{
147-
agentId: admission.agentId,
148-
sessionId: admission.sessionId,
149-
sessionKey: admission.sessionKey,
150-
storePath: admission.storePath,
151-
},
152-
admission,
153-
)) as SessionEntry[];
164+
return readTarget({
165+
agentId: admission.agentId,
166+
sessionId: admission.sessionId,
167+
sessionKey: admission.sessionKey,
168+
storePath: admission.storePath,
169+
});
154170
}
155171
return parseSessionEntries(await fs.readFile(target.sessionFile, "utf-8")) as SessionEntry[];
156172
}

‎packages/agent-core/src/harness/session/session.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,23 @@ import { selectResetKeptEntries } from "./tool-result-pairing.js";
1212
type ContextBoundary = CompactionEntry | ResetEntry;
1313
const SESSION_HISTORY_PRELUDE = Symbol.for("openclaw.sessionHistoryPrelude");
1414

15+
/** The same semantic cut is used before payload acquisition and when building messages. */
16+
export function resolveSessionContextWindow(
17+
entries: readonly { id: string; type: string; firstKeptEntryId?: string }[],
18+
): { boundaryIndex: number; firstKeptIndex: number } {
19+
const boundaryIndex = entries.findLastIndex(
20+
(entry) => entry.type === "reset" || entry.type === "compaction",
21+
);
22+
const firstKeptIndex = entries.findIndex(
23+
(entry) => entry.id === entries[boundaryIndex]?.firstKeptEntryId,
24+
);
25+
return {
26+
boundaryIndex,
27+
firstKeptIndex:
28+
firstKeptIndex >= 0 && firstKeptIndex < boundaryIndex ? firstKeptIndex : boundaryIndex,
29+
};
30+
}
31+
1532
/** Project persisted session entries into the message shared by replay and summarization. */
1633
export function projectSessionEntryMessage(entry: SessionTreeEntry): AgentMessage | undefined {
1734
switch (entry.type) {
@@ -106,8 +123,8 @@ export function buildSessionContext(pathEntries: SessionTreeEntry[]): SessionCon
106123
messages.push(summary);
107124
}
108125
}
109-
const boundaryIdx = pathEntries.findIndex((entry) => entry.id === boundary.id);
110-
const firstKeptIdx = pathEntries.findIndex((entry) => entry.id === boundary.firstKeptEntryId);
126+
const { boundaryIndex: boundaryIdx, firstKeptIndex: firstKeptIdx } =
127+
resolveSessionContextWindow(pathEntries);
111128
const keptEntries =
112129
firstKeptIdx >= 0 && firstKeptIdx < boundaryIdx
113130
? pathEntries.slice(firstKeptIdx, boundaryIdx)

0 commit comments

Comments
 (0)