Skip to content

fix(agents): guard prompt-cache reuse across replay and releases - #168392

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-micro-prompt-cache-release-e2e-20260919
Oct 10, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-micro-prompt-cache-release-e2e-20260919

Conversation

@steipete

@steipete steipete commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Adds an end-to-end guard for prompt-prefix and KV-cache regressions, in normal CI and Full Release Validation. The guard found and fixes replayed tool-result bytes, internal browser-session cache affinity, and an Anthropic cache marker that covered transient runtime context removed on reopen.

User Impact

Previously published tool results keep the same bounded, redacted text when replayed or reopened. Private subagent completion preserves its browser conversation's opaque cache key. Anthropic history checkpoints stop before unretained runtime context, including when steering or a tool loop follows it. No configuration, schema, migration, or public API change is required.

Change

The existing Anthropic cache harness owns the shared digest-only prefix oracle and live transport scenario. The offline matrix drives ten real admitted turns through each of OpenAI Responses, Chat Completions, Anthropic Messages, and Claude's in-history system route. It exercises large tool results, image cleanup, pruning, instruction refresh, MCP disconnect/reconnect, prompt hooks, steering, and reopen. A separate real Gateway test covers chat, model-issued subagent spawn, private completion, and server restart against persisted state.

The existing live-cache release job runs transport and real-agent cache checks, is selectable with live_suite_filter=live-cache, and remains part of the default stable/full profiles. No additional release runner job is introduced. Live checks require at least 80% reuse of the previous prompt, bounded request gaps, and no tracked cache-input diagnostic; there is no retry.

Before the repair, a previously sent 16,000-character tool result reopened at about 1,536 characters. Publication and replay now use identical bounded bytes. The Gateway negative control also exposed a 51-to-40-byte cache-key change on private completion; the repaired path preserves the same key.

Runtime fixes use the existing owners: one cap before tool-result publication/persistence; canonical projection identity through provider ID normalization; an event-scoped redaction preparer through listener/write settlement; the shared browser cache-key owner; and one Anthropic stable-prefix boundary. The old Gateway-local key helper is removed. The marker scan now starts before the first opted-out message, removing redundant per-message checks while retaining two checkpoints inside stable history.

Regression Catch Matrix

Reintroduced regression Observed gate failure
#167613 image-cleanup policy Request 7 / turn 6, history[14].block.type
#167642 MCP tool retention Request 4 / turn 3, tools[0].name
#167698 instruction-refresh policy Request 5 / turn 4, system: equal byte length, different digest
#167938 hook/model-prompt replay Request 3 / turn 2, history[0].block.text, 102 → 43 serialized bytes
Anthropic marker spanning transient context Request 8 / turn 6, history[24], marker 25; digest-only diagnostic

The first four controls were independently reversed and restored on the Linux rig. The new marker control reverses only this fix on the final-main candidate, requires the precise transient-history failure, and restores it before positive tests.

Evidence

  • Hetzner Crabbox cbx_d42e591643a6, final-base run: the marker reversal failed precisely; all four ten-turn request families passed after restoration. The real Gateway/subagent/restart file passed in 82.82 s. Cap/redaction/history/oracle/release tests passed. 241 Anthropic provider and transport sibling tests passed, including the corrected expectation that every marker must stay before transient context.
  • The same lease passed the export-name collision guard and 143 closure/planner tests across four files (130.69 s). The full changed gate passed all typechecks and guards through the dead-export audit, which reports 17 inherited findings in untouched authentication modules, a UI test helper, and the lint-tool entrypoint. An unchanged-base run reproduced the identical set. Every remaining canonical lint/guard command passed in the follow-up run; the inherited audit is not claimed green. The baseline-plus-remaining command completed in 1,178.326 s with exit 0.
  • AWS Crabbox cbx_a80006aa5bc4, live run: 20 requests passed. Transport minimum previous-prompt reuse was 99.95% for OpenAI and 99.75% for Anthropic. Real-agent minima were 84.49% and 95.37%, above the 80% floor. Maximum measured request gap was 5,593 ms; every diagnostic reported no tracked cache-input change. Combined bootstrap/live command: 171.470 s, exit 0. The live-agent file took 109.15 s.
  • Earlier native Testbox tbx_01m4j17pvjsppz9qnpxt21zx15 also passed OpenRouter transport reuse at 99.95%. OpenRouter credentials were unavailable on the fresh fallback run; this earlier result is not claimed as current-head proof.
  • Independent full-candidate and final staged-delta reviews found no actionable P0–P2 findings. Baseline and remaining-check proof uses the unchanged 44e9f45 main baseline. All heavy checks ran remotely. Unused queued Testboxes and completed AWS leases were stopped.

