Files
magpie/internal/gateway/reasoning_uncounted_test.go
T
yetone 9551fadcb4 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 base d0a61b856, then again after rebasing onto
origin/main f1d0c0bfd (gateway and usage packages, gofmt, vet). Pushed on 5174c0970,
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.
2026-10-31 17:46:51 +08:00

99 lines
4.4 KiB
Go

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)
}
})
}
}