Skip to content

fix(anthropic): preserve cache reuse across transient runtime context - #140621

Merged
steipete merged 8 commits into
openclaw:mainfrom
LightningWareLLC:fix/anthropic-carrier-cache-opt-out
Sep 9, 2026
Merged

steipete merged 8 commits into
openclaw:mainfrom
LightningWareLLC:fix/anthropic-carrier-cache-opt-out

Conversation

@LightningWareLLC

@LightningWareLLC LightningWareLLC commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Closes #140607

What Problem This Solves

Fixes an issue where Anthropic users running tool loops would repeatedly write growing conversation history to the prompt cache when temporary runtime context moved between requests. It also fixes requests with thinking disabled being rejected for an empty anthropic-beta header, found while exercising the cache repair against the live API.

Why This Change Was Made

Both Anthropic request builders now use the existing replay lifecycle contract to exclude transient runtime-context carriers from cache checkpoints from the initial request onward. Retained carriers remain valid checkpoints. Emitted message indexes account for filtered messages and grouped tool results, and empty beta headers are omitted without changing thinking-binding eligibility.

A packaged Docker regression exercises both builders through an initial request, two real tool continuations, and a subsequent user turn. Stable/full release verification requires this lane, validates its API-key credential specifically, and does not retry failed cache assertions. Executable workflow tests cover both the planning and run steps.

User Impact

Anthropic sessions reuse the growing stable conversation prefix while still receiving temporary runtime context. Sessions requiring retained context preserve their anchors. Release verification now catches this cache-cost regression through provider-reported cache reads and writes, in addition to deterministic payload tests.

Evidence

The new transient string/block cases failed before the cache fix. Disabled-thinking and hook-disabled-thinking cases failed before the empty-header repair. The corrected candidate passed 332 focused tests across the package, model contract, session boundary, Docker scheduler, and actual release-workflow selection/preflight. Typechecks, lint, workflow validation, package build/integrity checks, and independent review passed.

Both mock Docker and eight live Docker requests passed using the installed candidate package and claude-sonnet-4-6, short cache retention, 512 maximum output tokens, fixed system/tools per sequence, and a fresh synthetic conversation prefix for each builder. Requests have 90-second deadlines and no retries.

Builder Stage Cache read Cache write
Provider Initial 0 8042
Provider Tool result 1 8042 530
Provider Tool result 2 8572 503
Provider Next user 9075 18
Managed transport Initial 0 8041
Managed transport Tool result 1 8041 529
Managed transport Tool result 2 8570 503
Managed transport Next user 9073 18

The harness observes emitted checkpoints and unchanged cached prefixes without rewriting requests. Histories are synthetic and constructed by the harness: this is installed-builder/API proof; real Gateway lifecycle placement is covered by the session-boundary tests. The integration retains identical production, test, harness, and lockfile blobs from the live-validated candidate. Current main's Docker compatibility additions and split release documentation are preserved. Hosted CI on the updated PR head is the landing gate; the earlier ACP spawn failure is not counted as a pass.

The first integrated CI run identified a missing unused-file scanner entry for the shell-launched Docker runner. Declaring that entry made both unused-file scans pass with zero entries; the imported mock helper is discovered automatically, without an ignore or baseline change. That run also failed an unchanged terminal UI assertion and an unchanged Discord reset test timeout. Their complete focused files passed locally (29 and 16 tests respectively); updated-head Linux CI remains authoritative.

Final-head CI run 34379052492, attempt 2 passed on 18434a73af52a34720ea51d008ef19c2be61976b. An unchanged browser E2E animation-sampling assertion needed one accepted failed-jobs rerun together with its aggregate gate; no assertion, timeout, or product code was changed for that rerun.

Thanks to @LightningWareLLC for reporting the regression and contributing the lifecycle-aware cache fix.

@clawsweeper

clawsweeper Bot commented Sep 7, 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.

@openclaw-barnacle openclaw-barnacle Bot added triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. size: XS labels Sep 7, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 7, 2026
@clawsweeper

