Skip to content

fix(agents): keep session forks on the parent's cached prompt prefix - #197074

Merged
obviyus merged 3 commits into
mainfrom
fix/advisor-fork-cache-reuse
Nov 11, 2026
Merged

obviyus merged 3 commits into
mainfrom
fix/advisor-fork-cache-reuse

Conversation

@obviyus

@obviyus obviyus commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Advisor reviews and /btw side questions fork the live session to reuse its prompt cache, but on Anthropic routes they reused only the system prompt and tools. On Peanutto (cliproxy/claude-opus-5-5), 49 Advisor reviews logged a flat cacheRead of 14,575 tokens against contexts of 136k–740k (median 357k), so each review wrote the whole transcript to cache again: about $3 per review instead of about $0.10–0.16.

Two independent causes, each sufficient on its own:

  1. Tool-call IDs. Every foreground request passes messages through the attempt's normalizeToolCallIds (attempt-prompt-submit.ts). The live fork snapshot skipped it, so the fork sent toolu_778d44bb where the parent had sent toolu778d44bb, and the prefix diverged at the first tool call.
  2. tool_choice. The fork forced { type: "none" }. Anthropic documents that a tool_choice change invalidates every cached message block (What invalidates the cache).

Change

  • attempt-stream.ts / attempt-execution-phase.ts: the existing projectSessionForkMessages hook now ends with an ID-only variant of the attempt's own replay normalizer, so fork IDs match every foreground request. It skips tool-use pairing repair, so a parent tool that is still running keeps the fork's non-error "still running" placeholder instead of a synthesized "interrupted" error result. No new contract field.
  • session-fork.ts: on Anthropic Messages, keep the parent's tool_choice unless the request carries a hosted server tool such as web_search. A server tool runs before the fork could deny it, so none is still required there. Client tool calls are still denied by the existing three-attempt loop. OpenAI routes are unchanged.

Proof

scripts/perf/advisor-fork-prefix-gateway.ts starts an isolated Gateway (no credentials, no inherited service environment) with a loopback Anthropic Messages model that records every request body. The main turn calls a tool three times with Advisor at everyToolCalls: 1. The script then compares each fork request with the parent's preceding request.

Steady-state fork (after 3 tool calls) main (94a3775) This PR
First differing message 2 (first tool_use ID) none: full parent prefix matches
tool_choice changed to none unchanged
tools, system, other request keys same same

The first two forks still differ at message 1 on both branches. That's because the parent itself switches its runtime-context message from a block array to a string after its second request. It's a one-time foreground quirk early in each run and isn't fork-specific; I'll file it separately.

Tests: the live-fork integration case in embedded-agent-runner.session-fork.test.ts now covers Anthropic with a parent tool still running. With the full normalizer, it fails because the fork receives "Tool call interrupted before a result was recorded" (is_error: true). With the ID-only normalizer, it passes. The same case asserts that the client-tool tool_choice is the parent's. session-fork.test.ts covers both Anthropic branches (hosted tool → none; client tools → parent's choice). attempt-stream-prepare, attempt-execution-phase, and Advisor suites pass. pnpm check:changed passes, with the dead-export scan skipped. docs/plugins/sdk-runtime.md now describes the conditional Anthropic tool choice.

Not covered

  • The idle-session rebuild path (/btw on a session with no active run) still sends un-normalized IDs. Advisor only forks live runs. The rebuild path needs the attempt's tool allowlist, so it gets a follow-up.
  • OpenAI fork caching (team server: ~1% read) is unmeasured here. tool_choice: "none" and the deleted prompt_cache_key remain on that path.

@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 scripts Repository scripts agents Agent runtime and tooling size: M labels Nov 11, 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. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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. labels Nov 11, 2026
@clawsweeper

clawsweeper Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR normalizes live fork tool-call IDs and preserves Anthropic tool choice when only client tools are present.

Example: Advisor reviews a live Anthropic conversation containing tool call toolu_778d44bb.

  • Before: The fork sends the raw ID and forces tool_choice to none, diverging from the parent request.
  • After: The fork uses the parent's normalized ID and retains its tool choice for client-only tools.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The reported Gateway comparison supports the cache-prefix repair, but pending-call semantics regress and an affected integration assertion fails.
