Repository navigation
fix(agents): OpenAI session forks reuse the parent's prompt cache - #197226
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. |
42568d5 to
af619b4
Compare
|
Codex review: needs maintainer review before merge. What this changesSession 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.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherAdvisor 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]
Technical reviewBest 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
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +25, Tests -2, Docs +7. Total +30 across 11 files. Added test files: 0. View PR surface stats
Preflight sourceSource 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 clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. 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 (1 earlier review cycle)
Reviewed November 11, 2026, 11:49 AM ET / 16:49 UTC (Revision 2). |
Co-authored-by: obviyus <[email protected]>
af619b4 to
64b5a78
Compare
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]>
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
…enclaw#197226) Co-authored-by: obviyus <[email protected]>
What Problem This Solves
Session forks (Advisor reviews,
/btwforks,forkSession) on OpenAI Responses never read the parent's prompt cache. Each review reprocessed the whole conversation at full input price. On the bundledopenairoute 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 3session_statuscalls, AdvisoreveryToolCalls: 1) found four request differences between the fork and the parent it replays:prompt_cache_key<sessionId>:<boundaryCount>session-fork.tsdeleted it on every fork{type:"web_search"}addedbtw-stream.tspassed no native web-search policy context toapplyExtraParamsToAgentreasoning: {effort:"none"}btw-stream.tssentmapThinkingLevel()="off", not the parent'sresolveAgentReasoningOption()reasoning: {effort:"none"}{effort:"low"}(agentthinkingDefault: low)btw-stream.tsused only the session override, not the agent/model thinking defaultWhy 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; noprevious_response_id; native WebSocket forks still use their own socket, see the updatedllm-idle-timeout.codex-ws-chaintest). 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 deletingprompt_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 defaultresolveSessionBoundaryPromptCacheKeyderivation normal turns use.btw-stream.ts(fork path only):resolveAgentReasoningOption.anthropic-messagestoopenai-responses.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_writetokens. Every row ran twice with the same result (±3 tokens).Bundled
openairoute (fork captured on main, parent prefix ≈ 3058):tool_choice:"none"(this PR)prompt_cache_keyweb_searchreasoning:{effort:"none"}(parent unset)access_programstool_choice(parent-identical)tool_choice:"none"costs ~72 tokens; required for tool-free forks)Thinking default (
thinkingDefault: low, parent sendseffort: low):effort: low)effort: none(main)Custom
openai-responsesprovider (fork 4 vs preceding parent, prefix ≈ 3320):prompt_cache_keyLive before/after through the real route (isolated Gateway, Advisor reviews, provider usage)
Bundled
openai/gpt-5.6-luna, thinking off:Bundled
openai/gpt-5.6-luna,thinkingDefault: low:effort: none, +web_search)effort: low)On the bundled route each fork now reads the parent's cached prefix, minus the ~72-token
tool_choicedifference, and writes only its own question.Custom
openai-responsesprovider (openai-custom/gpt-5.6-luna):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
openairoute, which uses in-history developer updates, is unaffected.Tests
embedded-agent-runner.session-fork.test.ts(real embedded runtime, captured wire bytes). The OpenAI Responses parent's tool policy now omitsweb_search, and the test asserts the fork matches the parent's tools,prompt_cache_keyandreasoning, for both completed and running parents. Onmainit fails with the hostedweb_searchtool (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.OPENCLAW_CHECK_CHANGED_SKIP_DEADCODE=1 pnpm check:changedis 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,cancelsignal), 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
mainat 83fd655, which includes #197223 (forks on every guarded transport except Bedrock) and #197224 (Anthropic fork-only tail marked uncached). Git mergedsession-fork.tswithout manual edits. The result keeps all three behaviors: the Bedrock-only rejection, guarded fetch andtool_choice: nonefor the four known APIs (#197223); theuncachedSuffixMessagemarks on the fork-only tail (#197224); and this PR'sprompt_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.
mainis 83fd655:Bundled
openai/gpt-5.6-luna, thinking off:effort: none)Bundled
openai/gpt-5.6-luna,thinkingDefault: low:effort: none, +web_search)effort: low, same as the parent)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'stools,prompt_cache_keyandreasoningmatch 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'scacheWrite: 0still 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 exacttools[]without changingtool_choice, and blocks calls at dispatch (_inherit_parent_tool_surface). I replayed that variable on the final-head forks, three times each:tool_choice: "none"cachedtool_choiceomitted cachedtool_choiceOmitting 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.