Skip to content

fix(agents): stabilize user-turn serialization across turns to preserve prompt cache - #90811

Merged
jalehman merged 15 commits into
openclaw:mainfrom
Marvinthebored:fix-cache-stable-user-turn-serialization
Jun 6, 2026
Merged

jalehman merged 15 commits into
openclaw:mainfrom
Marvinthebored:fix-cache-stable-user-turn-serialization

Conversation

@Marvinthebored

@Marvinthebored Marvinthebored commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

AI-assisted PR (Claude). Marked per CONTRIBUTING; human-run real-behavior proof from a live setup is below.

Summary

What problem does this PR solve? — The gateway decorates the current user message (a [timestamp] prefix from #3658 + a content-block wrap) but does not persist the decoration. When that message ages into history it reverts to its bare stored string, so its wire bytes change and the provider prompt cache is invalidated from that message to the end of the prompt — on every new user turn.

Why now? — On anthropic-messages this re-writes the suffix at the 1.25× cache-write premium every turn and never collects the 0.1× reads, so it costs more than not caching at all. It also hits openai-completions and local vLLM/llama.cpp/Ollama (slower prefill). Full analysis: #90810.

Intended outcome — Every user message serializes byte-identically whether it is the current turn or history, so the cached prefix is reused across turns.

Out of scope — openai-chatgpt-responses (already immune via server-side continuation); the separate cache_control mechanisms in #86063 and the merged tool-loop fix #89488.

Success looks like — same user message is byte-identical as current turn and as history; cache_read tracks the growing prefix while cache_write collapses to the new delta.

Reviewer focus — (1) the boundary stamp is deterministic per message and never mutates on aging; (2) content-form canonicalization is applied only to text-only turns and does not alter attachment/image turns that legitimately need block arrays.

Linked context

Closes #90810

Related #86063 (different mechanism — cache_control placement / metadata strip), #89488 (merged, separate slice), #3658 (the feature this regresses from; kept intact).

Requested by a maintainer or owner? — No; filed proactively with the issue above.

How it works

  • normalizeMessagesForLlmBoundary now stamps every user turn (current and historical) from that message's own stored timestamp. Storage stays bare; the stamp is deterministic, so bytes never change as a message ages.
  • Text-only user turns canonicalize to a plain-string content (matching how history is stored/replayed); attachment/image turns keep their block arrays.
  • The four transient injectTimestamp call sites (chat.ts, agent.ts, tui/embedded-backend.ts, server-restart-sentinel.ts) are removed in favor of the single boundary stamp.

This keeps #3658 intact (same prefix-on-the-message format small local models parse reliably) and, as a bonus, the model now sees every message's timestamp — real historical time awareness, not just "now".

Real behavior proof (required for external PRs)

  • Behavior addressed: prompt cache invalidated on every new user turn on full-resend transports.
  • Real environment tested: OpenClaw 2026.6.1 GA, macOS 15 (Darwin 24.6.0), Node 25.9.0, npm-global install; live traffic on claude-opus-4-8 over an Anthropic-Messages-compatible provider, plus a transport-level wire capture on an OpenAI-compatible endpoint.
  • Exact steps or command run after this patch: built and swapped the patched dist into the live install; ran a normal multi-turn conversation; recorded the per-turn usage fields (input / cache_read / cache_write) and cross-checked them token-for-token against the provider's own billing dashboard. Separately captured two consecutive outbound request bodies and diffed the previous user message's serialization.
  • Evidence after fix (copied live output): copied live output from a ~30-minute multi-turn session: cache_read climbed with the conversation 83,300 → 85,789 while cache_write was the new delta only (27–713 tokens; write-share ~26% → ~1.4%). Reconciliation was token-exact vs the provider dashboard on every sampled turn (e.g. read 83,882 + write 470 = 84,352 cached). After a >5-min TTL gap, a single full re-write then reads resumed — impossible under the bug. Wire diff: the previous user message is now byte-identical as current turn and as history (before: decorated block "content":[{…}] vs bare string "content":"…").
  • Observed result after fix: prefix reused across turns; per-turn cost dropped from re-write-priced to read-priced.
  • Before evidence: pre-fix, cache_read was pinned at the static system+tools floor (~53,875) with the suffix re-billed as cache_creation every turn (worst case ~131k tokens re-written in one tool-heavy turn).
  • What was not tested: (1) decoration-as-sole-cause is wire-isolated on openai-completions; on anthropic-messages it is inferred (shared boundary serialization) but not separately wire-captured, because that path also carries cache_control. (2) the full pnpm build && pnpm check && pnpm test suite was not run end-to-end in this environment; targeted typechecks + the new regression test were run (below). (3) no codex review run.

Tests and validation

  • Commands run: tsgo core typecheck (clean) and tsgo core test typecheck (clean) on the rebased branch.
  • Regression coverage added: src/agents/embedded-agent-runner/run/attempt.llm-boundary.cache-stability.test.ts — asserts the same user turn serializes byte-identically as current vs historical at the LLM boundary.
  • What failed before this fix: that new test fails before the change (current sent decorated / historical sent bare) and passes after. Validated fail-before/pass-after.
  • The existing attempt.llm-boundary suite was extended to cover the boundary stamp.

Risk checklist

  • User-visible behavior change? Yes (minor): every user turn now carries a deterministic per-message [timestamp] prefix at the LLM boundary (previously only the current turn). This is the Feature: Gateway should inject timestamps for TUI/web messages #3658 format, applied consistently.
  • Config / env / migration change? No.
  • Security / auth / secrets / network / tool-execution change? No. (Touched files are not under any CODEOWNERS secops pattern.)
  • Highest-risk area: content-form canonicalization could, if mis-scoped, flatten attachment/image turns that need block arrays.
  • Mitigation: canonicalization is gated to text-only turns; attachment/image turns keep arrays, covered by the boundary tests.

Current review state

  • Next action: maintainer review.
  • Waiting on: CI; maintainer review. "Allow edits by maintainers" left enabled on the fork branch.
  • Bot/reviewer comments addressed: none yet (new PR).

Investigated and implemented with AI assistance (Claude). cc @Peetiegonzalez

…ve prompt cache

The gateway transiently decorated the CURRENT user message with a
timestamp prefix (injectTimestamp, issue #3658) plus a content
array-wrap before sending it to the model, but did not persist that
decoration. As soon as the message aged into history, its bare stored
form differed from the decorated form the model had seen — its wire
bytes changed between turns. On every full-resend transport
(anthropic-messages, openai-completions, local OpenAI-compat) this
byte-instability invalidated the prompt cache from that message to the
end of the prompt on every single user turn.

This change single-sources the per-message timestamp stamp at the LLM
boundary. normalizeMessagesForLlmBoundary now stamps every user turn —
current AND historical — from each message's own `timestamp`, so the
serialization a message produces is identical whether it is the active
turn or a historical one. The transient inject-at-send-time call sites
are removed, and the content form is canonicalized so a text-only user
turn serializes byte-identically current vs historical. Storage stays
bare; the stamp is applied only at the boundary.

Net effect: byte-stable history across turns, so the prompt cache is no
longer invalidated on each user turn. As a bonus, models now see true
per-message historical timestamps rather than only the current turn's.
Verified live on the wire: the same user message is byte-identical as
the active turn and after it has aged into history.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling size: L triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels Jun 6, 2026
@clawsweeper

clawsweeper Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed June 6, 2026, 2:17 PM ET / 18:17 UTC.

Summary
The PR moves user-turn timestamping from gateway/TUI ingress to the LLM boundary, canonicalizes text-only user content, preserves CLI prompt timestamping, normalizes inbound timestamps, and adds cache-stability regression tests.

PR surface: Source +360, Tests +585. Total +945 across 17 files.

Reproducibility: yes. Current source shows the current user turn is stamped before runtime while transcript storage remains bare, and the PR body supplies live cache/wire evidence; I did not rerun the paid/live provider scenario locally.

Review metrics: 1 noteworthy metric.

  • Prompt compatibility surface: 1 model-visible default changed. Historical embedded user turns gain deterministic timestamp prefixes at provider boundary, which is useful for cache stability but changes existing prompts.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Get explicit maintainer sign-off on the historical timestamp prompt change.
  • Run fresh validation for the latest head across the touched agent/gateway boundary.

Risk before merge

  • [P1] Merging intentionally changes model-visible transcript bytes: historical embedded user turns that previously replayed as bare text will now carry deterministic timestamp prefixes at the LLM boundary.
  • [P1] The PR body reports targeted typechecks and a regression test, but not a full build/check/test pass after the latest head, so maintainers still need fresh normal validation before merge.

Maintainer options:

  1. Accept the prompt-byte rollout (recommended)
    Maintainers can approve the compatibility tradeoff, require fresh green checks on the latest head, and merge the boundary-stamping design as the canonical cache fix.
  2. Require a compatibility-preserving shape
    If historical prompt bytes must remain unchanged by default, ask for a revised design that preserves existing prompt rendering unless a documented migration or explicit mode is accepted.
  3. Pause if the prompt contract is too broad
    If the cache savings do not justify changing all embedded historical user turns, pause this PR and keep the narrower linked cache issues as the canonical work.

Next step before merge

  • [P2] The remaining blocker is maintainer judgment on the prompt compatibility tradeoff plus normal validation, not a narrow automated repair.

Security
Cleared: The diff does not touch workflows, dependencies, lockfiles, secrets handling, permissions, or downloaded code execution paths.

Review details

Best possible solution:

Land the single LLM-boundary stamping design only after maintainers explicitly accept the prompt-compatibility change and the latest head has fresh green validation for the touched agent/gateway surfaces.

Do we have a high-confidence way to reproduce the issue?

Yes. Current source shows the current user turn is stamped before runtime while transcript storage remains bare, and the PR body supplies live cache/wire evidence; I did not rerun the paid/live provider scenario locally.

Is this the best way to solve the issue?

Unclear until maintainers accept the compatibility tradeoff. If changing historical prompt bytes is acceptable, the LLM boundary is the right owner because it is the shared provider serialization point.

AGENTS.md: found and applied where relevant.

Codex review notes: model gpt-5.5, reasoning high; reviewed against 59365959d3b0.

Label changes

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes after-fix live installed-build output and wire-diff evidence showing cache reads resume and the prior user message serializes byte-identically.

Label justifications:

  • P2: This is a normal-priority performance/cost bug fix with limited blast radius but compatibility-sensitive prompt behavior.
  • merge-risk: 🚨 compatibility: The diff changes default model-visible serialization for existing embedded sessions during upgrade.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body includes after-fix live installed-build output and wire-diff evidence showing cache reads resume and the prior user message serializes byte-identically.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes after-fix live installed-build output and wire-diff evidence showing cache reads resume and the prior user message serializes byte-identically.
Evidence reviewed

PR surface:

Source +360, Tests +585. Total +945 across 17 files.

View PR surface stats
Area Files Added Removed Net
Source 10 419 59 +360
Tests 7 613 28 +585
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 17 1032 87 +945

What I checked:

Likely related people:

  • conroywhitney: Authored the merged gateway timestamp-injection PR that this PR is stabilizing. (role: introduced behavior; confidence: medium; commits: 35988d77ecfb; files: src/gateway/server-methods/agent-timestamp.ts, src/gateway/server-methods/agent.ts, src/gateway/server-methods/chat.ts)
  • Tak Hoffman: Merged the original timestamp-injection PR into main according to the merge commit metadata. (role: merger; confidence: medium; commits: 35988d77ecfb; files: src/gateway/server-methods/agent-timestamp.ts)
  • Vincent Koc: Current shallow blame attributes the existing timestamp helper and LLM-boundary code snapshot to this source import/grafted commit, making this a low-confidence routing hint only. (role: recent area contributor; confidence: low; commits: 2a48a2655b; files: src/gateway/server-methods/agent-timestamp.ts, src/agents/embedded-agent-runner/run/attempt.llm-boundary.ts)
  • jalehman: Live PR context shows assignment/review request and multiple head-branch commits adapting the patch after review. (role: current PR reviewer/integrator; confidence: medium; commits: db0a2eb57157, 68510aa4030a, 3572122df754; files: src/agents/embedded-agent-runner/run/attempt.ts, src/agents/embedded-agent-runner/run/attempt.llm-boundary.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jun 6, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. label Jun 6, 2026
@clawsweeper clawsweeper Bot added rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jun 6, 2026
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. label Jun 6, 2026
@jalehman jalehman self-assigned this Jun 6, 2026
@clawsweeper clawsweeper Bot added 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. and removed rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. labels Jun 6, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. label Jun 6, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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 Jun 6, 2026
@openclaw-barnacle openclaw-barnacle Bot added app: macos App: macos extensions: diagnostics-otel Extension: diagnostics-otel extensions: memory-core Extension: memory-core cli CLI command changes scripts Repository scripts commands Command implementations docker Docker and sandbox tooling extensions: minimax extensions: moonshot extensions: memory-wiki extensions: codex extensions: google labels Jun 6, 2026
@openclaw-barnacle openclaw-barnacle Bot removed docs Improvements or additions to documentation channel: imessage Channel integration: imessage labels Jun 6, 2026
@jalehman

jalehman commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

Merged via squash.

Thanks @Marvinthebored!

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

Labels

agents Agent runtime and tooling app: web-ui App: web-ui gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

3 participants