Skip to content

fix(agents): OpenAI session forks reuse the parent's prompt cache - #197226

Merged
obviyus merged 2 commits into
mainfrom
openclaw/openai-fork-prompt-cache
Nov 11, 2026
Merged

obviyus merged 2 commits into
mainfrom
openclaw/openai-fork-prompt-cache

Conversation

@obviyus

@obviyus obviyus commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Session forks (Advisor reviews, /btw forks, forkSession) on OpenAI Responses never read the parent's prompt cache. Each review reprocessed the whole conversation at full input price. On the bundled openai route the fork was also about 2.5x the parent's prompt.

Live measurement on current main (isolated Gateway, openai/gpt-5.6-luna, one parent turn with 3 session_status calls, Advisor everyToolCalls: 1) found four request differences between the fork and the parent it replays:

Fork field (main) Parent Owner
no prompt_cache_key <sessionId>:<boundaryCount> session-fork.ts deleted it on every fork
hosted {type:"web_search"} added omitted by the tool policy btw-stream.ts passed no native web-search policy context to applyExtraParamsToAgent
reasoning: {effort:"none"} unset (thinking off) btw-stream.ts sent mapThinkingLevel() = "off", not the parent's resolveAgentReasoningOption()
reasoning: {effort:"none"} {effort:"low"} (agent thinkingDefault: low) btw-stream.ts used only the session override, not the agent/model thinking default

Why the key was deleted, and why it is safe to send

#182844 deleted the key because a rebuilt fork "does not share the parent's complete request preparation". #196754 (keep the key) was closed because the key was believed not to steer GPT-5.6+ caching. Measured replay shows the key decides whether a GPT-5.6 request can read another request's cache: without it the parent-identical prefix read 0 tokens. Forks remain independent requests (independentResponsesRequest; no previous_response_id; native WebSocket forks still use their own socket, see the updated llm-idle-timeout.codex-ws-chain test). A key that does not match the prefix costs at most a cache miss. This change also makes the fork's hosted tools and reasoning match the parent's, so the fork shares the parent's request preparation for every field that affects the cached prefix.

Change

  • session-fork.ts: stop deleting prompt_cache_key.
  • session-fork-context.ts: return the parent's key. For a running parent, the attempt's exact key, exposed on the live snapshot. For a completed session, the default resolveSessionBoundaryPromptCacheKey derivation normal turns use.
  • btw-stream.ts (fork path only):
  • The live snapshot type moves to src/sessions/session-fork-context.types.ts. Tool-schema projection moves to the fork consumer. Both changes keep two files under the 700-line cap.
  • docs/plugins/sdk-runtime.md: updated the fork cache-identity text.

Evidence

Per-variable live replays (one variable each, real OpenAI API, gpt-5.6-luna)

Method: each row first sends a fresh parent-shaped request (unique nonce prefix, parent fields). It then sends the fork body with only that one field changed and records the fork's input / cached / cache_write tokens. Every row ran twice with the same result (±3 tokens).

Bundled openai route (fork captured on main, parent prefix ≈ 3058):

Variant Fork input Cached Written
Fork as on main (no key, +web_search, effort none) 7737 0 7662
All fields matched to parent, tool_choice:"none" (this PR) 3305 2984 246
matched, minus prompt_cache_key 3305 0 3230
matched, plus hosted web_search 7743 0 7668
matched, plus reasoning:{effort:"none"} (parent unset) 3303 0 3228
matched, minus access_programs 3304 2983 246 (no effect, so not changed)
matched, minus tool_choice (parent-identical) 3307 3058 246 (tool_choice:"none" costs ~72 tokens; required for tool-free forks)

Thinking default (thinkingDefault: low, parent sends effort: low):

Variant Cached
matched (effort: low) 3009
matched but effort: none (main) 0

Custom openai-responses provider (fork 4 vs preceding parent, prefix ≈ 3320):

Variant Cached
Fork as on main 0
+ prompt_cache_key 2522
+ parent runtime-context carrier order 0
+ key + parent carrier order 3247

Live before/after through the real route (isolated Gateway, Advisor reviews, provider usage)

Bundled openai/gpt-5.6-luna, thinking off:

Fork 1 input / cached / written Parent prefix before fork 1 Fork 2 input / cached / written Parent prefix before fork 2
main 7714 / 0 / 7639 2637 aborted (run ended) 3226
this PR (final head) 3270 / 2949 / 246 2653 3756 / 3435 / 246 3126–3435

Bundled openai/gpt-5.6-luna, thinkingDefault: low:

