Files
magpie/internal/gateway/upbytes.go
T
yetone 925bc7188b usage: the Requests card's up arrow opens what the bytes sent upstream were made of
theforeveriris (X, 2121408745616162998) saw 8169 requests send 8.6 GB
up and 1.0 GB down and wanted to know why. About 1 MB a request is
normal: every request sends the whole conversation again, with the
system prompt and the tools' definitions. This shows it.

Gateway: promptOf, which already parses the body off the request path,
now also counts the bytes of the system prompt, the tool definitions
and images in the body it read. upParts scales those to the wire bytes
and puts them on Record.UpParts. Nothing new runs on the request path,
and a body that isn't parsed stays "Not measured".

Usage: a packed row keeps the mix in 255ths under flag rowUpParts
(32768); the row stays 152 bytes. Totals gain up_calls, up_measured,
up_system, up_tools and up_images, and Shares carry up_bytes and
up_calls by agent and by model. settledCountVersion goes 4 -> 5, so
settled days are counted again once on the next start.

GUI (Usage -> Requests): the "↑ 8.6 GB" on the Requests card is a
button that opens a "Sent upstream" card: the average per request, one
sentence on why, a bar and legend for Conversation / Tool definitions /
System prompt / Images / Not measured, and the top 8 agents and models
with bytes sent and per request. The open state is kept; × closes it.
A request's details get a "Made of" line. zh, zh-TW, ja, de strings.
Entrance is 200ms ease-out, no movement under reduced motion.

Run (mote, at this head on 27e43ed26):
- go test ./internal/usage ./internal/usageapi: ok
- go test -run 'Prompt|UpParts|UpBytes|DownBytes|Traffic|Ledger|
  CodexOwnTurn' ./internal/gateway: ok
- go test -run Budget ./internal/gui: ok (after the rebase)
- go vet -tags nogui for darwin, linux, windows on usage, gateway,
  usageapi, gui: ok; gofmt -l clean
- GUI: usage-upload.test.cjs 32/32 (chromium + webkit, 1180 and 420,
  en zh zh-TW ja de); with i18n-keys, i18n-en-no-cjk,
  usage-ledger-bytes, usage-traffic, usage-ledger-detail: 144 pass,
  0 fail
