Skip to content

Commit 4431033

Browse files
authored
fix(sessions): avoid excessive history copies and preserve fork provenance (#134238)
* fix(sessions): bound history acquisition and preserve fork provenance * fix(agents): preserve eligible settled-turn fallback
1 parent 85c8934 commit 4431033

32 files changed

Lines changed: 1485 additions & 809 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,6 @@ extensions/codex/src/app-server/reasoning-effort.ts 1
207207
extensions/codex/src/app-server/remote-workspace-media.ts 6
208208
extensions/codex/src/app-server/request.ts 2
209209
extensions/codex/src/app-server/run-attempt-context.ts 2
210-
extensions/codex/src/app-server/run-attempt-prompt.ts 2
211210
extensions/codex/src/app-server/run-attempt-resources.ts 13
212211
extensions/codex/src/app-server/run-attempt-runtime.ts 1
213212
extensions/codex/src/app-server/run-attempt-server-requests.ts 2
@@ -223,8 +222,7 @@ extensions/codex/src/app-server/sandbox-exec-server/processes.ts 1
223222
extensions/codex/src/app-server/sandbox-guard.ts 2
224223
extensions/codex/src/app-server/scheduled-app-authority.ts 5
225224
extensions/codex/src/app-server/session-binding.ts 4
226-
extensions/codex/src/app-server/session-history.ts 4
227-
extensions/codex/src/app-server/settled-turn-context.ts 3
225+
extensions/codex/src/app-server/settled-turn-context.ts 2
228226
extensions/codex/src/app-server/shared-client.ts 4
229227
extensions/codex/src/app-server/side-question.ts 8
230228
extensions/codex/src/app-server/startup-binding.ts 2
@@ -236,7 +234,7 @@ extensions/codex/src/app-server/transcript-history-projection.ts 2
236234
extensions/codex/src/app-server/transcript-mirror-attestation.ts 2
237235
extensions/codex/src/app-server/transcript-mirror.ts 4
238236
extensions/codex/src/app-server/transport-stdio.ts 1
239-
extensions/codex/src/app-server/upstream-fork-boundary.ts 2
237+
extensions/codex/src/app-server/upstream-fork-boundary.ts 1
240238
extensions/codex/src/app-server/usage-limit-error.ts 2
241239
extensions/codex/src/app-server/user-prompt-message.ts 1
242240
extensions/codex/src/command-handlers.ts 3
@@ -1459,7 +1457,6 @@ packages/agent-core/src/agent-loop.ts 3
14591457
packages/agent-core/src/harness/compaction/branch-summarization.ts 1
14601458
packages/agent-core/src/harness/compaction/compaction.ts 2
14611459
packages/agent-core/src/harness/messages.ts 3
1462-
packages/agent-core/src/harness/session/session.ts 1
14631460
packages/agent-core/src/harness/session/tool-result-pairing.ts 17
14641461
packages/agent-core/src/harness/session/uuid.ts 1
14651462
packages/agent-core/src/harness/utils/truncate.ts 1
@@ -1791,7 +1788,7 @@ src/agents/embedded-agent-runner/run/attempt-finalize.ts 3
17911788
src/agents/embedded-agent-runner/run/attempt-history.ts 17
17921789
src/agents/embedded-agent-runner/run/attempt-llm-boundary.ts 19
17931790
src/agents/embedded-agent-runner/run/attempt-normalization.ts 1
1794-
src/agents/embedded-agent-runner/run/attempt-prompt-build.ts 2
1791+
src/agents/embedded-agent-runner/run/attempt-prompt-build.ts 1
17951792
src/agents/embedded-agent-runner/run/attempt-prompt-helpers.ts 4
17961793
src/agents/embedded-agent-runner/run/attempt-prompt-submit.ts 2
17971794
src/agents/embedded-agent-runner/run/attempt-queue-message.ts 3

‎docs/plugins/sdk-agent-harness.md‎

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -775,14 +775,35 @@ rejects canonical failure, tool, delivery, replay, and lifecycle evidence, then
775775
projects only the narrow result. It is defense in depth after native isolation,
776776
not a substitute for removing the native capability surface.
777777

778-
A projection-backed harness must put the complete context on
779-
`settledAttempt.settledTurnFinalizationContext` with
780-
`source: "openclaw-transcript"`. It must capture the active branch after the
781-
settled turn is mirrored, prove that the current prompt and every current tool
782-
call/result are present through that boundary, and freeze the resulting message
783-
array before returning the attempt. The finalizer must reject a missing,
778+
A projection-backed harness must capture the active branch after the settled
779+
turn is mirrored and prove that the current prompt and every current tool
780+
call/result are present through that boundary. Put the frozen evidence on
781+
`settledAttempt.settledTurnFinalizationContext` as one of:
782+
783+
- `source: "openclaw-transcript"` with `messages`: the complete application
784+
transcript through the boundary.
785+
- `source: "harness"` with `data`: an immutable, bounded projection interpreted
786+
only by the owning harness. Core passes this opaque value through; the
787+
finalizer must verify its own context type before using it.
788+
- `source: "unavailable"`: the harness permits finalization for this settled
789+
turn, but safe replay evidence could not be captured. The finalizer must
790+
reject this state before provider or native I/O; core can still use its
791+
existing host-owned fallback without repeating tools.
792+
793+
The unavailable state records eligibility, not validated history. Eligible
794+
capture failures, including missing, drifting, or oversized evidence, can reach
795+
that no-model fallback. Do not emit it for failures the harness excludes from
796+
finalization, such as authentication or usage-limit errors. Command-only
797+
harnesses must retain the attributed assistant tool-call entry in
798+
`messagesSnapshot`; the host fallback can use that settled-batch identity when
799+
visible-assistant fields are absent.
800+
801+
Enforce projection limits while acquiring messages, rather than cloning the
802+
whole transcript before checking its size. Successful capture must finish all
803+
identity and source-evidence checks before returning the attempt. Do not retain
804+
an open transcript reader in `data`. The finalizer must reject a missing,
784805
unsupported, ambiguous, or oversized context. It must not truncate messages,
785-
drop earlier history, or describe this application transcript as exact native
806+
drop earlier history, or describe an application projection as exact native
786807
history. Harnesses that resume one restricted native session do not need this
787808
projection field.
788809

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

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ Each `sessionKey` points at a current `sessionId` (the SQLite transcript identit
156156
- **System events** (heartbeat, cron wakeups, exec notifications, gateway bookkeeping) may mutate the session row but never extend daily/idle reset freshness. Reset rollover discards queued system-event notices for the previous session before the fresh prompt is built.
157157
- **Automatic parent fork policy** uses OpenClaw's active branch when creating a thread or subagent fork. If that branch is too large (over a fixed internal cap, currently 100K tokens), OpenClaw starts the child with isolated context instead of failing or inheriting unusable history. Sizing is automatic and not configurable; legacy `session.parentForkMaxTokens` config is removed by `openclaw doctor --fix`.
158158
- **Operator forks**: `sessions.create { parentSessionKey, fork: true }` branches from the parent's current state. Admission uses the selected child model's effective usable input capacity, falling back to the 100K safety cap when model capacity is unavailable. A normal fork is refused while the parent has an active run; adding `forkFrom: "last-completed"` copies only through the last completed assistant message, excluding the in-progress tail. Unlike automatic parent forks, an operator fork over its capacity limit is rejected rather than accepted with isolated context. The child inherits the parent's model selection unless one is passed explicitly. The response marks it `forkedFromParent`, and token counters start fresh.
159-
- **Message forks**: `sessions.fork { sessionKey, entryId }` creates a child from the active-path prefix before the selected user message and returns that message to the composer for editing. The parent remains unchanged. Incognito forks retain the parent's in-memory storage class; restarting the Gateway removes both sessions. See [Control UI](/web/control-ui) for fork and rewind actions.
159+
- **Message forks**: `sessions.fork { sessionKey, entryId }` creates a child from the active-path prefix before the selected user message and returns that message to the composer for editing. The parent remains unchanged. Incognito forks retain the parent's in-memory storage class; restarting the Gateway removes both sessions. Codex fork verification compares complete attested submitted prompts, including whitespace; the bounded display-import projection is not a substitute for that evidence. See [Control UI](/web/control-ui) for fork and rewind actions.
160160

161161
## Session store schema
162162

@@ -206,6 +206,18 @@ History readers keep the latest reset window across later compactions: explicitl
206206

207207
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.
208208

209+
`SessionManager.readSessionContext(target, read, { admission? })` lets a synchronous
210+
consumer process full-fidelity context messages inside one read-only snapshot.
211+
The callback receives `(messages, header)`: a lazy message iterable and the
212+
unvalidated stored header. Missing stores supply an empty iterable and no header
213+
without creating a database. An optional admission excludes the current admitted
214+
user row and later events. Callback errors propagate, and the iterator closes
215+
when the callback returns or throws; it cannot be retained for later reads.
216+
This lets replay consumers enforce their existing limits during acquisition
217+
without silently dropping earlier history. Navigation still scales with the
218+
transcript, and individual selected rows are decoded whole; this is not a fixed
219+
process-memory ceiling.
220+
209221
OpenClaw intentionally does not "fix up" transcripts; the Gateway uses `SessionManager` to read/write them.
210222

211223
## Context windows vs tracked tokens

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

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -359,16 +359,16 @@ export async function finalizeCodexAttempt(
359359
result.messagesSnapshot.some((message) => message.role === "toolResult") &&
360360
(!finalPromptError || activeProjector.settledTurnFailureFinalizationAllowed);
361361
const settledTurnFinalizationContext = shouldCaptureSettledTurnFinalizationContext
362-
? await captureCodexSettledTurnFinalizationContext({
362+
? ((await captureCodexSettledTurnFinalizationContext({
363363
...activeTranscriptTarget,
364364
mirroredMessages: mirrorOutcome.mirroredMessages,
365365
settledMessages: result.messagesSnapshot,
366366
turnId: activeTurnId,
367-
})
367+
})) ?? Object.freeze({ source: "unavailable" as const }))
368368
: undefined;
369-
if (shouldCaptureSettledTurnFinalizationContext && !settledTurnFinalizationContext) {
370-
// The isolated child must not infer around a partial or drifting transcript.
371-
// Omitting this field preserves the existing incomplete-turn failure.
369+
if (settledTurnFinalizationContext?.source === "unavailable") {
370+
// Unavailable evidence forbids native inference, but must not revoke this
371+
// eligible turn's path to the existing host-owned fallback.
372372
embeddedAgentLog.warn("codex settled-turn finalization context is unavailable", {
373373
threadId: resourceState.thread.threadId,
374374
turnId: activeTurnId,

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

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@ import {
3232
codexDynamicToolsFingerprint,
3333
codexLegacyDynamicToolsFingerprint,
3434
} from "./thread-lifecycle.js";
35-
36-
const CODEX_META_KEY = "__openclaw";
35+
import { hasCodexMirrorOrigin } from "./transcript-mirror-attestation.js";
36+
import { readMirrorIdentity } from "./upstream-prompt-provenance.js";
3737

3838
function isRestrictivePromptToolsAllow(toolsAllow: string[] | undefined): boolean {
3939
return toolsAllow !== undefined && !toolsAllow.some((name) => name.trim() === "*");
@@ -343,15 +343,7 @@ export async function prepareCodexAttemptPrompt(context: CodexAttemptContext) {
343343
if (message.role !== "user" && message.role !== "assistant") {
344344
return false;
345345
}
346-
const meta = CODEX_META_KEY in message ? message[CODEX_META_KEY] : undefined;
347-
const mirrorIdentity =
348-
meta && typeof meta === "object" && !Array.isArray(meta)
349-
? (meta as Record<string, unknown>).mirrorIdentity
350-
: undefined;
351-
const mirrorOrigin =
352-
meta && typeof meta === "object" && !Array.isArray(meta)
353-
? (meta as Record<string, unknown>).mirrorOrigin
354-
: undefined;
346+
const mirrorIdentity = readMirrorIdentity(message);
355347
const timestamp =
356348
typeof message.timestamp === "number"
357349
? message.timestamp
@@ -364,8 +356,8 @@ export async function prepareCodexAttemptPrompt(context: CodexAttemptContext) {
364356
typeof message.idempotencyKey === "string" &&
365357
message.idempotencyKey.startsWith("codex-app-server:")
366358
) &&
367-
mirrorOrigin !== "codex-app-server" &&
368-
!(typeof mirrorIdentity === "string" && mirrorIdentity.startsWith("codex-app-server:")) &&
359+
!hasCodexMirrorOrigin(message) &&
360+
!mirrorIdentity?.startsWith("codex-app-server:") &&
369361
Number.isFinite(timestamp) &&
370362
timestamp > (Number.isFinite(cutoff) ? cutoff : 0)
371363
);

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

Lines changed: 65 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -4827,45 +4827,60 @@ describe("runCodexAppServerAttempt", () => {
48274827
});
48284828
});
48294829

4830-
it.each([
4831-
{ label: "completed turn", failure: undefined, expectedContext: true },
4832-
{
4833-
label: "provider overload after the tool result",
4834-
failure: {
4835-
message: "Selected model is at capacity. Please try a different model.",
4836-
codexErrorInfo: "serverOverloaded",
4830+
it.each(
4831+
[
4832+
{ label: "completed turn", failure: undefined, expectedContext: true },
4833+
{
4834+
label: "provider overload after the tool result",
4835+
failure: {
4836+
message: "Selected model is at capacity. Please try a different model.",
4837+
codexErrorInfo: "serverOverloaded",
4838+
},
4839+
expectedContext: true,
48374840
},
4838-
expectedContext: true,
4839-
},
4840-
{
4841-
label: "usage limit after the tool result",
4842-
failure: {
4843-
message: "Usage limit exceeded.",
4844-
codexErrorInfo: "usageLimitExceeded",
4841+
{
4842+
label: "usage limit after the tool result",
4843+
failure: {
4844+
message: "Usage limit exceeded.",
4845+
codexErrorInfo: "usageLimitExceeded",
4846+
},
4847+
expectedContext: false,
48454848
},
4846-
expectedContext: false,
4847-
},
4848-
{
4849-
label: "unauthorized response after the tool result",
4850-
failure: {
4851-
message: "Unauthorized.",
4852-
codexErrorInfo: "unauthorized",
4849+
{
4850+
label: "unauthorized response after the tool result",
4851+
failure: {
4852+
message: "Unauthorized.",
4853+
codexErrorInfo: "unauthorized",
4854+
},
4855+
expectedContext: false,
48534856
},
4854-
expectedContext: false,
4855-
},
4856-
])(
4857-
"captures the complete mirrored branch through a settled tool-result boundary for a $label",
4858-
async ({ failure, expectedContext }) => {
4857+
].flatMap((scenario) =>
4858+
[false, true].map((oversizedHistory) => ({ scenario, oversizedHistory })),
4859+
),
4860+
)(
4861+
"preserves settled finalization eligibility for a $scenario.label (oversized history: $oversizedHistory)",
4862+
async ({ scenario: { failure, expectedContext }, oversizedHistory }) => {
48594863
const storePath = path.join(tempDir, "settled-finalization-context.sqlite");
48604864
const sessionId = "session-settled-finalization-context";
48614865
const sessionFile = `agent:main:${sessionId}`;
48624866
const workspaceDir = path.join(tempDir, "workspace-settled-finalization-context");
48634867
const harness = createStartedThreadHarness();
48644868
const params = createParams(sessionFile, workspaceDir);
48654869
await attachSqliteSessionTarget(params, storePath, sessionId);
4870+
if (oversizedHistory) {
4871+
for (let index = 0; index < 201; index += 1) {
4872+
await appendSqliteHistoryMessage(
4873+
params,
4874+
userMessage(`Prior message ${index}`, index + 1),
4875+
);
4876+
}
4877+
}
48664878
params.prompt = "Send the update to Alice.";
48674879
const run = runCodexAppServerAttempt(params);
48684880
await harness.waitForMethod("turn/start");
4881+
const emptyAssistant = { type: "agentMessage", id: "empty-assistant", text: "" };
4882+
await harness.notify(itemNotification("item/started", emptyAssistant));
4883+
await harness.notify(itemNotification("item/completed", emptyAssistant));
48694884
await harness.notify(
48704885
itemNotification("item/started", {
48714886
type: "commandExecution",
@@ -4904,16 +4919,29 @@ describe("runCodexAppServerAttempt", () => {
49044919
const result = await run;
49054920
expect(Boolean(readAttemptTerminal(result).promptError)).toBe(Boolean(failure));
49064921
expect(Boolean(result.settledTurnFinalizationContext)).toBe(expectedContext);
4907-
if (result.settledTurnFinalizationContext) {
4922+
expect(result.currentAttemptAssistant).toBeDefined();
4923+
expect(result.replayMetadata).toMatchObject({
4924+
hadPotentialSideEffects: true,
4925+
replaySafe: false,
4926+
});
4927+
expect(result.itemLifecycle).toMatchObject({
4928+
startedCount: 2,
4929+
completedCount: 2,
4930+
activeCount: 0,
4931+
});
4932+
if (expectedContext && oversizedHistory) {
4933+
expect(result.settledTurnFinalizationContext).toEqual({ source: "unavailable" });
4934+
expect(Object.isFrozen(result.settledTurnFinalizationContext)).toBe(true);
4935+
} else if (result.settledTurnFinalizationContext) {
49084936
expect(result.settledTurnFinalizationContext).toMatchObject({
4909-
source: "openclaw-transcript",
4910-
messages: [
4937+
source: "harness",
4938+
data: [
49114939
expect.objectContaining({ role: "user" }),
4912-
expect.objectContaining({ role: "assistant" }),
4913-
expect.objectContaining({ role: "toolResult", toolCallId: "tool-settled" }),
4940+
expect.objectContaining({ type: "function_call" }),
4941+
expect.objectContaining({ type: "function_call_output", call_id: "tool-settled" }),
49144942
],
49154943
});
4916-
expect(Object.isFrozen(result.settledTurnFinalizationContext.messages)).toBe(true);
4944+
expect(Object.isFrozen(result.settledTurnFinalizationContext)).toBe(true);
49174945
}
49184946
},
49194947
);
@@ -4985,14 +5013,14 @@ describe("runCodexAppServerAttempt", () => {
49855013
});
49865014
expect(result.itemLifecycle).toEqual({ startedCount: 1, completedCount: 1, activeCount: 0 });
49875015
expect(result.settledTurnFinalizationContext).toMatchObject({
4988-
source: "openclaw-transcript",
4989-
messages: [
5016+
source: "harness",
5017+
data: [
49905018
expect.objectContaining({ role: "user" }),
4991-
expect.objectContaining({ role: "assistant" }),
4992-
expect.objectContaining({ role: "toolResult", toolCallId: "tool-settled" }),
5019+
expect.objectContaining({ type: "function_call" }),
5020+
expect.objectContaining({ type: "function_call_output", call_id: "tool-settled" }),
49935021
],
49945022
});
4995-
expect(Object.isFrozen(result.settledTurnFinalizationContext?.messages)).toBe(true);
5023+
expect(Object.isFrozen(result.settledTurnFinalizationContext)).toBe(true);
49965024
});
49975025
it("preserves every command failure from official app-server events", async () => {
49985026
const sessionFile = path.join(tempDir, "session-multi-command-failure.jsonl");

0 commit comments

Comments
 (0)