Skip to content

fix(agents): keep prompt-cache routing for session forks - #196754

Closed
obviyus wants to merge 2 commits into
mainfrom
fix/fork-prompt-cache-key
Closed

obviyus wants to merge 2 commits into
mainfrom
fix/fork-prompt-cache-key

Conversation

@obviyus

@obviyus obviyus commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Session forks (Advisor reviews, /btw, forkSession) stopped sending prompt_cache_key in #182844. Normal turns send it.

On the team Gateway (openai/gpt-6.1-sol), 46 of 205 Advisor reviews today reported cacheRead=0. Each one is a fork of a conversation of about 20k–200k tokens, so a miss re-processes the whole context. On Anthropic, Peanutto missed on 2 of 166 reviews.

What restoring the key does and does not promise: on models before GPT-5.6 the key helps OpenAI route to the cached prefix. On GPT-5.6 and later, including the team route, it separates cache accounting and OpenAI routes automatically (prompt caching); earlier live observations saw new sessions start cold with or without a shared key. So this change restores the parent's cache identity for forks, but it is not an established fix for the team route's misses. Whether it changes that miss rate is unmeasured.

Why The Key Was Safe To Restore

#182844 removed the key because a rebuilt fork doesn't share the parent's complete request preparation. Isolation doesn't depend on the key:

  • Forks are marked independentResponsesRequest. The ChatGPT WebSocket path then acquires a socket with no session id, so a fork never consumes or replaces the parent's cached continuation.
  • llm-idle-timeout.codex-ws-chain.test.ts shows this with the key now sent: the fork uses its own socket ([2, 1] sends per socket), the parent's next request still continues from resp_native_1, and the fork carries no previous_response_id.
  • The key never selects a connection or continuation. A wrong or stale key costs at most a cache miss, which is no worse than today.

Change

  • A fork of a running parent sends that attempt's exact promptCacheKey (new optional promptCacheKey on the live fork-context snapshot).
  • A fork of a completed session sends the session's default OpenAI key, resolveSessionBoundaryPromptCacheKey (<sessionId>:<compaction boundary count>), the same derivation normal turns use.
  • session-fork.ts no longer deletes prompt_cache_key from the payload.
  • To stay under the 700-line cap without trimming, the live fork-context type moves to src/sessions/session-fork-context.types.ts, and the tool-schema projection moves to run/session-fork-tools.ts.
  • docs/plugins/sdk-runtime.md describes the new behavior and its limit.

Known Gaps

  • Run-only explicit keys: a key set for a single run (for example finalization:<runId>) is not recorded after the run ends. A fork of a completed session falls back to the default key. Forks of a running parent get the exact key.
  • Detached helper sessions route under a private session id. A fork uses the target session's default key instead.
  • Codex native forks take a different path and are unchanged.
  • Measured effect: not yet observed live. fix(advisor): log review cache writes #196704 (merged) adds cacheWrite to Advisor's usage log, so the team miss rate can be compared once the team Gateway runs a release with both changes.

Evidence

  • cacheRetention: "none" still suppresses the key. I ran the real OpenAI Responses fork test temporarily with cacheRetention: "none": both the parent and the fork, including a fork of a running parent, sent no prompt_cache_key. The tests use "short", and that change wasn't committed.
  • Updated regressions: completed and running-parent forks now assert replay.prompt_cache_key === original.prompt_cache_key. On main they fail (undefined).
  • Fork, fork-transport, WebSocket chain, cache-TTL, attempt-prepare, btw and advisor tests pass. pnpm tsgo:core and pnpm tsgo:core:test pass; oxlint is clean; the test-lines and line-cap ratchets pass.

Forks dropped prompt_cache_key since #182844, so on OpenAI routes Advisor
reviews missed the cache on 46 of 205 team reviews and rewrote the full
forked context. Connection custody never depended on the key: forks use
their own WebSocket and leave the parent's continuation untouched.

Send the running attempt's exact key, or the session's default
sessionId:boundaryCount key for completed sessions. cacheRetention none
still suppresses the key.

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

clawsweeper Bot commented Nov 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 agents Agent runtime and tooling plugin: file-transfer size: S labels Nov 10, 2026
@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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 10, 2026
@clawsweeper

clawsweeper Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR preserves the running parent's prompt-cache key for session forks and derives the default session key for completed-session forks.

Example: Fork completed OpenAI session fork-openai at boundary count 0.

  • Before: The fork payload omits prompt_cache_key.
  • After: The fork payload includes prompt_cache_key: fork-openai:0 when caching is enabled.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused implementation and relevant transport regressions support the change; supplied proof remains harness-based and the routing explanation needs qualification.
Proof confidence 🦐 gold shrimp (3/6) This collaborator-authored PR is outside the ordinary contributor proof gate; supplied validation exercises fork owners with synthetic HTTP and WebSocket responses, and the author explicitly reports no live cache-effect measurement.
Patch quality 🐚 platinum hermit (4/6) 1 actionable review finding remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Background session reviews omit the parent's cache metadata and may process substantial conversation prefixes without reuse.
Reason: The feature author's maintainer-associated direction supports this small restoration, while the documented run-only key limitations remain explicit and live cache improvement remains unclaimed.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep open: this maintainer-authored PR restores fork cache metadata through existing owners, with one documentation correction needed and no introduced runtime defect found.

Priority: P2
Reviewed head: 3e6043ce1fe51a2ded6ad78c1ff8f8a3e57f9118

Before merge

  • Qualify the cache-routing explanation by model generation (P3) - For GPT-5.6 and later, including the route cited as motivation in the PR body, this blanket routing explanation conflicts with the current cache contract: docs/reference/prompt-caching.md:306 says the key separates cache accounting while OpenAI handles routing automatically. The existing live observations at that page also found cold starts with and without a shared key. Qualify this paragraph and the corresponding PR-body claims so users do not interpret restoring the key as an established fix for that route's cache misses.

Findings

  • [P3] Qualify the cache-routing explanation by model generation — docs/plugins/sdk-runtime.md:170-172

Tests

  • Missing end-to-end proof: No supplied shipped-entry-point run demonstrates the restored key or measures cache reuse after this change.
Agent review details

How this fits together

Advisor and plugin side questions use the existing fork path to reconstruct live or persisted conversation context, send a tool-free provider request, and return text and usage.

flowchart TD
  A[Advisor or plugin side question] --> B[Session read authority]
  B --> C[Live attempt or persisted transcript]
  C --> D[Fork context and cache key]
  D --> E[Independent provider request]
  E --> F[Text and usage]
Loading

Technical review

Best possible solution:

Preserve the existing fork isolation while restoring cache metadata, and describe its routing or accounting role according to the model.

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

Current main explicitly deletes prompt_cache_key, and the author reports matching regressions failing on main; that establishes metadata omission, but not its causal contribution to the reported cache misses.

Is this the best way to solve the issue?

The implementation reuses the existing attempt and session-boundary owners, preserves independent requests, and needs no persistent state; its claimed routing benefit should be qualified by model.

Full review comments:

  • [P3] Qualify the cache-routing explanation by model generation — docs/plugins/sdk-runtime.md:170-172
    For GPT-5.6 and later, including the route cited as motivation in the PR body, this blanket routing explanation conflicts with the current cache contract: docs/reference/prompt-caching.md:306 says the key separates cache accounting while OpenAI handles routing automatically. The existing live observations at that page also found cold starts with and without a shared key. Qualify this paragraph and the corresponding PR-body claims so users do not interpret restoring the key as an established fix for that route's cache misses.
    Confidence: 0.97

Overall correctness: patch is correct
Overall confidence: 0.91

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Fork prompt-cache identity changes intended behavior with a stated reason (cb00966: perf(agents): build session forks only when requested #182844 deliberately omitted parent cache identity because reconstructed forks did not share complete one-shot request preparation.)
  • Live fork context and tool projection keeps the original intent (cb00966: Live attempts lend context on demand while executors stay with the parent; the extracted type and projection retain that contract.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • git diff --check
  • pnpm docs:check-links

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit 164bd67 adds src/agents/embedded-agent-runner/session-fork.ts:272 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 164bd6756af1; files: src/agents/embedded-agent-runner/session-fork.ts)

PR surface

Source +23, Tests 0, Docs +3. Total +26 across 12 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 7 50 27 +23
Tests 4 6 6 0
Docs 1 6 3 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 12 62 36 +26

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.

Labels

Label changes:

  • add P2: Fork cache metadata affects optional background requests and potential processing cost, without evidence of an urgent workflow outage.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: Fork cache metadata affects optional background requests and potential processing cost, without evidence of an urgent workflow outage.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Align the SDK documentation and PR rationale with the model-specific cache contract.

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.

Reviewed November 10, 2026, 12:01 PM ET / 17:01 UTC.

@obviyus

obviyus commented Nov 10, 2026

Copy link
Copy Markdown
Collaborator Author

Closing. On GPT-5.6+ OpenAI routes cached prefixes automatically and prompt_cache_key only separates cache accounting (docs/reference/prompt-caching.md), so restoring it for forks is not an established fix for the observed Advisor cache misses. #182844's omission stands. We'll measure misses with the cacheWrite logging from #196704 before proposing anything here.

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 rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S 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