Files
magpie/internal/gateway/live.go
T
yetoneandCanda15 0f1b40bbc4 gateway: a reply in flight shows on Routing how much has arrived and roughly its tokens (#4951, Canda15)
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/main 7dd2434d3 run
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 onto 38f4f74e6 (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>
2026-11-04 19:39:08 +08:00

160 lines
4.4 KiB
Go

package gateway
import (
"sync"
"time"
"github.com/yetone/magpie/internal/provider"
)
// liveRow counts a reply as the gateway writes it to the agent, for the
// Routing page to show while it is out (#4951, Canda15): how many bytes
// the agent has had, when the model last wrote content, and what that
// content is worth in output tokens. A reply mid-reasoning or a long one
// otherwise looks stuck. It counts and drops: no byte is kept or changed.
//
// captureResponseWriter.Write, which every byte to the agent passes,
// calls observe; it may be called from a held stream's keepalive and the
// try's goroutine in turn, so everything is under mu, which nothing that
// blocks is called under.
type liveRow struct {
mu sync.Mutex
// bytes is every byte written to the agent, SSE framing and the
// gateway's own keepalive comments included
bytes int64
// contentAt is the epoch ms of the last write that was not only SSE
// comments: a keepalive never moves it, so a stuck reply shows still
contentAt int64
// provider and model are the try's that answers (routed), whose
// learned rate estimates the tokens
provider, model string
counter liveContentCounter
ended bool
f *inflight
// tr: f's trace, nil when its routes are in none
tr *trace
}
// liveBegin starts counting f's reply, from is the agent's protocol, which
// decides what its content is. A request not counted in flight (the
// gateway's own) has no route to tell, and is not counted.
func liveBegin(f *inflight, model string, from provider.Protocol) *liveRow {
if f == nil {
return nil
}
f.mu.Lock()
tr := f.tr
f.mu.Unlock()
l := &liveRow{f: f, tr: tr, model: model, counter: liveContentCounter{proto: from}}
f.live.Store(l)
return l
}
// liveOfInflight is f's counter, nil when there is none.
func liveOfInflight(f *inflight) *liveRow {
if f == nil {
return nil
}
return f.live.Load()
}
// observe counts one write to the agent and tells its route.
func (l *liveRow) observe(p []byte) {
if l == nil || len(p) == 0 {
return
}
l.mu.Lock()
l.bytes += int64(len(p))
if !commentOnly(p) {
l.contentAt = time.Now().UnixMilli()
}
l.counter.add(p)
bytes, contentAt, content := l.bytes, l.contentAt, l.counter.total
provider, model := l.provider, l.model
l.mu.Unlock()
l.tell(bytes, contentAt, provider, model, content)
}
// tell writes the running totals on the request's route, the first one
// begun for it (noteRoute); before it is begun a later write tells it,
// the numbers being totals.
func (l *liveRow) tell(bytes, contentAt int64, provider, model string, content int64) {
if l.tr == nil {
return
}
rt := l.f.route.Load()
if rt == nil {
return
}
l.tr.liveBytes(rt, bytes, contentAt, liveRates.estimate(provider, model, content))
}
// commentOnly reports whether p holds SSE comment lines and blank lines
// only, at least one comment: the gateway's keepalive. It allocates
// nothing, as it runs on every write.
func commentOnly(p []byte) bool {
saw, start := false, true
for _, c := range p {
switch {
case c == '\n':
start = true
case c == '\r' && start:
case start:
if c != ':' {
return false
}
saw, start = true, false
}
}
return saw
}
// totals are the row's bytes, content bytes and last content time.
func (l *liveRow) totals() (bytes, content, contentAt int64) {
if l == nil {
return 0, 0, 0
}
l.mu.Lock()
defer l.mu.Unlock()
return l.bytes, l.counter.total, l.contentAt
}
// routed names the provider and model of the try about to answer: after a
// fallback it is another than the first.
func (l *liveRow) routed(provider, model string) {
if l == nil {
return
}
l.mu.Lock()
l.provider = provider
if model != "" {
l.model = model
}
l.mu.Unlock()
}
// finish ends the count once: the last event still in the buffer is
// counted, and a streamed reply that did not fail and whose vendor said
// its output tokens is learned from. An agent that went away after the
// last content still makes a sample, the usage in hand saying the vendor
// finished the reply.
func (l *liveRow) finish(failed bool, output int) {
if l == nil {
return
}
l.mu.Lock()
if l.ended {
l.mu.Unlock()
return
}
l.ended = true
l.counter.flush()
sse, content := l.counter.sse, l.counter.total
bytes, contentAt, provider, model := l.bytes, l.contentAt, l.provider, l.model
l.mu.Unlock()
if sse && !failed && output > 0 {
liveRates.learn(provider, model, content, output)
}
l.tell(bytes, contentAt, provider, model, content)
}