Skip to content

fix(ollama): reuse prompt prefixes across subagent spawns - #164804

Merged
steipete merged 7 commits into
openclaw:mainfrom
aaa2015:pr/prompt-prefix-cache
Oct 10, 2026
Merged

steipete merged 7 commits into
openclaw:mainfrom
aaa2015:pr/prompt-prefix-cache

Conversation

@aaa2015

@aaa2015 aaa2015 commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Equivalent subagent spawns put unique child identities into native Ollama's system prompt, preventing reuse of the shared system and tool prefix.

User Impact

Native Ollama can reuse the shared prefix across equivalent children while preserving exact session keys and URLs. Follow-up turns and parent completion turns retain their earlier request bytes. No new configuration or migration is required.

Why This Change Was Made

The spawn envelope now carries the child/requester identities, label, and requester channel alongside the task. Ollama applies the existing guarded Runtime relocation contract to the first emitted user message; policy and hook instructions stay in the system role, including when delimiters are ambiguous or no carrier exists. The native message converter has one owner in a smaller sibling module, with the existing public runtime API preserved.

Main already retains native Ollama and Chat Completions runtime carriers (#168169), and the newer prompt/cache work owns temporal context and completion replay. This revision drops the original Responses capability-policy coupling and session-key folding, retaining the distinct subagent improvement. Thanks @aaa2015 for identifying the prefix-cache issue and the task-envelope approach; contributor commits are preserved by merging main.

Evidence

Live before/after uses pnpm openclaw --profile prefix-spawn agent through an isolated Gateway and native Ollama qwen3:8b /api/chat, with a transparent recording proxy. Two ordinary turns and two real model-requested sessions_spawn calls are captured; both children answer CHILD_PREFIX_OK. Comparisons cover equivalent child prompts and parent continuation separately; parent and child prompts intentionally differ.

Baseline main: 84b6b0858f387c5b3fbd3e4bc2bc72152b059692. Ordinary-turn system/tools and all three prior messages already matched; Ollama reported 2,989/3,151 cached tokens. The child system prompts differed (6,146 bytes each, 5,335-byte common prefix); the second child reused only 1,122/2,387 tokens. Parent completion retained all 11 prior wire messages.

Candidate: e8ad458791057a4621cbaf2e8b06ea23fd85fe43. Both child system prompts are now byte-identical (5,697 bytes), with identical tools. The second child reuses 2,071/2,387 tokens, reducing uncached prompt tokens from 1,265 to 316 (~75%). Its measured prompt evaluation fell from 935 ms to 247 ms on this run. Exact child IDs remain in the task/user context. Ordinary turns preserve all prior messages and report 2,997/3,159 cached tokens; parent completion again retains all 11 prior wire messages. Cache slots and shared model load can affect timings and counts.

Token delta: regenerated snapshots are unchanged; the captured first parent request grew by 8 tokens (3,002 → 3,010) from the new placement, while the sampled second-child prompt remains 2,387 tokens. Random child IDs make per-spawn token counts variable.

The new regressions fail on main for the original identity/raw-system behavior. Focused proof: 99 tests passed across the envelope, native message conversion, stream runtime, and runtime-context suites (112.58 s combined). Final standalone changed-file measurements with node scripts/run-vitest.mjs <file> --maxWorkers=1: stream-messages.test.ts 5 passed, 181.51 s wall; subagent-system-prompt.test.ts 15 passed, 19.15 s wall. The native test's cold compiled-worker preparation dominates elapsed time (95% transform); assertions run in milliseconds and the existing stream suite already pays for this dependency graph. Exact-head CI used 6,890 aggregate job-seconds (whole run, not incremental test cost).

An initial Ollama test collection failed because a concurrent build populated generated plugin directories during the compiler input snapshot. No Ollama tests ran in that attempt; serialized preparation and tests passed. Gateway-only dependency preparation also omitted the lint plugin workspace; full preparation supplies it. The extension declaration compiler exceeded its default 300-second budget on the shared host, so subsequent preparation uses its supported 900-second timeout. pnpm prompt:snapshots:gen regenerated seven files with no tracked byte/token delta.

Validation passed: pnpm build (final full setup build 6m 18.8s), targeted core/extension oxlint, pnpm tsgo:core, pnpm tsgo:extensions, and the required ratchets/config-doc/plugin-inventory checks. The build emits an advisory UI startup gzip budget warning (366.2 vs 366.1 KiB); this PR does not change UI source. Independent Codex autoreview: scoped-clean, no actionable P0–P2 findings, on the candidate above.

Exact-head CI: passed; openclaw/ci-gate is green on e8ad458791057a4621cbaf2e8b06ea23fd85fe43. ClawSweeper reviewed this exact head at 18:41 UTC: ready for maintainer review, proof sufficient, no findings, and no Before merge items (5/6 overall, proof, and patch quality). No merge or automerge was requested.

Production: +223/-206 lines (net +17); tests: +142/-2 (net +140). The small production increase implements the missing native boundary handling and keeps a coherent converter module; removing the redundant hook-key inventory and obsolete PR paths limits growth. Docs and a verified shrink-only assertion baseline update are separate.

@clawsweeper

clawsweeper Bot commented Oct 4, 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 triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. docs Improvements or additions to documentation channel: discord Channel integration: discord channel: googlechat Channel integration: googlechat channel: imessage Channel integration: imessage channel: line Channel integration: line channel: matrix Channel integration: matrix channel: mattermost Channel integration: mattermost channel: msteams Channel integration: msteams channel: nextcloud-talk Channel integration: nextcloud-talk channel: nostr Channel integration: nostr channel: signal Channel integration: signal channel: slack Channel integration: slack channel: telegram Channel integration: telegram channel: tlon Channel integration: tlon channel: voice-call Channel integration: voice-call channel: whatsapp-web Channel integration: whatsapp-web channel: zalo Channel integration: zalo channel: zalouser Channel integration: zalouser app: macos App: macos app: web-ui App: web-ui gateway Gateway runtime extensions: copilot-proxy Extension: copilot-proxy extensions: diagnostics-otel Extension: diagnostics-otel extensions: llm-task Extension: llm-task extensions: lobster Extension: lobster extensions: memory-core Extension: memory-core extensions: memory-lancedb Extension: memory-lancedb labels Oct 4, 2026
@github-actions

github-actions Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Dependency graph guard cleared

This PR no longer has dependency changes awaiting review. A future dependency graph change from an external contributor requires a maintainer's /allow-dependencies-change comment after the guard notice identifies that revision.

  • Current SHA: e8ad458791057a4621cbaf2e8b06ea23fd85fe43

@github-actions

github-actions Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Security-sensitive guard cleared

Current revision: e8ad458791057a4621cbaf2e8b06ea23fd85fe43

This PR no longer changes files in the maintainer security-review tier.

Separate CODEOWNERS requirements still apply to security policy and enforcement files.

@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR moves changing subagent identities and bounded native Ollama Runtime facts behind the shared system and tool prefix.

Example: Two equivalent subagents run through native Ollama qwen3:8b.

  • Before: Their system prompts differ, and the second child reuses 1,122 of 2,387 prompt tokens.
  • After: Their system prompts match byte-for-byte, and the recorded second child reuses 2,071 of 2,387 tokens while retaining its exact identity.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused, owner-aligned repair with sufficient live changed-behavior evidence, preserved exports, meaningful regressions, and successful exact-head validation.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Contributor-supplied live output exercises the exact candidate through the shipped CLI, isolated Gateway, and native Ollama qwen3:8b: real spawns complete, child system/tools match, exact identities remain available, and ordinary and parent-continuation request prefixes remain intact.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Equivalent local-model children repeatedly evaluate a shared prompt prefix because their system instructions contain changing identities.
Reason: The recorded live cache improvement supports user value, and the feature-history owner implemented the narrowed direction without the earlier retention-policy coupling.

Merge readiness

✅ Ready for maintainer review

This PR retains a useful fix that current main lacks; the reviewed head has sufficient live evidence, green CI, and no actionable findings.

Priority: P2
Reviewed head: e8ad458791057a4621cbaf2e8b06ea23fd85fe43

Before merge

None.

Findings

None.

Agent review details

How this fits together

The spawn owner prepares child instructions and task context; the Ollama adapter converts that context into native /api/chat messages.

flowchart LR
  A[Spawn request] --> B[Shared spawn envelope]
  B --> C[System instructions and task context]
  C --> D[Native Ollama message adapter]
  D --> E[Ollama chat request]
  E --> F[Child response]
Loading

Technical review

Best possible solution:

Land the focused spawn-envelope and native Ollama fix through the normal merge workflow.

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

Current-main source still inserts exact child identities into system instructions, and the supplied live baseline shows different child prompts and reduced cache reuse; this review ran no target code.

Is this the best way to solve the issue?

The change fixes identity placement at the existing spawn owner and reuses the shared guarded relocation contract while preserving instructions and public runtime exports.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Current main still embeds changing child identities: The current-main envelope places the label, requester session, requester channel, and exact child session in the system prompt. (src/agents/subagents/spawn/subagent-system-prompt.ts:126, 457515502e84)
  • Introduced native relocation: The adapter relocates only an unambiguous producer-delimited Runtime region into the first emitted user message; absent carriers and ambiguous markers retain the facts in the system role. (extensions/ollama/src/stream-messages.ts:178, e8ad45879105)
  • Existing shared relocation contract: The imported shared helper rejects duplicate or reversed delimiters, and the existing Chat Completions adapter consumes the same contract. (packages/ai/src/utils/system-prompt-cache-boundary.ts:18, e8ad45879105)
  • Recorded owner direction: GitHub verifies steipete authored the final implementation commit, whose recorded direction preserves exact identities, earlier request bytes, and system authority; the runtime-api export remains available. (extensions/ollama/runtime-api.ts:5, e8ad45879105)
  • Live changed-behavior evidence: The full PR body records isolated Gateway calls through the shipped CLI and native Ollama qwen3:8b, two real model-requested spawns returning CHILD_PREFIX_OK, identical candidate child system/tools, preserved exact identities, and unchanged earlier ordinary-turn and parent-completion messages. (e8ad45879105)
  • Exact-head validation: The linked CI run completed successfully on the reviewed SHA, and the current openclaw/ci-gate status is success; GitHub reports the PR cleanly mergeable. (e8ad45879105)

Likely related people:

  • Peter Steinberger: Raw commit 58a6953 adds src/agents/subagents/spawn/subagent-system-prompt.ts:31 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 58a6953549d0; files: src/agents/subagents/spawn/subagent-system-prompt.ts)
  • Vincent Koc: Raw commit c54c323 adds extensions/ollama/src/stream.runtime.ts:860 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c54c323275d9; files: extensions/ollama/src/stream.runtime.ts)

