diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go index 3f346ad5c..db6459990 100644 --- a/internal/gateway/anthropic.go +++ b/internal/gateway/anthropic.go @@ -119,8 +119,19 @@ func parseAnthropic(body []byte) (*Request, error) { } func parseAnthropicRequest(body []byte, clientMarks bool) (*Request, error) { + return readAnthropic(body, clientMarks, false) +} + +// readAnthropic is parseAnthropicRequest; for facts (readFacts) it leaves +// out what they never read, as readChat does: the assistant's blocks, the +// tools' outputs, and the copies of raw values a parse kept would need. +func readAnthropic(body []byte, clientMarks, facts bool) (*Request, error) { + decode := decodeJSON + if facts { + decode = decodeJSONView + } var a aRequest - if err := decodeJSON(body, &a); err != nil { + if err := decode(body, &a); err != nil { return nil, fmt.Errorf("invalid request: %v", err) } r := &Request{Model: a.Model, System: stringOrText(a.System), MaxTokens: a.MaxTokens, @@ -144,6 +155,10 @@ func parseAnthropicRequest(body []byte, clientMarks bool) (*Request, error) { } for mi, m := range a.Messages { msg := Message{Role: m.Role} + if facts && m.Role == "assistant" { + r.Messages = append(r.Messages, msg) + continue + } var s string if decodeJSON(m.Content, &s) == nil { if s != "" { @@ -151,7 +166,7 @@ func parseAnthropicRequest(body []byte, clientMarks bool) (*Request, error) { } } else { var blocks []aBlock - if err := decodeJSON(m.Content, &blocks); err != nil { + if err := decode(m.Content, &blocks); err != nil { return nil, fmt.Errorf("invalid message content: %v", err) } var raws []json.RawMessage // each block as the client sent it @@ -167,6 +182,10 @@ func parseAnthropicRequest(body []byte, clientMarks bool) (*Request, error) { case "tool_use": msg.Parts = append(msg.Parts, Part{Kind: ToolCall, ID: anthropicInID(b.ID), Name: b.Name, Args: b.Input}) 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)}) case "thinking": diff --git a/internal/gateway/chat.go b/internal/gateway/chat.go index 2f0bf60c9..6c8ca9a15 100644 --- a/internal/gateway/chat.go +++ b/internal/gateway/chat.go @@ -73,11 +73,22 @@ type cRequest struct { AccessPrograms json.RawMessage `json:"access_programs,omitempty"` } -func parseChat(body []byte) (*Request, error) { +func parseChat(body []byte) (*Request, error) { return readChat(body, false) } + +// readChat is parseChat; for facts (readFacts) it leaves out what they +// never read, as readResponses does: the assistant's words and calls, the +// tools' outputs, and the copies of raw values a parse kept would need. A +// plugin's request is read for its work folder on every try (tellWorkPlace), +// and a long conversation's history was most of what that allocated (#3472). +func readChat(body []byte, facts bool) (*Request, error) { + decode := decodeJSON + if facts { + decode = decodeJSONView + } body = liftMessageTools(body) // a request handle didn't see (#2322) body = shapeChatTools(body) // and its tools in another API's shape (#2622) var c cRequest - if err := decodeJSON(body, &c); err != nil { + if err := decode(body, &c); err != nil { return nil, fmt.Errorf("invalid request: %v", err) } r := &Request{Model: c.Model, MaxTokens: c.MaxCompletionTokens, Temp: c.Temperature, TopP: c.TopP, @@ -104,6 +115,10 @@ func parseChat(body []byte) (*Request, error) { case "user": r.Messages = append(r.Messages, Message{Role: "user", Parts: chatParts(m.Content)}) case "assistant": + if facts { + r.Messages = append(r.Messages, Message{Role: "assistant"}) + continue + } msg := Message{Role: "assistant"} // an earlier turn's thinking comes back in any of // messageReasoning's spellings, and every upstream that @@ -122,6 +137,10 @@ func parseChat(body []byte) (*Request, error) { } r.Messages = append(r.Messages, msg) case "tool": + if facts { + r.Messages = append(r.Messages, Message{Role: "user", Parts: []Part{{Kind: ToolResult, CallID: m.ToolCallID}}}) + continue + } out, images := toolOutput(m.Content) r.Messages = append(r.Messages, Message{Role: "user", Parts: []Part{{Kind: ToolResult, CallID: m.ToolCallID, Text: out, Images: images}}}) } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index b33b34f51..6362e4f69 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -6319,19 +6319,20 @@ func parse(proto provider.Protocol, body []byte) (*Request, error) { return parseIn(proto, body, false) } -// parseIn is parse, for facts only as readResponses says. +// parseIn is parse, for facts only as readResponses, readChat and +// readAnthropic say. func parseIn(proto provider.Protocol, body []byte, facts bool) (*Request, error) { var req *Request var err error switch proto { case provider.Chat: - req, err = parseChat(body) + req, err = readChat(body, facts) case provider.Responses: req, err = readResponses(body, facts) case provider.Gemini: req, err = parseGemini(body) default: - req, err = parseAnthropic(body) + req, err = readAnthropic(body, false, facts) } if err != nil { return nil, err diff --git a/internal/gateway/parse_memo_test.go b/internal/gateway/parse_memo_test.go index 1c6be0b7b..b0deda26f 100644 --- a/internal/gateway/parse_memo_test.go +++ b/internal/gateway/parse_memo_test.go @@ -7,7 +7,9 @@ import ( "net/url" "os" "path/filepath" + "runtime" "strings" + "sync/atomic" "testing" "time" "unsafe" @@ -84,8 +86,16 @@ func TestReadersOfAHeldBodyParseItOnce(t *testing.T) { // a body not held, of the same bytes, is parsed afresh: nothing says // its memory isn't written over clone := bytes.Clone(body) - if fresh := allocated(func() { factsOf(provider.Anthropic, clone) }); fresh < whole/2 { - t.Fatalf("a body not held read %d bytes, a parse %d: it got a held body's facts", fresh, whole) + var fresh atomic.Bool + seen := func(b []byte) { + if unsafe.SliceData(b) == unsafe.SliceData(clone) { + fresh.Store(true) + } + } + factsParsed.Store(&seen) + defer factsParsed.Store(nil) + if factsOf(provider.Anthropic, clone); !fresh.Load() { + t.Fatal("a body not held wasn't read: it got a held body's facts") } } @@ -152,14 +162,88 @@ func TestResponsesFactsAsTheWholeParse(t *testing.T) { } bodies[name] = b } + factsAsTheWholeParse(t, provider.Responses, bodies) +} + +// factsAsTheWholeParse fails where readFacts of a body, in proto, isn't +// what the whole parse of it gives. +func factsAsTheWholeParse(t *testing.T, proto provider.Protocol, bodies map[string][]byte) { + t.Helper() for name, body := range bodies { var want bodyFacts - if req, err := parse(provider.Responses, body); err == nil { + if req, err := parse(proto, body); err == nil { want.turn, want.within = turnIn(req) want.dir, want.git = workPlace(req) } - if got := readFacts(provider.Responses, body); got != want { + if got := readFacts(proto, body); got != want { t.Errorf("%s: facts %+v, the whole parse's %+v", name, got, want) } } } + +// Chat and Messages are read for facts as Responses is (#3472): what the +// assistant said, and the tools' outputs, never decide them. +func TestChatAndMessagesFactsAsTheWholeParse(t *testing.T) { + files := func(names ...string) map[string][]byte { + bodies := map[string][]byte{} + for _, name := range names { + b, err := os.ReadFile(filepath.Join("testdata", name)) + if err != nil { + t.Fatal(err) + } + bodies[name] = b + } + return bodies + } + chat := files("workdir/pi-1.1.0.json", "upstream_bodies/chat.json", "upstream_bodies/chat-group.json", + "upstream_bodies/anthropic-to-chat.json", "upstream_bodies/responses-to-chat.json") + chat["large"] = largeConversation(provider.Chat, "m", 20_000) + chat["said by the model and a tool"] = []byte(`{"model":"m","messages":[{"role":"user","content":"fix it"},` + + `{"role":"assistant","content":"/said/by/model","tool_calls":[{"id":"c1","type":"function","function":{"name":"sh","arguments":"{}"}}]},` + + `{"role":"tool","tool_call_id":"c1","content":"Current working directory: /not/this"},{"role":"user","content":[{"type":"text","text":"/work/b now"}]}]}`) + chat["answered, then a tool"] = []byte(`{"model":"m","messages":[{"role":"system","content":"Current working directory: /w/s"},{"role":"user","content":"go"},` + + `{"role":"assistant","content":null,"tool_calls":[{"id":"c1","type":"function","function":{"name":"sh","arguments":"{}"}}]},{"role":"tool","tool_call_id":"c1","content":"ok"}]}`) + chat["answered, then nothing said"] = []byte(`{"model":"m","messages":[{"role":"user","content":"go"},{"role":"assistant","content":"done"},{"role":"user","content":[]}]}`) + factsAsTheWholeParse(t, provider.Chat, chat) + + messages := files("workdir/claude-code-2.1.296.json", "context/claude-code.json", "upstream_bodies/anthropic.json", + "upstream_bodies/anthropic-group.json", "upstream_bodies/anthropic-image.json", "upstream_bodies/anthropic-thinking.json", + "upstream_bodies/chat-to-anthropic.json", "upstream_bodies/responses-to-anthropic.json") + messages["large"] = largeConversation(provider.Anthropic, "claude-opus-5-5", 20_000) + messages["said by the model and a tool"] = []byte(`{"model":"m","max_tokens":1,"messages":[{"role":"user","content":"fix it"},` + + `{"role":"assistant","content":[{"type":"thinking","thinking":"/thought","signature":"s"},{"type":"text","text":"/said/by/model"},{"type":"tool_use","id":"t1","name":"sh","input":{}}]},` + + `{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"Current working directory: /not/this"}]},{"role":"user","content":[{"type":"text","text":"/work/b"}]}]}`) + messages["a tool's result alone"] = []byte(`{"model":"m","max_tokens":1,"system":"Current working directory: /w/s","messages":[{"role":"user","content":"go"},` + + `{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"sh","input":{}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":[{"type":"text","text":"ok"}]}]}]}`) + factsAsTheWholeParse(t, provider.Anthropic, messages) +} + +// The facts a long Chat or Messages conversation is read for leave its +// history alone: they allocate a small part of what the whole parse does. +// Each is the least of three runs, as other tests' goroutines allocate +// meanwhile and only ever add to it. +func TestChatAndMessagesFactsLeaveTheHistory(t *testing.T) { + allocated := func(f func()) uint64 { + least := uint64(0) + for i := range 3 { + var ms runtime.MemStats + runtime.ReadMemStats(&ms) + before := ms.TotalAlloc + f() + runtime.ReadMemStats(&ms) + if n := ms.TotalAlloc - before; i == 0 || n < least { + least = n + } + } + return least + } + for _, proto := range []provider.Protocol{provider.Chat, provider.Anthropic} { + body := largeConversation(proto, "m", 200_000) + facts := allocated(func() { readFacts(proto, body) }) + parsed := allocated(func() { _, _ = parse(proto, body) }) + t.Logf("%s: %d-byte body, facts allocated %d bytes, the whole parse %d", proto, len(body), facts, parsed) + if facts*3 > parsed { + t.Errorf("%s: facts allocated %d bytes, a third or more of the whole parse's %d", proto, facts, parsed) + } + } +}