Skip to content

fix(agents): carry current-turn inbound metadata in a tail runtime-context message for byte-stable prompt caching - #100272

Merged
obviyus merged 3 commits into
openclaw:mainfrom
Marvinthebored:fix/active-message-metadata-byte-stability
Jul 7, 2026
Merged

obviyus merged 3 commits into
openclaw:mainfrom
Marvinthebored:fix/active-message-metadata-byte-stability

Conversation

@Marvinthebored

@Marvinthebored Marvinthebored commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #100271

Reported-by: @Peetiegonzalez
cc: @Peetiegonzalez

Problem

The channel layer decorates the ACTIVE user message with an inbound-metadata block
("Conversation info (untrusted metadata)" / "Reply target of current user message" / sender /
forwarded / chat-history), composed at request-build time via buildInboundUserContextPrefix
(src/auto-reply/reply/inbound-meta.ts) → currentInboundContext. But the session store persists
the BARE user text, and stripHistoricalInboundMetadataFromUserMessages
(src/agents/embedded-agent-runner/run/attempt.llm-boundary.ts) strips that block from historical
user turns before replay. The active turn becomes the previous turn's history the instant a new
turn arrives, so its serialized bytes change retroactively — decorated as the active turn, bare as
history — on every single turn, invalidating any prefix/exact-match provider prompt cache from that
point onward, every turn. (#90811 fixed the timestamp half of this same active/historical
asymmetry; this is the metadata half.)

Fix — tail-placed runtime-context carrier

This reworks the earlier "strip the active turn" approach (which lost model-visible context, the
blocker ClawSweeper raised) into one that keeps the context AND recovers the cache cost.

