Skip to content

fix(ai): preserve local model request prefixes - #137371

Merged
obviyus merged 3 commits into
openclaw:mainfrom
gwiltschek:fix/cache-boundary-suffix-after-tools
Sep 10, 2026
Merged

obviyus merged 3 commits into
openclaw:mainfrom
gwiltschek:fix/cache-boundary-suffix-after-tools

Conversation

@gwiltschek

@gwiltschek gwiltschek commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Closes #137257

What Problem This Solves

For local Chat Completions servers that render tools after the system message, fresh-session identifiers inside that message split the reusable system-and-tools prefix. The workspace, instructions, and tool schemas can be unchanged while each new conversation still requires prompt reprocessing.

Why This Change Was Made

Move only the bounded Runtime facts line onto the first emitted user message. Keep behavioral instructions—including coauthor guidance, hook additions, and permission notices—at system/developer authority. Reject duplicated, reversed, or incomplete marker regions, and preserve facts when no user message survives projection.

Explicit message-cache breakpoints retain their existing system layout. Other affected provider paths remove the new markers without changing cache policy. The contributor commit is preserved. The earlier trailing-user approach and its unsupported follow-up latency claim remain withdrawn.

User Impact

Fresh conversations retain an identical system-and-tools prefix on the supported local route. Follow-ups retain earlier user and tool history. Existing current-turn Runtime Context snapshots remain transient; this change does not persist them on the first message. Actual cache hits and latency still depend on the model server and chat template.

Evidence

  • Two public baseline configurations reproduce session-field divergence before unchanged tools. Five independent candidate cases cover the full and read-only catalogs plus literal opening, closing, and paired-marker workspace controls.
  • Each candidate case uses the built public CLI, certificate-verified loopback HTTPS, two fresh sessions, real file reads returning the complete 18 KiB input, and a same-session follow-up. All 25 complete requests are retained; five separate checks confirmed closed listeners and removed fixture keys.
  • Candidate system-and-tools values match across sessions: 85,208 bytes with all 41 tools, and 6,809 bytes with only read. The read-only complete previous request remains a prefix through the full tool result and follow-up. The full profile preserves real history but intentionally retains its pre-existing transient carrier; its unconditional complete-prefix comparison remains false.
  • 590 focused cases have passing final coverage across the original 589 passes and the corrected exact-byte coauthor case. Both committed system/developer regressions fail on original main for the intended session-field difference. Restoring the original splitter produces five intended ambiguity failures and three passing malformed-input controls.
  • Public proof uses built commit af13c228eeadae316f4df84531ea37704a44a08d. The subsequent two-line lint correction replaces equivalent fixed-string indexOf checks with includes; 51 fresh utility/converter tests pass. Original build and capture identities are retained.
  • Native formatting, syntax lint, changed-file guards, and normal commit hooks pass. Hosted type-aware checks and final review are evaluated against the current PR head; the checks tab is authoritative for their state.

These are request-production, role-preservation, and real tool-execution checks with scripted provider responses. They do not claim natural model inference, server cache hits, or a new measured speedup. Historical contributor timings, corrected claims, and earlier CI failures remain in the discussion and retained evidence.

@clawsweeper

clawsweeper Bot commented Sep 3, 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.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. labels Sep 3, 2026
@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 10, 2026, 4:44 AM ET / 08:44 UTC (Revision 14).

ClawSweeper review

What this changes

Moves bounded Runtime facts behind the system-and-tools prefix in eligible Chat Completions requests while preserving instruction roles and removing internal markers from other provider payloads.

Merge readiness

✅ Ready for maintainer review

This remains a useful fix: current main and the latest release retain the affected prompt layout. The earlier actionable findings are addressed, and the supplied production-path evidence supports the narrowed request-stability claim. No new blocking defect was found.

