Files
magpie/internal/usage/block_price.go
T
yetone 99fcddeeba usage: the Requests tab, its filters and refresh, the charts, the TUI and magpie usage answer at once over a long history (Vantiboo1ean)
Vantiboo1ean (Discord, macOS M2, v0.1.1157) has ~750,000 requests in
usage.jsonl. On Usage > Requests every filter, model pick and refresh
spun forever and the page never updated.

Reproduced in a sandbox HOME with 750k generated records in the real
format (400 MB usage.jsonl, ~84k sessions), on magpie web and in process.
The cause: the #563 budget dropped the index's blocks once they passed
24 MB (60 MB here), so every read, of any period, parsed the whole file
again (6 s CPU) and priced every call again; All took 12 s of CPU, the
heatmap 13 s, and the page read both at once.

What changed:
- log_index: the gateway's blocks are always kept (about 80 bytes a call,
  S2-compressed instead of flate); the file is parsed once, then only
  what was appended.
- block_price: the gateway's blocks are priced per query, once per set of
  provider/model/served/effort names rather than per call, into pooled
  buffers; range loops go by pointer (a packed row is 264 bytes).
- request_page: pages are always cached (16 at most), session-file chunks
  stay in the budget, and a page asked again while it is worked out (the
  refresh button, the timer) waits for that one instead of starting a
  second scan.
- Siblings that read the same history:
  - The heatmap names each day once.
  - A day filter no longer allocates per call.
  - The ledger behind the TUI, magpie usage, the CSV export and sync
    (LedgerOf, OwnDays) reads the gateway's calls from the index instead
    of Load parsing the whole file.
  - Direct/Summaries matches the session files' calls against the index's
    blocks without pricing all 750k gateway calls.
  - A summary of more than 1024 sessions is now cached with its top 1024
    (it was not cached at all). The Usage page's /api/usage gets the top
    100 (it was sent all 84k, 19 MB, which it never draws) plus a new
    sessionCount. /v1/magpie/usage still lists every session, and magpie
    usage says "top 10 of <sessionCount>".

Timings, CPU (the box was at load 130-190 on 14 cores, so wall is
inflated; min of repeated runs), before -> after:
  Requests today            6.0 s  -> 20 ms
  Requests 7d               5.8 s  -> 93 ms
  Requests 30d              ~6 s   -> 362 ms
  Requests all              12.4 s -> 2.4 s first, ~8 ms again
  all, model filter         12.3 s -> 1.5 s
  all, agent filter         11.3 s -> 1.8 s
  30d, search "opus"        6.7 s  -> 353 ms
  day filter                6.0 s  -> ~0.1 s
  heatmap                   13.7 s -> ~2.3 s first
  summary today / all       6.0 / 9.2 s -> 25 ms / 1.6 s first, <1 ms again
  /api/usage?period=all     1.6 s + 19 MB JSON each time -> <1 ms, 53 KB
  TUI Summaries(all)        ~8.5 s (Load + ledger) -> 1.1 s first, <1 ms again
  TUI Summaries(today)      ~6 s   -> 29 ms
  Visit 7d (budget, codex)  5.9 s  -> 10 ms
The first read of the file after start costs ~5 s of CPU, once.

Tests (each seen red with its guarantee broken by hand):
- TestUsageOverBudgetHistoryIsReadOnce
- TestUsageSessionChunksStayInBudget
- TestUsageOverBudgetPageIsCached
- TestUsagePageAskedTwiceIsWorkedOutOnce
- TestUsageLedgerReadsTheIndexNotTheFile
- TestUsageLargeSummaryIsCompleteAndKeptTrimmed (was ...ButNotCached)
- TestDirectCountsOnlySessionFileCalls, now with a request-id match,
  checks that Direct/Summaries equal the ledger's.

Run: go test -tags nogui ./... (temp HOME), gofmt -l, GOOS=linux and
GOOS=windows go vet on the touched packages.
2026-10-11 04:44:13 +08:00

147 lines
4.3 KiB
Go