Current-turn inbound metadata is routed out of the user prompt and into the existing hidden
runtime-context custom message (the mechanism from #89428 — credited below), and that carrier is
relocated to the absolute tail of the wire request — after the active user turn and any
tool-call scaffolding:

  • The user turn stays bare and byte-identical in both the active and historical positions (the
    cache-stability guarantee; the same property fix(agents): stabilize user-turn serialization across turns to preserve prompt cache #90811 established for the timestamp).
  • The volatile carrier sits at the tail, so when it vanishes next turn the first differing byte
    lands exactly where the next turn's new bytes (the assistant reply) begin anyway. The request is
    an append-only prefix-extension through the active user turn — only the trailing carrier is
    ever re-billed.
  • Providers must not anchor a cache breakpoint on the volatile carrier, or breakpoint quantization
    forfeits the win. A durable marker (UserMessage.runtimeContextCarrier, set by convertToLlm
    from the carrier's details) lets the Anthropic and OpenAI-completions transports skip it when
    selecting the deepest cache_control breakpoint, keeping the anchor on the last stable user turn.

Storage stays BARE (the documented invariant in src/sessions/user-turn-transcript.ts is
preserved); runtime-only turns (room events) keep their existing inline behavior when they have no
bare user turn to protect; legacy sessions with bare-stored user messages are unchanged.

Why tail placement, not before-user (the divergence-offset math)

The runtime-context carrier is per-turn and stripped on replay, so it necessarily vanishes at its
slot next turn. Where that slot sits decides how much re-bills on a prefix cache:

Design Active user turn context First differing byte in request N+1 Prefix-cache cost
A. Strip active turn (prior PR) ❌ lost (ClawSweeper P1) at/after userN (bare both ways) append-only ✅
B. Before-user carrier (#89428 as-is) ✅ preserved at the carrier slot, which is before userN userN + tool loop re-bill every turn ❌
C. Tail carrier (this PR) ✅ preserved at the carrier slot, which is after userN (where the assistant reply begins anyway) append-only ✅

C is the only option that preserves current-turn context AND is append-only. B keeps context but
recovers almost none of the cache cost on prefix caches (and only breakpoint scraps on Anthropic),
because the carrier vanishing before userN re-bills the whole tail — the same magnitude as the
bug. This PR stacks on #89428's runtime-context handoff and adds the tail placement + the
transport breakpoint anchor.

Review

Reviewed with N adversarial gpt-5.5 (codex) sweeps — correctness of the carrier/placement path,
byte-identity/cache-divergence, compatibility & transcript readers, and test adequacy. Reviewed with 5 adversarial gpt-5.5 (codex) read-only sweeps — correctness of the carrier/placement path, byte-identity/cache-divergence, compatibility & transcript readers, test adequacy, plus a final consolidated pass. Found + fixed: (1) a second Anthropic cache-anchor path — the managed transport (src/agents/anthropic-transport-stream.ts + anthropic-payload-policy.ts, the OAuth/managed path) was still anchoring the deepest cache_control breakpoint on the relocated tail carrier; it now carries the same carrier opt-out; (2) missing provider-payload breakpoint tests for the managed Anthropic transport and OpenAI-completions (added). A theoretical runtime-only inline mutation was verified unreachable (room-event/system context is not strip-eligible, and non-room turns always have a non-empty body so are never runtime-only) and pinned with a byte-stability test. The final consolidated sweep came back clean.

Tests

  • internal-runtime-context.test.ts: relocateCurrentRuntimeContextCarrierToTail unit coverage
    (before-user → tail, past tool scaffolding, idempotent no-op, no-carrier, no-active-user).
  • attempt.llm-boundary.cache-stability.test.ts: the active user turn is bare with the carrier at
    the tail; the same message is byte-identical once aged to history (carrier gone); request N+1 is
    a strict prefix-extension of request N through the active user turn.
  • anthropic.test.ts: the deepest cache breakpoint anchors on the last stable user turn, skipping
    a trailing runtime-context carrier.
  • messages.test.ts: convertToLlm marks a runtime-context carrier so providers skip cache
    anchoring; ordinary custom messages are unmarked.
  • attempt.spawn-workspace.context-engine.test.ts: updated to assert current-turn metadata now
    rides the runtime-context carrier (bare user prompt), for both the normal and suppressed
    room-event paths.

Typecheck (node scripts/run-tsgo.mjs -p tsconfig.core.json): zero new errors (47 pre-existing
ui/ module-resolution errors present on unmodified upstream main too).

Full shard results vs pristine upstream/main baseline — zero NEW failures: agents-embedded-agent
1629/1629; unit-fast 11088 passed (4 pre-existing test/scripts/{check,verify}.test.ts failures,
identical on base); packages (ai/agent-core/llm-core) 390/390.

What Problem This Solves

The active user turn's serialized text differed from how that same turn is later replayed as
history: the channel layer decorated the active turn with an untrusted-metadata block that
stripHistoricalInboundMetadataFromUserMessages strips for every historical turn but left in place
for the turn currently being sent. Since the active turn becomes the previous turn's history the
instant the next turn arrives, its bytes changed retroactively at that point in the conversation on
every single turn — invalidating any prefix/exact-match provider prompt cache from that point
onward. This PR keeps the metadata model-visible (now on both the active turn and — via the tail
carrier — nowhere in replayed history, so history stays clean) while making the user turn
byte-stable.

Evidence

The byte-stability property this PR gives the user turn (bare + append-only in both positions) is
the same one measured for the active/historical asymmetry in #100271:

  • OpenAI (gpt-5.5, ChatGPT-OAuth, session-affinity header from fix(agents): send session_id affinity header to ChatGPT Responses backend #100233 applied): 81.8% → 90.6%
    TRUE cache-hit rate once the active user turn stops mutating.
  • Anthropic (claude-sonnet-4-6), whose cache matches only at explicit cache_control breakpoints:
    over a 12-turn session cacheWrite 60,208 → 10,051 tokens (-83%), cacheRead advancing
    monotonically instead of resetting to the same system-prompt breakpoint every turn. This PR's
    transport breakpoint anchor is what keeps that win under tail placement (the breakpoint stays on
    the stable user turn, not the volatile trailer).
  • DeepSeek / Kimi (incremental multi-prefix caches) absorb the mutation already and are
    neutral-to-slightly-positive — not a regression.

Unlike the strip approach those numbers were first measured under, this design preserves the
current-turn sender/reply/mention context for the model (addressing ClawSweeper's P1) — it moves
the context to the runtime-context carrier rather than deleting it. The only added cost over pure
strip is the trailing carrier's own bytes once per turn (read-priced, never part of a reused
prefix).

Full per-call tables and the Anthropic breakpoint mechanism:
https://raw.githubusercontent.com/Marvinthebored/openclaw/proof-assets-metadata-byte-stability/pr-proof/100272-metadata-byte-stability/EVIDENCE.md

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Jul 5, 2026
@clawsweeper

clawsweeper Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed July 6, 2026, 11:04 PM ET / 03:04 UTC.

Summary
The PR moves current-turn inbound metadata into a hidden tail runtime-context carrier, marks that carrier through LLM conversion, and updates Anthropic/OpenAI-compatible cache-control selection plus tests to skip volatile carrier messages.

PR surface: Source +139, Tests +365. Total +504 across 17 files.

Reproducibility: yes. source inspection shows current main prepends currentInboundContext into the active prompt while the LLM boundary strips that same metadata only after the turn becomes historical. I did not run tests because this review is read-only.

Review metrics: 1 noteworthy metric.

  • Plugin SDK helper signature: 1 exported helper gained a required parameter. The changed Anthropic payload helper is re-exported through provider-stream SDK barrels, so signature compatibility matters before merge.

Stored data model
Persistent data-model change detected: persistent cache schema: packages/agent-core/src/harness/messages.test.ts, persistent cache schema: packages/ai/src/providers/anthropic.test.ts, persistent cache schema: packages/ai/src/providers/openai-completions.test.ts, persistent cache schema: src/agents/anthropic-payload-policy.test.ts, persistent cache schema: src/agents/embedded-agent-runner/run/attempt.llm-boundary.cache-stability.test.ts, serialized state: packages/ai/src/providers/openai-completions.test.ts, and 5 more. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #100271
Summary: This PR is the open candidate fix for the active-turn inbound metadata byte-stability issue; overlapping cache and runtime-context work is related but not the canonical remaining report.

Members:

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

Merge readiness
Overall: 🦪 silver shellfish
Proof: 🦞 diamond lobster ✨ media proof bonus
Patch quality: 🦪 silver shellfish
Result: blocked by patch quality or review findings.

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

Rank-up moves:

  • [P2] Default the new Anthropic payload-policy opt-out set to an empty readonly set and add a regression for the existing two-argument exported helper call.
  • [P2] Rerun the focused Anthropic payload-policy, Anthropic wrapper, and provider cache-anchor tests after the compatibility fix.

Mantis proof suggestion
A redacted Telegram transcript would materially prove that reply-targeted prompts still preserve sender and reply context after the metadata moves to the tail carrier. A maintainer can ask Mantis to capture proof by posting this exact PR comment:

@openclaw-mantis telegram live: verify a reply-targeted Telegram prompt still preserves sender and reply context after current-turn inbound metadata moves to the runtime-context carrier, and return redacted transcript/log proof.

Risk before merge

  • [P1] Merging as-is can break provider plugins or wrappers that call the SDK-exported applyAnthropicPayloadPolicyToParams(payload, policy) helper because the new required parameter is dereferenced with .has.
  • [P1] The PR changes current-turn sender/reply metadata from inline user text to a hidden tail runtime-context carrier, so maintainer-owned session/context compatibility and exact-head CI should remain visible before merge.

Maintainer options:

  1. Preserve helper compatibility before merge (recommended)
    Make the new cache-breakpoint opt-out set optional with an empty default and add a regression for the existing two-argument helper call.
  2. Accept an SDK break deliberately
    Maintainers could intentionally require plugin callers to pass the new index set, but that should be an explicit plugin API decision with upgrade notes.
  3. Pause for the runtime-context overlap
    Pause this PR if maintainers prefer the overlapping runtime-context handoff in fix: keep inbound metadata in runtime context #89428 to become the canonical implementation instead.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Make applyAnthropicPayloadPolicyToParams preserve its existing two-argument call shape by defaulting the new cacheBreakpointOptOutMessageIndexes parameter to an empty readonly set, keep the internal managed-transport callers passing real index sets, and add focused coverage that a two-argument call still applies the normal Anthropic payload policy without throwing.

Next step before merge

  • [P2] A narrow automated repair can preserve the existing exported helper call shape without changing the maintainer-approved tail-carrier design.

Security
Cleared: The diff changes prompt assembly, internal message metadata, provider cache-marker placement, and tests; I found no new dependency, workflow, lockfile, secret-handling, or downloaded-code execution concern.

Review findings

  • [P1] Preserve the exported Anthropic policy helper signature — src/agents/anthropic-payload-policy.ts:259
Review details

Best possible solution:

Keep the tail-carrier fix shape, but preserve two-argument SDK helper compatibility with an empty default before landing the prompt-cache repair.

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

Yes, source inspection shows current main prepends currentInboundContext into the active prompt while the LLM boundary strips that same metadata only after the turn becomes historical. I did not run tests because this review is read-only.

Is this the best way to solve the issue?

No as submitted: the carrier design is the right owner-boundary fix, but the exported helper signature needs a compatibility default before this is the best merge shape.

Full review comments:

  • [P1] Preserve the exported Anthropic policy helper signature — src/agents/anthropic-payload-policy.ts:259
    applyAnthropicPayloadPolicyToParams is re-exported through the plugin SDK provider-stream barrels, but this PR makes the new cacheBreakpointOptOutMessageIndexes argument required and then dereferences it with .has. Existing provider plugins or wrappers that still call the helper as (payload, policy) will now fail typechecking or throw at runtime; default the new parameter to an empty set while keeping the managed/internal callers passing real index sets.
    Confidence: 0.89

Overall correctness: patch is incorrect
Overall confidence: 0.87

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against e3c40efeb09f.

Label changes

Label changes:

  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦞 diamond lobster and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (linked_artifact): The PR body and linked artifact provide after-fix provider cache measurements plus runtime soak evidence, though the strongest A/B numbers came from the earlier strip design and the maintainer comment accepts that final tail-carrier proof gap.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦪 silver shellfish, so this older rating label is no longer current.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P2: This is a focused agent prompt-cache cost/performance bugfix with limited blast radius, not an outage, security issue, or blocked onboarding path.
  • merge-risk: 🚨 compatibility: The PR changes an SDK-exported helper signature and changes the prompt layout for existing current-turn inbound metadata.
  • merge-risk: 🚨 session-state: The PR changes how current-turn sender, reply, and history metadata is associated with the active session turn and provider cache boundary.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦞 diamond lobster and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (linked_artifact): The PR body and linked artifact provide after-fix provider cache measurements plus runtime soak evidence, though the strongest A/B numbers came from the earlier strip design and the maintainer comment accepts that final tail-carrier proof gap.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body and linked artifact provide after-fix provider cache measurements plus runtime soak evidence, though the strongest A/B numbers came from the earlier strip design and the maintainer comment accepts that final tail-carrier proof gap.
  • mantis: telegram-visible-proof: Mantis should capture Telegram visible proof. The PR affects how Telegram-style sender and reply metadata reaches the model, which can be demonstrated with a short redacted Telegram proof.
Evidence reviewed

PR surface:

Source +139, Tests +365. Total +504 across 17 files.

View PR surface stats
Area Files Added Removed Net
Source 10 177 38 +139
Tests 7 390 25 +365
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 17 567 63 +504

Acceptance criteria:

  • [P1] pnpm test src/agents/anthropic-payload-policy.test.ts extensions/anthropic/stream-wrappers.test.ts.
  • [P1] pnpm test packages/ai/src/providers/openai-completions.test.ts packages/ai/src/providers/anthropic.test.ts.
  • [P1] pnpm check:test-types.

What I checked:

Likely related people:

  • obviyus: Authored the latest PR-head refactor that threaded carrier index sets through the provider cache-policy paths now under review. (role: recent reviewer and fixup author; confidence: high; commits: 51b619d78e64; files: src/agents/anthropic-payload-policy.ts, src/agents/anthropic-transport-stream.ts, packages/ai/src/providers/openai-completions.ts)
  • vincentkoc: Current-main blame and git history put recent prompt-boundary and Anthropic payload-policy code in commits authored by Vincent Koc. (role: recent area contributor; confidence: medium; commits: 736c6743c1ab, e085fa1a3ffd, 067496b12934; files: src/agents/embedded-agent-runner/run/attempt.ts, src/agents/embedded-agent-runner/run/attempt.llm-boundary.ts, src/agents/anthropic-payload-policy.ts)
  • Marvinthebored: Authored the merged prior prompt-cache stability PR and the current PR's main bugfix commit for the same LLM-boundary area. (role: prior cache-stability contributor; confidence: high; commits: 1af55bc6654f, 04808385a30c; files: src/agents/embedded-agent-runner/run/attempt.llm-boundary.ts, src/agents/embedded-agent-runner/run/attempt.ts, src/agents/internal-runtime-context.ts)
  • steipete: Introduced the provider stream SDK seam that re-exports the Anthropic payload-policy helper affected by the signature change. (role: SDK seam contributor; confidence: medium; commits: be526d642312; files: src/plugin-sdk/provider-stream.ts, src/plugin-sdk/provider-stream-shared.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.
Review history (5 earlier review cycles)
  • reviewed 2026-07-05T10:32:13.608Z sha a5132761afc6f3a839c881917191a1f7aed050f3 :: needs real behavior proof before merge. :: [P1] Preserve current inbound context before stripping active turns
  • reviewed 2026-07-05T11:26:32.969Z sha 578b6f5fba653a2bc891b58b16505faa570edcb9 :: found issues before merge. :: [P1] Preserve current inbound context before stripping active turns
  • reviewed 2026-07-06T03:48:15.583Z sha e89b56b5652dde9611e9fb04d462b7b7deeaa936 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-06T08:32:59.914Z sha e29ed99c826123578839895bd5fd18f750bf260f :: needs maintainer review before merge. :: none
  • reviewed 2026-07-06T21:37:52.382Z sha 6bdb82b97b6cca43e1814a2436825a9a899446bb :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jul 5, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Jul 5, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 5, 2026
@Marvinthebored Marvinthebored changed the title fix(agents): strip inbound metadata from the active user turn too, for byte-stable prompt caching fix(agents): carry current-turn inbound metadata in a tail runtime-context message for byte-stable prompt caching Jul 6, 2026
@Marvinthebored

Copy link
Copy Markdown
Contributor Author

Reworked to follow ClawSweeper's recommended path. The P1 was correct — the
previous revision stripped the active turn's inbound metadata with no replacement
carrier, dropping current-turn sender/reply/mention context from the model.

This revision no longer strips: it moves the current-turn inbound metadata into
the hidden runtime-context custom message (the runtime-context handoff you pointed
to via #89428), so the model still sees sender/reply/forwarded/chat-history
context on the active turn. The user prompt itself stays bare and byte-identical
across the active↔historical positions, which is what fixes the cache mutation.

The cache-placement improvement over a plain before-user handoff: the carrier is
positioned at the absolute tail of the request (after the active user turn), so it
is append-only — its vanishing next turn lands where the assistant reply begins
anyway, instead of re-billing the whole tail. A durable marker keeps the Anthropic
(SDK + managed transport) and OpenAI-completions cache_control breakpoint anchored
on the stable user turn, not the volatile carrier.

Reviewed with adversarial gpt-5.5/codex sweeps (correctness, byte-identity,
compatibility, test adequacy); one found a second Anthropic cache-anchor path (the
managed transport) which is now fixed and covered by a provider-payload test.

@Marvinthebored

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper clawsweeper Bot added 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. mantis: telegram-visible-proof Mantis should capture Telegram visible proof. and removed 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 Jul 6, 2026
@clawsweeper
clawsweeper Bot temporarily deployed to qa-live-shared July 6, 2026 03:51 Inactive
@obviyus

obviyus commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator

Maintainer review + land prep.

Review: bug confirmed on main — the active user turn serializes with inbound metadata and is stripped once historical (src/agents/embedded-agent-runner/run/attempt.llm-boundary.ts, attempt.ts), so each turn's bytes mutate retroactively and invalidate prefix caches every turn. Carrier design is the right boundary: session storage stays bare, historical bytes unchanged, requests become strict prefix-extensions.

Fixup pushed (870db7f2a82): unified the three carrier-marking mechanisms into one explicit index-set threaded from message conversion to breakpoint selection; deleted both module-level WeakSet side channels (incl. the exported one mutated cross-module), −8 LOC, contract comments restored, tests exercise the new seam instead of mutating globals.

Validation (Blacksmith Testbox, PR tree): check:changed green; targeted suites all pass — anthropic-payload-policy + anthropic-transport-stream (106), extensions/anthropic stream-wrappers (22), internal-runtime-context (10), cache-stability (11), openai-completions (39), anthropic provider (52). Seven test/scripts/* tooling failures reproduced on the PR tree but pass on clean main sync — root-caused to a stale extensions/featherless partial directory from box sync (extension added to main after this PR's base); GitHub CI on the merge ref is the authoritative gate.

Known proof gap: headline A/B numbers were measured on the earlier strip-design revision; the shipped tail-carrier design shares the byte-stability property (unit-proven) but was not re-measured live. Accepted as maintainer decision. Landing after CI on the new head.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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 Jul 7, 2026
Peetiegonzalez and others added 3 commits July 7, 2026 08:53
…ntext message for byte-stable prompt caching

The active user turn was decorated at request-build time with an inbound
metadata block (Conversation info / reply-target / sender / forwarded /
chat-history), but the session store persists the bare text and the LLM boundary
strips that block from historical replay. So a user message's serialized bytes
changed retroactively — decorated as the active turn, bare as history — on every
turn, invalidating any prefix/exact-match provider prompt cache from that point
onward, every turn. (#90811 fixed the timestamp half of this same asymmetry.)

Rework of the earlier "strip the active turn" approach (which lost model-visible
context — ClawSweeper's P1) into one that keeps the context AND recovers the
cache cost:

- Route current-turn inbound metadata out of the user prompt and into the hidden
  runtime-context custom message (the mechanism from #89428), and
  relocate that carrier to the ABSOLUTE TAIL of the wire request (after the
  active user turn and any tool-call scaffolding). The user turn stays bare and
  byte-identical in both the active and historical positions; the volatile
  carrier vanishes next turn exactly where the assistant reply begins anyway, so
  the request is an append-only prefix-extension through the active user turn.
- A durable marker (UserMessage.runtimeContextCarrier, set by convertToLlm from
  the carrier's details) lets the Anthropic SDK transport, the managed Anthropic
  transport (anthropic-transport-stream / anthropic-payload-policy), and
  OpenAI-completions skip the carrier when selecting the deepest cache_control
  breakpoint, keeping the anchor on the last stable user turn.

Storage stays BARE (invariant preserved); runtime-only turns (room events) keep
their existing inline behavior, which is byte-stable because room-event/system
context is not strip-eligible; legacy bare-stored sessions are unchanged.

Reviewed with adversarial gpt-5.5/codex sweeps (correctness, byte-identity,
compatibility, test adequacy): found + fixed the managed Anthropic transport
cache-anchor path and added the missing OpenAI-completions/managed-transport
breakpoint tests; a theoretical runtime-only mutation was verified unreachable
and pinned with a test. Final sweep clean.

Co-authored-by: #89428 (runtime-context handoff approach)
@obviyus
obviyus merged commit 107a9d6 into openclaw:main Jul 7, 2026
109 of 110 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling extensions: anthropic extensions: qa-lab mantis: telegram-visible-proof Mantis should capture Telegram visible proof. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Active user message keeps inbound metadata that history strips, breaking prompt-cache byte-stability every turn

3 participants