diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 5b76cbd04..2d869c73a 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -1070,7 +1070,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st } try.TTFT, try.FirstText = fromTry(ttft), fromTry(text) try.Net = nt.timing(try.Start, 0) - t.ReasoningHidden = first.hidesReasoning(provider.Responses) + t.ReasoningHidden = first.hidesReasoning(provider.Responses, uu.Reasoning) try.ReasoningHidden = t.ReasoningHidden t.Done, t.Status, t.Error, t.Millis, t.Tokens = true, status, msg, ms, tokens if t.TitleLink != nil && isTitleKind(kind) && status < 400 && msg == "" && !titleReply.truncated { @@ -1470,8 +1470,8 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st call.Fallback = strings.TrimSuffix(call.Fallback, "; ") } call.TTFT, call.FirstText = first.ms() - call.ReasoningHidden = first.hidesReasoning(provider.Responses) uu.add(sniff.usage()) + call.ReasoningHidden = first.hidesReasoning(provider.Responses, uu.Reasoning) uu.Tier = servedTierAt(provider.HostOf(base), uu.Tier) call.Flow = first.flowFor(uu.Reasoning) call.Usage, served = uu, uu.Served diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index c52470d32..351e1e709 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3212,7 +3212,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro try.Swapped, try.Routed = swapped(asName, call.Usage.Served) && !usage.ListedAs(c.p.ID, c.model, call.Usage.Served), usage.GroupRouted(asName, call.Usage.Served) try.TTFT, try.FirstText = hw.first.ms() try.FirstReasoning = hw.first.reasoningMs(call.To) - try.ReasoningHidden = hw.first.hidesReasoning(call.To) + try.ReasoningHidden = hw.first.hidesReasoning(call.To, call.Usage.billed().Reasoning) call.ReasoningHidden = try.ReasoningHidden try.Flow = hw.first.flowFor(call.Usage.Reasoning) call.Flow = try.Flow diff --git a/internal/gateway/reasoning_speed_test.go b/internal/gateway/reasoning_speed_test.go index dc2cafcd1..f1eafec08 100644 --- a/internal/gateway/reasoning_speed_test.go +++ b/internal/gateway/reasoning_speed_test.go @@ -277,7 +277,7 @@ func TestEncryptedReasoningWithoutTokenDetails(t *testing.T) { func TestGeminiSummaryWithoutThoughtCount(t *testing.T) { f := firstToken{start: time.Now().Add(-time.Second)} f.see([]byte(`data: {"candidates":[{"content":{"parts":[{"text":"visible summary","thought":true}]}}]}` + "\n\n")) - if !f.hidesReasoning(provider.Gemini) || f.reasoningMs(provider.Gemini) != 0 { + if !f.hidesReasoning(provider.Gemini, 0) || !f.hidesReasoning(provider.Gemini, 7) || f.reasoningMs(provider.Gemini) != 0 { t.Fatal("Gemini summary timed without its hidden thought count") } } diff --git a/internal/gateway/reasoning_uncounted_test.go b/internal/gateway/reasoning_uncounted_test.go new file mode 100644 index 000000000..2c11aec8d --- /dev/null +++ b/internal/gateway/reasoning_uncounted_test.go @@ -0,0 +1,98 @@ +package gateway + +import ( + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// #4545: a reply that streamed its reasoning while its usage counted none +// of it has Reasoning 0 for "unknown", and the record says so +// (ReasoningHidden), so it isn't read as a reply that didn't reason. The +// Anthropic stream is DeepSeek's Anthropic endpoint's, as it came on +// 2026-10-31 (deepseek-v4-pro, thinking on): 33 thinking deltas, then +// "391", and a usage of output_tokens 35 with no thinking count, as +// Anthropic's own usage never has one. +func TestStreamedReasoningWithoutCount(t *testing.T) { + b, err := os.ReadFile("testdata/reasoning-uncounted-deepseek-anthropic.sse") + if err != nil { + t.Fatal(err) + } + var real []string + for _, ev := range strings.Split(strings.TrimSpace(string(b)), "\n\n") { + if strings.Contains(ev, `"content_block_delta"`) { + ev = "~" + ev // paced, as the deltas came + } + real = append(real, ev) + } + thought := func(s string) string { + return `~data: {"choices":[{"delta":{"reasoning_content":"` + s + `"}}]}` + } + tool := `~data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"check","arguments":"{}"}}]}}]}` + chatTool := func(details string) []string { + return []string{thought("We need"), thought(" to check"), thought(" it."), tool, + `data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":5,"completion_tokens":40` + details + `}}`, + `data: [DONE]`} + } + chatBody := `{"model":"fake/m1","stream":true,"messages":[{"role":"user","content":"hi"}]}` + for _, c := range []struct { + name string + proto provider.Protocol + events []string + path, body string + out, counted int + hidden bool + timed bool // its speed told (Decode) + }{ + {"anthropic", provider.Anthropic, real, "/v1/messages", `{"model":"fake/m1","stream":true,"max_tokens":400,"messages":[{"role":"user","content":"hi"}]}`, 35, 0, true, true}, + {"chat from anthropic", provider.Anthropic, real, "/v1/chat/completions", chatBody, 35, 0, true, true}, + {"responses from anthropic", provider.Anthropic, real, "/v1/responses", `{"model":"fake/m1","stream":true,"input":"hi"}`, 35, 0, true, true}, + // a Chat vendor's reasoning_content with no completion_tokens_details, + // a tool call its only answer: no text to time it from, and no count + // to take the reasoning out of its output, so no speed + {"chat tool, uncounted", provider.Chat, chatTool(""), "/v1/chat/completions", chatBody, 40, 0, true, false}, + {"anthropic from chat tool, uncounted", provider.Chat, chatTool(""), "/v1/messages", `{"model":"fake/m1","stream":true,"max_tokens":400,"messages":[{"role":"user","content":"hi"}]}`, 40, 0, true, false}, + // the same counted is known, and timed from its paced reasoning + {"chat tool, counted", provider.Chat, chatTool(`,"completion_tokens_details":{"reasoning_tokens":30}`), "/v1/chat/completions", chatBody, 40, 30, false, true}, + } { + t.Run(c.name, func(t *testing.T) { + fresh(t) + up := httptest.NewServer(&paced{events: c.events, gap: 80 * time.Millisecond}) + t.Cleanup(up.Close) + p := provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}} + if c.proto == provider.Anthropic { + p.Anthropic = up.URL + } else { + p.Chat = up.URL + "/v1" + } + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + s := New() + w := httptest.NewRecorder() + s.Handler().ServeHTTP(w, httptest.NewRequest("POST", c.path, strings.NewReader(c.body))) + if w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body) + } + u := lastUsage(t) + if u.Output != c.out || u.Reasoning != c.counted || u.TTFT <= 0 { + t.Fatalf("usage out %d reasoning %d ttft %d; want %d, %d, streamed", u.Output, u.Reasoning, u.TTFT, c.out, c.counted) + } + if u.ReasoningHidden != c.hidden { + t.Fatalf("reasoning streamed with a count of %d read as hidden=%v; want %v: %+v", c.counted, u.ReasoningHidden, c.hidden, u) + } + r := lastRoute(s) + if r.ReasoningHidden != c.hidden || len(r.Tries) != 1 || r.Tries[0].ReasoningHidden != c.hidden || s.Recent()[0].ReasoningHidden != c.hidden { + t.Fatalf("trace disagrees with the record (hidden %v): %+v", c.hidden, r) + } + if n, ms := u.Decode(); (n > 0 && ms >= usage.MinDecodeMs) != c.timed { + t.Fatalf("speed %d/%d ms; want told=%v: %+v", n, ms, c.timed, u) + } + }) + } +} diff --git a/internal/gateway/testdata/reasoning-uncounted-deepseek-anthropic.sse b/internal/gateway/testdata/reasoning-uncounted-deepseek-anthropic.sse new file mode 100644 index 000000000..34434b94d --- /dev/null +++ b/internal/gateway/testdata/reasoning-uncounted-deepseek-anthropic.sse @@ -0,0 +1,129 @@ +event: message_start +data: {"type":"message_start","message":{"id":"348d400a-36c1-46db-b7c3-896ebd274611","type":"message","role":"assistant","model":"deepseek-v4-pro","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":96,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":0,"service_tier":"standard"}}} + +event: content_block_start +data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}} + +event: ping +data: {"type":"ping"} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"We"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" need"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" answer"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" number"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" only"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" "}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"17"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"*"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"23"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"."}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" Compute"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":":"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" "}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"17"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"*"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"20"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"="}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"340"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":","}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" "}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"17"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"*"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"3"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"="}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"51"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" total"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" "}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"391"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"."}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" Answer"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" \""}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"391"}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"\"."}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"348d400a-36c1-46db-b7c3-896ebd274611"}} + +event: content_block_stop +data: {"type":"content_block_stop","index":0} + +event: content_block_start +data: {"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}} + +event: content_block_delta +data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"391"}} + +event: content_block_stop +data: {"type":"content_block_stop","index":1} + +event: message_delta +data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"input_tokens":96,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":35,"service_tier":"standard"}} + +event: message_stop +data: {"type":"message_stop"} + diff --git a/internal/gateway/ttft.go b/internal/gateway/ttft.go index 5f187ed83..913e6ee91 100644 --- a/internal/gateway/ttft.go +++ b/internal/gateway/ttft.go @@ -316,9 +316,15 @@ func (f *firstToken) flowFor(reasoning int) int64 { } // hidesReasoning excludes sealed thinking and Responses summaries even when -// the upstream omits a separate reasoning-token count. -func (f *firstToken) hidesReasoning(proto provider.Protocol) bool { - return f.hidden || (proto == provider.Responses || proto == provider.Gemini || proto == provider.CodeAssist) && f.reasoning > 0 +// the upstream omits a separate reasoning-token count. It also marks a +// reply whose reasoning streamed while counted, its usage's reasoning +// tokens, is 0 (#4545): that count is unknown, not none. Anthropic's usage +// never splits thinking out of output_tokens (DeepSeek's Anthropic endpoint +// streamed 33 thinking deltas and said only output_tokens 35), and a Chat +// vendor may send reasoning_content with no completion_tokens_details. The +// record's Reasoning stays the vendor's 0, never an estimate. +func (f *firstToken) hidesReasoning(proto provider.Protocol, counted int) bool { + return f.hidden || f.reasoning > 0 && (counted <= 0 || proto == provider.Responses || proto == provider.Gemini || proto == provider.CodeAssist) } // reasoningMs requires a paced visible channel. Responses and Gemini summaries diff --git a/internal/usage/usage.go b/internal/usage/usage.go index b12a656aa..6464b1d7f 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -114,8 +114,13 @@ type Record struct { // native Codex call established whether a gateway row compacted. Compaction *bool `json:"compaction,omitempty"` // FirstReasoning is the start of paced visible reasoning, absent for hidden reasoning. - FirstReasoning int64 `json:"first_reasoning_ms,omitempty"` - ReasoningHidden bool `json:"reasoning_hidden,omitempty"` + FirstReasoning int64 `json:"first_reasoning_ms,omitempty"` + // ReasoningHidden: the reply reasoned and its stream doesn't tell how + // much — sealed or summarised, or streamed with no reasoning count in + // its usage (#4545: Anthropic's usage never has one), when Reasoning is + // 0 for unknown, not for none. A reply of no text then tells no speed + // (Decode). + ReasoningHidden bool `json:"reasoning_hidden,omitempty"` // Sent: ms from the request to its answering try going out to the // vendor, its body written, as TTFT is counted: magpie's own time and // the tries that failed first are before it, and TTFT-Sent is how