Repository navigation
perf(agents): preserve prompt cache across instruction refreshes - #167698
Conversation
Pin the complete system prompt through the existing transcript-backed series owner and deliver refreshed sections as appended instructions. Enable the native OpenAI Responses path while preserving provider role compatibility. Keep personal bootstrap scoped to the selected profile, and report bounded section changes without retaining prompt contents in cache diagnostics.
|
🦞👀 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 changesThe agent preserves its initial instructions for provider cache reuse and appends refreshed skills, memory, and runtime guidance without rewriting earlier requests. Example: Instructions change from “Skill 0” to “Skill 1” between conversation turns.
Review scores
ProductKind: Performance · Worth it: Yes Merge readiness✅ Ready for maintainer review This PR addresses a current-main gap through the existing prompt-series owner. No blocking correctness or security defect was found. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherThe embedded agent combines workspace instructions and conversation history into model requests. Its transcript-backed prompt-series owner preserves previously sent instructions while provider transports encode subsequent updates. flowchart TD
A[Skills and workspace instructions] --> B[Prompt renderer]
B --> C[Transcript-backed prompt series]
D[Saved checkpoint and conversation] --> C
C --> E{Route or profile changed?}
E -->|Yes| F[Start fresh instruction series]
E -->|No| G[Keep initial prompt and append updates]
F --> H[Provider model request]
G --> H
Technical reviewBest possible solution: Keep instruction refresh and invalidation in the existing transcript-backed prompt-series owner. Do we have a high-confidence way to reproduce the issue? Yes: current main reconstructs the suffix and rejects checkpoint restoration when refreshed instructions differ. The submitted regression targets the second fresh attempt and is reported to fail before the fix; it was not rerun during this read-only review. Is this the best way to solve the issue? Yes: extending the existing prompt-series owner avoids a competing cache or refresh mechanism, and preserves explicit route, profile, reset, and compaction invalidation. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against c4887fb7de36. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +102, Tests +282, Docs +3. Total +387 across 16 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
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 Reviewed October 9, 2026, 4:00 AM ET / 08:00 UTC. |
…nclaw#167698) Pin the complete system prompt through the existing transcript-backed series owner and deliver refreshed sections as appended instructions. Enable the native OpenAI Responses path while preserving provider role compatibility. Keep personal bootstrap scoped to the selected profile, and report bounded section changes without retaining prompt contents in cache diagnostics.
## What Problem This Solves Fixes: the provider prompt cache misses completely on session-event turns, for example the exec-exit notification after a background `exec`. On real OpenAI that turn read 0 cached tokens, and the next turn missed part of its prefix again. The tool block changed on that turn in three ways. Each one alone breaks the cached prefix: 1. The turn builds fewer tools. It replays the producing turn's allowlist, which leaves out owner-only tools (`automations`, `conversations_*`). 2. The descriptions of `exec`, `process` and `sessions_send` change, because they name sibling tools (`applyToolAvailabilityDescriptions`) and those siblings are missing. 3. The provider-hosted `web_search` drops out of the request. The saved event allowlist holds only function tools, so the hosted tool's runtime gate saw no `web_search` entry. ## Why This Change Was Made #167698 already pins the system prompt per session in the transcript-backed prompt series. This extends the same owner to the tool block: - **Pin the tool list.** The session pins every tool definition it has sent (`prepareSessionToolSurface`, `session-prompt-state.ts`). A turn that builds fewer tools still sends the pinned definitions. A call to a tool this turn did not build is refused through `gateAgentToolExecution` (#175309), so authority is unchanged. - **Pin descriptions.** Within a pin, a tool keeps its pinned description while its parameters match. A new tool or a parameter change extends the pin once. - **When a new pin starts.** On a route or model change, compaction or reset, and when the tool policy config (`tools`, the agent's `tools`) changes, so configured removals leave the request. Only a digest of that config is stored. - **Storage.** The pin lives in the existing `openclaw.system-prompt` checkpoint entry. Routes without in-history prompt updates write a tools-only checkpoint. No schema change. - **Permission refresh.** It rebuilds the pinned surface from the current tool generation, so new executors replace revoked ones. - **Hosted `web_search`.** The saved session-event allowlist keeps it when the producing turn's full conversation policy allowed it (`isConversationToolAllowed`: profile, group, sender, sandbox, subagent and runtime caps). An event turn cannot gain `web_search` that its producer did not have. - **Compaction.** A checkpoint carries the pinned tools only when the pin's route and history match the snapshot, so compaction or a route change retires the pin, and the next attempt pins the current tools. - **`OPENCLAW_PROMPT_CACHE_ASSERT=1`.** It now also throws on tool-block changes within a session, except a pin change the pin declared, and names the turn (trigger, provenance, reply mode). ## User Impact Background and event turns reuse the cached prefix. No change to which tools a turn may run. ## Evidence Real OpenAI (`gpt-6-sol`, direct to `api.openai.com`) through the Gateway and a Telegram mock-user scenario: two user turns, image generation, a subagent spawn, a background `exec`, a system event and a closing user turn. Cached share of prompt tokens per request, from the Gateway's usage records: | Turn | Before | After | |---|---|---| | User turns | 94–98% | 92–98% | | Image completion | 98% | 99% | | Subagent completion | 98% | 98% | | **Exec-exit event** | **0%** | **95%** (94% in a second run) | | Turn after the event | 85% | 86% | | Whole session | 83.1% | 87.5% | The first request of each session and each new subagent is cold (0%) on both sides. Hosted-search authority at the final provider request (same real-OpenAI setup, request tool lists from `OPENCLAW_DEBUG_MODEL_PAYLOAD=tools`). The producing turn starts a background `exec` that sleeps 90 s. While it sleeps, the Gateway config gets `tools.deny: ["web_search"]` (hot reload): | Request | Tools sent | Hosted `web_search` | |---|---|---| | User turn and `exec` call, before the deny | 52 | sent | | Exec-exit event, after the deny | 39 | **not sent** | | Later user turns | 53 | not sent | A producer that sender policy denies search (`tools.toolsBySender: {"*": {deny: ["web_search"]}}`) sends 51 tools without hosted `web_search` on every request. That includes its exec-exit event, which reads 93.5% cached. The queued event does not keep hosted search after a revocation. The policy change also starts a new pin, which costs one cache miss, as designed. The allowed case is the exec-exit row in the cache table above: 52 tools, `web_search` sent. - Unit tests (`session-prompt-state.test.ts` and others): - A background turn keeps the user turn's definitions and refuses a missing tool. - The pin survives a restart, a prompt-series restart during admission and a system-prompt-only checkpoint. - A route or policy change starts a new pin. - A sibling-only description change keeps the pinned text. - A permission refresh uses the new executors. - The assert admits one declared pin change. - The session-event allowlist keeps hosted `web_search`. - Compaction retires the pin instead of carrying it into the new history. - A checkpoint written before this change (no `tools` key) still restores the system-prompt series, and a new pin starts from it. - Hosted search: a producer whose policy denies `web_search` saves no `web_search` entry. A saved entry still yields to the current policy when the event turn sends its request (`resolveWebSearchToolPolicy` with `tools.deny`). Each test for a fix fails without that fix. The pre-change checkpoint test and the two hosted-search policy tests cover behavior that already holds. - E2E: compaction hot-reload passes on the final head. On the previous head, background-exec restart, session resume restart, restored-requester settle, heartbeat session routing, subagent current-requester and the SQLite flip proof all pass (14/14). Earlier commits on this branch also passed the compaction hot-reload, image-generation, silent-reply, chat-tools and approval suites. One test expectation changed (`gateway-session-resume-restart`): a stale `exec` call after recovery restricted the session is still refused and its effect still never happens. The refusal now comes from the pinned gate, so the wording differs. - Upgrade: `pnpm test:docker:published-upgrade-survivor` from the current `latest` (`[email protected]`) passes on this head (881 s, no failures). An earlier run from `[email protected]` passed as well (915 s). The lane installs the published release with seeded config, sessions and transcripts, then updates in place to this branch. The Gateway, config and stored state survive. - Harness fix: the SQLite flip-proof helper now skips compressed (`event_zstd`) transcript rows, which the larger checkpoint entry produces. ## Merge danger Two-way door for behavior: a revert stops pinning, and older code ignores the `tools` field in checkpoint entries. Blast radius: the tool block of every embedded-runner request, and the allowlist stored with background exec and session events. Co-authored-by: Ayaan Zaidi <[email protected]>
## What Problem This Solves Fixes: the provider prompt cache misses completely on session-event turns, for example the exec-exit notification after a background `exec`. On real OpenAI that turn read 0 cached tokens, and the next turn missed part of its prefix again. The tool block changed on that turn in three ways. Each one alone breaks the cached prefix: 1. The turn builds fewer tools. It replays the producing turn's allowlist, which leaves out owner-only tools (`automations`, `conversations_*`). 2. The descriptions of `exec`, `process` and `sessions_send` change, because they name sibling tools (`applyToolAvailabilityDescriptions`) and those siblings are missing. 3. The provider-hosted `web_search` drops out of the request. The saved event allowlist holds only function tools, so the hosted tool's runtime gate saw no `web_search` entry. ## Why This Change Was Made openclaw#167698 already pins the system prompt per session in the transcript-backed prompt series. This extends the same owner to the tool block: - **Pin the tool list.** The session pins every tool definition it has sent (`prepareSessionToolSurface`, `session-prompt-state.ts`). A turn that builds fewer tools still sends the pinned definitions. A call to a tool this turn did not build is refused through `gateAgentToolExecution` (openclaw#175309), so authority is unchanged. - **Pin descriptions.** Within a pin, a tool keeps its pinned description while its parameters match. A new tool or a parameter change extends the pin once. - **When a new pin starts.** On a route or model change, compaction or reset, and when the tool policy config (`tools`, the agent's `tools`) changes, so configured removals leave the request. Only a digest of that config is stored. - **Storage.** The pin lives in the existing `openclaw.system-prompt` checkpoint entry. Routes without in-history prompt updates write a tools-only checkpoint. No schema change. - **Permission refresh.** It rebuilds the pinned surface from the current tool generation, so new executors replace revoked ones. - **Hosted `web_search`.** The saved session-event allowlist keeps it when the producing turn's full conversation policy allowed it (`isConversationToolAllowed`: profile, group, sender, sandbox, subagent and runtime caps). An event turn cannot gain `web_search` that its producer did not have. - **Compaction.** A checkpoint carries the pinned tools only when the pin's route and history match the snapshot, so compaction or a route change retires the pin, and the next attempt pins the current tools. - **`OPENCLAW_PROMPT_CACHE_ASSERT=1`.** It now also throws on tool-block changes within a session, except a pin change the pin declared, and names the turn (trigger, provenance, reply mode). ## User Impact Background and event turns reuse the cached prefix. No change to which tools a turn may run. ## Evidence Real OpenAI (`gpt-6-sol`, direct to `api.openai.com`) through the Gateway and a Telegram mock-user scenario: two user turns, image generation, a subagent spawn, a background `exec`, a system event and a closing user turn. Cached share of prompt tokens per request, from the Gateway's usage records: | Turn | Before | After | |---|---|---| | User turns | 94–98% | 92–98% | | Image completion | 98% | 99% | | Subagent completion | 98% | 98% | | **Exec-exit event** | **0%** | **95%** (94% in a second run) | | Turn after the event | 85% | 86% | | Whole session | 83.1% | 87.5% | The first request of each session and each new subagent is cold (0%) on both sides. Hosted-search authority at the final provider request (same real-OpenAI setup, request tool lists from `OPENCLAW_DEBUG_MODEL_PAYLOAD=tools`). The producing turn starts a background `exec` that sleeps 90 s. While it sleeps, the Gateway config gets `tools.deny: ["web_search"]` (hot reload): | Request | Tools sent | Hosted `web_search` | |---|---|---| | User turn and `exec` call, before the deny | 52 | sent | | Exec-exit event, after the deny | 39 | **not sent** | | Later user turns | 53 | not sent | A producer that sender policy denies search (`tools.toolsBySender: {"*": {deny: ["web_search"]}}`) sends 51 tools without hosted `web_search` on every request. That includes its exec-exit event, which reads 93.5% cached. The queued event does not keep hosted search after a revocation. The policy change also starts a new pin, which costs one cache miss, as designed. The allowed case is the exec-exit row in the cache table above: 52 tools, `web_search` sent. - Unit tests (`session-prompt-state.test.ts` and others): - A background turn keeps the user turn's definitions and refuses a missing tool. - The pin survives a restart, a prompt-series restart during admission and a system-prompt-only checkpoint. - A route or policy change starts a new pin. - A sibling-only description change keeps the pinned text. - A permission refresh uses the new executors. - The assert admits one declared pin change. - The session-event allowlist keeps hosted `web_search`. - Compaction retires the pin instead of carrying it into the new history. - A checkpoint written before this change (no `tools` key) still restores the system-prompt series, and a new pin starts from it. - Hosted search: a producer whose policy denies `web_search` saves no `web_search` entry. A saved entry still yields to the current policy when the event turn sends its request (`resolveWebSearchToolPolicy` with `tools.deny`). Each test for a fix fails without that fix. The pre-change checkpoint test and the two hosted-search policy tests cover behavior that already holds. - E2E: compaction hot-reload passes on the final head. On the previous head, background-exec restart, session resume restart, restored-requester settle, heartbeat session routing, subagent current-requester and the SQLite flip proof all pass (14/14). Earlier commits on this branch also passed the compaction hot-reload, image-generation, silent-reply, chat-tools and approval suites. One test expectation changed (`gateway-session-resume-restart`): a stale `exec` call after recovery restricted the session is still refused and its effect still never happens. The refusal now comes from the pinned gate, so the wording differs. - Upgrade: `pnpm test:docker:published-upgrade-survivor` from the current `latest` (`[email protected]`) passes on this head (881 s, no failures). An earlier run from `[email protected]` passed as well (915 s). The lane installs the published release with seeded config, sessions and transcripts, then updates in place to this branch. The Gateway, config and stored state survive. - Harness fix: the SQLite flip-proof helper now skips compressed (`event_zstd`) transcript rows, which the larger checkpoint entry produces. ## Merge danger Two-way door for behavior: a revert stops pinning, and older code ignores the `tools` field in checkpoint entries. Blast radius: the tool block of every embedded-runner request, and the allowlist stored with background exec and session events. Co-authored-by: Ayaan Zaidi <[email protected]>
What Problem This Solves
Skill, workspace-memory, and runtime refreshes could replace an established system prompt and discard the conversation's reusable prefix. A 24-hour production sample reported 114 stable-prompt and 105 suffix changes accompanying cache-read drops. These counts overlap with other cache-break causes.
User Impact
Native OpenAI Responses and supported direct Anthropic sessions retain their initial system prompt while receiving refreshed instructions as appended messages. Existing skill, memory, tool-policy, and permission refreshes remain effective. Route or selected personal-profile changes, reset, and compaction start a fresh series.
Why This Change Was Made
Reuse the existing transcript-backed prompt-series owner for the complete prompt, including its suffix. Restore its last rendered instructions after attempt disposal instead of requiring fresh inputs to match. The OpenAI plugin opts native Responses into this path, and its transport preserves instruction authority and position. The selected human profile joins the series identity so a shared session cannot pin the previous person's personal bootstrap. Unsupported endpoints retain their existing behavior.
No new configuration, checkpoint fields, database schema, or cache is introduced. Older checkpoints whose route/profile identity no longer matches naturally start a fresh series. Cache diagnostics name changed sections using bounded labels and hashes without logging prompt contents or arbitrary headings.
Production LOC: +102 (+82 diagnostics, +18 native policy/transport handling, +2 profile invalidation; the snapshot owner is net neutral). The requested diagnostic and instruction-authority contracts require that growth; the fresh-suffix reconstruction path and matching-input restore condition are removed.
Evidence
A 288-turn session simulating 24 hours used the production renderer, transcript checkpoints, attempt teardown/reacquisition, model boundary, and Responses payload builder. Skills and memory refreshed throughout, with a date rollover:
All 47 instruction updates were appended. This trades modest projection overhead for greater cache reuse.
A native OpenAI Responses control check (
gpt-5.6-luna, cold initial turns) changed the same verification instruction. Rebuildinginstructionsread 0 cached tokens and had 1,533 uncached input tokens. Pinning instructions and appending the update read 1,504 cached tokens, leaving 54 uncached input tokens. Both returned the updated answer. This is one cache observation; it does not establish a latency improvement (1,034 versus 1,356 ms).The separate three-turn production-transport live proof also kept instructions identical and obeyed the updated instruction. Cache reads were 0 → 1,372 → 1,396 tokens.
Validation:
tbx_01m4fc6bvj31j4amaspkav3a8v, profileopenclaw-check: focused owner/transport/policy/diagnostic command passed in 27.22 s; sibling replay/lifecycle command passed in 40.61 s, both with--maxWorkers=1.node scripts/check-changed.mjs --stagedpassed core types, all 27 core-test type shards, extension types/tests, and the preceding guards on the original candidate. It stopped at four inherited unused exports. The exact same production/full-tree findings reproduce on unchangedmain175146de74ad5103aa97f2a04c4d06423a84df56withnode --import ./scripts/tsx.mjs scripts/check-deadcode-exports.mts:bindCliQuestionAnswerAuthority,prepareSessionEventTargetForHost,readSessionEntryCreationTransition, andRESTART_CONTINUATION_CONTEXT_PREFIX. None is in this diff.tbx_01m4frgr5xe2jmskw0gxvyh64h(275.53 s, exit 0). No ignore or baseline was changed. An earlier rig typecheck was killed by global memory pressure; its successful replacement ran separately from the focused tests.0015e4a8f0c2preserves upstream fresh-session diagnostic reset and tool-change attribution. The affected observability/prompt-phase suites passed 79 tests after conflict resolution, and lint passed for the conflicted files. Fresh conflict-resolution review completed scoped-clean through P2 before the rebased commit was finalized.3d5897ed86ad6ff78bc626d55a83af0ec712f523: 486 s workflow wall time. Its 20 Node validation jobs totaled 2,970 runner-seconds, including shared setup and existing tests. The PR merged normally asa79e29ec04fc30517814ffcd28e713fe53540ed4; no admin exception or CI rerun was used.Focused validation commands
The first combined focused invocation exposed a fixture using the older provider entrypoint; the corrected test exercises the embedded Responses transport. The policy assertion was moved from an over-cap provider test file into its existing smaller Responses sibling. The commands above, plus that relocated-file run, provide the final focused proof.
Post-deployment production events/day is not yet measured; this PR does not deploy a Gateway. Synthetic prefix bytes and the small live control are not estimates of total production token savings.