magpie icon indicating copy to clipboard operation
magpie copied to clipboard

[Bug] Claude subscription: without the X-Magpie-Cache-Marks opt-in, a fresh claude -p run, including the interactive mode's unpasted fallback, sends Anthropic 5 cache_control blocks from its second request on

Open NickWilde18 opened this issue 2 weeks ago • 3 comments

magpie version

v0.1.4634 (cb0403c). The code below is unchanged in v0.1.4638 and on main at 1d58404.

Where

Gateway only

OS

Linux x64

Agent, provider and model

Claude Code 2.1.330 → Claude subscription (bridge run as claude -p, Claude Code 2.1.330) → claude-opus-5-5

Steps to reproduce

  1. Use Claude Code as the client, without X-Magpie-Cache-Marks: client (the default), on a Claude subscription route.
  2. Have a long conversation, more than historyChunk (16) messages.
  3. A bridge run starts anew for it as claude -p. Here it happened when pace routing moved the conversation to another subscription account, and the routing record says entry: print, entryWhy: unpasted: the interactive mode was on, but it didn't take the message and the run fell back to -p. Runs that stayed in the interactive mode never failed, since it is pasted the words without magpie's mark.
  4. The run's first request succeeds. Its second request (a tool result in the same turn, or the next turn going on in the same run) fails:
API Error: 400 A maximum of 4 blocks with cache_control may be provided. Found 5.

From then on every Claude turn of that conversation fails the same way, short messages included. Other providers keep working. Compacting does not help, because the extra mark is in the run's first message, which magpie writes.

What happened, and what you expected

The 400 is Anthropic's: the failing inner request has an Anthropic req_… id. It is not magpie's own check in readClientCache.

The inner Claude Code records the cache_control paths of each request it sends (api-request lines, cacheControl). These are the paths of one bridge run. All marks are ephemeral, ttl: 1h.

inner request marks paths result
1st (fresh run) 4 system[1] (scope: global), system[2], messages[0].content[16], messages[1].content[0] 200
2nd (same run) 5 system[1] (scope: global), system[2], messages[0].content[16], messages[2].content[2], messages[3].content[0] 400

messages[0].content[16] is magpie's mark: the last whole history chunk of the first message that renderClaudePromptAt built. In the run's transcript it is block 15; Claude Code puts one <system-reminder> block before it on the wire. The other four marks are Claude Code's own. The same 4 → 5 sequence was reproduced in three separate runs. The outer client's request had 4 marks every time.

Claude Code 2.1.330 uses all four slots itself. Across 660 inner requests recorded here, 611 carried 4 marks of its own (2 on the system prompt, 2 on the last messages). The 49 with 3 were first requests of a run.

Cause. With no client marks (req.clientCache == nil), renderClaudePromptAt puts one mark on the first message: on the last whole history chunk, or on the caller's instructions block when the history is shorter than a chunk. Its comment, and docs/subsystems/claude-subscription-bridge.md ("Why turns go on in one run"), assume "Claude Code keeps three of Anthropic's four". On this path Claude Code's own caching stays on, because startRun sets DISABLE_PROMPT_CACHING=1 only for client marks, and nothing counts the total. So the run's first request has 4 marks, and every later request in the run has 5.

  • https://github.com/yetone/magpie/blob/cb0403c890767deaeb3150f68e3b09c696c82987/internal/gateway/claude_subscription.go#L5358-L5382
  • https://github.com/yetone/magpie/blob/cb0403c890767deaeb3150f68e3b09c696c82987/internal/gateway/claude_subscription.go#L5299-L5302
  • https://github.com/yetone/magpie/blob/cb0403c890767deaeb3150f68e3b09c696c82987/internal/gateway/claude_subscription.go#L1322-L1327

I couldn't check whether earlier Claude Code versions used only 3 marks: they don't write these request records. Both 2.1.327 and 2.1.330 ship the prompt-caching-scope-2026-01-05 beta. I found no Claude Code switch that turns off only the scope: global system mark.

Expected. A bridge run never sends Anthropic more than four marks, and prompt caching keeps working.

Workaround (verified)

Send the opt-in header from the client, for example ANTHROPIC_CUSTOM_HEADERS='X-Magpie-Cache-Marks: client'. The same conversation then ran as a client-marks -p run. Its inner requests carried 3 marks, all the client's, with no Claude Code marks on the system prompt. The continuation that used to fail returned 200 and read about 278K tokens from the cache.

