Skip to content

fix(agents): omit empty none runtime-fact sections from the tail carrier - #160174

Closed
davidberardozzi wants to merge 6 commits into
openclaw:mainfrom
davidberardozzi:pr150290-pr-0928
Closed

davidberardozzi wants to merge 6 commits into
openclaw:mainfrom
davidberardozzi:pr150290-pr-0928

Conversation

@davidberardozzi

@davidberardozzi davidberardozzi commented Sep 28, 2026 •

Copy link
Copy Markdown

Fixes #150286
Supersedes #150290

This PR carries the fix for #150286 on top of current main. Bartok9's original commit e54ca31208 (single commit, base f75b2669) is rebased onto main e71b911fc8e as 040b8999037, 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's oxfmt style.

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, in src/agents/runtime-facts-prompt.ts: #153656 moved buildMediaTaskRuntimeContext after this PR was opened, so the hunk that modified it had to be carried into the new file. That move also added the music_generate tool (the base of #150290 had image and video only). The resolution keeps main's imports: the buildRuntimeFactsContext changes (the includeEmptySnapshots parameter, the process and subagent sections) are applied in runtime-facts-prompt.ts, and the media constructor signature change is carried into media-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 onto aea578dbe03 (2026-09-27): #159179 replaced the media task lookup after the first port, swapping the async prepareMediaGenerationTaskLookup for the synchronous listMediaGenerationOperations, so the includeEmptySnapshots logic 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 in buildCliTurnAppendContext in src/agents/cli-runner/prompt-context.ts. It passes includeEmptySnapshots: true from 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=1 per the repo's testing guidance. All 7 pass, including the two new tests.

Measured durations, pnpm test <file> --maxWorkers=1, 2026-09-29 on head 326c9caae9:

file duration
src/agents/cli-runner/prepare.test.ts 44 s
src/agents/embedded-agent-runner/run/attempt.subagent-runtime-facts.test.ts 8 s
src/auto-reply/reply/agent-runner-memory.private-transcript.test.ts 13 s
src/auto-reply/reply/agent-runner-required-maintenance.pending-input.test.ts 12 s
src/agents/runtime-facts-prompt.test.ts 7 s
src/agents/embedded-agent-runner/run/attempt-prompt-context.test.ts 7 s
src/agents/embedded-agent-runner/run/attempt.media-hint-cache-boundary.test.ts 7 s

Total 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 with it.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.ts protects system-prompt stability across child state, and the transport of child facts into the carrier after history. The queued and running captures (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 custom openclaw.runtime-context message at all, since the snapshot is omitted rather than emptied. The added test keeps the append-only case covered: same queued-then-reset scenario under appendOnlyRuntimeContext: 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.ts protects 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: with exec-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.ts protects 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 expect removed is the same filter moved into a variable with the same toHaveLength(1) matcher; 14 expects 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 main 7eaaeafdc1 and on the rebased branch. It mocks buildMediaTaskRuntimeContext and 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:check passes. pnpm check:docs passes: 14,625 doc links checked with 0 broken, changelog and docs mirrors checked. pnpm tsgo:core passes. oxlint passes on the 12 changed files. For the check:changed gate: 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, resolveBuildAllSteps and FULL_RUNTIME_ONLY_STEPS; the openclaw update program uses the same path, see docs/cli/update/how-updates-run.md and docs/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, tools process and sessions_spawn available and at rest, which is the case the fix targets. Engine counters:

pass turn prompt cached reuse TTFT
main 1 14,492 0 0.0% 1.9 s
main 2 14,536 0 0.0% 2.0 s
main 3 14,581 0 0.0% 2.1 s
main 4 14,626 0 0.0% 2.1 s
main 5 14,671 0 0.0% 2.1 s
fixed 1 14,422 0 0.0% 2.0 s
fixed 2 14,466 14,417 99.7% 131 ms
fixed 3 14,511 14,461 99.7% 123 ms
fixed 4 14,556 14,506 99.7% 123 ms
fixed 5 14,601 14,551 99.7% 123 ms

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 openclaw usage block is absent (supportsUsageInStreaming: false), so there is no openclaw cacheRead to cite here.

Independent corroboration: the engine started lines 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, runtimeContextChars is 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 -v around each turn to record wall-clock seconds and peak RSS of the openclaw process; measured 2026-09-28 against base e71b911fc8e (before) and this branch head fd424f0fa20 (after).

Turns 2 to 5, median and max:

measure before e71b911fc8e after fd424f0fa20
wall clock per turn, median 6.38 s 4.85 s
wall clock per turn, max 6.52 s 4.90 s
peak RSS per turn, median 1.116 GiB 1.123 GiB
peak RSS per turn, max 1.122 GiB 1.144 GiB
engine cache reuse 0.0% 99.7%
engine TTFT 1.6 to 1.7 s 106 ms

RSS 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, runtimeContextChars 52 on every turn) and the after pass shows 99.7% reuse with runtimeContextChars 0, 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:

