Skip to content

[Bug]: Turn-scoped developer instructions (SOUL.md/IDENTITY.md/USER.md) create different message prefixes between full-turn and tool-continuation calls, breaking DeepSeek KV cache (20%/99% oscillation) #96773

Closed as not planned

Description

@StewartXiang

Bug type

Performance regression — prompt cache hit rate degradation

Summary

In long conversational sessions, DeepSeek KV cache hit rate alternates between ~20% and ~99% on consecutive API calls within the same user message turn. This wastes 15M input tokens per long session ($27 at DeepSeek pricing).

Root cause traced to CODEX_TURN_SCOPED_WORKSPACE_DEVELOPER_CONTEXT_BASENAMES (SOUL.md, IDENTITY.md, USER.md) being injected as developer instructions differently between full-turn calls and tool-continuation calls, creating two different message prefixes that prevent cache reuse.

Affected versions

  • First observed: 2026.6.5
  • Still present: 2026.6.10 (latest)

Mechanism (code trace)

In run-attempt-*.js:

// Line 211-215: These files are marked as turn-scoped
const CODEX_TURN_SCOPED_WORKSPACE_DEVELOPER_CONTEXT_BASENAMES = new Set([
    "identity.md",
    "soul.md", 
    "user.md"
]);

// Line 8285-8291: Turn collaboration developer instructions differ between calls
const buildCodexTurnCollaborationDeveloperInstructions = () => 
    buildTurnCollaborationMode(params, {
        turnScopedDeveloperInstructions: workspaceBootstrapContext.turnScopedDeveloperInstructions,
        ...
    }).settings.developer_instructions ?? void 0;

const buildRenderedCodexDeveloperInstructions = () => 
    joinPresentSections(promptBuild.developerInstructions,
        buildCodexTurnCollaborationDeveloperInstructions());

buildTurnCollaborationMode() returns different developer instructions for full-turn calls vs tool-continuation calls. These instructions are injected at/near the front of the messages array, so the two call types produce different prefixes → DeepSeek KV cache cannot serve the conversation history on full-turn calls.

Observed pattern

Every consecutive API call within the same user message alternates:

Turn N   (full call):        hit=20.0%  in=108k  cache=27k   ⚠️ only system prompt cached
Turn N+1 (tool continuation): hit=99.9%  in=132   cache=138k  ✅ full history cached
Turn N+2 (full call):        hit=19.0%  in=118k  cache=27k   ⚠️ prefix mismatch again
Turn N+3 (tool continuation): hit=99.9%  in=26    cache=149k  ✅
...repeats for 200+ turns

Impact

  • Session-wide cache hit rate: 51% (should be 90%+)
  • Wasted tokens: ~15M input tokens per long session
  • Cost: ~$27 per session at DeepSeek rates
  • Latency: full context re-computation on every user message

Reproduction

  1. OpenClaw 2026.6.x with deepseek-v4-pro
  2. Have SOUL.md, IDENTITY.md, USER.md in workspace
  3. Start a conversation and let it run for 50+ turns with tool calls
  4. Observe usage.cacheRead alternating between near-zero and near-total on consecutive API calls

Session evidence

Full turn-by-turn analysis performed on session bb84ac8e (340 turns). Data available at ~/.openclaw/agents/main/sessions/.

Related issues

Suggested fix

Make buildTurnCollaborationMode return byte-identical developer instructions for full-turn and tool-continuation calls within the same user turn, OR move turn-scoped instructions to a position in the messages array that does not affect prefix matching (e.g., after the conversation history instead of before it).