Possible fixes

  1. (Suggested) No magpie mark on the default path. In renderClaudePromptAt, when clientCache == nil, leave both the history-chunk mark and the instructions-block mark out. Claude Code's own four marks cache the run as before. The cost: on this path, a run started anew no longer reads the history chunks an earlier run wrote. TestClaudeHistoryCachedAcrossNewRuns, TestClaudeToolLoopCachedAcrossNewRuns, TestClaudeInstructionsCachedApart and TestClaudeRunKeepsTheUsersCacheTTL assert that mark and would change. With client marks, magpie keeps adding its chunk mark when there is room (c.count < 4, with DISABLE_PROMPT_CACHING=1), so cross-run reuse stays on that path.
  2. Treat a Claude Code client's own marks as client marks by default (as if it sent X-Magpie-Cache-Marks: client) whenever they validate. A -p run then always disables Claude Code's caching and keeps magpie's chunk mark only when it fits. This keeps cross-run reuse, but changes the default for every Claude Code client, the interactive-mode accounting (#5585, #5655) included. That is a larger decision.

A regression test for either fix: render a fresh run's first message for a request with more than 16 messages and no client marks; add the four marks Claude Code 2.1.330 sends from a run's second request on; assert there are at most four.

NickWilde18 avatar Nov 21 '26 08:11 NickWilde18

Prepared a fix on fork branch eisen0419:fix/7420-claude-sub-cache-control-limit (commit 2e2a959c, based on main at f0b5804):

  • Fix: Implements option 1 in renderClaudePromptAt (internal/gateway/claude_subscription.go): when req.clientCache == nil, leave both the instructions block and the history chunks unmarked (and drop the unused Request.runMark helper), since startRun keeps Claude Code's own prompt caching on and Claude Code 2.1.330 uses all four cache_control slots from a run's second request on. Stable block/historyChunk boundaries and the clientCache != nil history-chunk mark (where -p sets DISABLE_PROMPT_CACHING=1) stay intact. Updated docs/subsystems/claude-subscription-bridge.md and prompt-cache tests.
  • Verified:
    • Red before fix: TestClaudePrintDefaultPathStaysWithinFourCacheMarks failed on long history, short instructions, and long tool loop (1 bridge mark + Claude Code's 4 marks = 5 > 4).
    • Green after fix on 2e2a959c: go test -race -count=1 ./internal/gateway -run 'TestClaude(ClientCache|Instructions|RunKeeps|AskedCache|HistoryCached|ToolLoopCached|PrintDefault|Append|Replay)|TestAskedCacheTTL', gofmt -l, and GOOS=darwin / GOOS=linux -tags nogui / GOOS=windows go vet ./....

Note: only local mock-script Claude bridge runs were executed; not tested against live Anthropic API.

eisen0419 avatar Nov 21 '26 13:11 eisen0419

Related: #7456. The -p run in this report wasn't picked by the user. It came from the interactive mode's silent unpasted fallback: the fresh run's first message (about 500 KB, the whole conversation) wasn't taken by the interactive mode (#6126), so the bridge redid the turn as claude -p with no warning. The two bugs together turned a long conversation into "every Claude turn fails": first the silent move to -p, then the fifth cache mark on that run.

NickWilde18 avatar Nov 21 '26 19:11 NickWilde18

An addition on why this is intermittent, from Claude Code 2.1.334 (magpie v0.1.4663 base).

Claude Code's own mark count depends on whether its request is on a server-kept message thread (message-threads-2026-08-12). Its api-request records carry a thread field next to cacheControl:

inner request thread.type Claude Code's own marks with magpie's first-message mark
a run's requests while threaded create / continue 3: system[1], system[2], newest message 4, accepted
the same run once the thread is dropped none 4: system[1], system[2], previous turn's end, newest message 5, 400

In one production run, 12 requests went through with thread create/continue and 4 marks in total (messages[0].content[6] being magpie's). The request after a reply that consulted the server-side advisor went out with thread: none, Claude Code added a mark at the end of the previous assistant message (messages[25].content[5]), and Anthropic returned the 400 (req_011ChdG6cWX6a4JyZq5NGQyJ). Claude Code's retry kept the same marks.

In the 2.1.334 binary, the previous-turn mark is the fork pin in the marker placement, gated by !threaded && <feature flag>; so on 2.1.330, as reported above, it was presumably on from the second request every time, and on 2.1.334 it appears whenever a request is not threaded. I did not pin down what drops the thread here (an advisor reply, or the 5m48s the advisor took); the fix below does not depend on it.

Reproduction with no advisor involved: a gateway with claudePrintMode: true, Claude subscription, claude-haiku-5-5, a system prompt plus 40 history messages, then one more turn in the same conversation. Unchanged code: the first turn has 4 marks including messages[0].content[3]; the second turn (thread: none) fails with Found 5. With option 1 from this issue (no magpie mark on the first message when req.clientCache == nil, both the instructions mark and the history-chunk mark removed): 3 marks on the first turn, 4 on the second (system[1], system[2], messages[2].content[0], messages[4].content[0]), both 200.

SipengXie2024 avatar Dec 03 '26 03:12 SipengXie2024