A long or reasoning reply looked stuck on the Routing page. A request still out now shows, on its row and beside the account answering it, the bytes the agent has had, "≈ n tokens" once a rate is learned, and how long ago content last came; after 15s with no content the account's dot stops pulsing. Nothing stays once the request is done. Ported from Canda15's 7f7bdb189 (github.com/Canda15/magpie), the idea and the per-protocol content extractors kept, the hot path and storage reworked: - every write to the agent passes captureResponseWriter.Write, which calls liveRow.observe; the row hangs on the request's inflight (an atomic pointer), not a context value made per request - rates are in memory only (256 pairs); the fork wrote a JSON file under the estimate lock on every finished request - a whole JSON reply is counted in bytes only: the fork held and decoded up to 8 MiB of it at the end; a stream is cut into lines in place, only a line cut by a write's end is copied, a line over 1 MiB passed over, and each event decoded once (the fork ran json.Valid then Unmarshal) - the reply's kind comes from its first byte, not a header read on every write; the keepalive check allocates nothing (the fork split each write) - everything a row counts is under its own lock, and inflight.tr is read under f.mu; the estimate is in float64 (the int64 product overflowed) - the route's Seq is bumped on every write and traceGather batches the wake-ups; the fork's global throttle could drop the last update before a pause - learned only from a streamed reply that did not fail and had the vendor's output tokens - left out: the finished row's "Received" metric and the ended caption (layout restraint; an ended row has its own metrics), a duplicate "Received" i18n key, the receive-monitor doc (the design is in gateway-routing.md now), the fork's xmod and Windows CI commits The Routing plugin and i18n.js are outside TestCoreScriptBudget. Run on mote at this head unless named: gofmt -l; go vet (darwin), GOOS=linux -tags nogui and GOOS=windows go vet ./...; go build ./...; go test -race on the live tests; go test ./internal/gateway ./internal/gui (gateway ok; gui red only on TestCoreScriptBudget, #5139, 1533907 > 1533802 before this change and untouched by it, and TestMainWindowCorners/macOS_26_SDK, #3949); routing-live-bytes.test.cjs and i18n-keys in Chromium and WebKit, en/zh/zh-TW/ja/de, 1100 and 420px (24/24); every routing-* and panel-routing* GUI file with i18n-keys in WSL Linux (Chromium all green; WebKit reds in 12 files, the same class at origin/main7dd2434d3run the same way: 25 there, 28 here, the sets differing by timing samples; routing-live-patch alone red 2 of 3 on main, 1 of 3 here; filed as #4121, #4520, #5156, #2174). Rebased onto38f4f74e6(gateway.go, trace.go and the Routing plugin moved): build, gateway vet, the live tests, routing-live-bytes and i18n-keys run again there, green (24/24). Broken by hand, each red, then put back: - no observe in capture.Write: TestLiveCountsARealStream - commentOnly never true: TestLiveHeartbeatIsBytesNotContent, TestCommentOnlyTellsHeartbeatsApart - learning from failed replies: TestRatesLearnFromRepliesTheVendorFinished - a whole reply read as a stream: TestContentCounterLeavesAWholeReply - no Seq bump in liveBytes: TestLiveWritesReachTheRoute - no quiet class, no per-second repaint: routing-live-bytes 0/20 Not tried: a real vendor's stream in the running app; the ChatGPT backend chain (codex_backend.go) writes past the capture writer and isn't counted; the full Go and GUI suites run after the tag. Co-authored-by: Canda15 <124772373+Canda15@users.noreply.github.com>
134 lines
3.9 KiB
Go
134 lines
3.9 KiB
Go
package gateway
|
|
|
|
import (
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// routeMoment reads what a request's route says now: the bytes received
|
|
// and when content last came, under the trace's lock the gateway writes
|
|
// them under.
|
|
func routeMoment(s *Server, model string) (bytes, contentAt int64, found bool) {
|
|
s.trace.mu.Lock()
|
|
defer s.trace.mu.Unlock()
|
|
for _, rt := range s.trace.routes {
|
|
if rt.Model == model {
|
|
return rt.Bytes, rt.ContentAt, true
|
|
}
|
|
}
|
|
return 0, 0, false
|
|
}
|
|
|
|
// A real request through the whole gateway, its vendor streaming slowly:
|
|
// while it is out its route has the bytes the client has had, once it
|
|
// ends exactly the bytes the client received, and the provider and model
|
|
// that answered have learned from it.
|
|
func TestLiveCountsARealStream(t *testing.T) {
|
|
freshRates(t)
|
|
chunks := []string{
|
|
"data: {\"choices\":[{\"delta\":{\"content\":\"one\"}}]}\n\n",
|
|
"data: {\"choices\":[{\"delta\":{\"content\":\"two\"}}]}\n\n",
|
|
"data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":3,\"completion_tokens\":5,\"total_tokens\":8}}\n\n",
|
|
"data: [DONE]\n\n",
|
|
}
|
|
// the vendor stops after the first event until the test has looked
|
|
release := make(chan struct{})
|
|
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("content-type", "text/event-stream")
|
|
w.WriteHeader(http.StatusOK)
|
|
for i, c := range chunks {
|
|
if _, err := io.WriteString(w, c); err != nil {
|
|
return
|
|
}
|
|
w.(http.Flusher).Flush()
|
|
if i == 0 {
|
|
<-release
|
|
}
|
|
}
|
|
}))
|
|
defer up.Close()
|
|
defer func() {
|
|
// let the vendor go on a failure half way, or httptest can't close
|
|
select {
|
|
case <-release:
|
|
default:
|
|
close(release)
|
|
}
|
|
}()
|
|
|
|
if err := provider.Save(provider.Provider{ID: "live", Name: "Live", Chat: up.URL + "/v1", Key: "k", Models: []string{"m"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
s := New()
|
|
rec := httptest.NewRecorder()
|
|
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"live/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`))
|
|
req.Header.Set("content-type", "application/json")
|
|
done := make(chan struct{})
|
|
go func() {
|
|
defer close(done)
|
|
s.Handler().ServeHTTP(rec, req)
|
|
}()
|
|
|
|
// wait for the first bytes to reach the client's route
|
|
var midBytes, midContentAt int64
|
|
deadline := time.Now().Add(5 * time.Second)
|
|
for {
|
|
if bytes, contentAt, ok := routeMoment(s, "live/m"); ok && bytes > 0 {
|
|
midBytes, midContentAt = bytes, contentAt
|
|
break
|
|
}
|
|
if time.Now().After(deadline) {
|
|
close(release)
|
|
_, _, found := routeMoment(s, "live/m")
|
|
t.Fatalf("a request whose first bytes arrived has no progress on its route (found=%v)", found)
|
|
}
|
|
time.Sleep(5 * time.Millisecond)
|
|
}
|
|
if midBytes != int64(len(chunks[0])) {
|
|
t.Fatalf("mid-stream bytes are %d, the client got %d", midBytes, len(chunks[0]))
|
|
}
|
|
if midContentAt == 0 {
|
|
t.Fatal("content arrived but the route has no content time")
|
|
}
|
|
|
|
close(release)
|
|
<-done
|
|
|
|
bytes, _, ok := routeMoment(s, "live/m")
|
|
if !ok {
|
|
t.Fatal("the route is gone")
|
|
}
|
|
if want := int64(rec.Body.Len()); bytes != want {
|
|
t.Fatalf("counted %d bytes, the client received %d", bytes, want)
|
|
}
|
|
if want := int64(len(strings.Join(chunks, ""))); bytes != want {
|
|
t.Fatalf("counted %d bytes, the upstream wrote %d", bytes, want)
|
|
}
|
|
|
|
s.trace.mu.Lock()
|
|
rt := s.trace.routes[len(s.trace.routes)-1]
|
|
done2, output := rt.Done, rt.Output
|
|
s.trace.mu.Unlock()
|
|
if !done2 {
|
|
t.Fatal("the route is still open after the reply ended")
|
|
}
|
|
// the vendor's 5, not an estimate
|
|
if output != 5 {
|
|
t.Fatalf("the route says %d output tokens, the vendor said 5", output)
|
|
}
|
|
|
|
liveRates.mu.Lock()
|
|
learned := liveRates.m["live/m"]
|
|
liveRates.mu.Unlock()
|
|
if learned.seen != 1 || learned.bytes != 6 || learned.output != 5 {
|
|
t.Fatalf("learned %+v from the reply, want 6 content bytes for 5 tokens", learned)
|
|
}
|
|
}
|