gateway: a classifier's own cache marks are kept, and a moved mark leaves its old block boundary in place (#3835)

Claude Desktop's auto mode classifier marks its transcript blocks with
native cache_control but sends none of magpie's private headers, so
serveSubscription took the default parse and the marks were dropped.
And even a request that opted in lost its older boundaries:
renderCachedParts ended a block only where a mark still stood, so a
mark that moved on with the conversation's growth let the block it
used to end merge into the next marked one. Anthropic's prefix check
looks back over block boundaries, not into them: the boundary gone,
each classifier turn found none of the last one's write and wrote the
whole transcript again (about 170k tokens a turn at the reporter's
site).

A part that came from one of the client's own content blocks now ends
its rendered block whether or not it still carries a mark; only the
mark's presence adds cache_control. A classifier-shaped Messages body
carrying cache_control is parsed for its marks like an opted-in
client's. Plain-string messages still merge into history chunks, so a
retained prefix reaches as far back as it did.

Changed from ggbdpq's patch: the classifier never asked for its marks
through X-Magpie-Cache-Marks, so a set the bridge can't keep (a TTL
order Anthropic refuses, more than four marks) now goes the default
way, as before, instead of being refused with a 400 that the old code
never gave. TestClaudeClientCacheClassifierBadMarksServedAsBefore
holds it. The bridge doc says so.

Run (mote, macOS):
- Red on origin/main (the reporter's offline repro, renamed beside the
  other client-cache tests): client_marks 6 -> 6 blocks with 307
  reusable bytes, as the issue reports; the classifier's marks dropped
  without the header.
- go test -tags nogui -count=1 -run 'TestClaudeClientCache|TestAudit|
  TestClaude|TestAutoMode|TestServerReview' ./internal/gateway: ok.