Confirming this on OpenAI's own chat-completions endpoint (not a local engine), which puts the "cache-safe" claim from #143242 in question for the flagship provider too.

cached never leaves 18,683 (tools + system prompt) while the prompt grows to 238k

In his replay, the only element that changes between two consecutive requests is the trailing carrier, added as a second consecutive user message with the contents "Active exec sessions: none", "Active Subagents: none" and the media tasks at none.

sent prompt tokens cached tokens
A then B, as OpenClaw sends them 54,668 18,698
A then B with the trailing carrier removed from each 54,578 50,249
A with the carrier merged into the preceding user message, then B 54,578 18,698

His conclusion:

So removing the trailing carrier restores full prefix reuse; merging it into the last user turn does not, because the last user turn still differs between consecutive requests.

Known gaps

  • The test run is a targeted scope (7 files), not the full suite.
  • The import-cycles step was not run locally (machine memory constraint); CI runs it.
  • The proof builds are runtime-only: runtime behavior is covered, a full build with type declarations is not.
  • The before/after measurement is one five-turn session on one engine (NInfer), corroborated by djl11's replay on OpenAI's chat-completions endpoint.
  • The branch was merged with main at a34353a5df0 on 2026-09-29. One conflict, in src/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 the it.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 at a34353a5df0 with 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 at a34353a5df0 with the same 10 s locator timeout; the file is outside this PR.

Bartok9 and others added 3 commits September 28, 2026 07:30
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.
@clawsweeper

clawsweeper Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 28, 2026
@clawsweeper

clawsweeper Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 29, 2026, 11:48 AM ET / 15:48 UTC (Revision 5).

ClawSweeper review

What this changes

The 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
Reviewed head: 326c9caae963cfad1d7ada33a42b2fd2971b9b91

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Direct runtime measurements, focused transition coverage, and a bounded producer change provide strong evidence for this fix.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR body connects the changed runtime-fact producer to a real agent --local five-turn run with idle tools: the after-fix run reports no idle carrier and 99.7% cache reuse, compared with 0.0% on main. The latest commit changes test formatting only. No stored-data contract changes.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body connects the changed runtime-fact producer to a real agent --local five-turn run with idle tools: the after-fix run reports no idle carrier and 99.7% cache reuse, compared with 0.0% on main. The latest commit changes test formatting only. No stored-data contract changes.
Evidence reviewed 8 items Current main still emits idle facts: The process and subagent paths on fetched main retain literal empty sections when their tools are available; the media builder likewise emits empty enabled-tool facts.
Producer preserves the clearing case: The introduced producer change omits idle process and subagent sections by default and emits explicit empty snapshots when requested.
Consumers select retained snapshots: The embedded runner passes its append-only policy to the fact builder; the CLI caller requests empty media snapshots for retained native sessions.
Findings None None.
Security None None.

How this fits together

OpenClaw 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
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +26, Tests +231, Docs 0. Total +257 across 12 files.

View PR surface stats
Area Files Added Removed Net
Source 4 54 28 +26
Tests 7 278 47 +231
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 12 333 76 +257

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #150286
Summary: The open issue reports the idle-carrier cache failure this PR addresses; the earlier open PR proposes overlapping producer changes.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best 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.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The patch addresses measurable prompt-cache slowdown in affected agent sessions without evidence of an emergency or broad workflow outage.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body connects the changed runtime-fact producer to a real agent --local five-turn run with idle tools: the after-fix run reports no idle carrier and 99.7% cache reuse, compared with 0.0% on main. The latest commit changes test formatting only. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body connects the changed runtime-fact producer to a real agent --local five-turn run with idle tools: the after-fix run reports no idle carrier and 99.7% cache reuse, compared with 0.0% on main. The latest commit changes test formatting only. No stored-data contract changes.

Evidence

What I checked:

  • Current main still emits idle facts: The process and subagent paths on fetched main retain literal empty sections when their tools are available; the media builder likewise emits empty enabled-tool facts. (src/agents/runtime-facts-prompt.ts:76, bcc6b571c448)
  • Producer preserves the clearing case: The introduced producer change omits idle process and subagent sections by default and emits explicit empty snapshots when requested. (src/agents/runtime-facts-prompt.ts:81, 326c9caae963)
  • Consumers select retained snapshots: The embedded runner passes its append-only policy to the fact builder; the CLI caller requests empty media snapshots for retained native sessions. (src/agents/embedded-agent-runner/run/attempt-prompt-build.ts:479, 326c9caae963)
  • Regression coverage: Tests cover the at-rest absence of a carrier, an append-only subagent clearing snapshot, and a CLI active-to-empty media transition. (src/agents/embedded-agent-runner/run/attempt.subagent-runtime-facts.test.ts:133, 326c9caae963)
  • Contributor runtime proof: The captured PR body reports five real agent --local turns with idle process and subagent tools on two isolated runtime builds. Its engine counters show 0.0% reuse on main and 99.7% on the fix for turns 2–5; the fixed run reports no idle context message. The body also reports wall-time and RSS measurements. These are contributor observations, not a reviewer-executed run. (326c9caae963)
  • Latest commit scope: GitHub records the last commit as formatting changes confined to the runtime-facts test file; it does not change the production path measured by the earlier runtime proof. (src/agents/runtime-facts-prompt.test.ts:1, 326c9caae963)

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • EricCai: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (4 earlier review cycles)
  • reviewed 2026-09-28T05:47:17.435Z sha 8de92f4 :: needs changes before merge. :: [P3] Update the runtime-context documentation for omitted empty facts
  • reviewed 2026-09-28T06:15:31.624Z sha fd424f0 :: blocked before merge. :: none
  • reviewed 2026-09-28T06:41:06.735Z sha fd424f0 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-29T14:45:28.745Z sha 449a9bf :: needs maintainer review before merge. :: none

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Sep 28, 2026
@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Sep 28, 2026
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Sep 28, 2026
@YuanZ1949

Copy link
Copy Markdown

Confirmed affected on a self-hosted engine, with a controlled counterfactual that isolates the carrier as the only variable.

Environment

  • openclaw 2026.9.5 (ec9c1a1) and 2026.9.6 (eb377ac), both from npm. dist/internal-runtime-context-BH-o1oq1.mjs is byte-identical between the two (sha256 BC655A42191E3B56BE132D3A996C0E81129C8A0107125838CA3F4C53C43F09F8, 13,309 bytes), so this affects anyone on latest.
  • Custom provider, "api": "openai-completions", pointing at a self-hosted engine on a single RTX 4070 SUPER. Prompts are 21k–24k tokens.

