Skip to content

fix(agents): keep the session system prompt stable across completion wakes - #197835

Merged
obviyus merged 5 commits into
mainfrom
fix/prompt-cache-stable-system-prompt
Nov 12, 2026
Merged

obviyus merged 5 commits into
mainfrom
fix/prompt-cache-stable-system-prompt

Conversation

@obviyus

@obviyus obviyus commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

The system prompt of one session changes between turns, depending on what started the turn. Anthropic prompt caching keys on an exact prefix, so each change discards the cache for the whole conversation. Long sessions (several hundred thousand tokens) then re-write the full prefix at cache-write price.

On a production gateway over 3 days (anthropic-messages, cacheRetention: short), the existing [prompt-cache] cache read dropped detector attributed most breaks to systemPrompt/systemPromptSuffix digest changes. The largest group was trigger=event provenance=internal_system:exec (background exec completion wakes): the stable prefix and almost every suffix section changed at once.

Root cause

  1. Completion wakes switch the prompt to minimal mode. A session event (exec or child completion wake) carries its producer's tool ceiling in toolsAllow (session-event-target.ts, session-event-handoff.ts). prepareEmbeddedAttemptSystemPrompt treats any restrictive toolsAllow as a narrowly scoped run and forces promptMode: "minimal". A wake therefore renders a different prompt for the same session: no Execution Bias, Bootstrap/Project Context changes, no Memory Recall, Documentation, Session routing, Output Directives, UI Presentation or messaging guidance. The tool definitions were already kept stable for these turns (resolveTurnToolSurface); only the prompt mode was not.
  2. Run-granted tools in the cached deferred-tool directory. skill_library is a run-granted core tool: it exists only on turns whose requester granted it. A system-started wake of the same session does not have it, so the "Available deferred-schema tools" list inside the Tooling section differed by one row between user turns and wakes.

Fix

  • A host system turn (trigger=event with internal_system provenance, the existing isHostSystemTurn) keeps the session's prompt mode. Its tool ceiling still gates calls exactly as before. Narrowly scoped runs that are not host wakes (cron toolsAllow, plugin commands, etc.) keep the minimal prompt.
  • The cached deferred-tool directory omits run-granted core tools. The turn that holds the grant lists them in its own runtime context, beside the turn's input, so its discoverability does not change.
  • Remote worker turns render that per-turn listing in the worker tool projection, before the projection disposes its catalog, and carry it into prompt preparation (including refresh).
  • When another catalog source shares a run-granted tool's name, or the entry requires an exact id, the listing names the exact catalog id (for example openclaw:core:skill_library), so tool_describe / dispatch_action resolve it.

Proof

Real route, before vs after. Isolated throwaway Gateway (scratch state, no channels), real Anthropic-compatible provider route, cacheRetention: short, the same configured scratch workspace for both arms. A logging proxy recorded the provider's own cache_read_input_tokens / cache_creation_input_tokens and the request system-prompt digest. One session per arm: user turn that starts a 10 s background exec → exec completion wake → user turn → wake → final user turn.

call kind before: read / write after: read / write
1 user 11,640 / 17,955 11,640 / 18,156
2 tool result 29,595 / 392 29,796 / 396
3 exec wake 12,157 / 16,379 30,192 / 987
4 user 29,987 / 1,331 31,179 / 441
5 tool result 31,318 / 419 31,620 / 440
6 exec wake 28,536 / 1,727 32,060 / 988
7 user 31,737 / 1,292 33,048 / 400
total 174,970 / 39,495 199,535 / 21,808
  • Before: 2 distinct system prompts in one session; the detector logged cache read dropped 29595 -> 12157 … trigger=event provenance=internal_system:exec with the same section signature seen in production.
  • After: 1 system prompt for all 7 calls; no [prompt-cache] drop warnings.
  • Cache writes in this short session fell 45% (39.5k → 21.8k). The first wake re-wrote 16.4k tokens before and 1k after. In the before arm, the second wake still hit, because both prompt variants were warm inside the 5-minute window. In production, each wake that arrives after the wake variant has expired re-writes the whole conversation. With 400–750k-token sessions, that is one full re-write per such wake.

The cost saving at production scale is an extrapolation from this mechanism. I measured it only on this short probe session, not on a production deployment.

