Repository navigation
fix(agents): omit empty none runtime-fact sections from the tail carrier - #160174
davidberardozzi wants to merge 6 commits into
Conversation
Literal none snapshots for idle process/subagent/media/exec facts made buildRuntimeContextCustomMessage attach on every turn, which pins local prefix caches at the system prompt. Keep none only when append-only runtime context needs an explicit empty supersede. Fixes #150286
…urn context Retained native sessions keep the prior turn facts across CLI turns. Without the preservation flag, a vanished active media task leaves the stale active snapshot as the model last known state. Pass includeEmptySnapshots so an explicit empty snapshot supersedes it.
Cover the CLI active-to-empty media transition through buildCliTurnAppendContext, give the private-transcript and required-maintenance fixtures a non-empty exec fact so the human turn carrier is observed with content, assert the at-rest no-carrier behavior in the subagent facts flow, and keep the append-only policy emitting the explicit empty subagent snapshot.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed September 29, 2026, 11:48 AM ET / 15:48 UTC (Revision 5). ClawSweeper reviewWhat this changesThe branch omits empty runtime facts from ordinary agent requests while retaining explicit empty snapshots for append-only and CLI sessions, and updates the related tests and documentation. Merge readiness✅ Ready for maintainer review Current main still emits information-free runtime context on idle turns. This PR addresses that behavior, preserves clearing snapshots for retained contexts, and has no supported blocking finding. Priority: P2 Review scores
Verification
How this fits togetherOpenClaw adds current process, subagent, media-task, and executable facts to an agent request after its conversation history. Whether that context message is present affects what the model receives and how later requests reuse the prompt cache. flowchart LR
A[Available tools] --> C[Runtime fact builder]
B[Active work] --> C
D[Transcript policy] --> C
C --> E{Facts to send?}
E -->|Yes| F[Current-turn context message]
E -->|No| G[No context message]
F --> H[Model request]
G --> H
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +26, Tests +231, Docs 0. Total +257 across 12 files. View PR surface stats
Review metricsNone. Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Keep idle ordinary turns free of an information-free carrier while retaining explicit clearing facts wherever earlier facts remain in the model context. Do we have a high-confidence way to reproduce the issue? Yes. Current main's source shows the idle sections, and the PR records a five-turn agent --local before-and-after run; I did not execute that scenario. Is this the best way to solve the issue? Yes. Changing the fact producer removes empty ordinary-turn output while the callers preserve clearing snapshots where prior facts remain relevant. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against bcc6b571c448. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (4 earlier review cycles)
|
|
Confirmed affected on a self-hosted engine, with a controlled counterfactual that isolates the carrier as the only variable. Environment
The counterfactual
Identical bytes, identical client, identical engine process — only the tail ordering differs. That is the frontier argument from the description, confirmed on a second engine: 23,765 tokens at the measured 820.7 tok/s is ~29 s, which is the TTFT seen on every turn. Before landing there I ruled out the other shape differences, reading the engine's own The carrier in this traffic is entirely empty. Both captured bodies (67 and 69 messages) end with two identical 262-char carriers: With no exec session and no subagent, Scope note, not a request. With a live exec session or subagent the carrier has real content, the tail moves again, and misses return — I read that as the root cause #158898 holds. For an idle session the empty case is the whole of it. One related finding while checking this: on a custom provider |
|
One measurement from a local engine that may be worth folding in, on top of the producer-side fix. What we saw. Our route is a config-defined so ~56 tokens (~0.9 s TTFT at ~95 t/s) are re-prefilled per turn for content the model already Why it is not covered by the empty-snapshot rule. You deliberately keep literal Possible complementary refinement. Drop the carrier when it is byte-identical to the one sent Related. #164804 (open, by us) covers the other half of the same problem: a config-defined or |
|
Superseded by #163471 (merged 2026-10-03), which adopted the empty-snapshot direction contributed here: current main now omits the reported idle runtime-fact sections (see the 2026-10-06 re-review on #150286). The before/after measurements in this PR body remain the supporting evidence for that direction. Closing so the issue cluster reflects the merged state; reopen if the merged path regresses. |
Fixes #150286
Supersedes #150290
This PR carries the fix for #150286 on top of current main. Bartok9's original commit
e54ca31208(single commit, basef75b2669) is rebased onto maine71b911fc8eas040b8999037, author preserved, commit not amended: authorship of the fix stays with Bartok9. On top of his commit this PR adds the CLI fix requested in review (39a658555fe), the test repairs (8de92f4c496), and a formatting-only commit (326c9caae9, 2026-09-29) that brings the changed test file into the repo'soxfmtstyle.What Problem This Solves
Fixes: prompt cache reuse stops growing across consecutive requests when the runtime context carrier is appended to every request with empty sections ("Active exec sessions: none", "## Active Subagents none", media tasks none) while the tracked tools are merely available and nothing is running.
User Impact
User impact: in a session where the runtime tools are available but nothing is active, consecutive requests reuse the shared prefix of the prompt instead of reprocessing it. In the measured five-turn session, reuse goes from 0.0% on main to 99.7% on the fix for turns 2 to 5, and per-turn TTFT on turns 3 to 5 goes from 2.1 s to 123 ms. The measurement was made on a prompt of about 14.5k tokens; the cost avoided grows with prompt length, because the re-prefill covers the whole prompt on every turn.
Why This Change Was Made
The carrier is appended as the last message of every request, and it is not kept in the history of the next one. The engine records its reuse frontier at the end of what it processed, the carrier included, so on the next request that frontier is no longer a prefix: the two streams diverge exactly where the carrier used to sit. On an engine whose reuse is all-or-nothing at the exact frontier this is a full miss, which is the 0.0% we measured. On an engine that falls back to an earlier point the frontier stays pinned at the system prompt, which is the 18,683 that djl11 reports on #150286 while the prompt grows to 238k.
The change omits the empty sections, and keeps the explicit empty snapshot only where the append-only policy (
appendOnlyRuntimeContext) requires one.This is also why the fix belongs at the producer. The text filter suggested in #150286 would drop those empty snapshots on append-only routes too, where they are what supersedes an earlier active fact, as the ClawSweeper review of the issue pointed out. The producer-level change keeps them there.
Changes
Rebase and port. The first rebase (onto
7eaaeafdc1, 2026-09-24) had one conflict, insrc/agents/runtime-facts-prompt.ts: #153656 movedbuildMediaTaskRuntimeContextafter this PR was opened, so the hunk that modified it had to be carried into the new file. That move also added themusic_generatetool (the base of #150290 had image and video only). The resolution keeps main's imports: thebuildRuntimeFactsContextchanges (theincludeEmptySnapshotsparameter, the process and subagent sections) are applied inruntime-facts-prompt.ts, and the media constructor signature change is carried intomedia-generation-task-status.ts. The loop over the enabled tools now covers the three tools of main (image_generate,music_generate,video_generate). The branch was then rebased ontoaea578dbe03(2026-09-27): #159179 replaced the media task lookup after the first port, swapping the asyncprepareMediaGenerationTaskLookupfor the synchronouslistMediaGenerationOperations, so theincludeEmptySnapshotslogic was grafted onto the new synchronous source and the two media test hunks were adapted to the new fixtures. Diff on the current base: 12 files, +333/-76.CLI caller. The ClawSweeper review pointed at
src/agents/cli-runner/prepare.ts; #153656 moved that caller since, so the fix lands inbuildCliTurnAppendContextinsrc/agents/cli-runner/prompt-context.ts. It passesincludeEmptySnapshots: truefrom the CLI caller (3 lines). A resumed CLI session keeps its context, and when a media task vanishes, without an explicit empty snapshot the last known active snapshot stays the model's state. With the flag, the task-less turn emits## Media Generation Tasks / - tool=…; none, which supersedes the previous active state explicitly, the same mechanism as the embedded-side append-only policy.Tests. Three test files that the change broke were repaired without weakening the property each one protects, and a transition test was added for the CLI case (active media task, then none). Details of what each file protects are under Evidence.
Evidence
Tests
Targeted scope, not the full suite: 7 test files, run with
--maxWorkers=1per the repo's testing guidance. All 7 pass, including the two new tests.Measured durations,
pnpm test <file> --maxWorkers=1, 2026-09-29 on head326c9caae9:src/agents/cli-runner/prepare.test.tssrc/agents/embedded-agent-runner/run/attempt.subagent-runtime-facts.test.tssrc/auto-reply/reply/agent-runner-memory.private-transcript.test.tssrc/auto-reply/reply/agent-runner-required-maintenance.pending-input.test.tssrc/agents/runtime-facts-prompt.test.tssrc/agents/embedded-agent-runner/run/attempt-prompt-context.test.tssrc/agents/embedded-agent-runner/run/attempt.media-hint-cache-boundary.test.tsTotal about 1.5 minutes for 239 tests.
src/agents/cli-runner/prepare.test.ts:supersedes a vanished active media task with an explicit empty snapshot (plugin execution %s), run withit.each([false, true]).src/agents/embedded-agent-runner/run/attempt.subagent-runtime-facts.test.ts:keeps emitting the explicit empty subagent snapshot under the append-only policy.The three files that were failing, and how each property stays protected:
src/agents/embedded-agent-runner/run/attempt.subagent-runtime-facts.test.tsprotects system-prompt stability across child state, and the transport of child facts into the carrier after history. Thequeuedandrunningcaptures (non-empty facts) and the stability assertions are kept as-is. The at-rest assertion used to expect a carrier containing## Active Subagents\nnone; it now expects no customopenclaw.runtime-contextmessage at all, since the snapshot is omitted rather than emptied. The added test keeps the append-only case covered: same queued-then-reset scenario underappendOnlyRuntimeContext: true, and after the children finish the carrier still carries the explicit empty snapshot, which that policy requires.src/auto-reply/reply/agent-runner-memory.private-transcript.test.tsprotects that the carrier attached to the human turn is its own, assembled for that turn, not the one from the memory inference. The carrier after the human turn at the expected position is kept; it is now inspected, contains a real exec fact (Active exec sessions:withexec-a running), and does not contain## Active Subagents, the empty section no longer being emitted outside append-only.src/auto-reply/reply/agent-runner-required-maintenance.pending-input.test.tsprotects that the foreground-turn carrier is built for the approved user message, not replayed from the maintenance. The assertions on the approved input itself are intact; the carrier now carries real content, same method as above.No assertion was removed without a replacement: the one
expectremoved is the same filter moved into a variable with the sametoHaveLength(1)matcher; 14expects were added; no matcher was widened.One file from the set CI reported as failing,
src/agents/embedded-agent-runner/run/attempt.media-hint-cache-boundary.test.ts, does not reproduce locally: it passes on main7eaaeafdc1and on the rebased branch. It mocksbuildMediaTaskRuntimeContextand tests system-prompt stability around an in-flight media task, which the omission of empty sections does not touch.Local checks
Whole-repo
pnpm format:checkpasses.pnpm check:docspasses: 14,625 doc links checked with 0 broken, changelog and docs mirrors checked.pnpm tsgo:corepasses. oxlint passes on the 12 changed files. For thecheck:changedgate: guards, typecheck and lint pass; the import-cycles step was not run locally (machine memory constraint); CI runs it.Real before/after proof
Two runtime-only builds (
OPENCLAW_RUN_NODE_SKIP_DTS_BUILD=1), the documented path of this repo (scripts/build-all.mts,resolveBuildAllStepsandFULL_RUNTIME_ONLY_STEPS; the openclaw update program uses the same path, seedocs/cli/update/how-updates-run.mdanddocs/install/updating/update-methods.md). The proof covers runtime behavior, not a full build with type declarations. Two isolated test instances with byte-identical configs: only the launch directory, hence the build, changed. State purged before each pass. Engine: NInfer, documented semantics: "Reuse is all-or-nothing at the exact frontier. There is no fallback to common-prefix matching." Scenario: five identical turns per pass, toolsprocessandsessions_spawnavailable and at rest, which is the case the fix targets. Engine counters:Mean of turns 2 to 5: main 0.0%, fixed 99.7%, a 99.7 point difference.
Limitation: the authoritative counter is the engine's. In this path (
agent --local) the openclawusageblock is absent (supportsUsageInStreaming: false), so there is no openclaw cacheRead to cite here.Independent corroboration: the engine
startedlines show one message more per turn on main (3/5/7/9/11) than on the fixed branch (2/4/6/8/10), with otherwise identical signatures (tools 12,max output 8,192). On the openclaw side,runtimeContextCharsis 52 on the five main turns and 0 on the five fixed turns. Production traffic ran in parallel during the measurement; the fixed pass shows the cache was available and not evicted, so the collapse on main is attributable to the build, the only variable.Seconds and RSS
Method: same protocol as the runtime proof above (two runtime-only builds, two isolated instances with byte-identical configs, one five-turn session per pass,
agent --local), with/usr/bin/time -varound each turn to record wall-clock seconds and peak RSS of the openclaw process; measured 2026-09-28 against basee71b911fc8e(before) and this branch headfd424f0fa20(after).Turns 2 to 5, median and max:
e71b911fc8efd424f0fa20RSS is unchanged within noise (median +0.6%, max +1.9%): the fix removes a few hundred bytes of prompt content per turn, not memory. The wall-clock gain of about 1.5 s per turn tracks the engine TTFT drop; the remainder of each turn is fixed CLI startup overhead. The before pass reproduces the defect on the current base (0.0% reuse,
runtimeContextChars52 on every turn) and the after pass shows 99.7% reuse withruntimeContextChars0, same as the earlier proof on the previous base.Independent confirmation
djl11 confirmed the defect on #150286 (comment of 2026-09-22), on OpenAI's own endpoint:
In his replay, the only element that changes between two consecutive requests is the trailing carrier, added as a second consecutive
usermessage with the contents "Active exec sessions: none", "Active Subagents: none" and the media tasks at none.His conclusion:
Known gaps
a34353a5df0on 2026-09-29. One conflict, insrc/agents/embedded-agent-runner/run/attempt.subagent-runtime-facts.test.ts, where test(agents,codex,config): remove low-value tests (batch d083) #160309 had trimmed theit.each([false, true])to a single code-mode test: resolved by keeping main's test structure, with our at-rest carrier omission and our append-only test unchanged.src/gateway/github-publication-personal-pending.test.ts(rechecks a terminal receipt when confirming an older pending read) also fails on current main ata34353a5df0with the same assertion (expected 'failed' to be 'needs_confirmation'); the file is outside this PR.ui/src/e2e/chat-stop-finished-run.real-gateway.e2e.test.ts(restores the composer after Stop targets a run the Gateway already finished) also fails on current main ata34353a5df0with the same 10 s locator timeout; the file is outside this PR.