PR surface

Source +17, Tests +140, Docs +6, Other 0. Total +163 across 14 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 6 223 206 +17
Tests 4 142 2 +140
Docs 3 8 2 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 14 374 211 +163

Review metrics

Metric Value Why it matters
Production versus tests Production +223/-206; tests +142/-2 The net production increase is 17 lines, largely relocating the existing converter into one owner; added tests protect prompt bytes, exact identities, and conservative relocation.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The fix reduces repeated local-model prompt evaluation during equivalent subagent spawns without changing setup or configuration.
  • merge-risk: 🚨 compatibility: The provider-facing helper export and native message projection change warrant compatibility visibility; recorded owner direction, preserved runtime exports, and conservative fallback resolve the identified tradeoff.
  • 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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (13 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-05T00:27:18.089Z sha 69313ad0e0d6abc6f5cc73216f103ccf104829a9 :: blocked before merge. :: none
  • reviewed 2026-10-05T00:40:30.882Z sha fab2404f646e5ad4a29c53a9774e66724a451527 :: blocked before merge. :: none
  • reviewed 2026-10-05T03:38:28.041Z sha fab2404f646e5ad4a29c53a9774e66724a451527 :: blocked before merge. :: none
  • reviewed 2026-10-09T18:37:26.053Z sha dde6876 :: blocked before merge. :: none
  • reviewed 2026-10-09T21:56:37.469Z sha e8313c1 :: blocked before merge. :: none
  • reviewed 2026-10-10T07:28:49.533Z sha 1e77c98ec539dda25b6d3774678a8fcb98963cda :: blocked before merge. :: none
  • reviewed 2026-10-10T08:59:35.579Z sha e8313c1 :: blocked before merge. :: none
  • reviewed 2026-10-10T18:41:25.947Z sha e8ad458 :: needs maintainer review before merge. :: none

Reviewed October 10, 2026, 2:54 PM ET / 18:54 UTC (Revision 14).

@aaa2015

aaa2015 commented Oct 4, 2026

Copy link
Copy Markdown
Contributor Author

Both replay-policy findings are fixed, and the branch is rebased onto current main (9c66d4c9) so the merge conflict is gone.

1. Fallback gate now matches the Responses helper (P2). You were right: the unowned fallback enabled append-only for any non-Google compatible route, including openai-completions, while the shared helper restricts the same gate to the Responses family — and my own new negative test asserted Chat Completions stays unchanged, so the two contradicted each other. The fallback is now gated on isOpenAiResponses && requiresStablePromptPrefix(...), and resolveTranscriptPolicy covers both APIs in one test:

// unowned openai-completions with supportsPromptCacheKey → appendOnlyRuntimeContext === false
// unowned openai-responses    with supportsPromptCacheKey → appendOnlyRuntimeContext === true

2. The capability predicate is now part of the memoized key (P2). resolveTranscriptPolicy keyed on config/provider/model/baseUrl/reasoning facts but not on the new input, so resolution order decided the result. The key now carries requiresStablePromptPrefix: requiresStablePromptPrefix(params.model), following the existing dropsThinkingForReasoningCompat / preservesReasoningContentReplay inputs, with a both-order regression test:

// resolve unflagged → flagged, then flagged → unflagged; each must get its own policy

I verified the second fix by reverting only the cache-key line: the both-order test then fails with expected false to be true, so it is actually guarding the behavior rather than passing incidentally.

tsgo -p tsconfig.core.json is clean; transcript-policy, provider-replay-helpers, subagent-system-prompt, session-key-utils.cache-scope and system-prompt suites pass; oxfmt --check is clean.

On the remaining items: happy to take the SDK-owner acceptance question you raised in whichever direction the maintainers prefer — the retention semantics are opt-in per model (compat.supportsPromptCacheKey or compat.supportsResponsesContinuation), and if you would rather land only the subagent half first, say so and I will split the branch so the prompt-assembly fix can go in without the replay-policy change.

@aaa2015

aaa2015 commented Oct 4, 2026

Copy link
Copy Markdown
Contributor Author

One more test on top of the two fixes, aimed at the class rather than the case: the shared helper and the unowned fallback now answer the same question through different code paths, and their mismatch was silent — each path looked reasonable alone. The new case pins the whole matrix (openai-responses / openai-chatgpt-responses / azure-openai-responses / openai-completions × no flag / supportsPromptCacheKey / supportsResponsesContinuation) and asserts the fallback always matches buildOpenAICompatibleReplayPolicy. If the two ever drift again, this fails instead of quietly retaining context on one path only.

@aaa2015

aaa2015 commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (67857281) as three linear commits; the three gates that were red are green again, and the CI gate now passes end to end.

  • PR context and evidence — the body carries the ## Evidence section the checker looks for.
  • checks-fast-baseline-ratchets — the new type assertion in provider-replay-helpers.ts now has the // SAFETY: line the ratchet wants. (It has to sit on the line directly above the as, not merely somewhere in a comment block above it — that tripped me once.)
  • ci-gate — follows from those two.

On the Decision needed question

You are right that this is not a decision the PR can make for itself, and I rewrote the body's "opt-in" paragraph because it understated the change: a config-defined route that already sets supportsPromptCacheKey or supportsResponsesContinuation does begin persisting runtime carriers and replaying earlier inbound metadata, with no edit to its settings. "Opt-in" is the wrong word for that group — they opted in earlier, to a narrower contract.

Three ways this can land, in the order I would pick them:

  1. Accept the coupled contract. The two flags already mean "this route keeps a provider-side copy of my prefix". Retaining the carrier is what keeps that copy usable turn over turn, so coupling is coherent rather than coincidental. Cost: existing configs change behavior silently, which is exactly why it needs your call.
  2. Split the PR. The subagent half (system-prompt-runtime.ts, session-key-utils.ts, and their tests) carries no compatibility question: it only stops a per-spawn id from landing in a shared prompt, and nothing about existing configuration changes. I can land that half alone and hold the replay half for the decision.
  3. Give retention its own key rather than reusing the transport flags. Existing configs then change nothing at all; the cost is a new setting for the routes that want the behavior.

I have no objection to 2 or 3. 1 is what I would choose, but it is your call, and I am not going to argue for it by pretending the PR is otherwise finished.

Migration compatibility (the P2 item)

Since the concern is resuming across the change, I went looking for what already covers it rather than adding tests for the checkbox. Three of the four were already covered on main; the fourth had a real gap and now has a case.

Scenario Test Result
pre-change session resume — history persisted without carriers, resumed under a policy that retains them new: resumes a session whose persisted history predates carrier retention (attempt-session-replay.test.ts) pass
compaction replays the same interrupted turn after pre-core-compaction with append-only context false / true; persists the next steer user after replay with append-only context true (compacted input=true) pass
active-to-empty fact supersession clears stale hints; uses one native owner snapshot for enabled media and refreshes it next turn; omits empty media facts … unless retained (runtime-facts-prompt.test.ts) pass
transient fallback the append-only context false arm of the replay matrix; appendOnlyRuntimeContext: false cases in attempt-prompt-phase.test.ts pass

The new case is the interesting one. Every existing replay case passes the same value for "history was built with carriers" and "this resume retains carriers", so none of them walks the transition — withInterruptedTurn(x, …) plus withReplaySession(fixture, x, …). The new case deliberately splits them (false for the history, true for the resume) and asserts the two things the transition could break: the interrupted user turn is replayed exactly once, and the already-persisted prefix stays byte-identical (after.slice(0, before.length)), which is what a provider-side cache needs in order to still match after the policy changed.

Verification on this revision

tsgo:core / tsgo:core:test                        exit 0
attempt-session-replay.test.ts                    pass (60 cases, incl. the new one)
runtime-facts-prompt.test.ts                      9 passed
oxfmt --check                                     clean
check-assertion-safety-ratchet / line-cap / max-lines   clean

Not supplied

To be explicit about what is still missing rather than leave it implied:

  • Process seconds and RSS before/after are not reported. The measurements in the body are TTFT and reused-prefix tokens from the local engine's own log lines; I have not run a before/after process-level comparison, and I would rather say so than pad the numbers.
  • The retention-owner acceptance in the P1 item is a human call and stays open.

Happy to take option 2 or 3 if you prefer either; say the word and I will push the split.

@aaa2015

aaa2015 commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

The performance reporting item is now supplied, in the body under Evidence → Changed-test cost and → CI seconds.

Summary: +13 tests, +3.6 s of wall time across the changed suites; 122 jobs / 10,766 job-seconds / 513 s CI wall on this head. Files that only had an assertion modified are flat within the ±0.5 s spread of repeated runs, so the delta is the added tests rather than existing ones slowing down.

One thing worth flagging, because it nearly went into the numbers: the first measurement pass reported transcript-policy.test.ts at 7.7 s, i.e. 11.5 s faster than main — on a file this PR adds tests to. That direction is not plausible, so I re-ran it alternating sides three times each: 18.4 / 17.2 / 17.6 s after against 17.1 / 17.6 / 16.7 s before. The 7.7 s did not reproduce; it was a warm-worker-cache artifact. The same pass also produced two unreproducible RSS readings for that file. Both are replaced with clean re-measurements in the body, and the repro details are in the footnote rather than quietly dropped.

I would rather hand you a flat result I trust than a flattering one I do not.

@xyrolle

xyrolle commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Evidence from a hosted route, in case it helps with the retention decision.

Setup: a config-defined provider whose model uses api: "openai-responses" (provider id is not openai), reached through an HTTP proxy to an OpenAI reasoning model, with compat.supportsPromptCacheKey: true, on OpenClaw 2026.9.6. Our proxy currently does not forward prompt_cache_key, so the numbers below are without it.

Token counts from our logs, before any change (10-05 to 10-09): on warm turns (39 of 56 first-of-turn calls; the rest followed an idle gap), the first call of a new turn reads about 11.2k–11.6k cached tokens, while 45k (p50) to 66k (p90) of its prompt is uncached. Later calls inside the same turn read everything except the last few tokens of the previous call.

Two consecutive turns' request bodies have a byte-identical system prompt and tools. What differs is the replayed history. The previous request's runtime-context carrier is gone, and the previous user message has lost its Active Memory prependContext line (#166271).

A change that late in the request costs the whole history because this provider appears to read only from checkpoints at the end of earlier requests, not from the longest common prefix. Three first calls whose first ~14k tokens were byte-identical each read exactly 11,644. That rule is inferred from token counts, not documented. On a longest-prefix cache like the engine in the PR body, the same change would cost only the tail.

Provider id: as the PR body notes, the bundled openai plugin already retains the carrier for the whole Responses family. buildOpenAIReplayPolicy does not look at baseUrl, though. An operator who names this same proxied route openai gets retention, and one who uses any other id falls through buildUnownedProviderTransportReplayFallback and does not. To us that argues for tying retention to the route's declared cache capability (option 1) rather than to a new key.

Local check: we enabled retention for our provider through a provider buildReplayPolicy hook, then ran three turns on 2026.9.6 with a synthetic model stream. Each turn's first request started with the previous turn's full last request. That also needed #166590, because Active Memory is on for our user turns (details there), and #167769 when reasoning summaries are requested. So on our route we would not expect retention alone to change the first-call read.

We have not measured the cache effect on the live provider with any of these changes.

@aaa2015

aaa2015 commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Thanks — this is exactly the shape of evidence the decision needs, and two of your three points land on the side the PR argues for. The third does not, and I want to say so rather than let the PR take credit for a number it cannot produce.

1. The provider-id asymmetry you describe is what this PR removes

You're right that buildOpenAIReplayPolicy doesn't look at baseUrl, so naming the route openai gets retention while any other id falls through the unowned fallback and doesn't. That fallback is the branch this PR changes. After it, the gate is the declared capability, not the provider id:

// src/agents/transcript-policy.ts (this PR, the unowned/config-defined path)
...(isOpenAiResponses && requiresStablePromptPrefix(params.model)
  ? { appendOnlyRuntimeContext: true }
  : {}),

with requiresStablePromptPrefix = compat.supportsPromptCacheKey === true || compat.supportsResponsesContinuation === true.

So a config-defined openai-responses route with supportsPromptCacheKey: true retains the carrier whatever the provider is called. The "name it openai or lose it" split you hit goes away — which is option 1, the one you argue for.

2. But on your route this PR is necessary, not sufficient — and I'd rather say that plainly

Your own local check is the evidence: enable retention and the first-call read doesn't move, because Active Memory's prependContext (#166271 / #166590) and reasoning summaries (#167769) are still changing the prompt above the tail. Until those land, retention alone buys you nothing measurable. So this PR should not be the thing that carries the decision on your numbers — it can't deliver them yet, and I'd rather the maintainer weigh the compatibility cost knowing that.

3. Your cache is checkpoint-based, which makes a given divergence cost more for you than for me

Three first calls with a byte-identical ~14k-token opening each read exactly 11,644 — that is a checkpoint rule, so one change anywhere after the last checkpoint costs the whole history. On the longest-prefix engine in the PR body, the same change costs only from the divergence point onward. Two consequences:

  • Once the remaining divergences are gone, the amount that comes back on your route is that 45k(p50)–66k(p90) — against ~3.2k for the same class of fix on my longest-prefix engine. The stake is an order of magnitude larger for a checkpointed backend, and item 2 is what currently hides it.
  • Many useful engines are checkpointed, so the blast radius of not retaining is bigger than my local measurement suggests.

Scope note so nobody extrapolates: every number in the PR body is from a longest-prefix engine with byte-for-byte matching. Yours behaves differently by construction, and your checkpoint inference is from token counts rather than documentation — worth pinning down with the backend if the decision ends up resting on it.

The honest gap

You haven't measured the cache effect live with these changes, and neither have I on a hosted route. If you do get to it after #166271 / #166590 / #167769, this thread is a good place for the result — it's the missing piece for the retention decision, and a hosted-route number would be worth more to it than another local one.


On my side: the branch is conflicted against main again, so I'm rebasing it now; the content above describes the revision that will be pushed, not the one currently on the branch.

A route that caches its prompt prefix, or continues from a stored response, re-prefills
everything from the first changed token. The runner strips historical runtime-context
carriers by default for OpenAI-compatible routes, which shifts every later item (tool
definitions included) as soon as a turn becomes history: the prefix then only matches up
to the system prompt and the whole tail is recomputed on every turn.

Treat these routes like the existing Claude-thinking-prefix case and keep their runtime
context append-only. Native OpenAI-family extensions already do this unconditionally; this
covers the shared helper used by provider plugins and the fallback used by config-defined
providers, which so far only opted in for prefix-binding Claude models.

Measured on a local engine whose prefix cache is compared byte-for-byte: a continuation
turn's reuse went from 7,680 to 10,752 of ~10,900 prompt tokens, and the re-prefilled
remainder from 3,252 tokens (~10.0 s) to 130 (~1.5 s).

Opt-in per model, so routes that do not declare the capability keep today's behavior.
A child session key carries a fresh id per spawn, and it was rendered into the system
prompt twice: in the Runtime line and in the "## Session Context" block. Two children of
the same shape therefore shipped different prompts, so no provider-side prompt cache could
be reused for them.

Measured locally with two identical spawns: they shared only the first 8,104 of ~10,900
prompt tokens, leaving ~3,250 tokens (about 10 s) to re-prefill per spawn. After moving the
per-spawn identity into the task message and rendering the Runtime line's session from a
scope with volatile cron/dashboard/subagent ids removed, the two prompts are byte-identical
and the same spawns reuse 10,752 tokens with 130 left to prefill (~1.5 s).

The child still receives its label and session key; they now travel in the task message,
which is not part of the cacheable prefix.
… by capability

Two defects from review of the append-only change:

* The unowned-provider fallback enabled append-only context for any non-Google compatible
  route, including `openai-completions`, while the shared Responses helper restricts the
  same gate to the Responses family and the new test asserts Chat Completions is unchanged.
  A custom Chat Completions setup would have retained old carriers and inbound metadata
  where the equivalent plugin-owned route stays transient. Gate the fallback identically.
* `resolveTranscriptPolicy` memoizes by config/provider/model identity, but this policy now
  depends on the model's capability flags. With one config, resolving an unflagged model and
  then an opted-in model returned the first policy, so the result depended on resolution
  order. Include the effective capability predicate in the key, as the existing
  reasoning-compat inputs already do, and cover both orders.

Verified: tsgo rc=0; `src/agents/transcript-policy.test.ts` passes, and the both-order case
fails when only the cache-key line is reverted.
@aaa2015

aaa2015 commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (f4cb17e8408) — three commits, conflict resolved, mergeable is back to MERGEABLE.

What the rebase changed: main deleted the system-prompt.test.ts case my second commit had modified (along with the rest of that file's runtime-line coverage, which now lives in src/agents/cli-runner/helpers.system-prompt.test.ts and src/agents/system-prompt.cache-prefix.test.ts). I dropped the row rather than re-add an assertion to a test that no longer renders the Runtime line; unit coverage for the folding is in src/sessions/session-key-utils.cache-scope.test.ts, which merged cleanly. Also confirmed main still lacks parseCacheStableSessionScope / requiresStablePromptPrefix, so nothing here is superseded.

Direct before/after of the actual behavior — buildRuntimeLine(...) for the same runtime info, only the session scope varying, main on the left and this branch on the right:

session scope passed in main this branch
…:subagent:1a2b3c4d-…-eeeeffff vs …:subagent:99998888-…-33332222 differ — the full spawn id lands in the line session=agent:main:subagent — identical
…:dashboard:7c0011f7-… vs …:dashboard:deadbeef-… differ session=agent:main:dashboard — identical
…:cron:job-1:run:run-aaa vs …:cron:job-1:run:run-bbb identical (cron runs were already folded) identical — unchanged
agent:main session=agent:main session=agent:main — unchanged

The quoted values are the whole session= field of the rendered line. Reproduce by calling buildRuntimeLine with a runtimeInfo whose sessionKey differs only in the volatile suffix; on main the two lines differ, here they do not, and a session key with no volatile suffix renders the same on both.

The subagent half is the part that matters for the check you raised: two children of the same shape previously produced different system prompts, so no provider-side prefix cache could serve both. The identity still reaches the child — it travels in the task message, which is not part of the cacheable prefix (src/agents/subagents/spawn/subagent-system-prompt.test.ts).

Suites re-run on the rebased head: session-key-utils.cache-scope, subagent-system-prompt, transcript-policy, provider-replay-helpers, system-prompt, system-prompt.cache-prefix, cli-runner/helpers.system-prompt — all pass (exit 0).

steipete and others added 2 commits October 10, 2026 10:15
Keep exact child identities in task context and relocate bounded Runtime facts after the native system and tool prefix. Preserve earlier message bytes across follow-up turns and tool results; retain system authority when no unambiguous carrier exists.

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

Copy link
Copy Markdown
Contributor

Merged via squash.

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 extensions: ollama merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: L 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.

3 participants