package usage
import (
"slices"
"sync"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// swapKnown marks a row whose Swapped flag was settled when it was priced,
// so reading it back needs no second look at the two names.
const swapKnown = 64
// pricedAs is what a gateway call is priced as, the same for every call of
// one provider, model, served model and effort.
type pricedAs struct {
provider string
flags uint8
price *catalog.Price
}
// blockPricer prices the gateway's raw blocks as a query reads them. What a
// row's price, provider id, swap and routing are depends on a few of its
// names only, so they are worked out once for each set of names, not once
// per call: 750k calls name a few hundred.
type blockPricer struct {
aliases map[string]string
wires map[string]string
price func(Record) *catalog.Price
by map[[4]string]pricedAs
agents map[string]string
pooled []*[]packedRow
}
// pricedRows are the rows of the blocks a query priced, handed back when
// it is done with them: a query over the whole history decodes every block,
// and allocating and clearing their rows again each time was a third of it.
var pricedRows = sync.Pool{New: func() any { s := make([]packedRow, 0, logBlockRows); return &s }}
// release hands the rows of the blocks it priced back, once the query no
// longer reads them (a page's rows are copies).
func (b *blockPricer) release() {
for _, rows := range b.pooled {
pricedRows.Put(rows)
}
b.pooled = nil
}
func newBlockPricer(aliases, wires map[string]string, price func(Record) *catalog.Price) *blockPricer {
return &blockPricer{aliases: aliases, wires: wires, price: price, by: map[[4]string]pricedAs{}, agents: map[string]string{}}
}
// as is priceRow's answer for a gateway call of these names.
func (b *blockPricer) as(prov, model, served, effort string) pricedAs {
k := [4]string{prov, model, served, effort}
if a, ok := b.by[k]; ok {
return a
}
if id, ok := b.aliases[prov]; ok {
prov = id
}
a := pricedAs{provider: prov, flags: swapKnown}
sent := provider.SentNameIn(b.wires, prov, model, effort)
if served != "" && Swapped(sent, served) && !(SameSpelled(model, served) || ServingName(model, served) || RelayRenamed(model, served)) {
a.flags |= 2
}
if GroupRouted(sent, served) {
a.flags |= 32
}
a.price = b.price(Record{Provider: prov, Model: model, Served: served, Effort: effort})
b.by[k] = a
return a
}
func (b *blockPricer) agent(ua string) string {
a, ok := b.agents[ua]
if !ok {
a = AgentOf(ua)
b.agents[ua] = a
}
return a
}
// block is the priced copy of a raw block, made for one query and not kept.
func (b *blockPricer) block(packed *rowChunk) *rowChunk {
buf := pricedRows.Get().(*[]packedRow)
raw := packed.unpackInto(*buf)
// unpackInto decodes into the buffer whenever it is large enough
if raw != nil && raw != packed && cap(*buf) >= len(raw.Rows) {
b.pooled = append(b.pooled, buf)
} else {
pricedRows.Put(buf)
}
if raw == nil {
return nil
}
c := *raw
if raw == packed {
c.Rows = slices.Clone(raw.Rows) // a block too small to compress is shared
}
c.Strings = slices.Clip(c.Strings)
added := map[string]uint32{}
intern := func(s string, was uint32) uint32 {
if c.Strings[was] == s {
return was
}
if id, ok := added[s]; ok {
return id
}
id := uint32(len(c.Strings))
c.Strings = append(c.Strings, s)
added[s] = id
return id
}
type ids struct {
provider uint32
flags uint8
price *catalog.Price
}
names := map[[4]uint32]ids{}
agents := map[uint32]uint32{}
for i := range c.Rows {
p := &c.Rows[i]
k := [4]uint32{p.Text[1], p.Text[5], p.Text[7], p.Text[8]}
got, ok := names[k]
if !ok {
a := b.as(c.Strings[k[0]], c.Strings[k[1]], c.Strings[k[2]], c.Strings[k[3]])
got = ids{intern(a.provider, k[0]), a.flags, a.price}
names[k] = got
}
agent, ok := agents[p.Text[0]]
if !ok {
agent = intern(b.agent(c.Strings[p.Text[0]]), p.Text[0])
agents[p.Text[0]] = agent
}
p.Text[0], p.Text[1] = agent, got.provider
p.Flags = p.Flags&^(1|2|32) | got.flags
p.Cost = 0
if got.price != nil && p.Tokens[0]+p.Tokens[1] > 0 {
p.Flags |= 1
p.Cost = got.price.CostSplit(int(p.Tokens[0]), int(p.Tokens[1]), int(p.Tokens[2]), int(p.Tokens[3]), int(p.Tokens[5]))
}
}
return &c
}