diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index a3b57c0f5..84315f154 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -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. | diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go index a90dbd31d..9cb96fd79 100644 --- a/internal/gateway/anthropic.go +++ b/internal/gateway/anthropic.go @@ -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) { diff --git a/internal/gateway/claude_cache.go b/internal/gateway/claude_cache.go index 12fb4ecec..08581d93e 100644 --- a/internal/gateway/claude_cache.go +++ b/internal/gateway/claude_cache.go @@ -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) { diff --git a/internal/gateway/claude_client_cache_boundary_test.go b/internal/gateway/claude_client_cache_boundary_test.go new file mode 100644 index 000000000..53a4eb738 --- /dev/null +++ b/internal/gateway/claude_client_cache_boundary_test.go @@ -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("\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("\n", false), + block("Return N 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 N.\n", true)}, + "messages": []map[string]any{ + {"role": "user", "content": []map[string]any{block("project rules", 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") + } +} diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 233d43079..ca10ee26b 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -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) } diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index 906bf03e6..0e9f03cc2 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -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.