The normal-CI matrix exceeds the 30-second review threshold: its four scenario cases totalled 67.26 s on the fresh runner, and the earlier isolated one-worker file command took 360.83 s including compilation. Real admission, plugin/MCP lifecycle, durable replay, and wire serialization are the contracts that cheaper helper tests missed. The shared oracle takes about 2 s; the live checks remain release-only. The earlier complete CI run took 419 s wall / 9,530 aggregate job-seconds, not all attributable to this change.

Scope and Limits

The Gateway restart is in-process, not an OS-process restart. The gate covers image cleanup and history pruning, not compaction. Live agent checks force full-history requests rather than retained HTTP continuation. External channel-session browser cache affinity is unchanged.

Against the final main base, the non-test delta is +539 lines (+878/−339); runtime code is +100 lines. Growth is required for the requested harness and for preserving the synchronous listener contract: late redaction-policy changes must still see uncapped already-redacted source until event settlement. That source belongs to one event, not a new session/process cache.

Builds on the merged Anthropic checkpoint policy from #168042. This PR adds the transient-marker boundary fix and has no Bedrock changes.

Reproducible Commands

node scripts/run-vitest.mjs src/agents/embedded-agent-runner.prompt-cache.test.ts src/gateway/gateway.prompt-cache.test.ts --maxWorkers=1
node scripts/run-vitest.mjs packages/ai/src/anthropic-cache-carrier-parity.test.ts packages/ai/src/anthropic-cache-transport-parity.test.ts --maxWorkers=1
node --import ./scripts/tsx.mjs scripts/e2e/anthropic-cache-live.mts
OPENCLAW_LIVE_CACHE_TEST=1 OPENCLAW_LIVE_ANTHROPIC_CACHE_MODEL=claude-sonnet-5 pnpm test:live src/agents/embedded-agent-runner.cache.live.test.ts --testNamePattern 'release prompt-prefix gate'
node --import ./scripts/tsx.mjs scripts/check-export-name-collisions.mts
node scripts/run-vitest.mjs test/scripts/eager-import-closure.test.ts test/scripts/pr-wrapper-source-closure.test.ts test/scripts/ci-node-test-plan.test.ts test/scripts/ci-node-test-plan.commands.test.ts --maxWorkers=1
node scripts/check-changed.mjs --staged --base <reviewed-base>

@clawsweeper

clawsweeper Bot commented Oct 10, 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 docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts docker Docker and sandbox tooling agents Agent runtime and tooling extensions: openai size: XL labels Oct 10, 2026
@steipete
steipete marked this pull request as ready for review October 10, 2026 10:38
@github-actions

github-actions Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 73b0a1c6352e3f1d95628b506f9e025e7f4556f6
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/command/attempt-auth-selection.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/sessions/session-tool-result-redaction.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR stabilizes replayed tool results and browser cache keys, prevents Anthropic checkpoints from covering transient context, and expands cache regression gates.

Example: An agent publishes a bounded 16,000-character tool result and later reopens the conversation.

  • Before: Replay could reduce the previously published result to about 1,536 characters, changing the cached prefix.
  • After: Publication, persistence, and replay use the same bounded, redacted text.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is coherent and has no open correctness finding; inspected proof is primarily production-path harness coverage, with live measurements recorded separately.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its body records live reuse and negative-control results, while inspected tests exercise real owners through in-process boundaries and linked Crabbox artifacts were inaccessible here.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Replayed conversation bytes and cache affinity can change between turns, causing avoidable provider cache rewrites.