Priority: P2
Reviewed head: 94dd52232ee7bf33ae4e16316db2d9d4d25831ae

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, well-supported repair with resolved prior findings and appropriately limited performance claims.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The captured PR body reports built-CLI request production through verified HTTPS, real file reads, and fresh-session/follow-up comparisons at af13c22. These observations support the changed prompt producer and converter; the verified two-line head correction preserves that behavior. Proof establishes request stability, not natural inference, server cache hits, or latency gains.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured PR body reports built-CLI request production through verified HTTPS, real file reads, and fresh-session/follow-up comparisons at af13c22. These observations support the changed prompt producer and converter; the verified two-line head correction preserves that behavior. Proof establishes request stability, not natural inference, server cache hits, or latency gains.
Evidence reviewed 10 items Verified introduced scope: Inspected the complete introduced production diff from the pinned merge base to the exact checkout head. The changes concern prompt production, request conversion, marker stripping, documentation, and regression coverage; endpoint drift was not attributed to this PR.
Bounded producer and instruction preservation: Only the Runtime facts line is enclosed by relocation markers. Coauthor, model, and reasoning guidance remain outside; the closed region also excludes subsequently appended hook and permission instructions.
Earlier findings resolved: The converter relocates only after finding an emitted user carrier, scans forward to preserve earlier requests on follow-up, and retains the complete prompt when no carrier survives. The splitter rejects duplicate, reversed, and incomplete regions. Tests cover these cases, instruction roles, images, full tool results, and composed workspace-marker collisions.
Findings None None.
Security None None.

How this fits together

OpenClaw assembles workspace instructions, runtime facts, conversation history, and tool definitions into model requests. Provider transports shape those inputs into payloads whose ordering affects prompt-cache reuse.

flowchart TD
  A[Workspace instructions and runtime facts] --> B[System prompt assembly]
  C[Conversation and tool definitions] --> D[Provider request builder]
  B --> D
  D --> E{Explicit message cache breakpoints?}
  E -->|Yes| F[Preserve system layout and strip markers]
  E -->|No| G[Move bounded facts to first emitted user message]
  F --> H[Model server request]
  G --> H
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +122, Tests +697, Docs +9. Total +828 across 17 files.

View PR surface stats
Area Files Added Removed Net
Source 7 132 10 +122
Tests 9 711 14 +697
Docs 1 9 0 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 17 852 24 +828

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +122 net lines; tests +697 net lines Production growth implements bounded relocation and provider marker cleanup; the larger test delta protects prompt bytes, instruction roles, and projection edge cases.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #137257
Summary: This PR is the candidate fix for the paired local-model prefix-cache issue; merged explicit-cache-marker work is related but distinct.

Members:

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

Technical review

Best possible solution:

Keep Runtime facts behind the reusable prefix while preserving instruction roles, existing explicit checkpoints, and transient runtime-context handling.

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

Yes: current source exposes session-specific Runtime bytes in the system message, and the supplied captures demonstrate divergence before unchanged tools. This read-only review did not execute the application or tests.

Is this the best way to solve the issue?

Yes: producer-bounded relocation addresses the unsupported-checkpoint route without moving behavioral instructions or replacing the existing transient carrier mechanism.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: Repairs repeated prompt processing for affected local Chat Completions deployments without evidence of a core outage.
  • 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. Sufficient (live_output): The captured PR body reports built-CLI request production through verified HTTPS, real file reads, and fresh-session/follow-up comparisons at af13c22. These observations support the changed prompt producer and converter; the verified two-line head correction preserves that behavior. Proof establishes request stability, not natural inference, server cache hits, or latency gains.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured PR body reports built-CLI request production through verified HTTPS, real file reads, and fresh-session/follow-up comparisons at af13c22. These observations support the changed prompt producer and converter; the verified two-line head correction preserves that behavior. Proof establishes request stability, not natural inference, server cache hits, or latency gains.

Evidence