Activity

  1. clawsweeper commented on Jun 25, 2026

    @clawsweeper
    Contributor

    Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve. Reviewed June 25, 2026, 8:31 AM ET / 12:31 UTC.

    Summary
    Keep open: current main and v2026.6.10 still contain the reported Codex app-server path that moves SOUL.md, IDENTITY.md, and USER.md into turn-scoped collaboration developer instructions, and the related DeepSeek prompt-cache trackers do not cover this exact Codex turn-scoped mechanism.

    Reproducibility: Do we have a high-confidence way to reproduce the issue? Not fully; current source reproduces the claimed placement of SOUL.md, IDENTITY.md, and USER.md into Codex turn collaboration developer instructions, but the specific DeepSeek cache oscillation still needs live or redacted session-log proof.

    Ways to help us reproduce this

    • Add a screenshot or short recording showing the behavior.
    • Add expected vs actual behavior.

    Next step
    The source-level mechanism is plausible, but the fix requires maintainer judgment about Codex collaboration-mode semantics and live DeepSeek cache validation.

    Review details

    Best possible solution:

    Keep this as the canonical tracker for the turn-scoped Codex workspace-instruction cache mechanism until maintainers either stabilize the model-visible prefix with live provider proof or explicitly fold this mechanism into a broader DeepSeek cache fix.

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

    Do we have a high-confidence way to reproduce the issue? Not fully; current source reproduces the claimed placement of SOUL.md, IDENTITY.md, and USER.md into Codex turn collaboration developer instructions, but the specific DeepSeek cache oscillation still needs live or redacted session-log proof.

    Is this the best way to solve the issue?

    Is this the best way to solve the issue? Unclear; byte-stabilizing Codex's model-visible prefix is the right target, but moving developer instructions after history may conflict with the Codex collaboration-mode contract.

    AGENTS.md: found and applied where relevant.

    Remaining risk / open question:

    • This review did not run a live DeepSeek session or inspect the reporter's private session data, so the exact 20%/99% cache oscillation remains externally reported rather than reproduced here.
    • The best fix may affect Codex collaboration-mode semantics because Codex treats developer_instructions as model-visible developer context, not a cache-only transport detail.

    Codex review notes: model internal, reasoning high; reviewed against 4ecb45bf7729.

    Label changes

    Label changes:

    • add P2: The report describes a costly provider prompt-cache regression with a plausible source path but without a live current-main reproduction in this review.
    • add impact:session-state: The affected surface is model-visible turn context and collaboration developer instruction state across Codex turns.
    • add impact:auth-provider: The user-visible impact is provider/model prompt-cache behavior on DeepSeek-compatible routing.
    • add issue-rating: 🐚 platinum hermit: Current issue advisory state selects this label.
    • add clawsweeper:needs-live-repro: Current issue advisory state selects this label.
    • add clawsweeper:no-new-fix-pr: Current issue advisory state selects this label.
    • add clawsweeper:needs-maintainer-review: Current issue advisory state selects this label.
    • add clawsweeper:needs-product-decision: Current issue advisory state selects this label.

    Label justifications:

    • P2: The report describes a costly provider prompt-cache regression with a plausible source path but without a live current-main reproduction in this review.
    • impact:session-state: The affected surface is model-visible turn context and collaboration developer instruction state across Codex turns.
    • impact:auth-provider: The user-visible impact is provider/model prompt-cache behavior on DeepSeek-compatible routing.
    Evidence reviewed

    Acceptance criteria:

    • Add focused source-level coverage comparing serialized Codex model-visible prompt/request prefix for full-turn and tool-continuation paths with SOUL.md, IDENTITY.md, and USER.md present.
    • Run a live DeepSeek or OpenAI-compatible cache proof that reports cacheRead behavior before and after any fix.

    What I checked:

    Likely related people:

    • lastguru-net: Commit 3fbd243 moved stable context into turn-scoped collaboration developer instructions, which is the ownership boundary implicated by this report. (role: introduced behavior; confidence: high; commits: 3fbd2432b696; files: extensions/codex/src/app-server/attempt-context.ts, extensions/codex/src/app-server/run-attempt.ts)
    • jalehman: GitHub history and current shallow blame point to recent Codex app-server file migration/refactor work across the exact current files. (role: recent area contributor; confidence: medium; commits: 258b83c4386c, 0cdb050bac19; files: extensions/codex/src/app-server/attempt-context.ts, extensions/codex/src/app-server/thread-lifecycle.ts, extensions/codex/src/app-server/run-attempt.ts)
    • steipete: Commit 530351e changed Codex app-server prompt injection and mirrored-history behavior in the same attempt-context path. (role: adjacent owner; confidence: medium; commits: 530351e394a1; files: extensions/codex/src/app-server/attempt-context.ts)
    • vincentkoc: Recent commits touched Codex app-server prompt bounds, delivery hints, and lifecycle behavior adjacent to the reported prompt-prefix surface. (role: recent area contributor; confidence: medium; commits: b78718f42a1c, 77012f980785; files: extensions/codex/src/app-server/run-attempt.ts, extensions/codex/src/app-server/thread-lifecycle.ts)
    How this review workflow works
    • 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.
  2. added
    P2Normal backlog priority with limited blast radius.
    impact:session-stateSession, memory, transcript, context, or agent state can drift or corrupt.
    impact:auth-providerAuth, provider routing, model choice, or SecretRef resolution may break.
    issue-rating: 🐚 platinum hermitGood issue quality with a plausible reproduction path needing some confirmation.
    clawsweeper:needs-live-reproClawSweeper needs live local, crabbox, or manual validation to confirm this issue.
    clawsweeper:no-new-fix-prClawSweeper does not recommend queueing a new automated fix PR for this issue.
    clawsweeper:needs-maintainer-reviewClawSweeper marked this issue as needing maintainer review before automation.
    clawsweeper:needs-product-decisionClawSweeper marked this issue as needing a product or behavior decision.
    on Jun 25, 2026
  3. openclaw-barnacle commented on Jul 10, 2026

    @openclaw-barnacle

    This issue has been automatically marked as stale due to inactivity.
    Please add updates or it will be closed.

  4. clawsweeper commented on Jul 10, 2026

    @clawsweeper
    Contributor

    ClawSweeper status: review started.

    I am starting a fresh review of this issue: [Bug]: Turn-scoped developer instructions (SOUL.md/IDENTITY.md/USER.md) create different message prefixes between full-turn and tool-continuation calls, breaking DeepSeek KV cache (20%/99% oscillation) This is item 1/1 in the current shard. Shard 16/32.

    This placeholder means the worker is alive and reading the current context. I will edit this same comment with the actual review when the claws are done clicking.

    Crustacean status: shell secured, claws on keyboard, evidence pebbles being sorted.

  5. openclaw-barnacle commented on Jul 18, 2026

    @openclaw-barnacle

    Closing due to inactivity.
    If this is still an issue, please retry on the latest OpenClaw release and share updated details.
    If you are absolutely sure it still happens on the latest release, open a new issue with fresh steps to reproduce.

  6. locked as resolved and limited conversation to collaborators on Sep 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Normal backlog priority with limited blast radius.clawsweeper:needs-live-reproClawSweeper needs live local, crabbox, or manual validation to confirm this issue.clawsweeper:needs-maintainer-reviewClawSweeper marked this issue as needing maintainer review before automation.clawsweeper:needs-product-decisionClawSweeper marked this issue as needing a product or behavior decision.clawsweeper:no-new-fix-prClawSweeper does not recommend queueing a new automated fix PR for this issue.impact:auth-providerAuth, provider routing, model choice, or SecretRef resolution may break.impact:session-stateSession, memory, transcript, context, or agent state can drift or corrupt.issue-rating: 🐚 platinum hermitGood issue quality with a plausible reproduction path needing some confirmation.staleMarked as stale due to inactivity

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions