Repository navigation
fix(ollama): reuse prompt prefixes across subagent spawns - #164804
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. |
Dependency graph guard clearedThis PR no longer has dependency changes awaiting review. A future dependency graph change from an external contributor requires a maintainer's
|
Security-sensitive guard clearedCurrent revision: This PR no longer changes files in the maintainer security-review tier. Separate CODEOWNERS requirements still apply to security policy and enforcement files. |
|
Codex review: needs maintainer review before merge. What this changesThis 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.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe 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]
Technical reviewBest 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
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +17, Tests +140, Docs +6, Other 0. Total +163 across 14 files. Added test files: 1. View PR surface stats
Review metrics
LabelsLabel changes: No label 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 (13 earlier review cycles; latest 8 shown)
Reviewed October 10, 2026, 2:54 PM ET / 18:54 UTC (Revision 14). |
|
Both replay-policy findings are fixed, and the branch is rebased onto current 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 // unowned openai-completions with supportsPromptCacheKey → appendOnlyRuntimeContext === false
// unowned openai-responses with supportsPromptCacheKey → appendOnlyRuntimeContext === true2. The capability predicate is now part of the memoized key (P2). // resolve unflagged → flagged, then flagged → unflagged; each must get its own policyI verified the second fix by reverting only the cache-key line: the both-order test then fails with
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 ( |
|
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 ( |
|
Rebased onto current
On the
|
| 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.
|
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 I would rather hand you a flat result I trust than a flattering one I do not. |
|
Evidence from a hosted route, in case it helps with the retention decision. Setup: a config-defined provider whose model uses 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 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 Local check: we enabled retention for our provider through a provider We have not measured the cache effect on the live provider with any of these changes. |
|
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 removesYou're right that // src/agents/transcript-policy.ts (this PR, the unowned/config-defined path)
...(isOpenAiResponses && requiresStablePromptPrefix(params.model)
? { appendOnlyRuntimeContext: true }
: {}),with So a config-defined 2. But on your route this PR is necessary, not sufficient — and I'd rather say that plainlyYour own local check is the evidence: enable retention and the first-call read doesn't move, because Active Memory's 3. Your cache is checkpoint-based, which makes a given divergence cost more for you than for meThree 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:
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 gapYou 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 |
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.
|
Rebased onto current What the rebase changed: Direct before/after of the actual behavior —
The quoted values are the whole 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 ( Suites re-run on the rebased head: |
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]>
|
Merged via squash.
|
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 agentthrough an isolated Gateway and native Ollamaqwen3:8b/api/chat, with a transparent recording proxy. Two ordinary turns and two real model-requestedsessions_spawncalls are captured; both children answerCHILD_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.ts5 passed, 181.51 s wall;subagent-system-prompt.test.ts15 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:genregenerated 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-gateis green one8ad458791057a4621cbaf2e8b06ea23fd85fe43. 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.