Repository navigation
fix(ai): preserve local model request prefixes - #137371
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. |
|
Codex review: needs maintainer review before merge. Reviewed September 10, 2026, 4:44 AM ET / 08:44 UTC (Revision 14). ClawSweeper reviewWhat this changesMoves 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 Review scores
Verification
How this fits togetherOpenClaw 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
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +122, Tests +697, Docs +9. Total +828 across 17 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest 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. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (13 earlier review cycles; latest 8 shown)
|
|
Both P1 findings are addressed in 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 ( 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. Verified on the wire rather than only in tests:
Narrowing cost nothing measurable: fresh-session latency is 14.5s / 14.6s / 16.1s versus 121.3s / 122.3s / 121.6s on Answering the decision you raised: no, OpenClaw should not globally trade system authority for cache reuse. Only producer-marked non-behavioral context moves.
|
|
Supplying the exact-head CI correlation requested in the last review. First, the failures that were real. The previous head Now the current head
Why I read these as runner pressure rather than the patch:
One way the patch does contribute, indirectly and worth stating. Touching Happy to re-run the failed shards if a maintainer can dispatch a retry — I cannot trigger one on this repo. |
Yigtwxx
left a comment
There was a problem hiding this comment.
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 onuser2.
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.
|
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: Exactly as you describe: the tail migrates off Why my evidence missed it. The "follow-up turn ~5.5 s, unchanged" row in the description was measured on Fix applied as you specified — 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 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. |
|
Pushed as Your probe, before and after: 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.
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 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 |
|
Thanks @gwiltschek! Proof: The built public CLI drove five independent loopback HTTPS cases, including real 18 KiB file reads and same-session follow-ups.
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. |
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
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.af13c228eeadae316f4df84531ea37704a44a08d. The subsequent two-line lint correction replaces equivalent fixed-stringindexOfchecks withincludes; 51 fresh utility/converter tests pass. Original build and capture identities are retained.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.