Focused tests:

  • attempt-system-prompt.test.ts: a completion wake with an inherited tool ceiling renders the user-turn prompt byte for byte. A non-wake restricted run still renders the minimal prompt.
  • tool-search-directory.test.ts: the cached directory is identical with or without the run grant, and the grant is listed separately. With a colliding client tool, the listing gives an exact id that ToolSearchRuntime.describe resolves.
  • worker-gateway-tool-runtime.test.ts: the worker projection leaves skill_library out of the cached directory and returns it in the per-turn listing.
  • Each test fails without its fix.

The real-route numbers above were measured before the worker and collision fixes. Those fixes change no prompt bytes on the measured embedded path.

Not covered (separate follow-ups)

  • User-turn systemPromptSuffix changes (Tooling / Session routing / Skills) on inter_session user turns (sessions_send, subagent settle). The Tooling part matches the run-granted directory row fixed here. The Session routing and Skills differences were not reproduced or measured in this PR.
  • History rewrites (historyRewrite: message N (assistant) differs … content.length, content[k].type/id/name/arguments). An earlier assistant message gains or changes tool-call blocks after it was already sent. This is often together with replayed thinking dropped … prefix_binding_mismatch, and sometimes with changed envelope.api/provider/model (a fallback route). This change does not address it.

…wakes

An exec or child completion wake runs as a host system turn with its
producer's tool ceiling in toolsAllow. Any explicit toolsAllow switched the
prompt to minimal mode, so the wake rebuilt a different system prompt for the
same session (no execution bias, memory, docs, routing or output sections).
The provider then missed the cache right after the tool block and rewrote the
whole conversation on every user/wake alternation.

A host system turn now keeps the session's prompt mode; its ceiling still
gates calls. Run-granted core tools (skill_library) exist only on turns whose
requester granted them, so the cached deferred-tool directory omits them and
the granting turn lists them in its runtime context instead.

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

clawsweeper Bot commented Nov 12, 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 agents Agent runtime and tooling size: S labels Nov 12, 2026
@obviyus
obviyus marked this pull request as ready for review November 12, 2026 17:10
@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. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. labels Nov 12, 2026
@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR preserves session prompt mode during completion wakes and moves run-granted deferred-tool discovery into the current turn’s context.

Example: An Anthropic-backed conversation resumes after a 10-second background exec completes.

  • Before: The first wake changes the system prompt and writes 16,379 cache tokens in the supplied probe.
  • After: The system prompt stays identical across all seven requests, and the first wake writes 987 cache tokens.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused repair with live embedded-path evidence, distinct worker and collision regressions, and no actionable findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied isolated-Gateway trace exercises real background exec completion wakes through an Anthropic-compatible route and records stable post-fix system prompts with lower cache writes; later worker and collision repairs have focused regression coverage and leave the measured embedded path unchanged.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Background completion wakes change a conversation’s system prompt, increasing provider cache-write cost and latency.
Reason: The maintainer-authored direction restores the documented stable-context contract, and the measured embedded scenario demonstrates reduced cache writes.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR addresses a current prompt-cache defect with useful live evidence and no actionable findings; exact-head CI remains pending.

Priority: P2
Reviewed head: cd137d33e48ac037d05ba958565426006d1c0ec9

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway-local and worker turns feed session facts, tool catalogs, and current-turn instructions into shared prompt preparation, which produces the system prompt and runtime context sent to the model provider.

flowchart TD
  A[User turn or completion wake] --> B[Session and tool preparation]
  B --> C[Shared system prompt preparation]
  B --> D[Worker tool projection]
  D --> C
  C --> E[Stable system prompt]
  C --> F[Current turn runtime context]
  E --> G[Model provider request]
  F --> G
Loading

Technical review

Best possible solution:

Keep prompt presentation session-stable through the existing preparation owners while retaining current-turn tool gates and grant discovery.

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

Current-main source shows the finite producer ceiling selecting minimal mode, and the contributor supplies a matching live before/after Gateway trace; this review ran no reproduction.

Is this the best way to solve the issue?

The patch uses the existing host-turn predicate, directory renderer, runtime-context carrier, and worker projection without adding persistence or competing authority.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Finite tool ceilings selecting minimal prompt mode changes intended behavior with a stated reason (e25434e: The wildcard-policy repair preserved finite restrictions; later reader-enabled skill guidance retained minimal mode for scoped runs.)
  • Deferred-tool directory membership changes intended behavior with a stated reason (f122363: Budget discovery text while preserving authorized catalog access; subsequent work removed unrelated external-inventory churn.)
  • Worker prompt projection keeps the original intent (06d4475: Give worker sessions the same canonical prompt preparation and runtime context as Gateway-local sessions.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 41b50b4 adds src/agents/embedded-agent-runner/run/attempt-system-prompt-prepare.ts:239 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 41b50b4dbcba; files: src/agents/embedded-agent-runner/run/attempt-system-prompt-prepare.ts)

PR surface

Source +74, Tests +65. Total +139 across 9 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 6 77 3 +74
Tests 3 66 1 +65
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 143 4 +139

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.

Root-cause cluster

Relationship: same_root_cause
Canonical: #191128
Summary: The prompt-mode repair shares the reported exec-wake cause, while the run-granted directory repair overlaps a separate skill-library cache proposal.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Completion wakes cause avoidable provider cache writes and processing cost in otherwise working conversations.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • 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 execution lanes are retired.

History

Review history (2 earlier review cycles)
  • reviewed 2026-11-12T17:26:09.013Z sha 59abecc :: needs changes before merge. :: [P2] Carry the run-granted listing through worker prompt projection | [P2] Preserve exact identities for colliding run-granted tool names
  • reviewed 2026-11-12T17:45:35.408Z sha 9e33503 :: needs maintainer review before merge. :: none

Reviewed November 12, 2026, 12:57 PM ET / 17:57 UTC (Revision 3).

… collisions

Remote worker turns render the deferred directory from a projection whose
catalog is disposed before prompt preparation, so the run-granted listing that
replaces the cached directory row was never emitted. The worker projection now
renders the listing before cleanup and carries it into prompt preparation,
including refresh.

When another catalog source shares a run-granted tool's name, or the entry
requires an exact id, the listing now names the exact catalog id instead of a
bare name that tool lookup rejects as ambiguous.

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

obviyus commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Nov 12, 2026
@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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. labels Nov 12, 2026
Keep this PR to the host-system-turn prompt-mode fix. Moving run-granted
tools out of the cached deferred directory needs worker projection and
name-collision handling; it returns as a separate change.

Co-authored-by: obviyus <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added size: XS and removed gateway Gateway runtime size: S labels Nov 12, 2026
@obviyus

obviyus commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

…on fixes

Reinstate the run-granted tool listing, with remote worker projection carrying
the per-turn listing and colliding names listed by exact catalog id.

Co-authored-by: obviyus <[email protected]>
@clawsweeper clawsweeper Bot added the clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. label Nov 12, 2026
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime and removed size: XS labels Nov 12, 2026
@obviyus

obviyus commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. 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. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 12, 2026
@obviyus

obviyus commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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. 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 12, 2026
@obviyus
obviyus merged commit a3d5baa into main Nov 12, 2026
134 checks passed
@obviyus
obviyus deleted the fix/prompt-cache-stable-system-prompt branch November 12, 2026 18:12
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 13, 2026
…wakes (openclaw#197835)

Completion wakes kept their producer's tool ceiling and forced the minimal prompt, so one session alternated between two system prompts and lost its Anthropic prompt cache on every wake. Host system turns now keep the session prompt mode; their tool ceiling still gates calls. Run-granted tools such as skill_library move out of the cached deferred-tool directory into the granted turn's own context, including remote worker turns, with exact catalog IDs when names collide.

Real route (cacheRetention short): 2 system prompts -> 1 per session; first wake cache write 16,379 -> 987; session cache writes 39.5k -> 21.8k.

Co-authored-by: obviyus <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 16, 2026
…wakes (#197835)

Completion wakes kept their producer's tool ceiling and forced the minimal prompt, so one session alternated between two system prompts and lost its Anthropic prompt cache on every wake. Host system turns now keep the session prompt mode; their tool ceiling still gates calls. Run-granted tools such as skill_library move out of the cached deferred-tool directory into the granted turn's own context, including remote worker turns, with exact catalog IDs when names collide.

Real route (cacheRetention short): 2 system prompts -> 1 per session; first wake cache write 16,379 -> 987; session cache writes 39.5k -> 21.8k.

Co-authored-by: obviyus <[email protected]>
(cherry picked from commit a3d5baa)
Co-authored-by: RomneyDa <[email protected]>
Backport-adaptation: Minimal runGranted fact/resolver from 3c8129e and prompt-only host-event classifier from 8100c60. No skill_library feature or cron authority migration. Group fixtures adapted with subsequent 197893.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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.

1 participant