- Broken by hand: the fallback removed, the new bad-marks test red
  ("refused before run startup: 400 ... a ttl='1h' cache_control block
  must not come after a ttl='5m'"); restored, green.
- gofmt -l clean. go vet (darwin, GOOS=windows, GOOS=linux) ok on
  gateway and provider. Full suite at b80d1ba7b (this commit, on the
  #2937 one, rebased on ddb1701fe): go test -tags nogui -count=1
  -timeout 45m ./... , 81 packages ok, no FAIL (gateway 755s). Other
  sessions' suites ran on mote at the same time (load ~20 to 30).
- Rebased on 2f65a33aa (gateway.go and providers-accounts.md changed
  upstream, in unrelated lines): gateway, provider, plugin and library
  rerun with -count=1 -timeout 45m, all ok.
- Then rebased on a0cb8b646 (Ark web search, gateway.go): go vet and
  -run 'TestClaude|TestAutoMode|TestExtraBody|TestHeaders|TestAudit|
  TestServerReview|Ark|Search' on gateway and provider at the pushed
  head, ok.

Not tried: a real Claude subscription A/B of the classifier's cache
reads (it would spend ~170k tokens a turn on the owner's live account);
the gain rests on the offline repro's block counts.

Fixes #3835

Co-authored-by: yetone <yetoneful@gmail.com>
This commit is contained in:
ggbdpq
2026-10-30 22:48:39 +08:00
committed by yetone
co-authored by yetone
parent 84a0330f07
commit e31ccf2307
6 changed files with 257 additions and 9 deletions
@@ -107,7 +107,10 @@ cache.
A client can send `X-Magpie-Cache-Marks: client` on a `/v1/messages`
request to a Claude subscription. Without that header, the bridge behaves
as before. Chat Completions and Responses ignore the header. The mode is
as before — except Claude Code's auto mode classifier, whose own marks are
kept like an opted-in client's when they are valid, and dropped as before when
they are not (#3835). Chat Completions and Responses
ignore the header. The mode is
part of the run's identity, including rewritten conversations and tool-result
handoffs: opted-in and ordinary requests never share a run.
@@ -122,6 +125,7 @@ to the client. `claude_cache.go` validates the marks before run selection;
| Top-level `cache_control` | Sets the request-level tail through `CLAUDE_CODE_EXTRA_BODY`. |
| Last message block | Sets the same request-level tail. |
| Earlier message block, new run | Ends a block at that point in the rendered history with the same TTL. |
| Earlier message block without a mark, new run | Ends a block there too, so a mark that moved on with the conversation's growth leaves the old boundary in place for Anthropic's prefix check (#3835). |
| Earlier message block, running or saved run | Dropped and reported; the existing history cannot be edited. |
| Tool definition | Dropped and reported; Claude Code owns the tools. |
| Bridge history-chunk mark | Uses only a free slot and never a longer TTL than a preceding mark. |
+6 -6
View File
@@ -194,22 +194,22 @@ func readAnthropic(body []byte, clientMarks, facts bool) (*Request, error) {
before := len(msg.Parts)
switch b.Type {
case "text":
msg.Parts = append(msg.Parts, Part{Kind: Text, Text: b.Text})
msg.Parts = append(msg.Parts, Part{Kind: Text, Text: b.Text, block: true})
case "image":
if b.Source != nil {
msg.Parts = append(msg.Parts, Part{Kind: Image, MediaType: b.Source.MediaType, Data: b.Source.Data, URL: b.Source.URL})
msg.Parts = append(msg.Parts, Part{Kind: Image, MediaType: b.Source.MediaType, Data: b.Source.Data, URL: b.Source.URL, block: true})
}
case "tool_use":
msg.Parts = append(msg.Parts, Part{Kind: ToolCall, ID: anthropicInID(b.ID), Name: b.Name, Args: b.Input})
msg.Parts = append(msg.Parts, Part{Kind: ToolCall, ID: anthropicInID(b.ID), Name: b.Name, Args: b.Input, block: true})
case "tool_result":
if facts {
msg.Parts = append(msg.Parts, Part{Kind: ToolResult, CallID: anthropicInID(b.ToolUseID)})
break
}
out, images := toolOutput(b.Content)
msg.Parts = append(msg.Parts, Part{Kind: ToolResult, CallID: anthropicInID(b.ToolUseID), Text: out, Images: images, IsError: b.IsError, Loads: toolRefs(b.Content)})
msg.Parts = append(msg.Parts, Part{Kind: ToolResult, CallID: anthropicInID(b.ToolUseID), Text: out, Images: images, IsError: b.IsError, Loads: toolRefs(b.Content), block: true})
case "thinking":
msg.Parts = append(msg.Parts, Part{Kind: Thinking, Text: b.Thinking, Signature: b.Signature})
msg.Parts = append(msg.Parts, Part{Kind: Thinking, Text: b.Thinking, Signature: b.Signature, block: true})
case "redacted_thinking":
// Claude's reasoning its safety systems sealed: it
// goes back to Messages whole, and is nothing to
@@ -218,7 +218,7 @@ func readAnthropic(body []byte, clientMarks, facts bool) (*Request, error) {
_ = decodeJSON(m.Content, &raws)
}
if i < len(raws) {
msg.Parts = append(msg.Parts, Part{Kind: Thinking, Sealed: raws[i], SealedBy: sealAnthropic})
msg.Parts = append(msg.Parts, Part{Kind: Thinking, Sealed: raws[i], SealedBy: sealAnthropic, block: true})
}
}
if clientMarks && !(mi == len(a.Messages)-1 && i == len(blocks)-1) {
+14
View File
@@ -1,6 +1,7 @@
package gateway
import (
"bytes"
"encoding/json"
"fmt"
"hash"
@@ -30,6 +31,19 @@ func wantsClientCache(r *http.Request, from provider.Protocol) bool {
return from == provider.Anthropic && r.Header.Get("X-Magpie-Cache-Marks") == "client"
}
// classifierClientCache reports whether a Messages body is Claude Code's
// auto mode classifier carrying cache marks of its own. Desktop's
// classifier marks its blocks but knows nothing of magpie's private header
// (#3835): its marks are kept like an opted-in client's, validated as
// theirs are. The bytes are looked at before the request is parsed, and
// only a classifier-shaped body carrying a cache_control field is parsed
// for its marks.
func classifierClientCache(from provider.Protocol, body []byte) bool {
return from == provider.Anthropic &&
bytes.Contains(body, []byte("cache_control")) &&
autoModeClassifierAsk(body)
}
// selected reports the mapping as soon as run selection is known. Starting
// Claude Code or waiting for its first output must not hold keepalives.
func (c *clientCache) selected(fresh bool) {
@@ -0,0 +1,209 @@
package gateway
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// classifierBody is the shape of Claude Desktop's auto mode classifier
// (#3835, from Claude Code 2.1.308): a system prompt asking for a severity,
// a user message of project instructions, and a user message whose text
// blocks hold the transcript, the operation to classify, and the trailing
// ask. Round one marks the transcript's end; round two's transcript has
// grown, so its mark moved to the newest entry. No account is read and no
// model is asked: the body is synthetic.
func classifierBody(t *testing.T, grown bool) []byte {
t.Helper()
mark := map[string]string{"type": "ephemeral", "ttl": "1h"}
block := func(s string, marked bool) map[string]any {
b := map[string]any{"type": "text", "text": s}
if marked {
b["cache_control"] = mark
}
return b
}
content := []map[string]any{
block("<transcript>\n", false),
block(strings.Repeat("earlier transcript entry\n", 20000), !grown),
}
if grown {
// the previous operation has become history; the old block stands
// unchanged but its mark moved on to the newest entry
content = append(content, block("previous screenshot action\n", false), block("new small entry\n", true))
}
content = append(content,
block("current operation\n", true),
block("</transcript>\n", false),
block("Return <severity>N</severity> only.", false),
)
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
// Desktop sends < and > as themselves; Marshal would escape them and
// miss the shapes the gateway reads in the raw bytes
enc.SetEscapeHTML(false)
if err := enc.Encode(map[string]any{
"model": "claude-sonnet-5", "max_tokens": 64,
"system": []map[string]any{block("Classify actions with <severity>N</severity>.\n", true)},
"messages": []map[string]any{
{"role": "user", "content": []map[string]any{block("<user_claude_md>project rules</user_claude_md>", true)}},
{"role": "user", "content": content},
},
}); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
// classifierPrefixes serializes each rendered block's content (cache_control
// is metadata, no part of the content a cache prefix covers) and reports
// every block's ending prefix, and which endings a mark wrote.
func classifierPrefixes(t *testing.T, blocks []map[string]any) (ends []string, writes map[string]bool) {
t.Helper()
var prefix strings.Builder
writes = map[string]bool{}
for _, b := range blocks {
content := map[string]any{}
for k, v := range b {
if k != "cache_control" {
content[k] = v
}
}
data, err := json.Marshal(content)
if err != nil {
t.Fatal(err)
}
prefix.Write(data)
prefix.WriteByte('\n')
ends = append(ends, prefix.String())
if b["cache_control"] != nil {
writes[prefix.String()] = true
}
}
return ends, writes
}
// reusablePrefix is the longest of round two's block endings that round one
// wrote a mark at: a position Anthropic's prefix check may find within its
// lookback of block boundaries. Serialized bytes are not tokens.
func reusablePrefix(t *testing.T, first, second []map[string]any) int {
t.Helper()
_, writes := classifierPrefixes(t, first)
ends, _ := classifierPrefixes(t, second)
longest := 0
for _, p := range ends {
if writes[p] && len(p) > longest {
longest = len(p)
}
}
return longest
}
// TestClaudeClientCacheKeepsEarlierTranscriptBoundary renders two rounds of
// the classifier and asks that the prefix round one wrote at its transcript
// mark still ends a block of round two, whose marks moved on with the
// growth: Anthropic's check looks back over block boundaries, not into
// merged blocks, so a boundary merged away is a cache written for nothing
// (#3835). The default path is a control: it keeps no transcript at all.
func TestClaudeClientCacheKeepsEarlierTranscriptBoundary(t *testing.T) {
for _, client := range []bool{false, true} {
name := "default"
if client {
name = "client_marks"
}
t.Run(name, func(t *testing.T) {
var rounds [2][]map[string]any
for i, grown := range []bool{false, true} {
r, err := parseAnthropicRequest(classifierBody(t, grown), client)
if err != nil {
t.Fatal(err)
}
if !autoModeClassifier(r) || len(r.Messages) != 2 {
t.Fatal("fixture does not match the observed two-message classifier shape")
}
rounds[i], err = renderClaudePrompt(r)
if err != nil {
t.Fatal(err)
}
}
longest := reusablePrefix(t, rounds[0], rounds[1])
t.Logf("before blocks=%d, after blocks=%d, reusable serialized prefix bytes=%d", len(rounds[0]), len(rounds[1]), longest)
if !client && longest > 1000 {
t.Fatal("default reproduction unexpectedly preserves the transcript")
}
if client && longest < 400000 {
t.Fatal("client marks survived, but the earlier transcript block boundary was merged away")
}
})
}
}
// TestClaudeClientCacheClassifierWithoutHeader serves the classifier through
// the subscription path as Desktop sends it: native cache_control, no
// private header. Its marks must be kept like an opted-in client's (#3835),
// and the transcript boundary must survive the round's growth.
func TestClaudeClientCacheClassifierWithoutHeader(t *testing.T) {
s := New()
t.Cleanup(s.subscription.abortAll)
var rounds [2]*Request
for i, grown := range []bool{false, true} {
body := classifierBody(t, grown)
r := httptest.NewRequest("POST", "/v1/messages", bytes.NewReader(body))
w := httptest.NewRecorder()
s.serveSubscription(w, r, provider.Anthropic, "Claude Code", "claude-sonnet-5", "test", body, &Usage{},
func(_ context.Context, req *Request) (*subscriptionRun, <-chan Event, error) {
rounds[i] = req
return nil, nil, fmt.Errorf("stop before a run starts")
})
}
if rounds[0] == nil || rounds[1] == nil {
t.Fatal("a request never reached run startup")
}
if rounds[0].clientCache == nil || rounds[1].clientCache == nil {
t.Fatal("classifier marks dropped without the private header")
}
first, err := renderClaudePrompt(rounds[0])
if err != nil {
t.Fatal(err)
}
second, err := renderClaudePrompt(rounds[1])
if err != nil {
t.Fatal(err)
}
if longest := reusablePrefix(t, first, second); longest < 400000 {
t.Fatalf("marks kept, boundary merged away: reusable serialized prefix bytes=%d", longest)
}
}
// A classifier whose marks the bridge can't keep (a 1h mark after a 5m
// one, which Anthropic refuses) never asked for them through magpie's
// header, so it is served the default way, as before #3835, not refused.
func TestClaudeClientCacheClassifierBadMarksServedAsBefore(t *testing.T) {
body := classifierBody(t, false)
body = bytes.Replace(body, []byte(`"cache_control":{"ttl":"1h","type":"ephemeral"}`), []byte(`"cache_control":{"ttl":"5m","type":"ephemeral"}`), 1)
if !bytes.Contains(body, []byte(`"ttl":"5m"`)) {
t.Fatal("fixture: no mark turned to 5m")
}
s := New()
t.Cleanup(s.subscription.abortAll)
var got *Request
r := httptest.NewRequest("POST", "/v1/messages", bytes.NewReader(body))
w := httptest.NewRecorder()
s.serveSubscription(w, r, provider.Anthropic, "Claude Code", "claude-sonnet-5", "test", body, &Usage{},
func(_ context.Context, req *Request) (*subscriptionRun, <-chan Event, error) {
got = req
return nil, nil, fmt.Errorf("stop before a run starts")
})
if got == nil {
t.Fatalf("refused before run startup: %d %s", w.Code, w.Body)
}
if got.clientCache != nil {
t.Error("marks the bridge can't keep were kept")
}
}
+17 -2
View File
@@ -3156,10 +3156,18 @@ func renderCachedParts(blocks []map[string]any, text *strings.Builder, parts []P
case Image:
blocks = imageBlocks(blocks, text, p)
}
if cached && p.cache != "" {
// A client block ends its rendered block even without a mark of its
// own: the mark a client put on this position last round has moved
// on with the conversation's growth, and with the boundary merged
// into the next marked block Anthropic's prefix check — which looks
// back over block boundaries, not into them — finds the old write
// no more and the whole history is written again (#3835)
if cached && (p.cache != "" || p.block) {
blocks = closeBlocks(blocks, text)
text.Reset()
blocks[len(blocks)-1]["cache_control"] = cacheMark(p.cache)
if p.cache != "" {
blocks[len(blocks)-1]["cache_control"] = cacheMark(p.cache)
}
}
}
return blocks
@@ -4469,6 +4477,13 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from
var err error
if name == "Claude Code" && wantsClientCache(r, from) {
req, err = parseAnthropicRequest(body, true)
} else if name == "Claude Code" && classifierClientCache(from, body) {
// the classifier never asked for its marks through magpie's
// header: a set the bridge can't keep (a TTL order Anthropic
// would refuse) goes the default way, as before, not refused
if req, err = parseAnthropicRequest(body, true); err != nil {
req, err = parse(from, body)
}
} else {
req, err = parse(from, body)
}
+6
View File
@@ -82,6 +82,12 @@ type Part struct {
Hits []Hit
cache string // opted-in Claude bridge breakpoint TTL; empty for none
// block reports the part came from one content block of the client's
// own: a client-marks prompt ends a rendered block there even when the
// client put no mark on it, or an earlier round's marked boundary is
// merged away and its cache write is found no more (#3835)
block bool
}
// The APIs a Part's Sealed reasoning is in.