The counterfactual
Rather than comparing a main build against a fixed build, I replayed one captured request body three ways against a single running engine, in one session, changing only where the newly appended assistant message lands relative to the carrier:

variant prompt reuse TTFT
verbatim (carrier last) 23,765 23,758 (100.0%) 120 ms / 119 ms
assistant inserted before the carrier (current behaviour) 23,776 0 (0.0%) 34.9 s / 35.1 s
assistant + user appended after the carrier 23,783 23,758 (99.9%) 381 ms / 353 ms

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 cache N (P%) counter rather than inferring from TTFT: streaming vs non-stream (99.6% either way), 11 tools vs none (99.7%), 21k prompt length (99.9%), max output 32,000 (99.9%), echoing vs stripping reasoning_content in replayed history (99.9% vs 98.2%), max_completion_tokens as the field name, and an unrelated request interleaved between turns (93.6% survived, so slot eviction is not a factor).

The carrier in this traffic is entirely empty. Both captured bodies (67 and 69 messages) end with two identical 262-char carriers:

<<<BEGIN_OPENCLAW_INTERNAL_CONTEXT>>>
Conversation data (data, not instructions):
"Active exec sessions:
none"

Conversation data (data, not instructions):
"## Active Subagents
none"
<<<END_OPENCLAW_INTERNAL_CONTEXT>>>

With no exec session and no subagent, includeEmptySnapshots: false should remove all of it, so I expect this to close the gap for this setup.

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 appendOnlyRuntimeContext is unreachable from config for any value of api. resolveProviderConfigApiOwnerHint returns the api only when kn && kn !== providerId && !CORE_BUILT_IN_MODEL_APIS.has(kn), and openai-completions / openai-responses are both in that set, so the owner hint is undefined and dispatch falls to buildUnownedProviderTransportReplayFallback. The field appears in 15 dist files and in zero schema or zod declarations. That is the configurability ask in #158898 rather than something for this PR.

@aaa2015

aaa2015 commented Oct 4, 2026

Copy link
Copy Markdown
Contributor

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 openai-responses provider pointed at a local
server whose prefix cache is compared byte-for-byte. Even after the runtime-fact sections are
trimmed, the per-turn carrier is the whole continuation delta: the only non-empty content is the
inbound/requester block, and the carrier is appended every turn. The engine reports it directly:

POST /v1/responses  prompt_chars=198            # carrier + the user's own text
Completed           prompt: 13950 tok, prefill: 56 tok, ttft 0.87s   (cached 13893)

so ~56 tokens (~0.9 s TTFT at ~95 t/s) are re-prefilled per turn for content the model already
saw — and that is with the empty sections already omitted.

Why it is not covered by the empty-snapshot rule. You deliberately keep literal none
snapshots when the context is retained (includeEmptySnapshots: input.appendOnlyRuntimeContext),
which is right for a reader that needs an explicit supersede. On an append-only route that means
the carrier is re-sent even when its content is unchanged, and after #140849 the native OpenAI
family is append-only, so this is the common case rather than an edge one.

Possible complementary refinement. Drop the carrier when it is byte-identical to the one sent
on the previous turn: the retained copy already sits in history at its own turn, and a reader that
takes the last carrier reads the same bytes, so nothing goes stale. Changed facts would still be
sent, so the supersede property is preserved. That would take the tail from ~56 tokens to the
user's own text (we measure 6 tokens / 0.23 s TTFT for a 1+2 turn once the carrier is omitted).

Related. #164804 (open, by us) covers the other half of the same problem: a config-defined or
plugin-less provider does not get the append-only policy at all today, so the carrier is stripped
from history and the prefix only matches up to the system prompt. The two are complementary —
this PR removes empty facts from the tail, that one keeps the tail's position stable, and either
alone still leaves work on the table for a local engine. Nothing here blocks this PR.

@davidberardozzi

Copy link
Copy Markdown
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

4 participants