clawsweeper Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 9, 2026, 12:56 PM ET / 16:56 UTC (Revision 7).

ClawSweeper review

What this changes

The PR preserves Anthropic conversation-cache reuse around temporary runtime context, omits empty beta headers, and adds packaged regression coverage to release verification.

Merge readiness

✅ Ready for maintainer review

This remains a useful repair: current main still permits transient context to receive cache checkpoints, and no merged replacement resolves it. The revised patch addresses the earlier lifecycle concern, has convincing live API evidence, and introduces no identified blocking defect.

Priority: P2
Reviewed head: 18434a73af52a34720ea51d008ef19c2be61976b

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused runtime repair with strong live cache evidence and useful regression coverage; no blocking correctness finding remains.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured live results exercise both installed Anthropic builders against the real API through initial history, two tool continuations, and a subsequent user turn, showing growing cache reads and small new writes. The inspected harness checks the changed checkpoint boundary; Gateway scheduling is explicitly outside this proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured live results exercise both installed Anthropic builders against the real API through initial history, two tool continuations, and a subsequent user turn, showing growing cache reads and small new writes. The inspected harness checks the changed checkpoint boundary; Gateway scheduling is explicitly outside this proof.
Evidence reviewed 9 items Pinned PR remains open: The REST API confirmed the PR is open and unmerged, with head 18434a7 and base a57c799. The supplied introduction delta matches those revisions; the stale test merge was not used to infer removals.
Current main still needs the repair: Current-main conversion does not collect transient-carrier exclusions, and the provider calls cache allocation without an exclusion set. The allocator consequently remains able to select the trailing carrier.
Lifecycle-aware exclusion: The shared converter uses the existing model contract and records emitted indexes only for nonempty transient carriers. Both request builders pass those indexes to the existing allocator, preserving grouped tool-result indexing and retained-context eligibility.
Findings None None.
Security None None.

How this fits together

OpenClaw’s Anthropic request builders turn conversation history, tool results, and runtime context into provider requests. Cache checkpoints determine which stable portions Anthropic can reuse on subsequent requests.

flowchart TD
  A[Conversation and tool results] --> C[Anthropic request builders]
  B[Runtime context] --> C
  C --> D{Context retained by model policy?}
  D -->|Yes| E[Allow context checkpoint]
  D -->|No| F[Checkpoint stable conversation]
  E --> G[Anthropic API and cache usage]
  F --> G
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +24, Tests +225, Docs +11, Config +7, Other +397. Total +664 across 19 files.

View PR surface stats
Area Files Added Removed Net
Source 3 29 5 +24
Tests 6 309 84 +225
Docs 1 11 0 +11
Config 2 7 0 +7
Generated 0 0 0 0
Other 7 399 2 +397
Total 19 755 91 +664

Review metrics

Metric Value Why it matters
Runtime versus proof growth Runtime net +24 lines; regression tests net +201; Docker proof harness +385 Most growth establishes regression evidence while the runtime repair reuses existing conversion and cache-policy owners.
Release proof budget 1 added lane; 8 requests; 0 retries; 15-minute lane deadline Stable/full release verification gains a bounded live cache check using the existing Docker scheduler.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #140607
Summary: This PR is the active implementation candidate for the linked transient-carrier cache defect; related coverage and capture work do not replace it.

Members:

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

Technical review

Best possible solution:

Keep cache eligibility tied to the existing context-retention contract in shared conversion, with packaged live regression coverage protecting reuse.

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

Yes, from source: with transient context and available cache-marker capacity, current main can checkpoint the carrier after it moves behind tool results. This review did not execute a failing current-main run.

Is this the best way to solve the issue?

Yes. Reusing the existing model lifecycle predicate and cache allocator repairs both builders without changing context roles, persisted history, or user cache settings.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 577492132500.

Labels

Label justifications:

  • P2: This repairs a model-specific prompt-cache efficiency defect without evidence of a core outage or lost messages.
  • 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 captured live results exercise both installed Anthropic builders against the real API through initial history, two tool continuations, and a subsequent user turn, showing growing cache reads and small new writes. The inspected harness checks the changed checkpoint boundary; Gateway scheduling is explicitly outside this proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured live results exercise both installed Anthropic builders against the real API through initial history, two tool continuations, and a subsequent user turn, showing growing cache reads and small new writes. The inspected harness checks the changed checkpoint boundary; Gateway scheduling is explicitly outside this proof.

Evidence

What I checked:

  • Pinned PR remains open: The REST API confirmed the PR is open and unmerged, with head 18434a7 and base a57c799. The supplied introduction delta matches those revisions; the stale test merge was not used to infer removals. (18434a73af52)
  • Current main still needs the repair: Current-main conversion does not collect transient-carrier exclusions, and the provider calls cache allocation without an exclusion set. The allocator consequently remains able to select the trailing carrier. (packages/ai/src/providers/anthropic.ts:665, 577492132500)
  • Lifecycle-aware exclusion: The shared converter uses the existing model contract and records emitted indexes only for nonempty transient carriers. Both request builders pass those indexes to the existing allocator, preserving grouped tool-result indexing and retained-context eligibility. (packages/ai/src/transports/anthropic-messages.ts:146, 18434a73af52)
  • Existing lifecycle contract and discussion: The provider documentation distinguishes retained prefix-binding context from transient context. The linked issue’s human comment correctly identifies appendOnlyRuntimeContext as the deciding branch; the revised patch respects that distinction rather than excluding every carrier. Public docs: docs/providers/anthropic.md. (docs/providers/anthropic.md:263, 18434a73af52)
  • After-fix live API proof: The captured PR body, sourceRevision af68b76b95d69f7c01f8b92259386846076b58147edc8b6e1a46077e411ead04, reports eight installed-package requests against claude-sonnet-4-6. Provider cache reads progress 8042→8572→9075 after the initial write; managed-transport reads progress 8041→8570→9073. Final writes are 18 tokens for both. The inspected harness observes production payloads without rewriting them, moves transient context across two returned tool calls and a new user turn, and checks prefix identity and cache usage. The body explicitly limits this to builder/API proof and reports unchanged live-validated implementation and harness blobs. (scripts/e2e/anthropic-cache-live.mts:113, 18434a73af52)
  • Release verification and security boundaries: The new lane uses the existing functional package image, limits execution to eight requests with deadlines and no retries, and requires an API key in both workflow preflights. Tests execute the workflow selection and credential checks. No Action reference, dependency source, permission grant, or persistent schema changes are introduced. (scripts/lib/docker-e2e-scenarios.mts:419, 18434a73af52)

Likely related people:

  • steipete: 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 (6 earlier review cycles)
  • reviewed 2026-09-07T02:06:00.381Z sha b0d839e :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-07T02:14:34.162Z sha 7bea5a8 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-07T02:23:18.807Z sha 7bea5a8 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-07T02:40:11.151Z sha 4e30fc4 :: needs real behavior proof before merge. :: [P2] Distinguish prior turns from actual carrier relocation
  • reviewed 2026-09-07T03:29:04.046Z sha 3b3c5b4 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-07T03:35:07.808Z sha 3b3c5b4 :: needs maintainer review before merge. :: none

@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Sep 7, 2026
@LightningWareLLC

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Added after-fix Anthropic Messages proof to the PR body:

  • Offline: broken (empty opt-out) anchors on relocated carrier; fixed anchors on stable user turn (trailing + tool-loop relocate).
  • Live (claude-sonnet-4-5-20250929): warmup cache_creation=1244 / cache_read=0; subsequent turn and tool-loop both cache_creation=0 / cache_read=1244 with request shape system(cache)+stable(cache)+carrier(no cache).

Also clarified model-dependent retained vs transient carrier lifecycle in Why This Change Was Made.

@clawsweeper

clawsweeper Bot commented Sep 7, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 7, 2026
Keep append-only carriers eligible as cache anchors (parity/CI), but exclude
carriers that trail assistant/tool turns after relocate so the stable prefix
keeps the deepest cache_control breakpoint.
@LightningWareLLC

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Updated head with relocate-aware carrier opt-out (not blanket):

@clawsweeper

clawsweeper Bot commented Sep 7, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. label Sep 7, 2026
@LightningWareLLC LightningWareLLC changed the title fix(anthropic): restore runtime-context carrier cache_control opt-out fix(anthropic): preserve cache reuse across transient runtime context Sep 7, 2026
@LightningWareLLC

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Updated head: 3b3c5b4.

Carrier cache eligibility now uses the canonical replay lifecycle policy, preserving retained anchors after an earlier completed turn and excluding transient carriers from the initial request. The PR Evidence section now connects both production builders' emitted markers to live one-hour cache usage through two tool rounds and a subsequent user turn, for transient and retained models. All 16 live calls passed (estimated $0.211 total); 380 focused tests passed and independent review found no actionable P0–P2 findings. Updated-head CI is running.

@clawsweeper

clawsweeper Bot commented Sep 7, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. labels Sep 7, 2026
Keep Anthropic cache checkpoints on retained conversation prefixes while
excluding transient runtime context from both request builders. Preserve
cache anchors for lifecycle-retained context.

Add regression coverage and a packaged live Docker cache test to stable/full
release verification, with explicit API-key preflight and no request retries.
Also omit empty Anthropic beta headers exposed by the live test.

Closes #140607

Co-authored-by: LightningWareLLC <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts docker Docker and sandbox tooling size: L and removed size: XS labels Sep 9, 2026
Declare the module launched by the Docker wrapper so dependency analysis follows its static mock-provider import. Keep the unused-file guard intact without ignores or baseline changes.
@obviyus obviyus removed their assignment Sep 9, 2026
@steipete
steipete merged commit faaf4b0 into openclaw:main Sep 9, 2026
392 of 395 checks passed
@steipete

steipete commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Merged via squash.

@vincentkoc

Copy link
Copy Markdown
Member

Real Gateway baseline: transient-carrier cache failure reproduced

Adding complementary pre-fix Gateway lifecycle evidence, not post-fix validation of this PR's merge faaf4b0fbd3b909e3400b686e854793b0b6c5112 at 17:35:57 UTC on September 9, 2026. The independent coverage stack is #143010 and #143012; capture prerequisite #143107 is merged. This run did not import or execute the runtime-fix branch.

On September 9, 2026, one openclaw-testbox-env pnpm test:live:cache:runtime:expanded command completed at Code/tooling SHA ea8aba48b06293d7341fb6e4e1b5257fd49c211f, receiver-verified tree 528c4a5d56ff0af390a3e6e4e72dd5213ca2eb18, based on frozen pre-runtime-fix main ef37c4f3755d4a424c12530d9339d48f2fbcdc8d.

Run: https://github.com/openclaw/openclaw/actions/runs/34381314585/attempts/1, job 102566589879. Frozen install and source/tree verification passed; Linux x64, Node 24.19.0, pnpm 12.3.4; the runner's build passed in 30.7s. The command exited 1: 2 passed, 8 failed, zero skipped, with 29 observed requests and no retry. The enclosing Actions run/job is cancelled after task-owned Testbox teardown, not an Actions pass or test-failure conclusion. The completed command/report carry the result.

All six Anthropic cells completed the real persisted Gateway path with exact two-request text or four-request read A -> read B -> final -> next-user flows. They had HTTP 200 successful SSE terminals, the expected runtime/model, exact raw-to-persisted usage parity, and zero transport-error rows. Ordered dependent reads and visible replies passed before the cache assertion.

Read scenario Cache reads, requests 1-4 Cache writes, requests 1-4 Carrier positions Read-A marginal reuse
Sonnet, transient 1069, 9458, 9458, 9458 20936, 23584, 23702, 23774 1 -> 3 -> 5 -> 7 0
Opus, transient 1065, 9402, 9402, 9402 20910, 23572, 23692, 23766 1 -> 3 -> 5 -> 7 0
Fable, retained control 1065, 21955, 33060, 33184 20890, 11105, 124, 171 original 1 retained; new 8 on next user 11105

Both Sonnet/Opus text cells also failed the transient-cache-breakpoint assertion, moving the carrier 1 -> 3; warm read/write was 9463/12670 and 9397/12642 respectively. Both Fable cells passed.

The transient carrier stayed byte-identical while moving: content SHA256 3a0755fe66354aa1f846fee897676f6bd04fa1620e8f512372842699f44030c1; its cache marker SHA256 remained c27228f064722342322226a9be5079aa7c0c485d1985b77cb8405ed83de7b490. Combined with the inspected lifecycle producer, the four transient cells reproduce the original invariant under the actual Gateway loop.

The four OpenAI failures are separate, not evidence for this Anthropic defect. Three completed cells expose a QA full-history-versus-Responses-continuation contract gap, with exact live lineage not retained. The expanded read case stopped on an assistant/capture count mismatch; a separate source-confirmed QA gap conflates projected display rows with provider completions, but its exact live cause is unproven. An additional daily-read cache-floor deficit remains unresolved. None is treated as passed.

Limits: projected message history was stable; full system/tool byte equality was not reached because the carrier assertion throws first. No raw DB/persisted-history export was retained. This is hashed structure/usage evidence plus inspected producer proof, not repaired-candidate validation, TLS attestation, or billing/savings proof. Report SHA256: d926e192e40851a5092f96ec46a1d01d543cb942228cf6bf43bf6199daa2dada (10 cases, 11,596 bytes). Full per-cell durations and classifications are in the coverage PR.

Thanks to @LightningWareLLC for the original report and repair. Sharing this baseline to complement the landed runtime work; no branch or assignment change is intended. The test stack remains held for its OpenAI harness gaps and live-result policy disposition, and no post-fix Gateway pass is claimed.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 10, 2026
…openclaw#140621)

Anthropic tool loops could repeatedly write growing conversation history to the
prompt cache because a moving runtime-context carrier owned the checkpoint.
Use the existing replay lifecycle contract to exclude transient carriers from
both request builders while preserving retained anchors. Also omit empty beta
headers that caused direct API requests with thinking disabled to fail.

Add deterministic regression coverage and a packaged Docker test that verifies
real cache reads and incremental writes across two tool continuations and a new
user turn in both builders. Require that lane in stable/full release validation,
with explicit API-key preflight, no request retries, and a declared runtime entry
for dependency analysis.

Validation includes focused package/model/session and workflow tests, build and
package integrity checks, static checks, independent review, mock Docker, and
eight successful live Anthropic Docker requests. Hosted CI run 34379052492 passed
on the final PR head at attempt 2, after one unchanged browser-animation rerun.

Closes openclaw#140607

Thanks to @LightningWareLLC for reporting the regression and contributing the
lifecycle-aware cache repair.

Co-authored-by: LightningWareLLC <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
RomneyDa pushed a commit that referenced this pull request Sep 25, 2026
…#140621)

Anthropic tool loops could repeatedly write growing conversation history to the
prompt cache because a moving runtime-context carrier owned the checkpoint.
Use the existing replay lifecycle contract to exclude transient carriers from
both request builders while preserving retained anchors. Also omit empty beta
headers that caused direct API requests with thinking disabled to fail.

Add deterministic regression coverage and a packaged Docker test that verifies
real cache reads and incremental writes across two tool continuations and a new
user turn in both builders. Require that lane in stable/full release validation,
with explicit API-key preflight, no request retries, and a declared runtime entry
for dependency analysis.

Validation includes focused package/model/session and workflow tests, build and
package integrity checks, static checks, independent review, mock Docker, and
eight successful live Anthropic Docker requests. Hosted CI run 34379052492 passed
on the final PR head at attempt 2, after one unchanged browser-animation rerun.

Closes #140607

Thanks to @LightningWareLLC for reporting the regression and contributing the
lifecycle-aware cache repair.

