Skip to content

Anthropic cache prefixes are rewritten during compaction and image overflow in long Codex turns #7307

Open

Description

@S0RYUASUKA

Client or integration

Codex App

Area

Provider adapter

Summary

Long Codex tasks routed through the Anthropic Messages adapter can repeatedly rewrite a large prompt cache even when most historical input is unchanged:

  • Routed compaction removes the tool catalog before requesting a summary. That changes the cached prefix independently of the later, necessary replacement of history with a summary.
  • Image normalization can demote historical images under aggregate pressure; the 413 recovery path rebuilds with tighter image tiers. Both change already-sent image bytes.
  • A separate, expected source of rewrites is five-minute TTL expiry while a main or child turn is still running tools. There is currently no opt-in running-turn renewal. This is not evidence of a prefix-rewrite bug by itself.

Expected: retain unchanged historical image encodings and the Anthropic system/tool prefix, prevent tools from executing during summaries, and compact old complete history units only when the actual request limit requires it. Optional renewal should protect verified running main/child turns and stop on completion or unknown state, without modifying Codex or its transcript.

Reproduction

  1. Route Codex Responses requests to Anthropic with short cache retention. Include client tools and a growing image history.
  2. Trigger routed compaction. Compare the ordinary request's tool catalog with the summary request: the current createResponsesEffects removes context.tools.
  3. Append enough valid images to exceed the aggregate image budget, or return an upstream 413. Compare historical image payloads before/after normalization or the biased retry.
  4. Separately, leave a turn running a long tool for more than five minutes. Its next natural request may legitimately miss expired cache. Do not conflate this with steps 2–3.

An offline regression against the current dev implementation reproduces step 2: the expected unchanged tool catalog becomes undefined. Public regression fixtures use generated PNGs, synthetic large rollout records, fake clocks and fake upstreams. No paid provider call is needed for these wire/lifecycle checks.

Version

Observed on installed 2.86.0. The compaction-prefix regression was also reproduced against dev at 8640c2f30edbd2fbb6947ed5c25e2793f5ae72a6 (2.89.0).

Operating system

Windows 11, build 26200

Provider and model

Anthropic Messages adapter / claude-opus-5-5

Logs or error output

Sanitized offline result from the unchanged dev compaction implementation:

compaction preserves client tool and system cache prefixes without changing tool choice
Expected: [ { name: "read", ... } ]
Received: undefined
0 pass, 1 fail

Low hit rates alone do not establish the cause. Some historical low-hit requests remain unattributed and are not claimed as fixed by this report.

Screenshots and supporting files

Related prior work: #4532 and closed, unmerged #4549 address stable image encoding. This report additionally covers compaction-prefix preservation, continued image-task recovery at real limits, and optional running-turn renewal. Private conversations, raw logs and actual user images are intentionally not attached.

Redacted configuration

{
  "cacheRetention": "short",
  "providers": {
    "anthropic": {
      "adapter": "anthropic",
      "baseUrl": "https://api.anthropic.com",
      "authMode": "key",
      "defaultModel": "claude-opus-5-5"
    }
  }
}

Authentication material is omitted. OAuth and custom provider names also need isolated ownership; they must not borrow a parent's thread as a child's own identity.

Checks

  • I searched existing issues and documentation.
  • I removed secrets, tokens, account details, request credentials, and personal data.

