Skip to content

fix(agents): keep the session prefix append-only for silent replies and worker turns - #198201

Closed
obviyus wants to merge 5 commits into
mainfrom
openclaw/tide-krill
Closed

obviyus wants to merge 5 commits into
mainfrom
openclaw/tide-krill

Conversation

@obviyus

@obviyus obviyus commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Supersedes #198183 (same commits plus the worker pin).

Problem

A deliberate silent reply (NO_REPLY) broke the prompt cache prefix on role-alternating transports.

  • Replay dropped the silent assistant row, so the user turn before it and the next user turn became adjacent.
  • OpenAI Chat Completions and Bedrock Converse merge adjacent user turns. The merge rewrote an already-sent user message, and every later request missed the cache from that point.
  • Anthropic Messages, OpenAI Responses and Google kept the turns separate, so they did not break.

Remote worker turns rendered a fresh system prompt every turn, so any change (skill, workspace file, tool policy) rewrote the prefix.

Fix 1: silent replies

Fix 2: worker turns use the session pin

  • src/gateway/worker-environments/worker-turn-system-prompt.ts runs the same prepareSessionSystemPrompt series as embedded turns. Before launch, the Gateway reads the openclaw.system-prompt checkpoint and sends the pinned prefix.
  • A change goes out as an appended prompt-update message. The Gateway stores it before the user turn, so stored order matches sent order.
  • The checkpoint is written in finalizeWorkerTurnResult, after the worker's rows are committed. A failed worker turn writes no checkpoint.
  • Rebuild points are the same as embedded turns: new session, compaction/reset, model or route change.
  • No worker protocol change: launch history already accepts openclaw.system-update prompt-update messages (WorkerRuntimeContextMessageSchema).

One invariant across five transports

New fake servers (test/helpers/fake-model-transports.ts) speak the five wire formats: anthropic-messages, openai-responses, openai-completions, google-generative-ai and bedrock-converse-stream (Bedrock uses a hand-built AWS event stream). Each transport has its own e2e file that runs one Gateway scenario:

first turn → background exec → subagent spawn and completion → inter-session send → skill install → workspace AGENTS.md edit → silent turn → next turn → compaction → turn after compaction.

The test canonicalizes each request (cache markers removed) and asserts exactly one prefix break, at compaction.

Transport main This PR
Anthropic Messages pass pass
OpenAI Responses pass pass
OpenAI Chat Completions break at silent turn pass
Google Generative AI pass pass
Bedrock Converse break at silent turn pass

Design references

  • Hermes treats prompt caching as an invariant, with compression as the only exception (AGENTS.md:18-21), and asserts breaks with prefix_breaks (tests/e2e/core/history/_helpers.py:214). The e2e assertion here copies that shape: count breaks and allow exactly one, at compaction.
  • Hermes delivers mid-session changes on the per-turn user channel, not by editing the system prompt (agent/surface_switch.py, agent/skills_index_delta.py), and reuses the stored prompt when it still matches (agent/conversation_loop.py:802, :957). The prompt-update delta and the checkpoint restore follow the same idea.
  • Pi keeps system prompt and tools as the leading log entry, and sends later system changes as deltas (packages/agent/src/agent.ts:78-87, packages/ai/src/types.ts). OpenClaw already sends in-history system updates and retained runtime context this way; the fake matrix shows that path holds on all five transports.
  • Not copied: Pi's per-transport collapseSystemMessages rebuild (packages/ai/src/utils/transcript.ts, google-shared.ts:195). Rebuilding the system block on transports without mid-conversation system messages would change the prefix.

Evidence

  • Unit: src/agents/embedded-agent-runner/replay-history.test.ts 60/60; src/gateway/worker-environments/worker-turn-system-prompt.test.ts 3/3 (delta, model-change rebuild, no checkpoint on failure).
  • E2E (fake servers): all five transport files pass on this head. On main, Chat Completions and Bedrock fail at the silent turn.
  • Real provider routes: a live Gemini measurement follows in a comment.

Not in this PR

  • Google managed explicit caching still opts out of retained runtime context (buildGoogleGeminiReplayPolicy). Removing that needs a live Gemini cache measurement.
  • Worker turns are covered by unit tests only, not by the gateway e2e journey.

obviyus and others added 5 commits November 13, 2026 13:45
…s append-only

Dropping a NO_REPLY row left two user turns adjacent. Chat Completions and Bedrock merge them, which rewrote an already-sent turn and broke the prompt cache. The row is now dropped only when another assistant turn follows (#99620).

Co-authored-by: obviyus <[email protected]>
…s append-only

OpenClaw-Publication: 0d81101e-150c-8ae4-acbb-e22613e64f78
Worker turns rendered a fresh system prompt every turn. The Gateway now reads the session prompt checkpoint before launch, sends the pinned prefix, stores any change as an appended prompt-update message before the user turn, and writes the checkpoint after the worker commits. No worker protocol change: launch history already carries prompt-update messages.

Co-authored-by: obviyus <[email protected]>
OpenClaw-Publication: 2459e91e-8b36-85be-9f3c-3aa5a487b3f4
@clawsweeper

clawsweeper Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: L labels Nov 13, 2026
@obviyus obviyus changed the title Publish openclaw/tide-krill fix(agents): keep the session prefix append-only for silent replies and worker turns Nov 13, 2026
@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 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. clawsweeper:intake:needs-repro 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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 13, 2026
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR retains silent assistant replies as conversation separators and adds session system-prompt pinning for remote worker turns.

Example: “Check deployment” receives NO_REPLY, followed by “Any update?”

  • Before: Replay removes the assistant separator, allowing Chat Completions and Bedrock to merge the user messages and rewrite the earlier prefix.
  • After: The silent assistant row separates the user messages and preserves the earlier prefix.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful direction and transport coverage, but the worker pin misses its actual storage boundary and an affected consumer fails exact-head CI.
Proof confidence 🦐 gold shrimp (3/6) Maintainer-authored work is outside the contributor live-proof gate; supplied evidence covers fake-provider Gateway journeys and worker helper tests, while compatibility evidence for newly persisted worker openclaw.system-prompt entries is absent.
Patch quality 🦪 silver shellfish (2/6) 3 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Silent replies and refreshed worker instructions can invalidate reusable conversation prefixes, increasing model cost and response latency.
Reason: The collaborator-authored direction addresses acknowledged exceptions to the documented session-prefix contract without adding user settings.

Merge readiness

⛔ Blocked before merge - 4 items remain

Keep open: this maintainer-authored PR addresses a real prefix-stability gap, but the worker integration and two replay-related defects need repair.

Priority: P2
Reviewed head: 5cfb312e4f19f20a6fea9b3ee94b7b89733f8891

Before merge

  • Restore worker pins through a full, durable transcript boundary (P2) - For turns with a user-turn recorder, readWorkerTurnInputContext passes a detached openModelContextAsync manager here. Its checkpoint navigation contains only data.restart, so prepareSessionSystemPrompt cannot recover prefix, hash, renderedPrefix, or routeKey and starts a new series each turn. The lease is disposed on return, so it cannot preserve the series between turns either. This leaves the stated worker fix ineffective. The same manager has no persistence target, so appendCustomMessageEntryAsync also cannot durably store a generated delta. Read the full checkpoint through the transcript owner and write updates through a persisted, admitted writer rather than this model-only view.
  • Find the next row without copying the remaining history (P2) - Every silent row copies the entire remaining array before find can stop at its immediate successor. A 2,000-row history alternating user and NO_REPLY rows copies 999,000 references per normalization, adding quadratic allocation work to repeated prompt preparation. Walk forward by index without materializing the suffix.
  • Update the consumer fixture that expects silence to be removed (P2) - The shrink-history test still supplies [user, NO_REPLY, user] and expects prePromptMessageCount=2 plus replacement with two user rows. This PR intentionally retains all three rows, and the exact-head check fails at line 568 with 3 instead of 2. Use a genuinely removable empty or failed assistant row and preserve the count-rebasing assertions.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

  • [P2] Restore worker pins through a full, durable transcript boundary — src/gateway/worker-environments/worker-turn-system-prompt.ts:64-69
  • [P2] Find the next row without copying the remaining history — src/agents/embedded-agent-runner/replay-history.ts:324
  • [P2] Update the consumer fixture that expects silence to be removed — src/agents/embedded-agent-runner/run/attempt-prompt-context.test.ts:557-560

Tests

  • Low-value test src/gateway/worker-environments/worker-turn-system-prompt.test.ts: Remove the no-checkpoint-on-failure case: it only prepares a pin and omits commit, so it cannot detect finalizeWorkerTurnResult checkpointing a failed worker turn.
  • Missing end-to-end proof: The persisted worker checkpoint needs a latest-stable session upgrade and resume demonstrating intact history and settings, followed by a prompt refresh and restart.
Agent review details

How this fits together

The Gateway projects stored transcripts and rendered instructions into provider requests, while remote workers return transcript rows that the Gateway commits and finalizes.

flowchart LR
  A[Stored transcript] --> B[Replay normalization]
  B --> C[Gateway prompt preparation]
  D[Session prompt checkpoint] --> C
  C --> E[Provider or remote worker]
  E --> F[Transcript finalization]
  F --> A
Loading

Technical review

Best possible solution:

Keep the shared replay and prompt-series owners, use indexed lookahead, repair the shrink-history fixture, and connect worker checkpoint reads and delta writes to durable transcript operations.

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

Current-main source removes silent separators and rebuilds worker prompts, while the preceding merged PR records the matching prefix breaks; no target code was executed during this read-only review.

Is this the best way to solve the issue?

Retaining separators and reusing the existing prompt-series owner address the causes, but the worker adapter must consume full checkpoint facts and persist deltas through the durable owner.

Full review comments:

  • [P2] Restore worker pins through a full, durable transcript boundary — src/gateway/worker-environments/worker-turn-system-prompt.ts:64-69
    For turns with a user-turn recorder, readWorkerTurnInputContext passes a detached openModelContextAsync manager here. Its checkpoint navigation contains only data.restart, so prepareSessionSystemPrompt cannot recover prefix, hash, renderedPrefix, or routeKey and starts a new series each turn. The lease is disposed on return, so it cannot preserve the series between turns either. This leaves the stated worker fix ineffective. The same manager has no persistence target, so appendCustomMessageEntryAsync also cannot durably store a generated delta. Read the full checkpoint through the transcript owner and write updates through a persisted, admitted writer rather than this model-only view.
    Confidence: 0.99
  • [P2] Find the next row without copying the remaining history — src/agents/embedded-agent-runner/replay-history.ts:324
    Every silent row copies the entire remaining array before find can stop at its immediate successor. A 2,000-row history alternating user and NO_REPLY rows copies 999,000 references per normalization, adding quadratic allocation work to repeated prompt preparation. Walk forward by index without materializing the suffix.
    Confidence: 0.99
  • [P2] Update the consumer fixture that expects silence to be removed — src/agents/embedded-agent-runner/run/attempt-prompt-context.test.ts:557-560
    The shrink-history test still supplies [user, NO_REPLY, user] and expects prePromptMessageCount=2 plus replacement with two user rows. This PR intentionally retains all three rows, and the exact-head check fails at line 568 with 3 instead of 2. Use a genuinely removable empty or failed assistant row and preserve the count-rebasing assertions.
    Confidence: 1

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Silent assistant-row removal changes intended behavior with a stated reason (bd5f760: Centralize terminal silence classification and prevent fabricated replies while preserving hidden model-context rows.)
  • Immutable replay normalization keeps the original intent (3ec819f: Reuse immutable message cleanup while keeping history-dependent decisions outside the memo.)
  • Worker prompt assembly changes intended behavior with a stated reason (06d4475: Give node sessions the Gateway's prompt and bootstrap preparation while retaining Gateway-owned context selection and settlement.)
  • Provider prefix journey keeps the original intent (bf0b800: Exercise mid-session changes through provider wire formats and permit the journey's prefix rebuild only at compaction.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/agents/embedded-agent-runner/replay-history.test.ts src/agents/embedded-agent-runner/run/attempt-prompt-context.test.ts
  • pnpm test src/gateway/worker-environments/worker-turn-system-prompt.test.ts
  • pnpm test src/agents/agent-tools.prefix-stability.test.ts
  • pnpm test:e2e:gateway test/prompt-cache-prefix-stability.anthropic.e2e.test.ts test/prompt-cache-prefix-stability.openai-completions.e2e.test.ts test/prompt-cache-prefix-stability.openai-responses.e2e.test.ts test/prompt-cache-prefix-stability.google.e2e.test.ts test/prompt-cache-prefix-stability.bedrock.e2e.test.ts
  • pnpm check:changed

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit bf0b800 adds test/prompt-cache-prefix-stability.test-support.ts:1 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: bf0b8002c2b9; files: test/prompt-cache-prefix-stability.test-support.ts)

PR surface

Source +197, Tests +381. Total +578 across 11 files. Added test files: 5.

View PR surface stats
Area Files Added Removed Net
Source 4 202 5 +197
Tests 7 536 155 +381
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 738 160 +578

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: canonical
Canonical: #198201
Summary: The author identifies this PR as the replacement for the earlier silent-reply PR, whose changes are included here.

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: The reported failures increase model processing cost and latency; no urgent availability failure is established.
  • 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 13, 2026, 4:30 AM ET / 09:30 UTC.

@obviyus
obviyus marked this pull request as draft November 13, 2026 09:48
@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator Author

Converting to draft. Held until the prefix-cache redesign reproduces the causes end to end from captured request bytes and proves a fix on real traffic; this may be superseded by that design.

@obviyus

obviyus commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator Author

Closing. The silent-reply half is covered on main (replay keeps the history append-only on routes that do not merge user turns; the remaining merge is a documented known exception, and #201843 covers projected prompt updates). The worker-turn half is still real, but a correct fix needs a worker protocol change to store the prompt-update delta in order. It is tracked in #202523 with measurements.

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. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L 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