Reason: Maintainer direction is established, the source defects are concrete, and the added coverage targets previously missed lifecycle boundaries.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it delivers distinct, maintainer-directed cache repairs and regression coverage. The prior redaction and transient-prefix findings are addressed, and no new actionable defect was found.

Priority: P2
Reviewed head: 73b0a1c6352e3f1d95628b506f9e025e7f4556f6

Before merge

None.

Findings

None.

Tests

  • Low-value test test/scripts/release-workflow-matrix-plan.test.ts: Remove the redundant four-profile parameterization: the evaluated job condition does not read release_test_profile, so those cases do not independently prove profile selection.
Agent review details

How this fits together

Agent session preparation turns stored conversation history, tool results, and runtime context into provider requests; provider transports serialize those requests and place cache checkpoints.

flowchart LR
  A[Chat and internal completion] --> B[Agent runner]
  B --> C[Tool result preparation]
  C --> D[Session transcript]
  D --> E[Replay preparation]
  E --> F[Provider transport]
  F --> G[Provider prompt cache]
Loading

Technical review

Best possible solution:

Land the shared-owner cache repairs and retain their production-boundary regression coverage.

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

Fetched-main source exposes the unsafe Anthropic marker path, and the supplied discussion records targeted failing controls; this review ran no target code.

Is this the best way to solve the issue?