Activity

  1. added
    bug
    provider
    on Oct 18, 2026
  2. Ingwannu commented on Oct 18, 2026

    @Ingwannu
    Owner

    Tracking the proposed implementation in Draft #7308. At dev 8640c2f30edb, the prefix-rewrite paths and the ordinary short-cache expiry need separate acceptance criteria: preserving an unchanged prefix must not depend on enabling renewal. Please keep regression receipts for tool/system preservation and historical image-byte stability separate from the optional running-turn renewal receipts (ended/unknown/expired turns produce no renewal). The draft PR is not a shipped fix; this issue stays open while its runtime-ownership, image recovery and validation gates are reviewed.

  3. OctopusEngineering commented on Oct 24, 2026

    @OctopusEngineering

    Field data from a shared Mac mini running Codex Desktop through opencodex 2.84.0 (Anthropic Messages adapter, claude-opus-5-5, default short cache retention). Aggregate numbers only; no transcripts or images attached.

    Over 30 days we looked at ~59k Anthropic requests. About 40% of relative input cost (uncached 1, cache read 0.1, cache write 1.25) came from requests that re-wrote most of the conversation into the cache. Classifying those full rewrites:

    Cause Share
    Gap of more than 5 minutes since the previous request (TTL expiry) 57% (about half human idle time, half long tool or subagent waits inside a running turn)
    Earlier prefix changed 22%
    Right after compaction 17%
    First request of a new thread or subagent 4%

    Image history correlates strongly with the prefix-change bucket. The large-rewrite rate per request was 3.8% when the conversation held 20 or fewer images. It rose to 20–38% once it held more than 100 images. That matches the age-tier demotion and textification described above. Page-by-page visual QA sessions (hundreds of screenshots) were the worst case.

    We also simulated cacheRetention: "long" on the same traffic: about -1% net, because the higher write price cancels most of the avoided TTL rewrites. So for us the image-byte stability and compaction-prefix parts of this issue matter more than renewal. For reference, we have since lowered providers.anthropic.modelAutoCompactTokenLimits to 400000 locally, so threads stop growing toward 900k between compactions.

    Happy to rerun the measurement against a build with #7308 if that helps validate the image-stability gate.

  4. lidge-jun commented on Oct 26, 2026

    @lidge-jun
    Owner

    Release triage for v2.93.0: the narrow prefix-preservation fix is merged into dev via #7749 (squash 162beb3d1509291e52f808bd4f11e389bf17c06f), carried from #7308 with credit to @S0RYUASUKA.

    What changed: when Codex triggers routed compaction on the Anthropic Messages adapter, the summary request now keeps the client tool catalog, system prompt and tool options byte-identical to the preceding ordinary request, so the cached tools/system prefix survives. Hosted server tools, or a mandatory tool choice, make the adapter send tool_choice: none; the tools and system are still built from the caller's choice, so their bytes match. A summary guard drops tool events and fails a summary that attempts a tool call or is empty. Other adapters keep the old behaviour. Image normalization and the HTTP 413 one-shot tighter-image retry are unchanged, as the triage asked.

    Still open, deferred until after the release: historical image-byte stability under aggregate image pressure and 413 bias (step 3 of the report), and the optional running-turn cache renewal. Both remain with #7308, which stays open. A request that advertises a sidecar web-search tool (for example Exa) also still changes its tool prefix on compaction; this is documented. Keeping this issue open for those parts.

  5. Brams75 commented on Nov 8, 2026

    @Brams75

    Additional field data for the still-open image part (historical image-byte stability under aggregate image pressure), from Windows Codex Desktop through opencodex 2.90.0 (Anthropic Messages adapter, claude-opus-5-5, default 1h retention for first-party Anthropic). Aggregate numbers only; no transcripts or images.

    Method: 7 days, measured per agent from Codex rollout token_usage_record lines (so subagents sharing a conversation key are not mixed), 666 threads and subagents, 31,701 Anthropic requests. A "rewrite" here is a request that writes more than half of its input to the cache less than 5 minutes after the previous request of the same agent, with input >= 80% of the previous one (so TTL expiry, compaction and thread start are excluded).

    Images in history Rewrite rate
    0 0.6%
    1-6 0.5%
    7-20 0.4%
    21-40 0.6%
    41-100 3.7%
    >100 62%
    • Above 100 images: 190 screenshots appended, 161 rewrites. In 41-100 images, 61 of 71 rewrites happened with more than 20 MiB of base64 image data, i.e. the aggregate budget path.
    • In 178 of the 378 rewrites the cache read was exactly the shared tools + system prefix (~10.5k tokens). That fits the breakpoint layout in applyPromptCaching (tools, system, penultimate and last user message): once an old image is textified or demoted, no breakpoint sits before it, so the whole tail is rewritten.
    • Rewrites after the screen-control tool (screenshots) happen at 4.4% vs 0.8% after a plain shell tool.
    • Image-heavy threads (>40 images) account for about 80% of the avoidable rewrite cost in this sample (about 11% of total spend).
    • The three image files (anthropic-image-guard.ts, anthropic-image-normalize.ts, anthropic-image-codec.ts) are byte-identical between 2.90.0 and 2.99.0, so updating does not change this.

    Suggestion: hysteresis when dropping or demoting. When the count reaches 100 (or the base64 budget is exceeded), textify or demote the oldest images down to a low-water mark (for example 60 images, or about 70% of the budget) in one step, and keep that state stable until the high-water mark is hit again. The prefix is then rewritten once per ~40 screenshots instead of on every new screenshot. With the numbers above that would remove most of the >100 bucket rewrites (161 down to about 5).

    Happy to rerun the same measurement against a build with such a change.

  6. bla3416 commented on Nov 12, 2026

    @bla3416

    Field data and a likely remaining cause on v2.97.0, which includes #7749. The summary request still does not share the cached prefix with the ordinary request before it.

    Setup: opencodex 2.97.0 (npm), codex-cli 0.166.0 on Linux, Anthropic Messages adapter (OAuth). Models: claude-opus-5-5 (Codex Desktop, effort max) and claude-sonnet-5-5 (codex exec, effort low). The cache writes are 1h. There are no images. Requests are seconds apart, so TTL expiry is not involved.

    Minimal repro (codex exec). Make two generated text files of about 115 KB each, then run:

    codex exec --ephemeral --skip-git-repo-check -s read-only \
      -m anthropic/claude-sonnet-5-5 -c model_reasoning_effort=low \
      -c model_auto_compact_token_limit=35000 \
      "Run exactly these steps with the shell tool, one command per step: 1) cat part1.txt  2) cat part2.txt  3) reply with the single word OK."
    

    Usage from ocx logs (input / cache read / cache write):

    # Request Input Cache read Cache write
    1 ordinary 36,916 10,063 26,849
    2 summary 53,115 0 53,111
    3 ordinary 38,043 8,921 29,118
    4 summary 37,752 9,844 27,904
    5 ordinary 37,797 37,273 520

    I ran the same repro again within the hour. Both summary requests read exactly 9,844 tokens. They hit the prefix of the earlier summary request, never the ordinary prefix.

    Codex Desktop session (Opus 5.5, max):

    • The ordinary request had 216,347 input tokens and read 212,000 from cache.
    • The summary request right after it had 187,882 input tokens, read 0, and wrote 187,878.
    • The second compaction, 23 minutes later, had 161,708 input tokens and read 13,574.
    • Each summary input was smaller than the ordinary request before it (by about 28K tokens the first time).

    What Codex sends. I captured the Codex → opencodex bodies with a local pass-through logger. The summary request matches the ordinary request in tools (same hash), instructions, prompt_cache_key, reasoning, include, parallel_tool_calls and the leading input items. The history is unchanged, and the tail is {"type":"compaction_trigger"}. So the divergence comes from the opencodex side.

    Likely cause. Codex's ordinary tool list includes {"type":"web_search"}, next to exec, wait, request_user_input, request_user_input_async and clock. In src/server/responses/response-effects.ts, the routed-compaction branch runs delete parsed._webSearch unconditionally, before the preserveCompactionPrefix check. Without _webSearch, planWebSearch() does not activate the web-search sidecar. The summary request is then built without the web-search tool that ordinary turns carry. Tools are the first part of the Anthropic cache prefix, so the whole prefix misses. This would also explain why later summary requests hit only each other's ~10K prefix. I have not inspected the upstream request bytes directly, so please treat this as the leading hypothesis.

    Impact. In one Desktop session (42 minutes, 135 requests), the two compactions and the two requests right after them were about 23% of the session's relative cost (cache read 0.1, 1h write 2.0, output 5.0). If the summary requests had reused the ordinary prefix, about 17% of the session's cost would have been saved.

    Suggestion. When preserveCompactionPrefix is true, keep the web-search tool definition in the summary request and skip only the sidecar execution. The summary guard already rejects tool calls.

  7. lidge-jun commented on Nov 19, 2026

    @lidge-jun
    Owner

    Status from the L5 maintainer lane: the owner-accepted image-413 recovery from #7308 landed in #8927 (e4ea3c6433). It is off by default and enabled per provider. It allows one tool-disabled summary and one smaller resend, pinned to the credential and endpoint that refused the request, with separate spend accounting for each send. The prefix-preservation half landed earlier in #7749.

    This issue stays open for the remaining evidence. Two reports are still unexplained: the summary request on v2.97.0 does not share the cached prefix with the ordinary request before it (@bla3416), and historical image bytes are unstable under aggregate image pressure (@Brams75). A fresh trace on a build that includes #8927 would help. Please include the cache read and write tokens for the turn before the 413 and for the recovery sends, so we can tell whether a separate prefix fix is still needed.

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

    bugprovider

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions