diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index 5aff798d9..581dc6de3 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -772,6 +772,28 @@ a large body shows as a burst. `TestTrafficCountsWhatRowsCount`, `TestUsageTrafficSaysWhatTheGatewayCounted` and `usage-traffic.test.cjs` cover it. +What the bytes up were made of (theforeveriris on X: 8.6 GB up over 8169 +requests). Every request resends the whole conversation, so ~1 MB a request +is a long context, not a leak. The prompt reader (`promptOf`, already run off +the request path by `inspectPrompt`) adds each piece's length as it reads it +into `Prompt.sent`: the system prompt (with skills and memory), the tools' +definitions, images, and everything read (`all`). A tool result shared by the +files it read counts once (`again`). `upParts` scales those to the bytes +that went on the wire into the row's `UpParts`. A row gets none when its +bytes up aren't its body's: a Responses WebSocket delta, a body whose images +went as files, or a body not read. The request page keeps the parts in +255ths of `UpBytes` in the packed row (`upMix`, flag `rowUpParts`, still 152 +bytes). `Totals` sum `UpCalls` (requests that sent any bytes), `UpMeasured` +(the bytes of those with parts) and the three parts, per period and per +agent, model or provider. The Requests card's ↑ opens `#ledUp`. It shows the +bytes a request, a bar of the conversation, tools, system prompt, images and +what wasn't measured, and the bytes of each agent and model. A request's +details say "Made of". `TestPromptKnowsWhatItsBytesWere` (fails if a shared +tool result is counted per file), `TestUpPartsScaleToTheWire`, +`TestLedgerKeepsUpParts`, `TestRowUpPartsKept`, `TestTotalsSumUpParts` and +`usage-upload.test.cjs` cover it. `BenchmarkPromptOfLargeBody` times the +reader on a 1.2 MB body. + ### Calls read from the agents' own files A call an agent made without magpie reaches Usage only when its own files diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 83256f1ac..432c63241 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -1089,8 +1089,9 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st captureTitle := false effort := "" // the reasoning Codex asked for, which goes on as it is end := func(status int, msg string, tokens, out int) {} - var tools *toolScan // whether the reply calls a tool, for a turn's end - var live *liveRow // the reply counted as it reaches Codex (live.go) + var sentPrompt *Prompt // what the body was made of, read at end (upParts) + var tools *toolScan // whether the reply calls a tool, for a turn's end + var live *liveRow // the reply counted as it reaches Codex (live.go) if rest != "/responses" { // no route of its own (a compaction, a memory): recorded alone noteMasked(r, "chat", maskedHits, sentOf(maskedHits, body), 0, "openai", modelOf(body)) @@ -1142,6 +1143,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st replyDigest = titleReplyDigest(titleReply.buf.Bytes(), nil) } prompt := promptRead() // outside the trace's lock, which reading it takes + sentPrompt = prompt s.trace.update(tr, func(t *Route) { // what masking took: magpie's own time isn't split here t.Masking = maskingMs(r.Context(), 0) @@ -1676,6 +1678,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st if up := upBytesOf(r.Context()); up != nil { rec.UpBytes, rec.PlainBytes, rec.Socket = up.wire, up.plain, up.socket rec.DownBytes = up.downOf() + rec.UpParts = upParts(sentPrompt, up) } appendUsage(r, rec) } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index dcc038e81..805ff91d4 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -5626,6 +5626,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if up := upBytesOf(r.Context()); up != nil { rec.UpBytes, rec.PlainBytes, rec.Socket = up.wire, up.plain, up.socket rec.DownBytes, rec.ImageFilesSaved, rec.ImageFiles = up.downOf(), up.saved, up.images + rec.UpParts = upParts(prompt, up) } failedWith(&rec, call.Status, call.Error, call.Usage.ErrType) withBodies(&rec, &call) diff --git a/internal/gateway/prompt.go b/internal/gateway/prompt.go index ce01a67a8..b01fc4437 100644 --- a/internal/gateway/prompt.go +++ b/internal/gateway/prompt.go @@ -52,8 +52,23 @@ type Prompt struct { Held bool `json:"held,omitempty"` Turns int `json:"turns,omitempty"` // the user's turns in it Parts []PromptPart `json:"parts"` + // sent is what the body's bytes were made of (sentSizes), for the + // ledger row's Record.UpParts; never written to the routing history + sent sentSizes } +// sentSizes is a body's bytes by what they were, as the builder read the +// pieces it already had in hand: the agent's own prompt and its +// instructions (system, skills, memory), the tools' definitions, the +// images and documents sent inline, and all it read (the rest is the +// conversation, and the JSON around it). Counting them is a length added +// per piece, no second read of the body (#upload). +type sentSizes struct{ system, tools, images, all int } + +// size is how many bytes a piece took in the body: its raw JSON, its +// text, an image's source, a sealed piece's size. +func (pc *PromptPiece) size() int { return len(pc.raw) + len(pc.img) + len(pc.Text) + pc.Size } + // PromptPart is one kind of what a prompt holds. type PromptPart struct { Kind string `json:"kind"` @@ -111,6 +126,11 @@ type promptBuilder struct { // (itemKey), for PromptText; off when only the sizes are read keep bool pieces map[string][]PromptPiece + // sent: the pieces' bytes by what they were (sentSizes); again off + // while one tool result is shared among the files it read (result), + // so its bytes count once + sent sentSizes + again bool } // PromptPiece is a stretch of an item's text as the request sent it: a @@ -172,6 +192,18 @@ func (b *promptBuilder) add(kind, name, tag string, tokens int, pc PromptPiece) } it.N++ it.Tokens += tokens + if !b.again { + n := pc.size() + b.sent.all += n + switch { + case tag == "image": + b.sent.images += n + case kind == PartSystem || kind == PartSkills || kind == PartMemory: + b.sent.system += n + case kind == PartTools: + b.sent.tools += n + } + } if b.keep { b.pieces[kind+"\x00"+key] = append(b.pieces[kind+"\x00"+key], pc) } @@ -188,7 +220,7 @@ func (b *promptBuilder) chat(tokens int, pc PromptPiece) { func (b *promptBuilder) newTurn() { b.turn++ } func (b *promptBuilder) prompt() *Prompt { - p := &Prompt{Held: b.held, Turns: b.turn, Parts: []PromptPart{}} + p := &Prompt{Held: b.held, Turns: b.turn, Parts: []PromptPart{}, sent: b.sent} for _, kind := range partOrder { m := b.parts[kind] if len(m) == 0 { @@ -611,8 +643,10 @@ func (b *promptBuilder) result(callID string, tokens int, pc PromptPiece) { if !readTools[c.name] { tag = "shell" } + b.again = i > 0 b.add(PartFiles, f, tag, n, pc) } + b.again = false return } b.add(PartResults, c.name, "result", tokens, pc) diff --git a/internal/gateway/upbytes.go b/internal/gateway/upbytes.go index 592d1138e..6525ae571 100644 --- a/internal/gateway/upbytes.go +++ b/internal/gateway/upbytes.go @@ -5,6 +5,8 @@ import ( "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 @@ -172,3 +174,17 @@ func (d *downCount) Read(b []byte) (int, error) { // 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)} +} diff --git a/internal/gateway/upparts_test.go b/internal/gateway/upparts_test.go new file mode 100644 index 000000000..8d66a7c74 --- /dev/null +++ b/internal/gateway/upparts_test.go @@ -0,0 +1,156 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// upPartsBody is a Chat Completions request with every part: a system +// prompt, a tool's definition, an inline image, and a conversation whose +// one tool call read two files, its result shared between them. +func upPartsBody(model string) (body string, system, tool, image, result int) { + sys := strings.Repeat("You are a careful agent. ", 200) + def := `{"type":"function","function":{"name":"exec_command","description":"` + strings.Repeat("Runs a command. ", 100) + `","parameters":{"type":"object","properties":{"cmd":{"type":"string"}}}}}` + img := "data:image/png;base64," + strings.Repeat("iVBORw0KGgo", 300) + out := strings.Repeat("package main // the files' text\n", 300) + q, _ := json.Marshal(out) + body = `{"model":"` + model + `","messages":[` + + `{"role":"system","content":"` + sys + `"},` + + `{"role":"user","content":[{"type":"text","text":"read these"},{"type":"image_url","image_url":{"url":"` + img + `"}}]},` + + `{"role":"assistant","content":null,"tool_calls":[{"id":"c1","type":"function","function":{"name":"exec_command","arguments":"{\"cmd\":\"cat a.go b.go\"}"}}]},` + + `{"role":"tool","tool_call_id":"c1","content":` + string(q) + `}],` + + `"tools":[` + def + `]}` + return body, len(sys), len(def), len(img), len(out) +} + +// A request's body is told apart by what its bytes were, as the prompt +// is read: the system prompt, the tools' definitions and the images each +// at least their own bytes, and nothing counted twice — a tool result +// shared among the files it read counts once, so the parts never sum past +// the body (theforeveriris on X: what are 8.6 GB up made of?). +func TestPromptKnowsWhatItsBytesWere(t *testing.T) { + body, system, tool, image, result := upPartsBody("m") + p := promptOf(provider.Chat, []byte(body)) + if p == nil { + t.Fatal("the body wasn't read") + } + read := 0 + for _, it := range partOf(p, PartFiles).Items { + if it.Name == "a.go" || it.Name == "b.go" { + read++ + } + } + if read != 2 { + t.Fatalf("the cat's two files weren't read as files: %+v", p.Parts) + } + s := p.sent + if s.system < system || s.tools < tool || s.images < image { + t.Fatalf("parts %+v; the body holds system %d, tools %d, an image %d", s, system, tool, image) + } + if s.all > len(body) { + t.Fatalf("the parts read %d bytes of a %d-byte body: something counted twice", s.all, len(body)) + } + if rest := s.all - s.system - s.tools - s.images; rest < result { + t.Fatalf("the conversation is %d bytes; its tool result alone is %d", rest, result) + } +} + +// What the parts are on a row is what went on the wire, each part scaled +// by it; none where the bytes up aren't the body's. +func TestUpPartsScaleToTheWire(t *testing.T) { + p := &Prompt{sent: sentSizes{system: 100, tools: 200, images: 300, all: 1000}} + got := upParts(p, &upBytes{wire: 500}) + if got == nil || *got != (usage.UpParts{System: 50, Tools: 100, Images: 150}) { + t.Fatalf("got %+v", got) + } + for name, c := range map[string]struct { + p *Prompt + u *upBytes + }{ + "not read": {nil, &upBytes{wire: 500}}, + "nothing went": {p, &upBytes{}}, + "a socket delta": {p, &upBytes{wire: 500, socket: true}}, + "images by file": {p, &upBytes{wire: 500, images: 2}}, + "empty body": {&Prompt{}, &upBytes{wire: 500}}, + } { + if got := upParts(c.p, c.u); got != nil { + t.Errorf("%s: %+v, want none", name, got) + } + } +} + +// A request's ledger row keeps what its bytes up were made of, the parts +// within what went up and each where the body has it. +func TestLedgerKeepsUpParts(t *testing.T) { + fresh(t) + got := 0 + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + got = len(b) + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, chatOK) + })) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "a", Name: "A", Key: "k", Models: []string{"m"}, Chat: up.URL + "/v1"}); err != nil { + t.Fatal(err) + } + body, system, tool, image, _ := upPartsBody("a/m") + s := New() + if code, reply := postAs(t, s, "", body); code != 200 { + t.Fatalf("%d %s", code, reply) + } + route := lastRoute(s).ID + var row *usage.Record + for deadline := time.Now().Add(10 * time.Second); row == nil && time.Now().Before(deadline); { + for _, u := range usage.Load(time.Time{}) { + if u.RouteID == route { + row = &u + } + } + if row == nil { + time.Sleep(20 * time.Millisecond) + } + } + if row == nil { + t.Fatal("no row for the request") + } + if row.UpBytes != got || row.UpParts == nil { + t.Fatalf("UpBytes %d (the vendor got %d), parts %+v", row.UpBytes, got, row.UpParts) + } + u := row.UpParts + if u.System+u.Tools+u.Images > row.UpBytes { + t.Fatalf("parts %+v sum past %d bytes up", u, row.UpBytes) + } + // the body went on as it came, near enough: each part near its share + near := func(part, want int) bool { return part >= want*9/10 && part <= want*13/10 } + if !near(u.System, system) || !near(u.Tools, tool) || !near(u.Images, image) { + t.Fatalf("parts %+v; the body holds system %d, tools %d, an image %d", u, system, tool, image) + } +} + +// Reading a large body's parts is a length added per piece the prompt +// already reads, nothing beside it: its cost is promptOf's. +func BenchmarkPromptOfLargeBody(b *testing.B) { + var msgs []string + for i := range 400 { + msgs = append(msgs, `{"role":"user","content":"`+strings.Repeat("a line of the conversation ", 40)+`"}`) + msgs = append(msgs, `{"role":"assistant","content":null,"tool_calls":[{"id":"c`+string(rune('a'+i%26))+`","type":"function","function":{"name":"exec_command","arguments":"{\"cmd\":\"cat a.go b.go\"}"}}]}`) + msgs = append(msgs, `{"role":"tool","tool_call_id":"c`+string(rune('a'+i%26))+`","content":"`+strings.Repeat("x", 1500)+`"}`) + } + body := []byte(`{"model":"m","messages":[{"role":"system","content":"` + strings.Repeat("s", 40000) + `"},` + strings.Join(msgs, ",") + `]}`) + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for b.Loop() { + if promptOf(provider.Chat, body) == nil { + b.Fatal("not read") + } + } +} diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index b111cd42f..3b1d9f3ae 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1494,6 +1494,25 @@ body.masked :hover > .acct-eye, body.masked .pq-card:hover .acct-eye, body.maske .led-strip .meter { height: 5px; margin-top: 8px; border-radius: 3px; background: var(--pill); overflow: hidden; } .led-strip .meter i { display: block; height: 100%; border-radius: 3px; background: var(--green); } .led-trend { padding: 10px 14px 10px; background: var(--card); border: 1px solid var(--line); border-radius: 12px; } +/* what the bytes sent upstream were made of, opened from the Requests card's ↑ */ +.led-up { margin-top: 10px; padding: 10px 14px 12px; background: var(--card); border: 1px solid var(--line); border-radius: 12px; } +.led-up[hidden] { display: none; } +.led-up .led-bar { align-items: center; } +.led-up-each { font-size: 12px; color: var(--muted); font-variant-numeric: tabular-nums; } +.led-up-x { margin-left: 6px; font-size: 16px; line-height: 1; padding: 0 4px; color: var(--muted); } +.led-up-note { margin: 4px 0 10px; font-size: 12px; color: var(--muted); } +.led-up-bar { display: flex; gap: 2px; height: 8px; border-radius: 4px; overflow: hidden; background: var(--pill); } +.led-up-seg { display: block; min-width: 2px; flex-basis: 0; } +.led-up-seg.rest { background: var(--pill); } +.led-up-legend { display: flex; flex-wrap: wrap; gap: 4px 16px; margin-top: 8px; font-size: 12px; font-variant-numeric: tabular-nums; } +.led-up-key { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; } +.led-up-key .dot { width: 8px; height: 8px; border-radius: 2px; background: var(--pill); } +.led-up-key b { font-weight: 600; } +.led-up-key .pc, .led-up-key.rest { color: var(--muted); } +.led-up-lists { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 4px 24px; margin-top: 12px; } +.led-up-by td.nm { position: relative; } +.led-up-by td.nm > span { display: block; overflow: hidden; text-overflow: ellipsis; } +.led-up-meter { display: block; height: 2px; margin-top: 3px; border-radius: 1px; background: var(--c1); opacity: .55; } .led-speed { margin-top: 10px; padding: 10px 14px 6px; background: var(--card); border: 1px solid var(--line); border-radius: 12px; } .led-speed[hidden] { display: none; } .led-spd-t { font-size: 13px; font-weight: 600; } diff --git a/internal/gui/assets/plugins/usage/client.js b/internal/gui/assets/plugins/usage/client.js index d18642c84..e68b0eeaa 100644 --- a/internal/gui/assets/plugins/usage/client.js +++ b/internal/gui/assets/plugins/usage/client.js @@ -78,6 +78,7 @@ magpie.plugin("usage", (ctx) => {

Gateway and session-log calls; local rejections excluded from totals.