What I checked:

  • Verified introduced scope: Inspected the complete introduced production diff from the pinned merge base to the exact checkout head. The changes concern prompt production, request conversion, marker stripping, documentation, and regression coverage; endpoint drift was not attributed to this PR. (94dd52232ee7)
  • Bounded producer and instruction preservation: Only the Runtime facts line is enclosed by relocation markers. Coauthor, model, and reasoning guidance remain outside; the closed region also excludes subsequently appended hook and permission instructions. (src/agents/system-prompt.ts:1551, 94dd52232ee7)
  • Earlier findings resolved: The converter relocates only after finding an emitted user carrier, scans forward to preserve earlier requests on follow-up, and retains the complete prompt when no carrier survives. The splitter rejects duplicate, reversed, and incomplete regions. Tests cover these cases, instruction roles, images, full tool results, and composed workspace-marker collisions. (packages/ai/src/openai-completions-messages.ts:322, 94dd52232ee7)
  • Current main still needs the fix: Current main serializes the complete system prompt through the converter and emits session-specific Runtime facts inside that prompt. The merged explicit-checkpoint work at fix(openai-completions): apply Anthropic cache markers on the managed transport #140781 addresses a different route and does not supersede this local-server fix. (packages/ai/src/openai-completions-messages.ts:78, 5815dd0379c5)
  • Latest release check: The supplied latest release, v2026.9.3, also emits the Runtime line inside the system prompt without the relocation region. Its source was inspected through GitHub after the local tag lookup was unavailable. (src/agents/system-prompt.ts:1542, 1391f7cd2d40)
  • Production-path proof and its limits: The supplied PR body, captured under sourceRevision d73ebc0b1db412af3220b8881a63c6d9be53f600a985ee3e01a026c88ff0c71e, reports built-CLI runs through certificate-verified loopback HTTPS: five candidate scenarios, 25 complete requests, real 18 KiB file reads, fresh sessions, and follow-ups. System-and-tools values match across sessions at 85,208 bytes with 41 tools and 6,809 bytes with read only. The full profile retains its existing transient carrier; natural inference, cache hits, and speedup are explicitly not claimed. No separate raw capture files were present in the supplied scratch directory. (af13c228eead)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Yigtwxx: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (13 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-03T19:46:47.486Z sha 3ddf0439f2035260af79a0f2f229c6c905a40f29 :: blocked before merge. :: none
  • reviewed 2026-09-03T20:58:07.939Z sha d4ec9ac417fe0d070d0c89adc14d5983abd72bf5 :: blocked before merge. :: none
  • reviewed 2026-09-06T10:52:41.763Z sha c0e7407f89b6317093193ba449e4a464c04231e2 :: blocked before merge. :: [P1] [P1] Bound relocation before subsequently appended system instructions
  • reviewed 2026-09-06T19:43:29.659Z sha 07ed83c4db839a06f72b31596542c84ddfd372c9 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-07T07:16:53.259Z sha 0ff7424d99a2017bbd2c012b07b137844d067cf1 :: blocked before merge. :: none
  • reviewed 2026-09-07T07:43:08.965Z sha 59633ac :: needs maintainer review before merge. :: none
  • reviewed 2026-09-07T09:21:00.002Z sha 59633ac :: needs maintainer review before merge. :: none
  • reviewed 2026-09-10T08:28:19.522Z sha 94dd522 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 3, 2026
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M and removed size: S labels Sep 3, 2026
@gwiltschek

Copy link
Copy Markdown
Contributor Author

Both P1 findings are addressed in b3f28e7. PR description updated in full; summary here.

P1: suffix could be dropped when the carrier turn projects away — confirmed and fixed. You were right. My guard checked the transformed transcript, but a user turn whose media projects to empty content is skipped at emit time (content.length === 0 → continue), so the tail was removed from the system prompt with nothing left to carry it. The relocation is now atomic: the system message keeps the full prompt until a carrier turn is actually emitted, and only then shrinks to the stable prefix. Regression test added for a user turn that projects away.

P1: behavioral guidance demoted to user authority — took your recommendation to narrow. Rather than defend the generic relocation, the non-behavioral tail is now marked explicitly by the producer. SYSTEM_PROMPT_RELOCATABLE_BOUNDARY is emitted in system-prompt.ts just above watched sessions, and the converter relocates only what follows it. Approval UI, owner identity, Messaging and Reactions keep system/developer authority.

Verified on the wire rather than only in tests:

behavioral guidance stays at system authority:
   Approval        system=True   user=False
   ## Messaging    system=True   user=False
relocated tail:
   session=        system=False  user=True
   sessionId=      system=False  user=True

system prompts IDENTICAL across sessions: True
internal markers on the wire:             False

stripSystemPromptCacheBoundary now strips both markers, so existing consumers (Anthropic policy, Responses, cli-runner) keep the no-leak guarantee without each needing to know about the new one.

Narrowing cost nothing measurable: fresh-session latency is 14.5s / 14.6s / 16.1s versus 121.3s / 122.3s / 121.6s on main. I had expected the narrower version to be faster still and it is not — the relocated tail shrank from ~2.2k to ~630 chars, but that saving is small next to fixed generation cost.

Answering the decision you raised: no, OpenClaw should not globally trade system authority for cache reuse. Only producer-marked non-behavioral context moves.

packages/ai 2277 passing, src/agents/system-prompt* 206 passing, all five oxlint core stripes pass locally.

@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 rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 3, 2026
@gwiltschek

Copy link
Copy Markdown
Contributor Author

Supplying the exact-head CI correlation requested in the last review.

First, the failures that were real. The previous head 3ddf043 failed 14 jobs, and that was my defect, not noise: packages/ai/src/transports/anthropic-payload-policy.ts(196,50): error TS2345: Argument of type 'unknown' is not assignable to parameter of type 'string'. A Record<string, unknown> property does not stay narrowed across a call. All 14 traced to that one error — the four typecheck jobs directly, and check-lint plus its five stripes because tsgolint is type-aware and cannot run when types do not compile. Fixed in d4ec9ac by binding the text to a local const. tsgo:core, tsgo:test and all five oxlint core stripes pass locally on the current head.

Now the current head d4ec9ac. No typecheck, lint, build, CodeQL or security job fails. Every remaining failure is a 120 s test timeout, in a different file per shard:

Job Test file Failure
compact-large-2 src/gateway/local-request-context.session-tools.test.ts Test timed out in 120000ms (a second assertion in the same file then sees post-timeout state)
compact-large-10 src/agents/subagents/spawn/subagent-spawn.authority.test.ts Test timed out in 120000ms, plus swarm scheduler run already exists
compact-large-17 src/gateway/server-methods/chat.abort-incarnation.test.ts Test timed out in 120000ms
changed-extensions-config-48 extensions/qa-lab/.../slack-live.runtime.test.ts Test timed out in 120000ms
compact-large-9 — log ends at Post job cleanup with no test output at all

Why I read these as runner pressure rather than the patch:

  • They pass locally. local-request-context.session-tools.test.ts runs 14/14, and slack-live.runtime.test.ts 62/62.
  • The margin is thin. That session-tools file uses ~73 s of test time against a 120 s budget on an unloaded machine, so a contended runner tips it over.
  • The shards wander. Across four runs on this branch the failures moved: compact-small-50, then changed-extensions-config-48, then compact-large-2/9, now compact-large-2/9/10/17. A deterministic break does not move.
  • No mechanism connects them. The changed surface is the Chat Completions message converter, the Anthropic system-block builders, and one marker line in the prompt builder. The failing assertions are session-generation strings (Session removed. vs Session changed; newer session kept.), swarm scheduling and Slack fallback chunking. slack-live.runtime.test.ts mocks Slack entirely with vi.fn() and never builds a prompt.

One way the patch does contribute, indirectly and worth stating. Touching src/agents/system-prompt.ts widens change-based test selection: the earlier packages/ai-only head ran zero extension shards, while these heads run 29. More shards in parallel means more pressure on timeout-marginal tests. That is scheduling load, not a behavioural change from the diff, but it does explain why these appeared on this branch and not on the earlier one.

Happy to re-run the failed shards if a maintainer can dispatch a retry — I cannot trigger one on this repo.

@Yigtwxx Yigtwxx left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed head d4ec9ac417f. The diagnosis is right and worth stating plainly: for Chat Completions the tool schemas serialize after the whole system message, so a volatile tail inside that message forks the prefix ahead of every tool definition, and stripping the boundary one line before convertMessages (the removed pre-strip in openai-completions-params.ts) is what made the existing boundary inert. The atomic relocation, the marker stripping on the Anthropic and preserveSystemPromptCacheBoundary paths, and keeping behavioral guidance at system authority all read correctly. I re-ran the changed converter myself and no internal marker reaches the wire on either arm. One finding on the claim that follow-up turns are unchanged.

The relocated tail moves between turns, so the previous user turn changes on every follow-up request.

I ran the real convertMessages from packages/ai on this head and on main, same model (openai-completions, non-OpenAI base URL, resolveOpenAICompletionsCompat), with the system prompt laid out the way system-prompt.ts emits it on each arm (marker immediately before the Runtime: line on this head, none on main), for a two-turn conversation: turn 1 is [user1], turn 2 is [user1, assistant(tool call), toolResult (30 KB), assistant, user2].

  • main: turn 1's params are a full prefix of turn 2's params (first differing param: none).
  • this head: the first differing param is index 1, user1. In turn 1 it ends with \n\nRuntime: name=main agent=main session=... sessionId=...; in turn 2 it does not, because the tail now sits on user2.

For a prefix cache that already holds the previous exchange (llama.cpp keeps the generated tokens of the slot, so after turn 1 the KV covers system, tools, user1, the tool call and its result), turn N+1 recomputes from user N onward: the whole previous exchange, tool results included. In the probe that is the 30 KB tool result; on the deployment in the description, one file read can be the size of the tool schemas this PR saves once per conversation. Within a turn's tool loop the trailing user turn does not change, so the intra-turn prefix stays stable; it is the per-turn boundary that moves. On main the equivalent volatile text travels as a transcript-persisted runtimeContextCarrier message, which is why it never moved between requests there.

The fix is small: attach the tail to the first user turn after the system message instead of the trailing one. It still lands after the tool schemas, which is all the repair needs, and the first user turn is byte-identical for the life of the conversation, so both the cross-conversation prefix this PR wins and the within-conversation prefix main already had stay stable. The projected-away fallback and the cacheOptOutIndexes marking carry over unchanged; relocateNonBehavioralSuffix just walks forward from systemParamIndex + 1 instead of backward from the end. A second row in the evidence table, "second message of the same conversation", would pin it: on the current head that number should move for the reason above.

@gwiltschek

Copy link
Copy Markdown
Contributor Author

Thank you — this is a real defect and you found it in the one place my evidence could not see it.

Reproduced before accepting it. I ran your comparison against the changed converter, two turns, 30 KB tool result:

first differing param index: 1
  turn1[1]: {"role":"user","content":"user1\n\n## Runtime\nRuntime: session=alpha | sessionId=abc"}
  turn2[1]: {"role":"user","content":"user1"}

Exactly as you describe: the tail migrates off user1 on the follow-up, so the prefix forks at index 1 and everything after it — the tool call and its result included — is recomputed.

Why my evidence missed it. The "follow-up turn ~5.5 s, unchanged" row in the description was measured on hi → what's 2+2?. No tool calls, so the recomputed span was a few tokens and invisible in wall-clock. I reported the intra-conversation case as unaffected on a conversation chosen to be trivial, which is not a measurement of the thing I claimed. Your 30 KB probe is the case that matters and I did not construct it.

Fix applied as you specified — relocateNonBehavioralSuffix now walks forward from systemParamIndex + 1 rather than backward from the end, so the tail lands on the first user turn. It still sits after the tool schemas, and the first user turn is byte-identical for the life of the conversation. The projected-away fallback and the cacheOptOutIndexes marking carry over unchanged, as you said they would. The probe now reports first differing param index: -1, and packages/ai is green at 2282 tests.

I have added two regression tests rather than one, deliberately paired: the previous turn staying byte-identical across follow-ups, and the system message staying identical across conversations. The two are in tension and I satisfied the second by breaking the first, so a test for either alone would not have caught this.

Not pushed yet. I will not push until pnpm build, both typecheck lanes and the lint stripes have run — vitest does not typecheck, and skipping that is how I put a TS2345 into 14 CI jobs earlier in this PR. The machine I build on needs a memory increase for that, which lands tomorrow. Your requested "second message of the same conversation" row needs a real measurement against the endpoint and will come with the same push.

One thing I would rather flag than let stand: the description's claim that follow-up turns are unchanged is wrong on the current head, for the reason you give, and I have not yet corrected the description. I will do that in the same update rather than quietly restating the numbers.

@gwiltschek

Copy link
Copy Markdown
Contributor Author

Pushed as c0e7407. Fix applied exactly as you specified — relocateNonBehavioralSuffix walks forward from systemParamIndex + 1, so the tail lands on the first user turn. The projected-away fallback and the cacheOptOutIndexes marking carried over unchanged, as you said they would.

Your probe, before and after:

turn 1: [user1]
turn 2: [user1, assistant(tool call), toolResult(30 KB), user2]

before: first differing param index = 1
        turn1[1] "user1\n\n## Runtime\nRuntime: session=alpha | sessionId=abc"
        turn2[1] "user1"
after:  first differing param index = -1

Both properties now have regression tests, kept as a pair on purpose: the previous turn staying byte-identical across follow-ups, and the system message staying identical across conversations. A test for either alone would not have caught this, since I satisfied the second by breaking the first.

packages/ai 2282 passing, pnpm build, tsgo:core, tsgo:test and all five oxlint core stripes green locally.

On the "second message of the same conversation" row you asked for — I tried it and I am not going to quote it, because the measurement does not support a number. Two-turn conversation on the deployment in the description, one arm per loop direction:

turn 2   fixed 189.1 s   trailing 202.5 s   -> 13.4 s in the predicted direction
turn 1   fixed 341.1 s   trailing 284.9 s   -> 56.2 s in the WRONG direction

Turn 1 is identical code on both arms — with a single user turn the two implementations select the same param — so that 56 s spread is pure run-to-run noise, and it is four times the turn-2 effect. My harness used a live web-search tool call, so result size and generation length varied freely between runs; the effect is smaller than the variance I introduced. Quoting the 6.6% would be quoting noise.

Doing it properly needs a deterministic tool payload rather than a network call, and repeated samples per arm. I have not done that, and the description now says so rather than implying the row exists. What establishes the behaviour is the assertion above — which is the same form of evidence you used, and I think the better one here: it is exact, it does not depend on my hardware, and it fails loudly if someone reintroduces the regression.

I have also withdrawn the "follow-up turns are unchanged" line from the description rather than restating it. It was measured on hi → what's 2+2?, where the recomputed span is a few tokens, and it was wrong for precisely the reason you gave.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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 P1 High-priority user-facing bug, regression, or broken workflow. 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. labels Sep 6, 2026
@openclaw-barnacle openclaw-barnacle Bot added 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: android App: android app: ios App: ios 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 labels Sep 10, 2026
@obviyus

obviyus commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator

Thanks @gwiltschek!

Proof: The built public CLI drove five independent loopback HTTPS cases, including real 18 KiB file reads and same-session follow-ups.

  • Bug: Fresh-session Runtime identifiers split the system-and-tools prefix on compatible local Chat Completions routes.
  • Fix: Carry only bounded facts on the first emitted user message, retain instruction authority, reject ambiguous regions, and preserve explicit cache policies.
  • Validation: 590 focused cases have passing coverage; 51 affected cases were rechecked after the equivalent lint correction. The required exact-head review and CI passed.
Before After
Fresh sessions change system content before unchanged tools. System-and-tools content stays identical across sessions: 85,208 bytes with 41 tools.
Read-only history already preserves its complete earlier request. That complete prefix remains intact through a full file result and follow-up.
Earlier candidate: ambiguous literal markers can select instructions for relocation. Project and core instructions remain in system content; cache/relocation markers are stripped.

The full profile retains its existing transient Runtime Context carrier, so its unconditional complete-request-prefix comparison still fails at that moving carrier. Earlier real user/tool history stays intact. These captures prove request shaping and tool execution, not natural model inference, cache hits, or a new latency improvement.

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: amazon-bedrock 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: 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.

[Bug]: ## Runtime below SYSTEM_PROMPT_CACHE_BOUNDARY still voids the prefix cache — tool schemas serialize after the system message

3 participants