Files
magpie/internal/gateway/capture.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

187 lines
4.7 KiB
Go

package gateway
import (
"bytes"
"io"
"net/http"
"os"
"github.com/yetone/magpie/internal/redact"
"github.com/yetone/magpie/internal/usage"
)
// Recent-call bodies are diagnostics, not an unbounded traffic log. Keeping the
// first 256 KiB is enough to inspect ordinary prompts and responses while
// preventing images or long streams from multiplying into tens of MiB across
// 40 calls.
const callBodyLimit = 256 << 10
// wholeBodyLimit asks a spool for every byte it is given, for a body the OTLP
// export wants uncut (#538).
const wholeBodyLimit = -1
type capturedBody struct {
buf bytes.Buffer
truncated bool
}
func (c *capturedBody) add(p []byte) {
if c.buf.Len() >= callBodyLimit {
c.truncated = c.truncated || len(p) > 0
return
}
n := min(len(p), callBodyLimit-c.buf.Len())
_, _ = c.buf.Write(p[:n])
if n < len(p) {
c.truncated = true
}
}
func (c *capturedBody) text() string { return c.buf.String() }
// captureRequestBody is a request's first callBodyLimit bytes, copied once:
// through a capturedBody it was copied into a buffer and then again into
// its string, 512 KiB for every request of 256 KiB or more.
func captureRequestBody(p []byte) (string, bool) {
return string(p[:min(len(p), callBodyLimit)]), len(p) > callBodyLimit
}
type captureResponseWriter struct {
http.ResponseWriter
body capturedBody
// full: the whole body, for the request archive, when it is on
full *spool
// whole: the whole body, for an observer that asks for it uncut (#538)
whole *spool
// tools: whether the reply calls a tool, for a turn's end (turns)
tools *toolScan
// live: the reply counted for the Routing page while it is out
// (live.go), nil when it isn't
live *liveRow
}
func (w *captureResponseWriter) Write(p []byte) (int, error) {
w.live.observe(p)
w.body.add(p)
w.tools.add(p)
if w.full != nil {
w.full.add(p)
}
if w.whole != nil {
w.whole.add(p)
}
return w.ResponseWriter.Write(p)
}
// spool keeps a body whole for the request archive, beyond the first 256
// KiB Recent calls holds: in a temporary file, not in memory, up to limit
// bytes; past that only its size is counted. A negative limit keeps every
// byte (#538). A file that can't be written leaves what was kept so far, cut.
type spool struct {
pattern string // empty uses the request archive
f *os.File
limit, kept int64
size int64 // every byte that came, kept or not
failed bool
}
func (s *spool) add(p []byte) {
s.size += int64(len(p))
if s.failed || (s.limit >= 0 && s.kept >= s.limit) || len(p) == 0 {
return
}
if s.f == nil {
pattern := s.pattern
if pattern == "" {
pattern = "magpie-archive-*"
}
f, err := os.CreateTemp("", pattern)
if err != nil {
s.failed = true
return
}
s.f = f
}
n := int64(len(p))
if s.limit >= 0 {
n = min(n, s.limit-s.kept)
}
if _, err := s.f.Write(p[:n]); err != nil {
s.failed = true
return
}
s.kept += n
}
// cut is whether less than the whole body was kept.
func (s *spool) cut() bool { return s.kept < s.size }
// read is what was kept, the file gone after.
func (s *spool) read() ([]byte, error) {
if s.f == nil {
return nil, nil
}
defer s.discard()
if _, err := s.f.Seek(0, io.SeekStart); err != nil {
return nil, err
}
return io.ReadAll(io.LimitReader(s.f, s.kept))
}
// discard removes the file: nothing is kept.
func (s *spool) discard() {
if s.f != nil {
s.f.Close()
os.Remove(s.f.Name())
s.f = nil
}
}
func (w *captureResponseWriter) Flush() {
if f, ok := w.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}
// withBodies hands a call's captured request and reply to its usage
// record while an observer wants them (the OTLP export's bodies, #538) —
// their secrets scrubbed as the request archive's are, on top of the
// placeholders Mask secrets puts in — and leaves the record without them
// otherwise. A call captured whole (usage.WholeBodies) carries them in
// wholeIn/wholeOut; otherwise the first 256 KiB Recent calls keeps is what
// goes.
func withBodies(rec *usage.Record, c *Call) {
if usage.ObservedBodies() == usage.NoBodies {
return
}
in, inCut := c.RequestBody, c.RequestTruncated
if c.wholeIn != nil {
in, inCut = string(c.wholeIn), c.wholeInCut
}
if c.maskIn != nil {
if m := c.maskIn.body(); c.wholeIn != nil {
in = string(m)
} else {
in, inCut = captureRequestBody(m)
}
}
out, outCut := c.ResponseBody, c.ResponseTruncated
if c.wholeOut != nil {
out, outCut = string(c.wholeOut), c.wholeOutCut
}
rec.BodyIn = bodyForExport(in, inCut)
rec.BodyOut = bodyForExport(out, outCut)
}
func bodyForExport(body string, cut bool) string {
if body == "" {
return ""
}
body = string(redact.ScrubJSON([]byte(body)))
if cut {
body += usage.BodyCut
}
return body
}