gateway: reasoning streamed with no count in its usage is marked unknown, not read as none (#4545)
A reply whose stream carried reasoning (reasoning_content, Anthropic thinking deltas) while its usage counted no reasoning tokens was recorded Reasoning 0, ReasoningHidden false: the same record as a reply that never reasoned, and a tool-only one was timed with its reasoning counted as answer. hidesReasoning now takes the usage's reasoning count and marks such a reply ReasoningHidden, the record's existing "the stream doesn't tell how much it reasoned". Reasoning stays the vendor's 0; nothing is estimated, so no new field or Flags bit (rowReasoningHidden 512 is the one it already uses). Who does this, from real bytes and docs: Anthropic's Messages usage has no thinking count at all (output_tokens includes it), so every visible Anthropic-protocol thinking reply was this case. The fixture testdata/reasoning-uncounted-deepseek-anthropic.sse is DeepSeek's Anthropic endpoint as it came on 2026-10-31 (deepseek-v4-pro, thinking on): 33 thinking deltas, "391", usage output_tokens 35 and nothing else. The owner's usage.jsonl has 12 kiro claude-haiku-4.5 rows with paced first_reasoning_ms and reasoning 0, the same case through a plugin. DeepSeek's Chat endpoint does count (completion_tokens_details), and those rows are unchanged. No captured Chat vendor omits the count; the Chat subtests are built from the shape, not a capture. Siblings: Responses, Gemini and Code Assist were already marked hidden whenever reasoning streamed (summaries). The Codex backend's two calls pass its count too (no change for Responses; its call record now reads the count after the sniffed usage is added). The Claude subscription bridge counts thinking from the CLI and is unchanged. What changes for a reader: Decode already leaves a hidden reply with no text untimed, so a thinking + tool-call reply with no count tells no speed now; one with text is timed as before (whole output from first content). The GUI's decodeOf/ledDecode read the same flag; no GUI code changed. Run on mote at based0a61b856, then again after rebasing onto origin/mainf1d0c0bfd(gateway and usage packages, gofmt, vet). Pushed on5174c0970, which changes only GUI files after that run: - go test -tags nogui -timeout 45m -count=1 ./internal/gateway/... ./internal/usage/...: ok gateway 612s, ok usage 41s; at the rebased tree ok gateway 593s, ok usage 42s - TestStreamedReasoningWithoutCount with the counted check taken out of hidesReasoning by hand: red in 4 of 6 subtests (anthropic, chat from anthropic, chat tool uncounted, anthropic from chat tool uncounted); green restored. "responses from anthropic" was already hidden on the old code (the translated Responses stream carries encrypted_content). - gofmt -l internal/gateway internal/usage: clean; go vet for darwin, GOOS=linux and GOOS=windows on both packages: ok. - node --test reasoning-speed.test.cjs usage-speed-every-row.test.cjs (Chromium and WebKit, five languages) on the Linux VM (wsl-run): 16 pass, 0 fail. On mote the same run had 8 TimeoutErrors at load ~25, beside four other sessions' whole GUI suites running 18 to 30 hours; no GUI code changes here. Not tried: a real Claude API key (Anthropic's own endpoint) and Zhipu, vLLM or Ollama Chat streams; no full go test ./...; no Windows or Linux run of the tests.
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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"}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user