The repairs fit the existing publication, replay, cache-key, and transport owners and remove the replaced Gateway-local key implementation.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Anthropic history checkpoints changes intended behavior with a stated reason (4895fbb: Preserve preceding conversation checkpoints across large content batches while retaining the marker budget.)
  • Tool-result projection identity keeps the original intent (fix(agents): keep long-context tool-result prompts cache-stable #95624: Keep bounded tool-result projections byte-stable and occurrence-safe across repeated identities.)
  • Live tool-result redaction and immutable payloads keeps the original intent (fix: mask secrets before live tool-result delivery #146596: Mask recognized secrets before model delivery while rechecking changed policy and preserving prepared bytes.)
  • Browser conversation cache affinity keeps the original intent (f702469: The Gateway workflow split carried the existing opaque key helper forward; its original introduction was not established.)
  • Anthropic live transport harness keeps the original intent (fix(anthropic): preserve cache reuse across transient runtime context #140621: Prove growing stable-prefix reuse through real provider-reported cache reads and writes without retries.)
  • Command auth-profile selection keeps the original intent (unknown: The base explicitly prioritizes a user session choice over configured model affinity and stale automatic selection; the extraction preserves that logic.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 4895fbb adds packages/ai/src/transports/anthropic-payload-policy.ts:338 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 4895fbb191c3; files: packages/ai/src/transports/anthropic-payload-policy.ts)
  • Vincent Koc: Raw commit 067496b adds src/agents/anthropic-payload-policy.ts:61 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 067496b12934; files: src/agents/anthropic-payload-policy.ts)
  • Ayaan Zaidi: Raw commit c718afe adds src/agents/anthropic-payload-policy.ts:148 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: c718afe24706; files: src/agents/anthropic-payload-policy.ts)

PR surface

Source +101, Tests +1646, Docs +174, Config +14, Other +421. Total +2356 across 42 files. Added test files: 4.

View PR surface stats
Area Files Added Removed Net
Source 14 304 203 +101
Tests 16 1800 154 +1646
Docs 5 175 1 +174
Config 2 16 2 +14
Generated 0 0 0 0
Other 5 554 133 +421
Total 42 2849 493 +2356

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit. Replaced prior rating: 🦪 silver shellfish.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Replay and checkpoint instability increases provider cache misses and inference cost without establishing an urgent availability or delivery failure.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit. Replaced prior rating: 🦪 silver shellfish.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (5 earlier review cycles)
  • reviewed 2026-10-10T10:46:08.121Z sha 457a26d :: needs changes before merge. :: [P2] Preserve redaction preparation when capping live tool results
  • reviewed 2026-10-10T10:57:05.611Z sha 457a26d :: needs changes before merge. :: [P2] Preserve redaction preparation when capping live tool results
  • reviewed 2026-10-10T11:05:11.410Z sha 457a26d :: needs changes before merge. :: [P2] Preserve redaction preparation when capping live tool results
  • reviewed 2026-10-10T13:26:51.377Z sha 298ddf6 :: needs changes before merge. :: none
  • reviewed 2026-10-10T13:47:59.590Z sha 298ddf6 :: needs changes before merge. :: [P2] [P2] Exclude verified transient carriers from the matrix prefix

Reviewed October 10, 2026, 6:01 PM ET / 22:01 UTC (Revision 6).

@steipete
steipete marked this pull request as draft October 10, 2026 10:54
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. labels Oct 10, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Addressed the redaction preparation finding. The truncation producer preserves preparation only for identical text. Shortened text is prepared before publication, and one event-scoped preparer retains the already-redacted uncapped source until listener and write settlement finish. This preserves full context for late patterns without introducing a session/process cache; listener text replacements invalidate the projection, and policy/secret-registry revisions still control re-preparation.

Regression coverage now compares listener, provider, persisted, and reopened text for oversized multi-block and single-block results, late patterns, secret registration, and listener text replacement. The final proof and gate results are recorded in the PR body.

@steipete
steipete marked this pull request as ready for review October 10, 2026 13:19
@steipete
steipete marked this pull request as draft October 10, 2026 13:39
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 10, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

The CI follow-up confirms two distinct issues.

The UI ownership guard failure reproduces on unchanged main 7b125134f3860743c55696b3f273ed82abe535dc: ui/src/e2e/browser-capabilities.e2e.test.ts is missing from the existing private-server inventory. This PR does not touch that fixture or inventory.

The prompt-prefix gate exposed a real Anthropic breakpoint issue after steering and reopen. A synthetic request has unretained runtime context at history index 24, but its cache marker is at index 25. On reopen, that context disappears, changing bytes inside the marked prefix. The policy currently skips placing a marker on an opted-out message but still permits a marker after it. The prepared owner fix stops the cacheable prefix at the first opted-out message.

The local follow-up is rebased onto current main. Its harness compares the actual marked prefix and directly rejects any breakpoint that includes unretained runtime context. That guard fails on the current provider implementation, as expected: boundary proof. The draft remains open while the provider-owner fix is coordinated; marked context is not being exempted from comparison.

Share live and persisted tool-result preparation, preserve canonical projection
identity through replay normalization, and keep the browser conversation cache
key for internal child completions.

Add four-family admitted-turn and real Gateway child/restart regression checks.
Extend the existing live-cache release gate with full-prefix and per-turn cache
reuse assertions, and document its cost and coverage boundaries.
Keep valid preparation metadata on unchanged text blocks and prepare shortened
text before publication. Retain uncapped, already-redacted text only for the
current event so late listener policies can match their full context, while
listener text replacements invalidate the projection.

Extend listener, provider, persistence, and reopen coverage for oversized and
shortened results, late patterns, secret registration, and text replacement.
@steipete
steipete force-pushed the steipete/perf-micro-prompt-cache-release-e2e-20260919 branch from 298ddf6 to 73b0a1c Compare October 10, 2026 21:44
@steipete steipete changed the title fix(agents): preserve prompt-cache prefixes across tool replay fix(agents): guard prompt-cache reuse across replay and releases Oct 10, 2026
@steipete
steipete marked this pull request as ready for review October 10, 2026 21:47
@steipete
steipete merged commit d13db41 into main Oct 10, 2026
237 of 238 checks passed
@steipete
steipete deleted the steipete/perf-micro-prompt-cache-release-e2e-20260919 branch October 10, 2026 22:03
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
…nclaw#168392)

* fix(agents): preserve prompt cache prefixes across replay

Share live and persisted tool-result preparation, preserve canonical projection
identity through replay normalization, and keep the browser conversation cache
key for internal child completions.

Add four-family admitted-turn and real Gateway child/restart regression checks.
Extend the existing live-cache release gate with full-prefix and per-turn cache
reuse assertions, and document its cost and coverage boundaries.

* fix(agents): preserve redaction through capped tool-result settlement

Keep valid preparation metadata on unchanged text blocks and prepare shortened
text before publication. Retain uncapped, already-redacted text only for the
current event so late listener policies can match their full context, while
listener text replacements invalidate the projection.

Extend listener, provider, persistence, and reopen coverage for oversized and
shortened results, late patterns, secret registration, and text replacement.

* fix(anthropic): keep cache checkpoints before transient context
RomneyDa added a commit that referenced this pull request Oct 11, 2026
Keep up to two Anthropic conversation checkpoints so a prior write stays
reachable when a new turn exceeds the provider's 20-block lookback, and
place every conversation checkpoint before transient runtime context
(steering and tool loops after an unretained carrier).

Backport of 4895fbb (#168042) adapted for 2026.10.2:
Anthropic Messages payload policy only; the Bedrock cache-policy
consolidation from that PR is not included.
Also includes the Anthropic checkpoint part of
d13db41 (#168392)
("keep cache checkpoints before transient context").
RomneyDa pushed a commit that referenced this pull request Oct 11, 2026
…8392)

Share live and persisted tool-result preparation so the text first sent
to the model is capped and redacted once and replayed byte-identically
after persistence, replay, and reopen (including oversized results and
late listener redaction changes). Preserve canonical tool-result
projection identity through replay normalization, keep the browser
conversation cache key for internal child completions, and disambiguate
repeated native OpenAI Chat Completions tool-call IDs deterministically.

Backport of d13db41 (#168392) adapted for 2026.10.2:
- the Anthropic checkpoint part ships in the #168042 port commit
- live-cache release-gate, workflow, and release-docs changes are not included;
  the offline prefix-stability helper is kept for the new regression tests
- the attempt auth-selection extraction (no behavior change) is not included
- the admitted-turn regression test declares this line's image retention
  (rolling three-turn window), its trailing transient Chat Completions
  carrier, and keeps one instruction revision because in-history instruction
  updates for those routes are not on 2026.10.2
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 15, 2026
Upstream first-parent #1297, stopping just before #1298 (tool-call XML
grouping) so that change gets its own step. Four conflicts:

- delivery-queue-sqlite-bound: keep both imports, upstream's
  emptyOutboundDeliveryQueueAdmission (openclaw#168643) and our row codec type.
- attempt-execution: keep our startAttemptContinuation; take upstream's
  resolveCommandAuthProfileSelection (openclaw#168392). Upstream's other edits in
  the file (inlined pinnedHarnessId, internal-continuation promptCacheKey)
  merged cleanly; our resolveClaudeCliFallbackPrelude extraction is
  untouched by upstream.
- session.test: keep our custody test state; take upstream's
  buildCommandContextForTest (openclaw#168482).
- plugin-sdk-surface-report: measured 3683/2137 (upstream 3672/2133, +11/+4).

Also: test-mock-exports baseline pruned 10162 -> 10142 (20 stale rows from
#1433's fixes; shrink only, check --prune), worker-access-inventory regen.
pnpm install after the lockfile change.

tsgo core/core-test/ext/ext-projects 0; sdk --check 0; inventory 0;
config docs 0; mock-export ratchet OK. db-worker ratchet 706 -> 709 vs
upstream is #1432 (unchanged vs step 25).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Jhynq2GVpzuVQQieebEubg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docker Docker and sandbox tooling docs Improvements or additions to documentation extensions: openai gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts security-sensitive-changed size: XL 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.

1 participant