usage: time tool-only replies only with visible reasoning evidence

Revises #1463 after the hidden-reasoning inflation review. Keep answers separate, retain evidence in routes and cached ledger rows, and exclude sealed or summary-only reasoning even without a token breakdown. Sync the backend and both GUI formulas.

Checked real WorkBuddy DeepSeek, Codex and Claude bridge responses in an isolated HOME; sanitized timings and failures are in docs/verification. Chromium/WebKit speed regressions pass (20 tests, five languages). New edge regressions and loop-order check pass under race repetition. Restoring the old formula or removing the hidden guard fails TestVisibleReasoningSpeed. macOS/Linux/Windows vet/build pass. Full-suite verification is recorded in the issue at this head; inherited proxy/Bun 1.3.14 failures are retained, with clean Bun 1.4.2 rerun in progress. No installed app replacement.

Rebased onto main by yetone (#1463). Conflicts with main's Own/Retried/
Queued/Tries row fields, HandedOn and the Codex speed floors were resolved
by keeping both. The packed row's ReasoningHidden bit was 64, which main
has since given to block_price.go's swapKnown, and main's rowHandedOn took
128, filling the uint8: Flags is now uint16 and ReasoningHidden is bit 512
(rowReasoningHidden; #1874's rowOwnCost took 256), read back in row(). The docs/verification notes and
their sample JSON are left out of the tree; they stay on the contributor's
branch and the issue. Run after the rebase: go test -tags nogui ./internal/usage/
and the gateway's reasoning/speed/TTFT tests, ok.
This commit is contained in:
congee949
2026-10-13 06:43:50 +08:00
committed by yetone
parent cc93b566e2
commit 2d3b33bb78
19 changed files with 803 additions and 63 deletions
+39
View File
@@ -31,6 +31,45 @@ three.
## Constraints and failure behavior
### Streamed output speed
Usage rows and aggregates use `Record.Decode` and `DecodeOf` in
[`internal/usage/usage.go`](../../internal/usage/usage.go). Routing uses
`decodeOf` in [`routing.js`](../../internal/gui/assets/routing.js); Usage
rows use `ledDecode` in [`app.js`](../../internal/gui/assets/app.js).
When an answer follows reasoning, only answer tokens are timed from the
first answer text. Without answer text, all output tokens are timed only
when the gateway records paced visible reasoning and a usable content flow.
`firstToken.reasoningMs` in
[`ttft.go`](../../internal/gateway/ttft.go) requires reasoning at the first
content and subsequent reasoning deltas at least 100 ms later. It excludes
native Responses and Gemini, whose summaries do not measure their reported
reasoning tokens, and redacted thinking, including translated sealed blocks.
The upstream protocol is retained when the client receives a translation.
These are receive-side timing checks, not access to the vendor's generation
clock: a relay that releases a buffered reply evenly can still look paced.
Without an upstream guarantee, this is an observed output-rate estimate.
Summaries stay excluded rather than extending their visible portion's time
to an unobserved reasoning-token count.
`Record.FirstReasoning` (`first_reasoning_ms`) and the corresponding
`Call`, `Route` and `Try` field (`firstReasoning`) record this evidence with
the same origin as their duration. Historical records have no evidence and
keep their previous speed. Request-page caches and compressed snapshots
preserve the optional field. `ReasoningHidden` (`reasoning_hidden` in the
ledger, `reasoningHidden` in traces) suppresses a no-text speed even when
redacted/encrypted thinking has no reported reasoning-token count. A
Responses summary is marked this way on its own-login path too. Optional
OTel attributes carry the evidence without response text. The existing burst and held-content limits in
`DecodeOf` still apply, and hidden reasoning does not enter average speed.
`TestVisibleReasoningSpeed`, `TestReasoningSpeedEvidence`,
`TestReasoningSpeedThroughGateway`, `TestMixedRedactedReasoning`,
`TestHiddenReasoningThroughTranslation`, `TestSlowReleasedReasoningIsUntimed` and
[`reasoning-speed.test.cjs`](../../internal/gui/tests/reasoning-speed.test.cjs)
cover the calculation, cache round trip, translated streams and both pages.
### Routing purpose filter
The request heading's purpose menu in [`routing.js`](../../internal/gui/assets/routing.js)
+4 -1
View File
@@ -705,6 +705,8 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
s.trace.update(tr, func(t *Route) {
t.Tries[0].Done, t.Tries[0].Status, t.Tries[0].Millis, t.Tries[0].Error = true, status, ms, msg
t.Tries[0].TTFT, t.Tries[0].FirstText = ttft, text
t.ReasoningHidden = first.hidesReasoning(provider.Responses)
t.Tries[0].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 {
link := *t.TitleLink
@@ -917,6 +919,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
Provider: "openai", Agent: agentOf(r), Kind: kind, Status: res.StatusCode,
Millis: time.Since(start).Milliseconds(), Fallback: resetNote}
call.TTFT, call.FirstText = first.ms()
call.ReasoningHidden = first.hidesReasoning(provider.Responses)
uu.add(sniff.usage())
call.Flow = first.flowFor(uu.Reasoning)
call.Usage, served = uu, uu.Served
@@ -932,7 +935,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
rec := usage.Record{RouteID: tr.ID, Time: start, Agent: call.Agent, Provider: call.Provider, Host: provider.HostOf(base), Model: call.Model,
Requested: call.Model, Served: served,
Input: uu.Input, Output: uu.Output, CacheRead: uu.CacheRead, CacheWrite: uu.CacheWrite,
Reasoning: uu.Reasoning, Effort: effort, Millis: call.Millis, TTFT: call.TTFT, FirstText: call.FirstText, Flow: call.Flow, Status: call.Status, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind,
Reasoning: uu.Reasoning, Effort: effort, Millis: call.Millis, TTFT: call.TTFT, FirstText: call.FirstText, ReasoningHidden: call.ReasoningHidden, Flow: call.Flow, Status: call.Status, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind,
RequestID: requestID(res.Header), ResponseID: uu.ResponseID, Endpoint: r.URL.Path}
failedWith(&rec, call.Status, call.Error, errType)
appendUsage(r, rec)
+11
View File
@@ -325,6 +325,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
// try's reasoning was found stuck in a loop before it had, and it is
// let go to ask again (loopReasks)
var spoke, relooped bool
var summaryUpstream bool
reasks := 0
if h, ok := w.(*holdWriter); ok {
h.onLoop(func(t loopTrip) bool {
@@ -346,6 +347,15 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
}
spoke = spoke || saysSomething(ev)
switch ev.Kind {
case KThink, KSealed:
if ev.Kind == KThink && !summaryUpstream {
break
}
if h, ok := w.(*holdWriter); ok {
h.mu.Lock()
h.first.hidden = true
h.mu.Unlock()
}
case KError:
if ev.Code == "" && cont.possible() && !inGroupTry(r.Context()) {
// held while the reply may yet go on; sent when it can't
@@ -408,6 +418,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
}
if err == nil {
u.RequestID = requestID(res.Header)
summaryUpstream = actual == provider.Responses || actual == provider.Gemini || actual == provider.CodeAssist
empty = emptyFails(actual)
}
if err == nil && res.StatusCode >= 400 {
+15 -4
View File
@@ -304,6 +304,9 @@ type Call struct {
// it was streamed (#196)
TTFT int64 `json:"ttft,omitempty"`
FirstText int64 `json:"firstText,omitempty"`
// FirstReasoning is the start of paced visible reasoning, absent for hidden reasoning.
FirstReasoning int64 `json:"firstReasoning,omitempty"`
ReasoningHidden bool `json:"reasoningHidden,omitempty"`
// Flow: the ms its content took to come, from where its speed is
// counted (firstToken.flowMs): next to none for a reply that came in
// a burst, so it tells no speed
@@ -2320,11 +2323,18 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
asName := provider.SentNameOnIn(wiresOf(r.Context()), c.p.ID, accountAgent(c.p), c.model, sent)
try.Swapped, try.Routed = swapped(asName, 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)
call.ReasoningHidden = try.ReasoningHidden
try.Flow = hw.first.flowFor(call.Usage.Reasoning)
call.Flow = try.Flow
// the request's, from when it came as its ms are: the time before
// this try, the ones that failed first, is in it
call.TTFT, call.FirstText = sinceStart(began.Sub(start), hw.first.first), sinceStart(began.Sub(start), hw.first.text)
call.FirstReasoning = 0
if try.FirstReasoning > 0 {
call.FirstReasoning = sinceStart(began.Sub(start), hw.first.reasoning)
}
sentMs, ownMs, retriedMs, queuedMs = 0, 0, 0, 0
if at := wrote.Load(); at > 0 && call.TTFT > 0 {
sentMs = min(max(time.Unix(0, at).Sub(start).Milliseconds(), 1), call.TTFT)
@@ -2344,7 +2354,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// rest, a long prompt being slow to start anywhere
call.Status, call.Error = http.StatusGatewayTimeout, fmt.Sprintf("%s: no first token in %ds", c.p.Name, g.FirstToken)
try.Status, try.Error, try.Fail = call.Status, call.Error, failSlow
call.TTFT, call.FirstText, call.Flow = 0, 0, 0
call.TTFT, call.FirstText, call.Flow, call.FirstReasoning = 0, 0, 0, 0
telemetry.attempt(call, try, c.p.ID, sent, hw, capture)
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try })
if other == nil {
@@ -2434,7 +2444,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
Requested: call.Model, Served: call.Usage.Served, Upstream: call.Usage.Upstream,
Input: call.Usage.Input, Output: call.Usage.Output, CacheRead: call.Usage.CacheRead,
CacheWrite: call.Usage.CacheWrite, CacheWrite1h: call.Usage.CacheWrite1h, Reasoning: call.Usage.Reasoning, Effort: wentAt, Millis: time.Since(began).Milliseconds(), Status: call.Status,
TTFT: try.TTFT, FirstText: try.FirstText, Flow: try.Flow, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind,
TTFT: try.TTFT, FirstText: try.FirstText, FirstReasoning: try.FirstReasoning, ReasoningHidden: try.ReasoningHidden, Flow: try.Flow, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind,
RequestID: call.Usage.RequestID, Endpoint: endpointOf(r, from, call.To, c.p, c.model), Archive: call.archiveName(), HandedOn: true}
failedWith(&rec, call.Status, call.Error, call.Usage.ErrType)
// what this account answered is its refusal, the reply
@@ -2477,7 +2487,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
Requested: call.Model, Served: call.Usage.Served,
Input: call.Usage.Input, Output: call.Usage.Output, CacheRead: call.Usage.CacheRead,
CacheWrite: call.Usage.CacheWrite, CacheWrite1h: call.Usage.CacheWrite1h, Reasoning: call.Usage.Reasoning, Effort: wentAt, Millis: time.Since(began).Milliseconds(), Status: call.Status,
TTFT: try.TTFT, FirstText: try.FirstText, Flow: try.Flow, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind,
TTFT: try.TTFT, FirstText: try.FirstText, FirstReasoning: try.FirstReasoning, ReasoningHidden: try.ReasoningHidden, Flow: try.Flow, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind,
RequestID: call.Usage.RequestID, Endpoint: endpointOf(r, from, call.To, c.p, c.model), Archive: call.archiveName(), HandedOn: true}
failedWith(&rec, call.Status, call.Error, call.Usage.ErrType)
// what this account answered is its refusal, the reply
@@ -2876,6 +2886,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
t.Usage = append(t.Usage, routeUsage(call.Provider, model, call.Usage)...)
}
t.Tokens = call.Usage.Input + call.Usage.Output + call.Usage.CacheRead + call.Usage.CacheWrite
t.FirstReasoning, t.ReasoningHidden = call.FirstReasoning, call.ReasoningHidden
t.Output, t.Reasoning, t.TTFT, t.FirstText, t.Flow = call.Usage.Output, call.Usage.Reasoning, call.TTFT, call.FirstText, call.Flow
if prompt != nil {
t.Prompt = prompt.calibrated(promptCounted(t.Usage), window)
@@ -2892,7 +2903,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
Requested: call.Model, Served: call.Usage.Served, Upstream: call.Usage.Upstream,
Input: call.Usage.Input, Output: call.Usage.Output, CacheRead: call.Usage.CacheRead,
CacheWrite: call.Usage.CacheWrite, CacheWrite1h: call.Usage.CacheWrite1h, Reasoning: call.Usage.Reasoning, Effort: wentAt, Millis: call.Millis, Status: call.Status,
TTFT: call.TTFT, FirstText: call.FirstText, Flow: call.Flow, Sent: sentMs, Own: ownMs, Retried: retriedMs, Queued: queuedMs, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind,
TTFT: call.TTFT, FirstText: call.FirstText, FirstReasoning: call.FirstReasoning, ReasoningHidden: call.ReasoningHidden, Flow: call.Flow, Sent: sentMs, Own: ownMs, Retried: retriedMs, Queued: queuedMs, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind,
RequestID: call.Usage.RequestID, ResponseID: call.Usage.ResponseID, Endpoint: endpointOf(r, from, call.To, lastTried, model), Stop: call.Usage.Stop, Archive: call.archiveName()}
if tries > 1 {
// answered, or not, after a try that failed first: the ledger
+1 -1
View File
@@ -115,7 +115,7 @@ func (t *otelRequest) attempt(call Call, attempt Try, providerID, effort string,
rec := usage.Record{OTel: span, RouteID: t.routeID, Time: attempt.Start, Agent: call.Agent,
Provider: providerID, Model: attempt.Model, Requested: call.Model, Served: u.Served, Effort: effort,
Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, Reasoning: u.Reasoning,
Millis: time.Since(attempt.Start).Milliseconds(), Status: attempt.Status, TTFT: attempt.TTFT, FirstText: attempt.FirstText}
Millis: time.Since(attempt.Start).Milliseconds(), Status: attempt.Status, TTFT: attempt.TTFT, FirstText: attempt.FirstText, FirstReasoning: attempt.FirstReasoning, ReasoningHidden: attempt.ReasoningHidden}
if usage.OTelBodies() {
reply, cut := capture.body.text(), capture.body.truncated
if !held.passing {
@@ -0,0 +1,15 @@
package gateway
import (
"testing"
"time"
)
func BenchmarkReasoningTiming(b *testing.B) {
ev := []byte(`data: {"choices":[{"delta":{"reasoning_content":"The user wants a file written."}}]}` + "\n\n")
b.ReportAllocs()
for b.Loop() {
f := firstToken{start: time.Now()}
f.see(ev)
}
}
+329
View File
@@ -0,0 +1,329 @@
package gateway
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
func TestReasoningSpeedEvidence(t *testing.T) {
thought := `data: {"choices":[{"delta":{"reasoning_content":"a thought"}}]}` + "\n\n"
for _, c := range []struct {
name string
proto provider.Protocol
event string
hidden bool
want bool
}{
{"chat", provider.Chat, thought, false, true},
{"anthropic", provider.Anthropic, `data: {"type":"content_block_delta","delta":{"type":"thinking_delta","thinking":"a thought"}}` + "\n\n", false, true},
{"late Responses summary", provider.Responses, `data: {"type":"response.reasoning_summary_text.delta","delta":"a thought"}` + "\n\n", false, false},
{"translated hidden Responses", provider.Responses, thought, false, false},
{"translated redacted thinking", provider.Anthropic, thought, true, false},
{"Gemini summary", provider.Gemini, thought, false, false},
} {
t.Run(c.name, func(t *testing.T) {
f := firstToken{start: time.Now().Add(-time.Second), hidden: c.hidden}
f.see([]byte(c.event))
f.start = f.start.Add(-time.Second)
f.see([]byte(c.event))
if got := f.reasoningMs(c.proto) > 0; got != c.want {
t.Fatalf("reasoning evidence=%v; want %v", got, c.want)
}
})
}
f := firstToken{start: time.Now().Add(-time.Second)}
f.see([]byte(thought + thought))
if f.reasoningMs(provider.Chat) != 0 {
t.Fatal("a buffered burst acquired reasoning timing")
}
}
func TestReasoningSpeedThroughGateway(t *testing.T) {
events := []string{
`~data: {"choices":[{"delta":{"reasoning_content":"first thought"}}]}`,
`~data: {"choices":[{"delta":{"reasoning_content":"second thought"}}]}`,
`~data: {"choices":[{"delta":{"reasoning_content":"third thought"}}]}`,
`~data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"check","arguments":"{}"}}]}}]}`,
`data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":5,"completion_tokens":120,"completion_tokens_details":{"reasoning_tokens":100}}}`,
`data: [DONE]`,
}
for _, path := range []string{"/v1/chat/completions", "/v1/responses", "/v1/messages"} {
t.Run(path, func(t *testing.T) {
fresh(t)
up := httptest.NewServer(&paced{events: events, gap: 150 * time.Millisecond})
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Chat: up.URL + "/v1", Key: "k", Models: []string{"m1"}}); err != nil {
t.Fatal(err)
}
body := `{"model":"fake/m1","stream":true,"messages":[{"role":"user","content":"hi"}],"max_tokens":300}`
if path == "/v1/responses" {
body = `{"model":"fake/m1","stream":true,"input":"hi"}`
}
s := New()
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body)))
u := lastUsage(t)
r := lastRoute(s)
if rec.Code != 200 || u.FirstReasoning <= 0 || u.FirstText != 0 || u.Reasoning != 100 {
t.Fatalf("streamed reasoning missing: %d %+v %s", rec.Code, u, rec.Body)
}
n, w := u.Decode()
if n != 120 || w < usage.MinDecodeMs {
t.Fatalf("visible reasoning has no speed: %d/%d %+v", n, w, u)
}
if r.FirstReasoning != u.FirstReasoning || len(r.Tries) != 1 || r.Tries[0].FirstReasoning <= 0 || s.Recent()[0].FirstReasoning != u.FirstReasoning {
t.Fatalf("trace disagrees: %+v %+v", u, r)
}
})
}
}
func TestHiddenReasoningThroughTranslation(t *testing.T) {
events := []string{
`data: {"type":"response.created","response":{"id":"r1","status":"in_progress","output":[]}}`,
`~data: {"type":"response.reasoning_summary_text.delta","delta":"first summary"}`,
`~data: {"type":"response.reasoning_summary_text.delta","delta":"second summary"}`,
`~data: {"type":"response.reasoning_summary_text.delta","delta":"third summary"}`,
`data: {"type":"response.output_item.added","item":{"type":"function_call","call_id":"c1","name":"check"}}`,
`data: {"type":"response.function_call_arguments.delta","delta":"{}"}`,
`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":1500,"output_tokens_details":{"reasoning_tokens":1400}}}}`,
}
for _, path := range []string{"/v1/responses", "/v1/chat/completions", "/v1/messages"} {
t.Run(path, func(t *testing.T) {
fresh(t)
up := httptest.NewServer(&paced{events: events, gap: 150 * time.Millisecond})
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Responses: up.URL + "/v1", Key: "k", Models: []string{"m1"}}); err != nil {
t.Fatal(err)
}
body := `{"model":"fake/m1","stream":true,"messages":[{"role":"user","content":"hi"}],"max_tokens":300}`
if path == "/v1/responses" {
body = `{"model":"fake/m1","stream":true,"input":"hi"}`
}
s := New()
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body)))
u := lastUsage(t)
r := lastRoute(s)
n, w := u.Decode()
if rec.Code != 200 || u.FirstReasoning != 0 || r.FirstReasoning != 0 || n != 0 || w != 0 || u.Reasoning != 1400 {
t.Fatalf("hidden reasoning acquired speed after translation: %d %+v %s", rec.Code, u, rec.Body)
}
})
}
}
// A visible portion never licenses timing a sealed portion of the same turn.
func TestMixedRedactedReasoning(t *testing.T) {
events := []string{
`data: {"type":"message_start","message":{"id":"m","role":"assistant","model":"m1","content":[],"usage":{"input_tokens":5,"output_tokens":0}}}`,
`data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}`,
`~data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"first thought"}}`,
`~data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"second thought"}}`,
`data: {"type":"content_block_stop","index":0}`,
`data: {"type":"content_block_start","index":1,"content_block":{"type":"redacted_thinking","data":"sealed-test"}}`,
`data: {"type":"content_block_stop","index":1}`,
`data: {"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"t1","name":"check","input":{}}}`,
`data: {"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"{}"}}`,
`data: {"type":"content_block_stop","index":2}`,
`data: {"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":120}}`,
`data: {"type":"message_stop"}`,
}
for _, path := range []string{"/v1/messages", "/v1/chat/completions", "/v1/responses"} {
t.Run(path, func(t *testing.T) {
fresh(t)
up := httptest.NewServer(&paced{events: events, gap: 150 * time.Millisecond})
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Anthropic: up.URL, Key: "k", Models: []string{"m1"}}); err != nil {
t.Fatal(err)
}
body := `{"model":"fake/m1","stream":true,"messages":[{"role":"user","content":"hi"}],"max_tokens":300}`
if path == "/v1/responses" {
body = `{"model":"fake/m1","stream":true,"input":"hi"}`
}
s := New()
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, httptest.NewRequest("POST", path, strings.NewReader(body)))
row := lastUsage(t)
n, ms := row.Decode()
if w.Code != 200 || row.FirstReasoning != 0 || !row.ReasoningHidden || n != 0 || ms != 0 {
t.Fatalf("mixed sealed reasoning timed: %d %+v", w.Code, row)
}
})
}
}
func TestReasoningPacingEdges(t *testing.T) {
thought := []byte(`data: {"choices":[{"delta":{"reasoning_content":"thought"}}]}` + "\n\n")
tool := []byte(`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{}"}}]}}]}` + "\n\n")
for _, c := range []struct {
name string
gap time.Duration
want bool
}{
{"below 100ms", 99 * time.Millisecond, false}, {"100ms", 100 * time.Millisecond, true},
} {
t.Run(c.name, func(t *testing.T) {
f := firstToken{start: time.Now().Add(-time.Second)}
f.see(thought)
f.start = time.Now().Add(-f.reasoning - c.gap)
f.see(thought)
if got := f.reasoningMs(provider.Chat) > 0; got != c.want {
t.Fatalf("paced=%v; want %v", got, c.want)
}
})
}
f := firstToken{start: time.Now().Add(-time.Second)}
f.see(tool)
f.start = f.start.Add(-time.Second)
f.see(thought)
f.start = f.start.Add(-time.Second)
f.see(thought)
if f.reasoningMs(provider.Chat) != 0 {
t.Fatal("a tool-first turn acquired reasoning timing")
}
// Two writes after a long quiet start still form a burst below the decode minimum.
f = firstToken{start: time.Now().Add(-14 * time.Second)}
f.see(thought)
f.see(thought)
if f.reasoningMs(provider.Chat) != 0 {
t.Fatal("buffered reasoning acquired timing")
}
}
func TestSlowReleasedReasoningIsUntimed(t *testing.T) {
f := firstToken{start: time.Now().Add(-time.Second)}
thought := []byte(`data: {"choices":[{"delta":{"reasoning_content":"one visible thought"}}]}` + "\n\n")
f.see(thought)
first := f.reasoning
for i := 0; i < 40; i++ {
f.start = time.Now().Add(-first - 10*time.Second - time.Duration(i)*6*time.Millisecond)
f.see(thought)
}
end := first.Milliseconds() + 10250
n, w := usage.DecodeOf(500, 450, end, first.Milliseconds(), 0, f.flowFor(450), f.reasoningMs(provider.Chat))
if n != 0 || w != 0 {
t.Fatalf("held reasoning inflated speed: %d/%d flow=%d", n, w, f.flowFor(450))
}
}
func TestEncryptedReasoningWithoutTokenDetails(t *testing.T) {
f := firstToken{start: time.Now().Add(-time.Second)}
f.see([]byte(`data: {"type":"response.output_item.done","item":{"type":"reasoning","encrypted_content":"synthetic-seal"}}` + "\n\n"))
if !f.hidden {
t.Fatal("encrypted reasoning discarded its hidden marker")
}
}
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 {
t.Fatal("Gemini summary timed without its hidden thought count")
}
}
func TestCodexBackendHiddenReasoningWithoutCount(t *testing.T) {
setup(t, provider.Chat, &fake{t: t})
p := &paced{events: []string{
`data: {"type":"response.created","response":{"id":"r1","status":"in_progress","output":[]}}`,
`~data: {"type":"response.reasoning_summary_text.delta","delta":"summary"}`,
`~data: {"type":"response.output_item.done","item":{"type":"reasoning","encrypted_content":"synthetic-seal"}}`,
`~data: {"type":"response.function_call_arguments.delta","delta":"{}"}`,
`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":120}}}`,
}, gap: 150 * time.Millisecond}
chatgpt(t, func(w http.ResponseWriter, r *http.Request) { p.ServeHTTP(w, r) })
if code, body := codexPost(t, `{"model":"gpt-5.5","stream":true,"input":"hi"}`); code != 200 {
t.Fatalf("%d %s", code, body)
}
r := lastUsage(t)
n, ms := r.Decode()
if !r.ReasoningHidden || n != 0 || ms != 0 {
t.Fatalf("Codex hidden reasoning timed with no count: %+v", r)
}
}
func TestResponsesToolWithoutReasoningStillTimed(t *testing.T) {
events := []string{
`data: {"type":"response.created","response":{"id":"r1","status":"in_progress","output":[]}}`,
`data: {"type":"response.output_item.added","item":{"type":"function_call","call_id":"c1","name":"check"}}`,
`~data: {"type":"response.function_call_arguments.delta","delta":"{\"value\":"}`,
`~data: {"type":"response.function_call_arguments.delta","delta":"1290}"}`,
`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":10}}}`,
}
fresh(t)
up := httptest.NewServer(&paced{events: events, gap: 150 * time.Millisecond})
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Responses: up.URL + "/v1", Key: "k", Models: []string{"m1"}}); err != nil {
t.Fatal(err)
}
s := New()
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"fake/m1","stream":true,"messages":[{"role":"user","content":"hi"}]}`)))
row := lastUsage(t)
n, ms := row.Decode()
if w.Code != 200 || row.ReasoningHidden || n != 10 || ms < usage.MinDecodeMs {
t.Fatalf("tool-only response lost timing: %d %+v", w.Code, row)
}
}
func TestMultipleVisibleReasoningBlocks(t *testing.T) {
f := firstToken{start: time.Now().Add(-time.Second)}
for i, ev := range []string{
`data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}`,
`data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"first thought"}}`,
`data: {"type":"content_block_stop","index":0}`,
`data: {"type":"content_block_start","index":1,"content_block":{"type":"thinking","thinking":""}}`,
`data: {"type":"content_block_delta","index":1,"delta":{"type":"thinking_delta","thinking":"second thought"}}`,
} {
f.start = time.Now().Add(-time.Second - time.Duration(i)*150*time.Millisecond)
f.see([]byte(ev + "\n\n"))
}
if first := f.reasoningMs(provider.Anthropic); first <= 0 || first != f.first.Milliseconds() {
t.Fatal("multiple visible blocks lost their first reasoning time")
}
}
func TestLiveVisibleReasoningFixture(t *testing.T) {
var sample struct {
First int64 `json:"first_reasoning_ms"`
Events []struct {
At int64 `json:"at_ms"`
Delta string `json:"delta"`
} `json:"events"`
Record struct {
Out, Reasoning int
Ms int64
TTFT int64 `json:"ttft_ms"`
Flow int64 `json:"flow_ms"`
} `json:"record"`
}
b, err := os.ReadFile("testdata/reasoning-speed-visible.json")
if err != nil {
t.Fatal(err)
}
if err = json.Unmarshal(b, &sample); err != nil {
t.Fatal(err)
}
f := firstToken{}
for _, e := range sample.Events {
delta, _ := json.Marshal(e.Delta)
f.start = time.Now().Add(-time.Duration(e.At) * time.Millisecond)
f.see([]byte(`data: {"choices":[{"delta":{"reasoning_content":` + string(delta) + `}}]}` + "\n\n"))
}
if f.reasoningMs(provider.Chat) != sample.Events[0].At {
t.Fatalf("live reasoning fixture lost its start: %d/%d", f.reasoningMs(provider.Chat), sample.Events[0].At)
}
n, ms := usage.DecodeOf(sample.Record.Out, sample.Record.Reasoning, sample.Record.Ms, sample.Record.TTFT, 0, sample.Record.Flow, sample.First)
if n != 76 || ms != 731 {
t.Fatalf("live tool turn speed %d/%d; want 76/731", n, ms)
}
}
+161
View File
@@ -0,0 +1,161 @@
{
"source": "WorkBuddy DeepSeek v4.1 flash; 2026-10-10; translated Chat reasoning_content",
"first_reasoning_ms": 6787,
"events": [
{
"at_ms": 6789,
"delta": "We"
},
{
"at_ms": 6831,
"delta": " need"
},
{
"at_ms": 6841,
"delta": " answer"
},
{
"at_ms": 6841,
"delta": "."
},
{
"at_ms": 6851,
"delta": " Need"
},
{
"at_ms": 6852,
"delta": " compute"
},
{
"at_ms": 6877,
"delta": " "
},
{
"at_ms": 6877,
"delta": "17"
},
{
"at_ms": 6877,
"delta": "*"
},
{
"at_ms": 6877,
"delta": "23"
},
{
"at_ms": 6877,
"delta": "="
},
{
"at_ms": 6877,
"delta": "391"
},
{
"at_ms": 6883,
"delta": ","
},
{
"at_ms": 6883,
"delta": " "
},
{
"at_ms": 6883,
"delta": "29"
},
{
"at_ms": 6883,
"delta": "*"
},
{
"at_ms": 6883,
"delta": "31"
},
{
"at_ms": 6888,
"delta": "="
},
{
"at_ms": 6888,
"delta": "899"
},
{
"at_ms": 6888,
"delta": ","
},
{
"at_ms": 6888,
"delta": " sum"
},
{
"at_ms": 6888,
"delta": " "
},
{
"at_ms": 6888,
"delta": "129"
},
{
"at_ms": 7002,
"delta": "0"
},
{
"at_ms": 7002,
"delta": "."
},
{
"at_ms": 7002,
"delta": " Call"
},
{
"at_ms": 7002,
"delta": " check"
},
{
"at_ms": 7002,
"delta": "_value"
},
{
"at_ms": 7002,
"delta": " with"
},
{
"at_ms": 7002,
"delta": " "
},
{
"at_ms": 7002,
"delta": "129"
},
{
"at_ms": 7002,
"delta": "0"
},
{
"at_ms": 7002,
"delta": "."
},
{
"at_ms": 7002,
"delta": " Then"
},
{
"at_ms": 7002,
"delta": " final"
},
{
"at_ms": 7002,
"delta": " concise"
},
{
"at_ms": 7002,
"delta": "."
}
],
"record": {
"out": 76,
"reasoning": 37,
"ms": 7518,
"ttft_ms": 6787,
"flow_ms": 187
}
}
+6
View File
@@ -76,6 +76,9 @@ type Route struct {
// counts: streamed replies only (#196)
TTFT int64 `json:"ttft,omitempty"`
FirstText int64 `json:"firstText,omitempty"`
// FirstReasoning is the start of paced visible reasoning, absent for hidden reasoning.
FirstReasoning int64 `json:"firstReasoning,omitempty"`
ReasoningHidden bool `json:"reasoningHidden,omitempty"`
// Flow: the ms its content took to come (Call.Flow)
Flow int64 `json:"flow,omitempty"`
// Served: the model the reply says answered, as the last try has it;
@@ -266,6 +269,9 @@ type Try struct {
// first text, when it streamed any (#196)
TTFT int64 `json:"ttft,omitempty"`
FirstText int64 `json:"firstText,omitempty"`
// FirstReasoning is the start of paced visible reasoning, absent for hidden reasoning.
FirstReasoning int64 `json:"firstReasoning,omitempty"`
ReasoningHidden bool `json:"reasoningHidden,omitempty"`
// Flow: the ms its content took to come (Call.Flow)
Flow int64 `json:"flow,omitempty"`
// Served: the model its reply said answered, when it named one;
+69 -26
View File
@@ -11,6 +11,8 @@ import (
"bytes"
"encoding/json"
"time"
"github.com/yetone/magpie/internal/provider"
)
// firstMost is the most of a stream read for its first tokens: a reply
@@ -20,13 +22,15 @@ const firstMost = 8 << 20
// firstToken times a stream's first content and first text from start,
// and when the rest of its content came (flowMs).
type firstToken struct {
start time.Time
first time.Duration // to the first content; 0 until it comes
text time.Duration // to the first text
off bool // not a stream, or read as far as it is
began bool
read int
pend []byte
start time.Time
first time.Duration // to the first content; 0 until it comes
text time.Duration // to the first text
reasoning, lastReasoning time.Duration
hidden bool // redacted thinking cannot be timed by its visible portion
off bool // not a stream, or read as far as it is
began bool
read int
pend []byte
// flow: how many bytes of content events had come by each time, one
// mark a millisecond, from the first content on
flow []flowMark
@@ -75,7 +79,14 @@ func (f *firstToken) see(b []byte) {
}
continue
}
content, text := firstKind(ev)
content, text, reasoning, hidden := timingKind(ev)
f.hidden = f.hidden || hidden
if reasoning {
if f.reasoning == 0 {
f.reasoning = d
}
f.lastReasoning = d
}
if !content && !text {
continue
}
@@ -162,6 +173,11 @@ func (f *firstToken) ms() (first, text int64) {
// agent speaks, carries content — text, reasoning or a tool call — and
// whether that is text the reader sees.
func firstKind(ev []byte) (content, text bool) {
content, text, _, _ = timingKind(ev)
return
}
func timingKind(ev []byte) (content, text, reasoning, hidden bool) {
var name string
var data []byte
for _, ln := range bytes.Split(ev, []byte("\n")) {
@@ -176,8 +192,8 @@ func firstKind(ev []byte) (content, text bool) {
// only deltas, a tool call's start and Gemini's parts carry any: the
// rest go by unread
if len(data) == 0 || !(bytes.Contains(data, []byte("delta")) || bytes.Contains(data, []byte(`"parts"`)) ||
bytes.Contains(data, []byte("content_block_start")) || bytes.Contains(data, []byte("output_item.added"))) {
return false, false
bytes.Contains(data, []byte("content_block_start")) || bytes.Contains(data, []byte("output_item.added")) || bytes.Contains(data, []byte("encrypted_content"))) {
return false, false, false, hidden
}
var v struct {
Type string `json:"type"`
@@ -186,7 +202,8 @@ func firstKind(ev []byte) (content, text bool) {
Type string `json:"type"`
} `json:"content_block"`
Item *struct {
Type string `json:"type"`
Type string `json:"type"`
EncryptedContent string `json:"encrypted_content"`
} `json:"item"`
Choices []struct {
Delta struct {
@@ -209,12 +226,18 @@ func firstKind(ev []byte) (content, text bool) {
} `json:"candidates"`
}
if json.Unmarshal(data, &v) != nil {
return false, false
return false, false, false, hidden
}
typ := v.Type
if typ == "" {
typ = name
}
if v.Item != nil && v.Item.EncryptedContent != "" {
hidden = true
}
if v.ContentBlock != nil && v.ContentBlock.Type == "redacted_thinking" {
hidden = true
}
switch typ {
case "content_block_delta": // Anthropic
var d struct {
@@ -226,31 +249,34 @@ func firstKind(ev []byte) (content, text bool) {
json.Unmarshal(v.Delta, &d)
switch {
case d.Text != "":
return true, true
case d.Thinking != "", d.PartialJSON != "":
return true, false
return true, true, reasoning, hidden
case d.Thinking != "":
return true, false, true, false
case d.PartialJSON != "":
return true, false, reasoning, hidden
}
return false, false
return false, false, false, hidden
case "content_block_start":
if b := v.ContentBlock; b != nil && (b.Type == "tool_use" || b.Type == "server_tool_use") {
return true, false
return true, false, reasoning, hidden
}
return false, false
return false, false, false, hidden
case "response.output_text.delta", "response.refusal.delta": // Responses
return filled(v.Delta), filled(v.Delta)
return filled(v.Delta), filled(v.Delta), false, false
case "response.reasoning_summary_text.delta", "response.reasoning_text.delta",
"response.function_call_arguments.delta", "response.custom_tool_call_input.delta":
return filled(v.Delta), false
return filled(v.Delta), false, (typ == "response.reasoning_text.delta" || typ == "response.reasoning_summary_text.delta") && filled(v.Delta), false
case "response.output_item.added":
if it := v.Item; it != nil && (it.Type == "function_call" || it.Type == "custom_tool_call") {
return true, false
return true, false, reasoning, hidden
}
return false, false
return false, false, false, hidden
}
for _, c := range v.Choices { // Chat
d := c.Delta
reasoning = reasoning || filled(d.ReasoningContent) || filled(d.Reasoning)
if filled(d.Content) || filled(d.Refusal) {
return true, true
return true, true, reasoning, hidden
}
if filled(d.ReasoningContent) || filled(d.Reasoning) || filled(d.ToolCalls) || filled(d.FunctionCall) {
content = true
@@ -260,13 +286,14 @@ func firstKind(ev []byte) (content, text bool) {
for _, p := range c.Content.Parts {
switch {
case p.Text != "" && !p.Thought:
return true, true
return true, true, reasoning, hidden
case p.Text != "", filled(p.FunctionCall):
content = true
reasoning = reasoning || p.Thought && p.Text != ""
}
}
}
return content, false
return content, false, reasoning, hidden
}
// filled is a JSON value with something in it.
@@ -282,8 +309,24 @@ func filled(raw json.RawMessage) bool {
// usage.DecodeOf counts it: its first text when it reasoned, else its
// first content.
func (f *firstToken) flowFor(reasoning int) int64 {
if reasoning > 0 {
if reasoning > 0 && f.text > 0 {
return f.flowMs(f.text.Milliseconds())
}
return f.flowMs(f.first.Milliseconds())
}
// 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
}
// reasoningMs requires a paced visible channel. Responses and Gemini summaries
// do not measure their full reasoning count; translation keeps that restriction.
func (f *firstToken) reasoningMs(proto provider.Protocol) int64 {
if proto != provider.Chat && proto != provider.Anthropic || f.hidden || f.off ||
f.reasoning == 0 || f.reasoning != f.first || f.lastReasoning-f.reasoning < 100*time.Millisecond {
return 0
}
return f.reasoning.Milliseconds()
}
+7 -6
View File
@@ -18000,7 +18000,7 @@ function renderLedgerDash(l) {
const gs = ledGroupSpeed(l);
block("Output speed", gs ? gs.mainParts : "—",
line(...[ledTTFT(l) ? t("first token in {ms} on average", { ms: ledTook(ledTTFT(l)) }) : t("no streamed replies timed")].concat(gs?.floor ? [" · ", gs.floor] : [])),
"", [gs?.title, t("Output tokens a second after the first, over the streamed replies") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it")].filter(Boolean).join("\n"));
"", [gs?.title, t("Output tokens a second after the first, over the streamed replies") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it") + ". " + t("No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed")].filter(Boolean).join("\n"));
drawLedTrend();
}
@@ -18276,12 +18276,13 @@ const LED_COLS = [
// Discord): its content came in under a quarter of its window (flow_ms),
// or its answer at over 20 times the pace its reasoning came before it
const ledDecode = (r) => {
if (ledFailed_(r) || !(r.ttft_ms > 0)) return null;
const think = r.reasoning > 0, n = think ? r.out - r.reasoning : r.out, from = think ? r.first_text_ms : r.ttft_ms;
if (ledFailed_(r) || r.reasoning_hidden && !(r.first_text_ms > 0) || !(r.ttft_ms > 0)) return null;
const think = r.reasoning > 0, visible = think && !(r.first_text_ms > 0) && r.first_reasoning_ms >= r.ttft_ms && r.flow_ms > 0 && r.reasoning <= r.out;
const n = think && !visible ? r.out - r.reasoning : r.out, from = visible ? r.first_reasoning_ms : think ? r.first_text_ms : r.ttft_ms;
const w = r.ms - from;
if (!(n > 0 && from > 0 && w >= 100 && n * 1000 <= 10000 * w)) return null;
if (r.flow_ms > 0 && r.flow_ms * 4 < w) return null;
if (think && n * (r.first_text_ms - r.ttft_ms) > 20 * r.reasoning * w) return null;
if (think && r.first_text_ms > 0 && n * (r.first_text_ms - r.ttft_ms) > 20 * r.reasoning * w) return null;
return { n, w };
};
// how fast a reply wrote, in tokens a second: 0 when it can't tell
@@ -18591,8 +18592,8 @@ function renderLedger() {
// how fast it wrote once it began, as CC Switch's log has it (#860)
const v = ledRowSpeed(r), floor = ledFloorSpeed(r);
td(v ? t("{n} tok/s", { n: ledNum(Math.round(v)) }) : floor ? "≥" + t("{n} tok/s", { n: ledNum(Math.round(floor)) }) : "—", "n speed" + (v || floor ? "" : " faint"),
v ? (r.reasoning > 0 ? t("{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out", { n: ledNum(ledDecode(r).n), ms: ledTook(ledDecode(r).w), r: ledNum(r.reasoning) })
: t("{n} output tokens in {ms} after the first", { n: ledNum(r.out), ms: ledTook(r.ms - r.ttft_ms) })) + " · " + t("TTFT {ms}", { ms: ledTook(r.ttft_ms) })
v ? (r.reasoning > 0 && r.first_text_ms > 0 ? t("{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out", { n: ledNum(ledDecode(r).n), ms: ledTook(ledDecode(r).w), r: ledNum(r.reasoning) })
: t("{n} output tokens in {ms} after the first", { n: ledNum(ledDecode(r).n), ms: ledTook(ledDecode(r).w) })) + " · " + t("TTFT {ms}", { ms: ledTook(r.ttft_ms) })
: floor && ledFloor_(r).answer ? t("At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. The session file has no first text, so reasoning after the first token is counted too", { n: ledNum(ledFloor_(r).n), ms: ledTook(ledFloor_(r).w), r: ledNum(r.reasoning) }) + " · " + t("TTFT {ms}", { ms: ledTook(r.ttft_ms) })
: floor ? t("At least: {n} output tokens in {ms}, from the line that asked for it to its last. The session file has no first token, so the wait for it is counted too", { n: ledNum(r.out), ms: ledTook(r.ms) })
: r.ttft_ms || untimed || ledFailed_(r) ? "" : timed ? t("The session file has no first token to time a speed from") : t("Not streamed: no first token to time a speed from"));
+4
View File
@@ -3668,6 +3668,7 @@ const I18N = {
"At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. The session file has no first text, so reasoning after the first token is counted too": "下限:首字后 {ms} 输出 {n} 个正文 token,{r} 个推理 token 不计。会话文件没有首个正文的时间,首字后的推理时间也算在里面",
"The session file has no first token to time a speed from": "会话文件没有首字时间,算不出速度",
"A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "有推理的回复只算正文部分,从首个正文起计:推理在流里出现前就已写完",
"No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed": "没有正文时,仅在可见推理持续流式输出时将其计入速度;隐藏推理不显示速度",
"{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out": "首个正文后 {ms} 输出 {n} 个正文 token,之前的 {r} 个推理 token 不计",
"Not streamed: no first token to time a speed from": "非流式:没有首字时间,算不出速度",
"Cache": "缓存",
@@ -8181,6 +8182,7 @@ const I18N = {
"At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. The session file has no first text, so reasoning after the first token is counted too": "下限:首字後 {ms} 輸出 {n} 個正文 token,{r} 個推理 token 不計。會話檔案沒有首個正文的時間,首字後的推理時間也算在裡面",
"The session file has no first token to time a speed from": "會話檔案沒有首字時間,算不出速度",
"A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "有推理的回覆只算正文部分,從首個正文起計:推理在流裡出現前就已寫完",
"No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed": "沒有正文時,僅在可見推理持續串流輸出時將其計入速度;隱藏推理不顯示速度",
"{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out": "首個正文後 {ms} 輸出 {n} 個正文 token,之前的 {r} 個推理 token 不計",
"Not streamed: no first token to time a speed from": "非流式:沒有首字時間,算不出速度",
"Cache": "快取",
@@ -12708,6 +12710,7 @@ const I18N = {
"At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. The session file has no first text, so reasoning after the first token is counted too": "下限:最初のトークン後 {ms} で回答 {n} トークン(推論 {r} トークンは含めず)。セッションファイルには最初の本文の時刻がないため、最初のトークン後の推論の時間も含まれます",
"The session file has no first token to time a speed from": "セッションファイルには、速度を計れる最初のトークンの時刻がありません",
"A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "推論した応答は、最初の本文からの回答部分のみ数えます。推論はストリームに出る前に書き終わっています",
"No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed": "本文がない場合、継続的にストリームされた可視の推論のみ速度に含めます。非表示の推論には速度を表示しません",
"{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out": "最初の本文後 {ms} で回答 {n} トークン(その前の推論 {r} トークンは含めず)",
"Not streamed: no first token to time a speed from": "ストリーミングではないため、速度を計れる最初のトークンの時刻がありません",
"Cache": "キャッシュ",
@@ -17238,6 +17241,7 @@ const I18N = {
"At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. The session file has no first text, so reasoning after the first token is counted too": "Mindestens: {n} Antwort-Token in {ms} nach dem ersten Token, ohne die {r} Reasoning-Token. Die Sitzungsdatei hat keinen ersten Text, also zählt Reasoning nach dem ersten Token mit",
"The session file has no first token to time a speed from": "Die Sitzungsdatei hat kein erstes Token, an dem sich ein Tempo messen ließe",
"A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "Eine Antwort mit Reasoning zählt nur ihre Antwort ab dem ersten Text: Das Reasoning entstand, bevor der Stream es zeigte",
"No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed": "Ohne Antworttext zählt Reasoning nur bei sichtbar gestreamter Ausgabe; verborgenes Reasoning hat kein Tempo",
"{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out": "{n} Antwort-Token in {ms} nach dem ersten Text, ohne die {r} Reasoning-Token davor",
"Not streamed: no first token to time a speed from": "Nicht gestreamt: kein erstes Token, an dem sich ein Tempo messen ließe",
"Cache": "Cache",
+10 -8
View File
@@ -286,17 +286,19 @@
// (usage.DecodeOf, John on Discord: Kimi Code at 2,237 tok/s): its
// content came in under a quarter of its window (flow), or its answer
// at over 20 times the pace its reasoning came before its first text.
function decodeOf(r, ms, ttft, firstText, flow = r.flow) {
const think = reasoningOf(r), n = think > 0 ? r.out - think : r.out, from = think > 0 ? firstText : ttft;
function decodeOf(r, ms, ttft, firstText, flow = r.flow, firstReasoning = r.firstReasoning, reasoningHidden = r.reasoningHidden) {
if (reasoningHidden && !(firstText > 0)) return null;
const think = reasoningOf(r), visible = think > 0 && !(firstText > 0) && firstReasoning >= ttft && flow > 0 && think <= r.out;
const n = think > 0 && !visible ? r.out - think : r.out, from = visible ? firstReasoning : think > 0 ? firstText : ttft;
const w = ms - from;
if (!(n > 0 && ttft > 0 && from > 0 && w >= 100 && n * 1000 <= 10000 * w)) return null;
if (flow > 0 && flow * 4 < w) return null;
if (think > 0 && n * (firstText - ttft) > 20 * think * w) return null;
if (think > 0 && firstText > 0 && n * (firstText - ttft) > 20 * think * w) return null;
return { n, w };
}
const reasoningOf = (r) => r.reasoning ?? (r.usage?.length ? r.usage[r.usage.length - 1].reasoning || 0 : 0);
const speedOf = (r, ms = r.ms, ttft = r.ttft, firstText = r.firstText, flow = r.flow) => {
const d = decodeOf(r, ms, ttft, firstText, flow);
const speedOf = (r, ms = r.ms, ttft = r.ttft, firstText = r.firstText, flow = r.flow, firstReasoning = r.firstReasoning, reasoningHidden = r.reasoningHidden) => {
const d = decodeOf(r, ms, ttft, firstText, flow, firstReasoning, reasoningHidden);
return d ? d.n / (d.w / 1000) : 0;
};
function promptOf(r) {
@@ -342,7 +344,7 @@
cache: ["cache-hit", "Cache", prompt ? pct(100 * read / prompt) : "—",
t("Cache hit rate") + ": " + t("The share of the prompt read from the cache")],
speed: ["speed", "Speed", speed ? t("{n} tok/s", { n: Math.round(speed) }) : "—",
t("Output tokens a second after the first, over the streamed replies") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it")],
t("Output tokens a second after the first, over the streamed replies") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it") + ". " + t("No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed")],
cost: ["cost", "Cost", routeCost(r), r.priced ? costNote() : t("No known price or token counts for this request")],
};
return visibleMetrics.map((key) => values[key]).filter((metric) => metric[2] !== "—");
@@ -358,7 +360,7 @@
function firstNote(r, tr) {
let s = tr.ttft ? " · " + t("first token in {ms}", { ms: took(tr.ttft) }) : "";
if (tr.ttft && tr.firstText > tr.ttft) s += " · " + t("first text in {ms}", { ms: took(tr.firstText) });
const v = speedOf(r, tr.ms, tr.ttft, tr.firstText, tr.flow);
const v = speedOf(r, tr.ms, tr.ttft, tr.firstText, tr.flow, tr.firstReasoning || 0, tr.reasoningHidden || false);
if (v) s += " · " + t("{n} tok/s", { n: Math.round(v) });
const { prompt, read } = promptOf(r);
if (prompt) s += " · " + t("request cache hit rate {p}", { p: pct(100 * read / prompt) });
@@ -2177,7 +2179,7 @@
if (g.key && visibleMetrics.includes("cache") && total.prompt) meta.push(metricElement(["cache-hit", "Avg. cache", pct(100 * total.read / total.prompt),
t("Total cache reads divided by total prompt tokens; larger prompts carry more weight") + "\n" + coverage(total.cached)]));
if (g.key && visibleMetrics.includes("speed") && total.decodeMs) meta.push(metricElement(["speed", "Avg. speed", t("{n} tok/s", { n: Math.round(total.decodeOut * 1000 / total.decodeMs) }),
t("Total output tokens divided by total decode time; excludes waiting and replies without usable timing") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it") + "\n" + coverage(total.timed)]));
t("Total output tokens divided by total decode time; excludes waiting and replies without usable timing") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it") + ". " + t("No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed") + "\n" + coverage(total.timed)]));
const metaSig = JSON.stringify([bits, tokenHelp, meta.map((e) => [e.textContent, e.title])]);
if (x.meta.dataset.sig !== metaSig) { x.meta.replaceChildren(...meta); x.meta.dataset.sig = metaSig; }
setText(x.cost, total.priced ? "≈" + fmtCost({ cost: total.cost, unpriced: 0 }) + (total.unpriced ? "+" : "") : "");
+20 -6
View File
@@ -24,22 +24,29 @@ const timing = [
[2200, 2000, 0, 15500, 14000, 14000], // the turn: 200 in 1.5 s, 133 tok/s
[1300, 0, 1000, 9000, 6000, 6000], // an older route: 300 in 3 s, 100 tok/s
[1500, 1400, 0, 9000, 8000, 0], // reasoning, then tool calls only: none
[500, 0, 0, 7000, 2000, 2000], // no reasoning: 500 in 5 s, 100 tok/s
[500, 0, 0, 7000, 2000, 2000],
[1500, 1400, 0, 15000, 1000, 0], // paced visible reasoning: 107 tok/s
[1500, 1400, 0, 9000, 8000, 0], // a late summary stays untimed
[120, 0, 0, 9000, 1000, 0], // mixed redacted thinking without a reasoning count // no reasoning: 500 in 5 s, 100 tok/s
];
const routes = timing.map(([out, reasoning, usageReasoning, ms, ttft, firstText], i) => ({
...(i === 4 ? { firstReasoning: 1000, flow: 12000 } : {}),
...(i === 6 ? { reasoningHidden: true, flow: 7000 } : {}),
id: 100 - i, seq: 100 - i, time: at(i), agent: "codex", session: "think-chat", model: "codex/gpt-6.1-sol", provider: "codex",
order: [seat], tries: [{ id: seat.id, model: seat.model, start: at(i), done: true, status: 200, ms, ttft, firstText }],
done: true, status: 200, ms, ttft, firstText, tokens: out + 9000, out, ...(reasoning ? { reasoning } : {}),
usage: [{ provider: "codex", model: seat.model, in: 9000, out, ...(reasoning || usageReasoning ? { reasoning: reasoning || usageReasoning } : {}) }],
}));
const rows = timing.map(([out, reasoning, usageReasoning, ms, ttft, firstText], i) => ({
...(i === 4 ? { first_reasoning_ms: 1000, flow_ms: 12000 } : {}),
...(i === 6 ? { reasoning_hidden: true, flow_ms: 7000 } : {}),
route_id: 100 - i, t: at(i), agent: "codex", agentName: "Codex", icon: "codex-color", provider: "codex", providerName: "Codex",
host: "test@example.com", req: "codex/gpt-6.1-sol", model: "gpt-6.1-sol", served: "gpt-6.1-sol", in: 9000, out,
...(reasoning || usageReasoning ? { reasoning: reasoning || usageReasoning } : {}), ms, ttft_ms: ttft, ...(firstText ? { first_text_ms: firstText } : {}),
status: 200, ep: "/backend-api/codex/responses", cost: 0.01, priced: true,
}));
// what the server sums: 1000 answer tokens in 9.5 s
const M = { id: "gpt-6.1-sol", calls: 4, input: 36000, output: 5500, cache_read: 0, cache_write: 0, cost: 0.04, timed: 4, ttft_ms: 30000, decode_ms: 9500, decode_out: 1000 };
// what the server sums: 1000 answer tokens plus 1500 visible output tokens in 23.5 s
const M = { id: "gpt-6.1-sol", calls: 7, input: 63000, output: 8620, cache_read: 0, cache_write: 0, cost: 0.04, timed: 4, ttft_ms: 30000, decode_ms: 23500, decode_out: 2500 };
function serve(lang) {
const state = { agents: [{ id: "codex", name: "Codex", path: "/t/c.toml", icon: "codex-color", fields: [] }], profiles: [], settings: { lang, theme: "light" } };
@@ -71,6 +78,7 @@ function serve(lang) {
}
const L = {
"zh-TW": { s: (n) => `${n} token/秒`, speed: "速度", note: /首個正文後/, rule: /有推理的回覆只算正文部分/ },
en: { s: (n) => `${n} tok/s`, speed: "Speed", note: /200 answer tokens in 1\.5 s after the first text, the 2,000 reasoning tokens before it left out/, rule: /A reply that reasoned counts only its answer/ },
zh: { s: (n) => `${n} token/秒`, speed: "速度", note: /首个正文后 1\.5 秒 输出 200 个正文 token,之前的 2,000 个推理 token 不计/, rule: /有推理的回复只算正文部分/ },
ja: { s: (n) => `${n} トークン/秒`, speed: "速度", note: /回答 200 トークン(その前の推論 2,000 トークンは含めず)/, rule: /推論した応答は/ },
@@ -99,6 +107,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(await speedOf(1), w.s(100), "an older route's reasoning is its try's");
assert.equal(await speedOf(2), "", "tool calls after reasoning tell no speed");
assert.equal(await speedOf(3), w.s(100), "no reasoning: as before");
assert.equal(await speedOf(4), w.s(107), "visible reasoning timed from its first delta");
assert.equal(await speedOf(5), "", "late hidden summary stays untimed");
assert.equal(await speedOf(6), "", "redacted reasoning stays untimed without a count");
assert.match(await reqs.nth(0).locator(".speed").getAttribute("title"), w.rule);
await reqs.nth(0).click();
await page.waitForTimeout(200);
@@ -107,8 +118,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await page.locator(".rt-group-by button").nth(1).click();
const group = page.locator("button.rt-session").first();
await group.waitFor();
// 1000 answer tokens over 9.5 s of answers, not 4500 over them
assert.equal((await group.locator(".speed .v").textContent()).trim(), w.s(105));
// Hidden reasoning is excluded; visible reasoning adds its own decode window.
assert.equal((await group.locator(".speed .v").textContent()).trim(), w.s(106));
assert.match(await group.locator(".speed").getAttribute("title"), w.rule);
// the Usage page's requests: each row, its tooltip, and the period's
@@ -126,8 +137,11 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal((await cell(1).textContent()).trim(), w.s(100));
assert.equal((await cell(2).textContent()).trim(), "—");
assert.equal((await cell(3).textContent()).trim(), w.s(100));
assert.equal((await cell(4).textContent()).trim(), w.s(107));
assert.equal((await cell(5).textContent()).trim(), "—");
assert.equal((await cell(6).textContent()).trim(), "—");
const kpi = page.locator("#ledKpi .blk").nth(4);
assert.equal((await kpi.locator(".v").textContent()).trim(), w.s(105));
assert.equal((await kpi.locator(".v").textContent()).trim(), w.s(106));
assert.match(await kpi.getAttribute("title") || await kpi.locator("[title]").first().getAttribute("title"), w.rule);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, "no sideways scroll");
assert.deepEqual(errors, []);
+6
View File
@@ -83,6 +83,12 @@ func (e *otelExporter) traces(records []Record) any {
otelInt("gen_ai.usage.input_tokens", int64(r.Input+r.CacheRead+r.CacheWrite)), otelInt("gen_ai.usage.output_tokens", int64(r.Output)),
otelInt("gen_ai.usage.cache_read.input_tokens", int64(r.CacheRead)), otelInt("gen_ai.usage.cache_creation.input_tokens", int64(r.CacheWrite)),
otelInt("gen_ai.usage.reasoning.output_tokens", int64(r.Reasoning)), otelInt("magpie.ttft_ms", r.TTFT), otelInt("magpie.first_text_ms", r.FirstText))
if r.FirstReasoning > 0 {
a = append(a, otelInt("magpie.first_reasoning_ms", r.FirstReasoning))
}
if r.ReasoningHidden {
a = append(a, otelInt("magpie.reasoning_hidden", 1))
}
if r.RouteID != 0 {
a = append(a, otelInt("magpie.route.id", r.RouteID))
}
@@ -0,0 +1,72 @@
package usage
import (
"testing"
"time"
)
func TestVisibleReasoningSpeed(t *testing.T) {
visible := Record{Time: time.Now(), Output: 1500, Reasoning: 1400, Millis: 15000, TTFT: 1000, FirstReasoning: 1000, Flow: 12000, Status: 200}
for _, c := range []struct {
name string
r Record
n int
w int64
}{
{"visible tool turn", visible, 1500, 14000},
{"answer remains separate", func() Record { r := visible; r.FirstText = 14000; r.Flow = 1000; return r }(), 100, 1000},
{"hidden and old records", func() Record { r := visible; r.FirstReasoning = 0; return r }(), 0, 0},
{"unknown flow", func() Record { r := visible; r.Flow = 0; return r }(), 0, 0},
{"held reasoning at quarter boundary", func() Record { r := visible; r.Flow = 3500; return r }(), 1500, 14000},
{"held reasoning just below quarter", func() Record { r := visible; r.Flow = 3499; return r }(), 0, 0},
{"held reasoning", func() Record { r := visible; r.Flow = 1000; return r }(), 0, 0},
{"invalid count", func() Record { r := visible; r.Reasoning = 1600; return r }(), 0, 0},
{"below decode minimum", Record{Output: 10, Reasoning: 5, Millis: 1099, TTFT: 1000, FirstReasoning: 1000, Flow: 99}, 0, 0},
{"at decode minimum", Record{Output: 10, Reasoning: 5, Millis: 1100, TTFT: 1000, FirstReasoning: 1000, Flow: 100}, 10, 100},
{"above max speed", Record{Output: 1001, Reasoning: 5, Millis: 1100, TTFT: 1000, FirstReasoning: 1000, Flow: 100}, 0, 0},
{"at max speed", Record{Output: 1000, Reasoning: 5, Millis: 1100, TTFT: 1000, FirstReasoning: 1000, Flow: 100}, 1000, 100},
{"redacted with no reasoning count", Record{Output: 120, Millis: 9000, TTFT: 1000, Flow: 7000, ReasoningHidden: true}, 0, 0},
{"late hidden think", Record{Output: 1500, Reasoning: 1400, Millis: 9000, TTFT: 8000, Flow: 900}, 0, 0},
} {
t.Run(c.name, func(t *testing.T) {
if n, w := c.r.Decode(); n != c.n || w != c.w {
t.Fatalf("speed counted %d tokens/%d ms; want %d/%d", n, w, c.n, c.w)
}
})
}
var chunk rowChunk
for i := 0; i < 80; i++ {
chunk.add(Row{Record: visible}, "", int64(i), false)
}
packed := chunk.pack()
if len(packed.Archive) == 0 {
t.Fatal("snapshot not compressed")
}
for _, c := range []*rowChunk{&chunk, packed.unpack()} {
row := c.row(0)
if n, w := row.Decode(); row.FirstReasoning != 1000 || n != 1500 || w != 14000 {
t.Fatalf("cache lost streamed reasoning: %+v", row)
}
}
sealed := visible
sealed.ReasoningHidden = true
var hiddenChunk rowChunk
for i := 0; i < 80; i++ {
hiddenChunk.add(Row{Record: sealed}, "", int64(i), false)
}
for _, c := range []*rowChunk{&hiddenChunk, hiddenChunk.pack().unpack()} {
row := c.row(0)
n, w := row.Decode()
if !row.ReasoningHidden || n != 0 || w != 0 {
t.Fatal("cache lost hidden reasoning flag")
}
}
var sum Totals
sum.addRow(Row{Record: visible})
hidden := visible
hidden.FirstReasoning = 0
sum.addRow(Row{Record: hidden})
if sum.DecodeOut != 1500 || sum.DecodeMs != 14000 {
t.Fatalf("hidden reasoning lifted aggregate: %+v", sum)
}
}
+13 -5
View File
@@ -65,7 +65,7 @@ type packedRow struct {
Text [30]uint32
Tokens [6]int64
Millis, TTFT, FirstText, Order int64
Sent, Flow int64
Sent, Flow, FirstReasoning int64
Own, Retried, Queued int64
RouteID int64
Cost float64
@@ -73,8 +73,13 @@ type packedRow struct {
Flags uint16
}
// rowHandedOn is the Flags bit of Record.HandedOn
const rowHandedOn = 128
// rowHandedOn is the Flags bit of Record.HandedOn, rowReasoningHidden
// Record.ReasoningHidden's: 64 is block_price.go's swapKnown, 256
// rowOwnCost
const (
rowHandedOn = 128
rowReasoningHidden = 512
)
// rowOwnCost marks a reported call that said what it cost (#1874): Cost is
// that, which the block pricer keeps, and reading the row back gives
@@ -121,7 +126,7 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
c.Bytes += int64(len(s) + 48)
return id
}
p := packedRow{Time: r.Time, Tokens: [6]int64{int64(r.Input), int64(r.Output), int64(r.CacheRead), int64(r.CacheWrite), int64(r.Reasoning), int64(r.CacheWrite1h)}, Millis: r.Millis, TTFT: r.TTFT, FirstText: r.FirstText, Sent: r.Sent, Flow: r.Flow, Own: r.Own, Retried: r.Retried, Queued: r.Queued, Order: order, RouteID: r.RouteID, Cost: r.Cost, Status: int32(r.Status), Tries: int32(r.Tries)}
p := packedRow{Time: r.Time, Tokens: [6]int64{int64(r.Input), int64(r.Output), int64(r.CacheRead), int64(r.CacheWrite), int64(r.Reasoning), int64(r.CacheWrite1h)}, Millis: r.Millis, TTFT: r.TTFT, FirstText: r.FirstText, FirstReasoning: r.FirstReasoning, Sent: r.Sent, Flow: r.Flow, Own: r.Own, Retried: r.Retried, Queued: r.Queued, Order: order, RouteID: r.RouteID, Cost: r.Cost, Status: int32(r.Status), Tries: int32(r.Tries)}
for i, s := range rowText(&r) {
p.Text[i] = intern(*s)
}
@@ -138,6 +143,9 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
if r.SessionOfficialLogin {
p.Flags |= 8
}
if r.ReasoningHidden {
p.Flags |= rowReasoningHidden
}
if r.Routed {
p.Flags |= 32
}
@@ -160,7 +168,7 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
}
func (c *rowChunk) row(i int) Row {
p := &c.Rows[i]
r := Row{Record: Record{RouteID: p.RouteID, Time: p.Time, Input: int(p.Tokens[0]), Output: int(p.Tokens[1]), CacheRead: int(p.Tokens[2]), CacheWrite: int(p.Tokens[3]), CacheWrite1h: int(p.Tokens[5]), Reasoning: int(p.Tokens[4]), Millis: p.Millis, TTFT: p.TTFT, FirstText: p.FirstText, Sent: p.Sent, Flow: p.Flow, Own: p.Own, Retried: p.Retried, Queued: p.Queued, Status: int(p.Status), Tries: int(p.Tries), HandedOn: p.Flags&rowHandedOn != 0, Rejected: p.Flags&4 != 0, SessionOfficialLogin: p.Flags&8 != 0}, Cost: p.Cost, Priced: p.Flags&1 != 0, Swapped: p.Flags&2 != 0, Routed: p.Flags&32 != 0}
r := Row{Record: Record{RouteID: p.RouteID, Time: p.Time, Input: int(p.Tokens[0]), Output: int(p.Tokens[1]), CacheRead: int(p.Tokens[2]), CacheWrite: int(p.Tokens[3]), CacheWrite1h: int(p.Tokens[5]), Reasoning: int(p.Tokens[4]), Millis: p.Millis, TTFT: p.TTFT, FirstText: p.FirstText, FirstReasoning: p.FirstReasoning, ReasoningHidden: p.Flags&rowReasoningHidden != 0, Sent: p.Sent, Flow: p.Flow, Own: p.Own, Retried: p.Retried, Queued: p.Queued, Status: int(p.Status), Tries: int(p.Tries), HandedOn: p.Flags&rowHandedOn != 0, Rejected: p.Flags&4 != 0, SessionOfficialLogin: p.Flags&8 != 0}, Cost: p.Cost, Priced: p.Flags&1 != 0, Swapped: p.Flags&2 != 0, Routed: p.Flags&32 != 0}
for i, s := range rowText(&r) {
*s = c.Strings[p.Text[i]]
}
+2 -1
View File
@@ -55,7 +55,7 @@ func (c *rowChunk) pack() *rowChunk {
for _, n := range p.Tokens {
put(uint64(n))
}
for _, n := range []int64{p.Millis, p.TTFT, p.FirstText, p.Order, p.RouteID, p.Sent, p.Flow, p.Own, p.Retried, p.Queued} {
for _, n := range []int64{p.Millis, p.TTFT, p.FirstText, p.Order, p.RouteID, p.Sent, p.Flow, p.Own, p.Retried, p.Queued, p.FirstReasoning} {
put(uint64(n))
}
put(math.Float64bits(p.Cost))
@@ -154,6 +154,7 @@ func (c *rowChunk) unpackInto(into []packedRow) *rowChunk {
p.RouteID = int64(take())
p.Sent, p.Flow = int64(take()), int64(take())
p.Own, p.Retried, p.Queued = int64(take()), int64(take()), int64(take())
p.FirstReasoning = int64(take())
p.Cost, p.Status, p.Flags = math.Float64frombits(take()), int32(take()), uint16(take())
p.Tries = int32(take())
}
+19 -5
View File
@@ -83,6 +83,9 @@ type Record struct {
// none for a reply that wasn't streamed (#196)
TTFT int64 `json:"ttft_ms,omitempty"`
FirstText int64 `json:"first_text_ms,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"`
// 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
@@ -464,7 +467,9 @@ func DecodeWindow(out int, ms, ttft int64) int64 {
// written before the first content, over time the window from it doesn't
// hold, and counting them read a 2,000-token think and a 200-token answer
// in 1.5 s as 1,467 tok/s. Its time goes to the wait before the answer.
// One with reasoning and no text (all tool calls) tells no speed. The
// With no answer text, paced visible reasoning can time all output from
// firstReasoning. Missing evidence (including older records), hidden reasoning
// and an unknown flow leave the speed untold. The
// window is DecodeWindow's: 0 for a reply that tells none.
//
// A reply its vendor held back and let go in a burst at its end tells
@@ -488,10 +493,16 @@ func DecodeWindow(out int, ms, ttft int64) int64 {
// reasoning hidden from the stream (OpenAI's, Claude's omitted) comes
// before the first content and leaves this time short; one that
// streams comes at the pace its answer does.
func DecodeOf(out, reasoning int, ms, ttft, firstText, flow int64) (tokens int, w int64) {
func DecodeOf(out, reasoning int, ms, ttft, firstText, flow int64, firstReasoning ...int64) (tokens int, w int64) {
start := ttft
if reasoning > 0 {
out, start = out-reasoning, firstText
if firstText > 0 {
out, start = out-reasoning, firstText
} else if len(firstReasoning) > 0 && firstReasoning[0] >= ttft && flow > 0 && reasoning <= out {
start = firstReasoning[0]
} else {
return 0, 0
}
}
if ttft <= 0 {
return 0, 0
@@ -502,7 +513,7 @@ func DecodeOf(out, reasoning int, ms, ttft, firstText, flow int64) (tokens int,
if flow > 0 && flow*HeldShare < w {
return 0, 0
}
if reasoning > 0 && int64(out)*(firstText-ttft) > ThinkPace*int64(reasoning)*w {
if reasoning > 0 && firstText > 0 && int64(out)*(firstText-ttft) > ThinkPace*int64(reasoning)*w {
return 0, 0
}
return out, w
@@ -519,7 +530,10 @@ const (
// Decode is the record's DecodeOf.
func (r Record) Decode() (tokens int, w int64) {
return DecodeOf(r.Output, r.Reasoning, r.Millis, r.TTFT, r.FirstText, r.Flow)
if r.ReasoningHidden && r.FirstText <= 0 {
return 0, 0
}
return DecodeOf(r.Output, r.Reasoning, r.Millis, r.TTFT, r.FirstText, r.Flow, r.FirstReasoning)
}
// FormatCost renders an effective-price cost, kept in USD everywhere it's