- GUI subset i18n*, usage*, ledger* at f1f34d624: the only reds are
  usage-agents-hide, usage-cards-hide, usage-fold,
  usage-hidden-way-back, usage-ledger, usage-range-times and
  usage-speed-all-models. They are red the same way on origin/main
  f1f34d624 without this change and are already filed (#3414, #3415,
  #6003, #6294, #6295, #6499, #5834).
- Screenshots of the card: chromium en 1180 light, webkit zh 1180
  dark, chromium zh 420 light.
- Benchmark: promptOf on a 1.17 MB body, 2.8-3.9 ms/op with counting
  vs 3.2-3.7 without, same allocations (noise).
- Broken by hand: without the b.again guard,
  TestPromptKnowsWhatItsBytesWere goes red.

Not run: the full go test ./... and the full GUI suite. mote and mica
were loaded, with a suite already queued under suite.lock.
2026-11-14 10:22:25 +08:00

191 lines
6.6 KiB
Go

package gateway
import (
"context"
"io"
"net/http"
"sync/atomic"
"github.com/yetone/magpie/internal/usage"
)
// upBytes is what a request's tries sent up to the vendor, kept in the
// request's context as a tool call's mcpUse is: forwardOnce adds a try's
// bytes where it already has them (sent), and the request's ledger row
// reads the sum, so the row says what a session's upstream traffic was
// and a hand-on's re-send stands beside Tries (#4456).
type upBytes struct {
wire int // the bytes that went on the wire, tries summed
plain int // the last try's body before compression
// down is the bytes of the vendor's replies read, tries summed: added
// as a body is read, which can be on another goroutine than the
// request's (a stream's pump), so atomic
down atomic.Int64
// saved is what DeepSeek's image files kept out of the tries' bodies,
// less what uploading them cost this request (withDeepSeekFiles)
saved int
// images is how many inline images went by file instead, the most of
// any one try: a retry sends the same ones again
images int
// last is what sentUp last counted, the try's body as HTTP sends it;
// socket says that try went over the Responses WebSocket instead
// (overSocket), which counted what it was sent in its place
last int
socket bool
// ws is what the socket was written for that try so far (wroteSocket)
ws int
// tally is the gateway's own count of every request's bytes, which
// each try's are added to as they are to this row's (Traffic)
tally *traffic
}
// traffic is what all of a gateway's requests sent up to their vendors and
// read back, since it started: the bytes their ledger rows sum, counted as
// they go, so a request still streaming is in it already. Read twice a
// moment apart, it is how fast the gateway's upstream traffic flows now.
type traffic struct{ up, down atomic.Int64 }
// Traffic is a gateway's bytes up and down so far (traffic).
type Traffic struct {
Up int64 `json:"up"`
Down int64 `json:"down"`
}
// Traffic says how many bytes the gateway's requests have sent up to their
// vendors and read back since it started, tries and streams included.
func (s *Server) Traffic() Traffic {
return Traffic{Up: s.traffic.up.Load(), Down: s.traffic.down.Load()}
}
// countBytes is the context a request's tries add their bytes in (upBytes),
// each also added to the gateway's own count (Traffic).
func (s *Server) countBytes(ctx context.Context) context.Context {
return context.WithValue(ctx, upBytesKey{}, &upBytes{tally: &s.traffic})
}
// addUp adds n bytes sent up to the row's and to the gateway's count.
func (u *upBytes) addUp(n int) {
u.wire += n
u.tallyUp(n)
}
// tallyUp adds n bytes sent up to the gateway's count alone (Traffic).
func (u *upBytes) tallyUp(n int) {
if u.tally != nil && n != 0 {
u.tally.up.Add(int64(n))
}
}
type upBytesKey struct{}
func upBytesOf(ctx context.Context) *upBytes {
u, _ := ctx.Value(upBytesKey{}).(*upBytes)
return u
}
// sentUp is that a try went to the vendor: wire the bytes it sent
// (len(body), or what CodexCompressed left on req), plain the body before
// that. Read and written on the request's own goroutine — the ledger row
// is assembled after the last try came back — so no lock.
func sentUp(ctx context.Context, wire, plain int) {
if u := upBytesOf(ctx); u != nil {
u.addUp(wire)
u.plain = plain
u.last, u.socket, u.ws = wire, false, 0
}
}
// wroteSocket counts a message the Responses WebSocket was sent for the
// try sentUp last counted: a kept socket's delta, or the whole turn on a
// new one.
func wroteSocket(ctx context.Context, n int) {
if u := upBytesOf(ctx); u != nil {
u.ws += n
u.tallyUp(n)
}
}
// toSocket is that the try sentUp last counted goes to the Responses
// WebSocket, which writes its own messages (wroteSocket) in place of the
// HTTP body: the gateway's count (Traffic) takes that body back at once,
// so a kept socket's turn isn't a burst of the whole conversation in the
// live rate, and gives it again if the turn goes over HTTP after all
// (toHTTP). The row's own sum is settled once, at the end (sentOnSocket).
func toSocket(ctx context.Context) {
if u := upBytesOf(ctx); u != nil {
u.tallyUp(-u.last)
}
}
// toHTTP is that a try toSocket took goes over HTTP after all.
func toHTTP(ctx context.Context) {
if u := upBytesOf(ctx); u != nil {
u.tallyUp(u.last)
}
}
// sentOnSocket settles that try once the socket is done with it. A turn
// the socket answered (only) sent what the socket was written, not the
// body sentUp counted: #5781's matrix0487 saw 13 MB a row while a kept
// socket was sent the new input alone. One that went over HTTP after
// all sent both.
func sentOnSocket(ctx context.Context, only bool) {
u := upBytesOf(ctx)
if u == nil {
return
}
if only {
u.wire += u.ws - u.last
u.last = u.ws
} else {
u.wire += u.ws
u.last += u.ws
}
u.socket, u.ws = only, 0
}
// gotDown counts res's body for the request's ledger row as it is read
// (upBytes.down), and gives res back. A body is counted as Go's client
// hands it over: after the transport undid a gzip it asked for, so a
// gzipped reply counts more than its wire bytes. A 101's body is the
// connection itself and is left as it is.
func gotDown(ctx context.Context, res *http.Response) *http.Response {
u := upBytesOf(ctx)
if u == nil || res == nil || res.Body == nil || res.Body == http.NoBody || res.StatusCode == http.StatusSwitchingProtocols {
return res
}
res.Body = &downCount{ReadCloser: res.Body, u: u}
return res
}
type downCount struct {
io.ReadCloser
u *upBytes
}
func (d *downCount) Read(b []byte) (int, error) {
n, err := d.ReadCloser.Read(b)
d.u.down.Add(int64(n))
if d.u.tally != nil {
d.u.tally.down.Add(int64(n))
}
return n, err
}
// downOf is the reply bytes counted so far (upBytes.down).
func (u *upBytes) downOf() int { return int(u.down.Load()) }
// upParts is what a request's bytes up were made of (usage.UpParts): the
// parts of the body the prompt was read from, each scaled to what went on
// the wire, so a compressed or retried request's parts sum to its bytes
// as its whole does. None when the body wasn't read (p nil), nothing
// went, the last try went over a kept socket (its bytes a delta, not the
// body) or images went by file (the bytes no longer the body's).
func upParts(p *Prompt, u *upBytes) *usage.UpParts {
if p == nil || u == nil || u.wire <= 0 || u.socket || u.images > 0 || p.sent.all <= 0 {
return nil
}
of := func(n int) int { return int(int64(n) * int64(u.wire) / int64(p.sent.all)) }
return &usage.UpParts{System: of(p.sent.system), Tools: of(p.sent.tools), Images: of(p.sent.images)}
}