Fork 1 Fork 2
main 7739 / 0 / 7664 (effort: none, +web_search) 8247 / 6927 / 1245 (reads only fork 1's entry)
this PR 3339 / 3018 / 246 (effort: low) 3696 / 3018 / 603 (parent prefix 3090)

On the bundled route each fork now reads the parent's cached prefix, minus the ~72-token tool_choice difference, and writes only its own question.

Custom openai-responses provider (openai-custom/gpt-5.6-luna):

Fork 1 cached / parent prefix Fork 2 cached / parent prefix
main 0 / 2714 2494 / 2994–3294 (reads fork 1's entry, not the parent's)
this PR 2495 / 2715 2495 / 2996–3297

Known gap: custom routes without in-history system updates do not fully reach the bar

On this route the fork reads the parent's instructions and tools but not the current turn's history. The live fork context orders the runtime-context carrier before the current user prompt. The parent's provider request carries it after the prompt (the replay above: fixing the order raises fork reads from 2522 to 3247). The parent is not consistent here either. In another main run it dropped the carrier on a later request and its own cache read fell from 2990 to 2559. The right fix belongs at the parent's carrier placement, not the fork, so this PR leaves it alone. In long sessions only the current turn's tail is lost, because older carriers are stripped in both requests. The bundled openai route, which uses in-history developer updates, is unaffected.

Tests

  • Regression in embedded-agent-runner.session-fork.test.ts (real embedded runtime, captured wire bytes). The OpenAI Responses parent's tool policy now omits web_search, and the test asserts the fork matches the parent's tools, prompt_cache_key and reasoning, for both completed and running parents. On main it fails with the hosted web_search tool (Responses) and a missing key (Completions). On this branch it passes.
  • llm-idle-timeout.codex-ws-chain.test.ts: the native WebSocket fork now sends the parent key while keeping its own socket and leaving the parent's continuation in place.
  • Passing: fork, fork-transport, ws-chain, cache-ttl, attempt-stream-prepare, btw, prompt-prefix stability and Advisor tests. OPENCLAW_CHECK_CHANGED_SKIP_DEADCODE=1 pnpm check:changed is clean. Test-lines ratchet: OK, net −1 after the rebase onto fix(agents): fork sessions on every guarded provider transport #197223/fix(agents): stop Anthropic session forks from caching their own suffix #197224. Line-cap ratchet: OK.

Other observation (not changed)

Advisor cancels in-flight reviews when the run ends (extensions/advisor/index.ts, cancel signal), which explains the aborted OpenAI forks. This is intended Advisor behavior and does not affect the parent cache.

Rebased onto #197203 (merged). The thinking-default condition now covers anthropic-messages || openai-responses. A live run on the rebased head (bundled route) shows fork 1 at 3311 input / 2990 cached / 246 written, with a 2641 parent prefix.

Rebased onto #197223/#197224

Rebased onto main at 83fd655, which includes #197223 (forks on every guarded transport except Bedrock) and #197224 (Anthropic fork-only tail marked uncached). Git merged session-fork.ts without manual edits. The result keeps all three behaviors: the Bedrock-only rejection, guarded fetch and tool_choice: none for the four known APIs (#197223); the uncachedSuffixMessage marks on the fork-only tail (#197224); and this PR's prompt_cache_key, hosted-tool policy, parent reasoning and fork-side tool-schema projection.

Live runs after the rebase. Each uses an isolated Gateway with a static API key, Advisor reviews and provider usage. Values are input / cached / written. main is 83fd655:

Bundled openai/gpt-5.6-luna, thinking off:

Fork 1 Parent request beside fork 1 (cached) Fork 2
main 7724 / 0 / 7649 (no key, +web_search, effort: none) 2669 8188 / 6946 / 1167 (reads only fork 1's entry)
this PR (rebased) 3420 / 2611 / 734 2683 aborted (run ended)

Bundled openai/gpt-5.6-luna, thinkingDefault: low:

Fork 1 Parent request beside fork 1 (cached)
main 7759 / 0 / 7684 (effort: none, +web_search) 2693
this PR (rebased) 3323 / 2624 / 624 (effort: low, same as the parent) 2696

After the rebase, the fork again reads the parent's cached prefix: 2611 vs 2683 and 2624 vs 2696, a gap of 72 tokens each, which is the known tool_choice: "none" cost. The fork's tools, prompt_cache_key and reasoning match the parent's request.

Direct Anthropic anthropic/claude-haiku-5-5 (thinking high, #197224 check): fork 1 is 889 / 4090 / 0. Its parent prefix is 4090, so the fork reads it all and writes nothing. #197224's cacheWrite: 0 still holds after this PR.

Compared with Hermes' cache-parity fork (hermes-agent/agent/background_review.py)

Hermes keeps the parent's cache scope and prompt_cache_key (build_cache_parity_fork, #109964) and copies the parent's reasoning config verbatim (_same_model_parity_kwargs, #30532). This PR now does both, and the replays above show each is required. Hermes also sends the parent's exact tools[] without changing tool_choice, and blocks calls at dispatch (_inherit_parent_tool_surface). I replayed that variable on the final-head forks, three times each:

Fork tool_choice: "none" cached tool_choice omitted cached Tool calls without tool_choice
1 (input 3270) 3195 3267 0 of 3
2 (input 3756) 3681 3753 0 of 3

Omitting it saves a fixed ~72 tokens per fork; the saving does not grow with context. OpenClaw already denies execution at dispatch, but a fork that does call a tool costs another round trip. I kept the documented tool_choice: "none" contract. Dropping it is a possible follow-up.

@clawsweeper

clawsweeper Bot commented Nov 11, 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 agents Agent runtime and tooling plugin: file-transfer size: S labels Nov 11, 2026
@clawsweeper clawsweeper Bot added the clawsweeper:intake:bug Preliminary submission classification; full source review pending. label Nov 11, 2026
@obviyus
obviyus force-pushed the openclaw/openai-fork-prompt-cache branch from 42568d5 to af619b4 Compare November 11, 2026 13:28
@clawsweeper clawsweeper Bot added clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 11, 2026
@clawsweeper

clawsweeper Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Session forks reuse the parent's prompt-cache key and align hosted-tool policy and reasoning settings with the parent request.

Example: An Advisor review forks an OpenAI Responses session with thinking off.

  • Before: The reported baseline fork reads 0 cached tokens.
  • After: The reported rebased fork reads 2611 cached tokens against the parent's 2683-token cached prefix.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused owner-based repair with supplied live provider evidence, relevant transport regressions, and no remaining actionable finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied live output exercises isolated Gateways with Advisor, real provider requests, thinking off and low, and before/after usage showing restored parent-cache reads; the cold-ancestor repair is supported by the extended production-path integration fixture.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Background session reviews repeatedly process conversation input that should reuse the parent's cached prefix.
Reason: Measured cache reads establish user value, and the collaborator-authored direction preserves the existing tool-free fork contract without adding configuration or persistent state.

Merge readiness

✅ Ready for maintainer review

This PR fixes a current cache-reuse defect and addresses the prior capability-preparation finding. No new actionable defect was found; required CI remains pending.

Priority: P2
Reviewed head: 280ad1dfbd6015d5e5d7bcc3f3bf33c723747437

Before merge

None.

Findings

None.

Agent review details

How this fits together

Advisor and plugin side questions borrow live session context or reconstruct persisted history, then send an independent, tool-free request through the existing provider transport.

flowchart TD
  A[Advisor or plugin question] --> B[Session fork preparation]
  C[Live attempt or persisted transcript] --> B
  B --> D[Parent cache identity and request settings]
  D --> E[Independent guarded provider request]
  E --> F[Answer and usage]
Loading

Technical review

Best possible solution:

Use the existing fork, request-preparation, and boundary-key owners to restore cache reuse while retaining tool denial and independent continuation state.

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

Current main shows the cache-key deletion and request-setting mismatches, and the author supplies controlled live reproductions; this read-only review executed no target code.

Is this the best way to solve the issue?

The patch addresses the measured request differences through existing owners; the documented custom-route carrier-order limitation belongs to the unchanged parent preparation path.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit 7743284 adds src/agents/btw-stream.ts:84 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7743284267c6; files: src/agents/btw-stream.ts)

PR surface

Source +25, Tests -2, Docs +7. Total +30 across 11 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 6 74 49 +25
Tests 4 29 31 -2
Docs 1 10 3 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 113 83 +30

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Root-cause cluster

Relationship: canonical
Canonical: #197226
Summary: This PR replaces the earlier unmeasured cache-key proposal with measured request alignment.

Members:

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

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🦞 diamond lobster, 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: The defect increases input-processing cost for optional background reviews without establishing an urgent outage.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-11T13:46:53.173Z sha af619b4 :: needs changes before merge. :: [P2] Prepare persisted capability reads before resolving fork policy

Reviewed November 11, 2026, 11:49 AM ET / 16:49 UTC (Revision 2).

@obviyus
obviyus force-pushed the openclaw/openai-fork-prompt-cache branch from af619b4 to 64b5a78 Compare November 11, 2026 15:51
Session forks resolve the parent's hosted web-search tool policy while
building the fork stream. For a delegated child, that policy reads the
persisted envelope of the child and its ancestors, and the fork had not
prepared those rows, so a cold row failed with "Session capability
metadata requires worker preparation" before any provider request.

Prepare the reads around the same applyExtraParamsToAgent call, as the
parent attempt does.

Co-authored-by: obviyus <[email protected]>
@obviyus

obviyus commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed 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. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 11, 2026
@obviyus
obviyus merged commit ae651f1 into main Nov 11, 2026
127 checks passed
@obviyus
obviyus deleted the openclaw/openai-fork-prompt-cache branch November 11, 2026 17:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. plugin: file-transfer proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S 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.

1 participant