Co-authored-by: LightningWareLLC <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
(cherry picked from commit faaf4b0)
RomneyDa added a commit that referenced this pull request Sep 25, 2026
* fix(agents): scope append-only runtime context to prefix-binding Claude models (#136990)

* fix(agents): scope append-only runtime context to prefix-binding Claude models

Append-only runtime-context replay (persisted carriers, retained inline
inbound metadata, no consecutive-user merge on the Messages API) exists
because Claude Fable 5.1 binds thinking to the exact request prefix. It was
enabled for every Anthropic-family route, so Opus 5, Sonnet 5, Opus 4.8,
Sonnet 4.6 and Haiku 4.5 sessions paid for persisted carriers on every later
request (cache-read billing plus context) without any prefix to protect.

- Add `bindsClaudeThinkingPrefix` to the llm-core Claude contracts (Fable 5.1
  and Mythos 5.1 identities, including cloud ids and canonical deployment
  metadata) and derive `appendOnlyRuntimeContext` from it in the core
  fallback and the shared Anthropic replay helpers; GitHub Copilot stays
  transient. Non-binding Claude models return to transient carriers and
  normal user-turn merging.
- Next-turn carriers now carry only the delimited context body. The shared
  instruction (runtime context for the user request it follows, not
  user-authored, keep internal details private, continue without waiting)
  moves once into the stable system prompt prefix for every provider, so it
  is cached instead of re-sent per turn. Runtime-event prefaces are
  unchanged; historical prefaced carriers are still stripped from
  user-visible surfaces.
- Docs: anthropic provider page, transcript hygiene, system prompt.

Live proof on a recording proxy with drop_block binding controls: an Opus 5
session merged consecutive user turns and kept its model-switch carrier
transient; a Fable 5.1 session switched to Opus 5 and back, then ran three
more turns with tool loops while the persisted compact carrier stayed in
place, thinking blocks accumulated (1 -> 3) and every response reported
input_transformations: [].

* fix(agents): limit prefix-binding replay to Fable 5.1 and match compact carriers in e2e

`bindsClaudeThinkingPrefix` now covers only the Fable 5.1 identity. Mythos 5.1
is not registered in the bundled Anthropic catalog and has no live replay
proof, so it keeps transient carriers and normal user-turn merging like every
other non-Fable model; extending the predicate requires live proof for the
new model. Predicate, transcript-policy, replay-helper and provider plugin
tests assert the narrowed set.

The qa-lab gateway RPC chat e2e test still imported the removed next-turn
carrier preface; its carrier filter now matches the delimiter-only shape.

* test(agents): expect merged user turns for non-binding Claude replay

(cherry picked from commit de7518b)

* fix(anthropic): preserve cache reuse across transient runtime context (#140621)

Anthropic tool loops could repeatedly write growing conversation history to the
prompt cache because a moving runtime-context carrier owned the checkpoint.
Use the existing replay lifecycle contract to exclude transient carriers from
both request builders while preserving retained anchors. Also omit empty beta
headers that caused direct API requests with thinking disabled to fail.

Add deterministic regression coverage and a packaged Docker test that verifies
real cache reads and incremental writes across two tool continuations and a new
user turn in both builders. Require that lane in stable/full release validation,
with explicit API-key preflight, no request retries, and a declared runtime entry
for dependency analysis.

Validation includes focused package/model/session and workflow tests, build and
package integrity checks, static checks, independent review, mock Docker, and
eight successful live Anthropic Docker requests. Hosted CI run 34379052492 passed
on the final PR head at attempt 2, after one unchanged browser-animation rerun.

Closes #140607

Thanks to @LightningWareLLC for reporting the regression and contributing the
lifecycle-aware cache repair.

Co-authored-by: LightningWareLLC <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
(cherry picked from commit faaf4b0)

* fix(anthropic): bind cache carriers to replay policy

* fix(release): qualify prefix-bound anthropic replay

* fix(github-copilot): keep replay context transient

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: LightningWare LLC <[email protected]>
Co-authored-by: LightningWareLLC <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docker Docker and sandbox 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: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: 2026.9.2 Anthropic cache_control can attach to relocating runtime-context carrier (opt-out removed in #136782)

4 participants