Repository navigation
fix(agents): guard prompt-cache reuse across replay and releases - #168392
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
|
Codex review: needs maintainer review before merge. What this changesThis 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.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherAgent 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]
Technical reviewBest 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
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +101, Tests +1646, Docs +174, Config +14, Other +421. Total +2356 across 42 files. Added test files: 4. View PR surface stats
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (5 earlier review cycles)
Reviewed October 10, 2026, 6:01 PM ET / 22:01 UTC (Revision 6). |
|
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. |
|
The CI follow-up confirms two distinct issues. The UI ownership guard failure reproduces on unchanged main 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.
298ddf6 to
73b0a1c
Compare
…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
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").
…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
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
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-cacherelease job runs transport and real-agent cache checks, is selectable withlive_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
history[14].block.typetools[0].namesystem: equal byte length, different digesthistory[0].block.text, 102 → 43 serialized byteshistory[24], marker 25; digest-only diagnosticThe 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
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.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.tbx_01m4j17pvjsppz9qnpxt21zx15also 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.44e9f45main 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