Proof confidence 🦐 gold shrimp (3/6) This collaborator-authored PR is outside the ordinary contributor proof gate; its body reports an isolated Gateway using the real Anthropic transport against a loopback endpoint, with matching steady-state parent prefixes after the fix, but does not establish live provider cache-hit or billing improvement.
Patch quality 🦪 silver shellfish (2/6) 3 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Background reviews can repeatedly process large conversation prefixes instead of reusing the parent's Anthropic cache.
Reason: The feature author's collaborator-associated direction supports the focused live-fork repair; idle-session reconstruction and OpenAI cache behavior are explicitly outside its scope.

Merge readiness

⛔ Needs changes before merge - 4 items remain

Keep open: this maintainer-authored PR addresses a concrete cache-prefix defect, but introduces incorrect pending-tool context and leaves a diff-caused integration-test failure.

Priority: P2
Reviewed head: 5347937a424c6a992aa489b05f389295dd61b048

Before merge

  • Preserve pending-call placeholders before running pairing repair (P2) - When a live Anthropic parent has an unfinished tool call, this invokes more than ID normalization: attempt-stream.ts passes repairToolUseResultPairing=true, so sanitizeReplayToolCallIdsForStream first synthesizes an error result saying the tool was interrupted. prepareEmbeddedSessionForkContext runs this projection before runEmbeddedSessionFork can insert its non-error 'still running' placeholder. The latter then sees an existing result and preserves the false failure, misleading the background reviewer about ongoing work. Preserve pending-call pairing before repair, or reuse the ID-only normalization operation here, and cover this through the live-context path.
  • Update the sibling fork integration test for conditional tool choice (P2) - The client-only Anthropic branch now retains the parent's undefined tool_choice, but src/agents/embedded-agent-runner.session-fork.test.ts:335-337 still unconditionally expects { type: 'none' }. The exact-head checks-node-changed annotation reports that mismatch. Update this consumer's assertion to preserve the parent choice for client-only Anthropic tools while retaining hosted-tool suppression and local-execution denial coverage.
  • Document when Anthropic forks retain the parent's tool choice (P3) - The existing SDK runtime documentation says fork tool choice is set to none and explains the resulting Anthropic message-cache invalidation. After this change that description is incorrect for client-only Anthropic forks. Update the built-in runtime paragraph to distinguish client-tool denial from hosted-tool suppression and describe the improved cache-prefix behavior.
  • Explain or restore the original intent of Pending-call ordering affected by normalization - f4f0255: Pending calls must receive non-error placeholders before provider replay repair can classify missing results as interrupted.

Findings

  • [P2] Preserve pending-call placeholders before running pairing repair — src/agents/embedded-agent-runner/run/attempt-execution-phase.ts:166
  • [P2] Update the sibling fork integration test for conditional tool choice — src/agents/embedded-agent-runner/session-fork.ts:96-101
  • [P3] Document when Anthropic forks retain the parent's tool choice — docs/plugins/sdk-runtime.md:191-194

Provenance

  • Pending-call ordering affected by normalization changes intended behavior without addressing why it exists (f4f0255: Pending calls must receive non-error placeholders before provider replay repair can classify missing results as interrupted.)

Tests

  • Missing end-to-end proof: The supplied Gateway scenario covers completed tool calls, not a live Anthropic fork while a parent tool is still running.
Agent review details

How this fits together

Advisor and session side questions reconstruct conversation context through the embedded runner, send an independent provider request, and return text and usage without executing local tools.

flowchart TD
  A[Advisor or side question] --> B[Session read authority]
  B --> C[Live attempt context]
  C --> D[Projection and ID normalization]
  D --> E[Independent provider request]
  E --> F[Tool denial or text response]
  F --> G[Text and usage]
Loading

Technical review

Best possible solution:

Reuse the existing ID-normalization owner after preserving pending-call semantics, update the affected integration assertion, and document conditional Anthropic tool choice.

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

Source confirms that foreground requests normalize IDs while current-main live fork projections do not; the PR also reports a before/after Gateway request comparison, but no target code was executed during this review.

Is this the best way to solve the issue?

Using existing projection and normalization owners is appropriately small, but invoking the full pairing-repair normalizer before fork pending-call handling violates an established ordering contract.

Full review comments:

  • [P2] Preserve pending-call placeholders before running pairing repair — src/agents/embedded-agent-runner/run/attempt-execution-phase.ts:166
    When a live Anthropic parent has an unfinished tool call, this invokes more than ID normalization: attempt-stream.ts passes repairToolUseResultPairing=true, so sanitizeReplayToolCallIdsForStream first synthesizes an error result saying the tool was interrupted. prepareEmbeddedSessionForkContext runs this projection before runEmbeddedSessionFork can insert its non-error 'still running' placeholder. The latter then sees an existing result and preserves the false failure, misleading the background reviewer about ongoing work. Preserve pending-call pairing before repair, or reuse the ID-only normalization operation here, and cover this through the live-context path.
    Confidence: 0.99
  • [P2] Update the sibling fork integration test for conditional tool choice — src/agents/embedded-agent-runner/session-fork.ts:96-101
    The client-only Anthropic branch now retains the parent's undefined tool_choice, but src/agents/embedded-agent-runner.session-fork.test.ts:335-337 still unconditionally expects { type: 'none' }. The exact-head checks-node-changed annotation reports that mismatch. Update this consumer's assertion to preserve the parent choice for client-only Anthropic tools while retaining hosted-tool suppression and local-execution denial coverage.
    Confidence: 1
  • [P3] Document when Anthropic forks retain the parent's tool choice — docs/plugins/sdk-runtime.md:191-194
    The existing SDK runtime documentation says fork tool choice is set to none and explains the resulting Anthropic message-cache invalidation. After this change that description is incorrect for client-only Anthropic forks. Update the built-in runtime paragraph to distinguish client-tool denial from hosted-tool suppression and describe the improved cache-prefix behavior.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Live fork message projection keeps the original intent (cb00966: On-demand forks replay admitted tool-result projections through the existing live-context owner without retaining eager request snapshots.)
  • Anthropic tool-choice suppression changes intended behavior with a stated reason (cb00966: Reconstruction retained the tool-free fork contract, including hosted-tool suppression; this PR explains retaining parent choice only when tools execute locally and remain denied.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/agents/embedded-agent-runner/session-fork.test.ts src/agents/embedded-agent-runner.session-fork.test.ts --maxWorkers=1
  • pnpm test src/agents/embedded-agent-runner/run/attempt-execution-phase.test.ts src/agents/embedded-agent-runner/run/attempt-stream-prepare.test.ts --maxWorkers=1
  • pnpm test src/agents/agent-tools.prefix-stability.test.ts --maxWorkers=1
  • pnpm check:changed
  • git diff --check

What I checked:

Likely related people:

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

PR surface

Source +12, Tests -2, Other +265. Total +275 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 17 5 +12
Tests 1 7 9 -2
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 265 0 +265
Total 4 289 14 +275

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: The change addresses repeated background inference costs, with a bounded pending-tool context regression and a focused integration-test repair.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: The change addresses repeated background inference costs, with a bounded pending-tool context regression and a focused integration-test repair.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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 11, 2026, 1:25 AM ET / 06:25 UTC.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation plugin: file-transfer labels Nov 11, 2026
@obviyus
obviyus force-pushed the fix/advisor-fork-cache-reuse branch from 8552b2e to ce345dd Compare November 11, 2026 08:11
obviyus and others added 3 commits November 11, 2026 14:18
Advisor reviews and /btw side questions fork the live session, but their
Anthropic requests never reused the parent's cached messages:

- the fork sent raw transcript tool-call IDs, while every foreground request
  sends them through the attempt's ID normalizer, so the prefix diverged at
  the first tool call;
- the fork forced tool_choice none, and Anthropic invalidates every cached
  message block when tool_choice changes.

Apply the attempt's own ID normalizer to live fork messages, and keep the
parent's Anthropic tool_choice unless the request carries a hosted server
tool, which runs before the fork can deny it. Client tool calls are still
denied by the existing loop.

scripts/perf/advisor-fork-prefix-gateway.ts records the main and fork
request bodies from an isolated Gateway with a loopback Anthropic model.

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

The live fork reused the attempt's full replay normalizer, which also repairs
tool-use pairing. On Anthropic that synthesized an "interrupted" error result
for a tool still running in the parent, before the fork could add its
non-error "still running" placeholder, so a reviewer saw a false failure.

Expose an ID-only variant of the same normalizer for forks. Extend the live
Anthropic fork integration case to a parent tool that is still running, keep
the client-tool tool_choice assertion on the parent's value, and document the
conditional Anthropic tool choice.

Co-authored-by: obviyus <[email protected]>
@obviyus
obviyus force-pushed the fix/advisor-fork-cache-reuse branch from ce345dd to 2d7bfc8 Compare November 11, 2026 08:48
@obviyus
obviyus merged commit 2706a18 into main Nov 11, 2026
17 checks passed
@obviyus
obviyus deleted the fix/advisor-fork-cache-reuse branch November 11, 2026 08:48
obviyus added a commit that referenced this pull request Nov 11, 2026
… prefix (#197074)" (#197175)

This reverts commit 2706a18.

Live provider measurements showed no cache gain. On Anthropic (haiku-5-5 and
opus-5-5, thinking off and on, direct and custom routes), forks read the same
parent prefix before and after: replaying one fork with the parent's
tool_choice, with tool_choice none, and with mismatched tool IDs differed by
0-2 cached tokens. With thinking on, both tool IDs were already identical.

The measured cause of fork cache misses is the fork's thinking config (it sends
thinking disabled or a different effort and keeps or drops thinking blocks
differently from the parent), and on OpenAI the deleted prompt_cache_key.

Co-authored-by: obviyus <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 12, 2026
…penclaw#197074)

* fix(agents): keep session forks on the parent's cached prompt prefix

Advisor reviews and /btw side questions fork the live session, but their
Anthropic requests never reused the parent's cached messages:

- the fork sent raw transcript tool-call IDs, while every foreground request
  sends them through the attempt's ID normalizer, so the prefix diverged at
  the first tool call;
- the fork forced tool_choice none, and Anthropic invalidates every cached
  message block when tool_choice changes.

Apply the attempt's own ID normalizer to live fork messages, and keep the
parent's Anthropic tool_choice unless the request carries a hosted server
tool, which runs before the fork can deny it. Client tool calls are still
denied by the existing loop.

scripts/perf/advisor-fork-prefix-gateway.ts records the main and fork
request bodies from an isolated Gateway with a loopback Anthropic model.

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

* fix(agents): normalize only fork tool-call IDs before pending-call pairing

The live fork reused the attempt's full replay normalizer, which also repairs
tool-use pairing. On Anthropic that synthesized an "interrupted" error result
for a tool still running in the parent, before the fork could add its
non-error "still running" placeholder, so a reviewer saw a false failure.

Expose an ID-only variant of the same normalizer for forks. Extend the live
Anthropic fork integration case to a parent tool that is still running, keep
the client-tool tool_choice assertion on the parent's value, and document the
conditional Anthropic tool choice.

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

* test(agents): keep fork test lines within the ratchet

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

---------

Co-authored-by: obviyus <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 12, 2026
… prefix (openclaw#197074)" (openclaw#197175)

This reverts commit 9cae7fa.

Live provider measurements showed no cache gain. On Anthropic (haiku-5-5 and
opus-5-5, thinking off and on, direct and custom routes), forks read the same
parent prefix before and after: replaying one fork with the parent's
tool_choice, with tool_choice none, and with mismatched tool IDs differed by
0-2 cached tokens. With thinking on, both tool IDs were already identical.

The measured cause of fork cache misses is the fork's thinking config (it sends
thinking disabled or a different effort and keeps or drops thinking blocks
differently from the parent), and on OpenAI the deleted prompt_cache_key.

Co-authored-by: obviyus <[email protected]>
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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: M 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