Files
magpie/internal/usage/block_price.go
T
yetone 4042aa4d1d usage: a row keeps the strings its chunk shares once, in Shapes
The usage page holds every row of the period at once, and a packed row
was 328 bytes, 140 of them 35 string ids. On the owner's real history
(364,013 calls in 6,445 chunks) only five of those vary call by call:
the error, the request id, the archive, the response id and the message
id. The other 30 (agent, provider, model, session, endpoint, client...)
repeat for most rows of a chunk: 364k rows have 7,300 distinct sets.

So a row keeps those five ids and a Shape, an index into its chunk's
Shapes table, which holds every other set once. packedRow is 216 bytes.
A snapshot (process-private, nothing on disk) writes the table once
after the strings and per row the shape and the five ids, so archives
shrink too. block() renames and re-prices per shape, not per row.

Same output: f5b015742 and this build served byte-identical bodies on
the real history for 14 endpoints, signed in: requests.csv of every row
(94,292,195 bytes); the requests page for all, offset 20000, month,
week, day, agent=codex, agent=claude, failed=1, q=opus and
provider=anthropic; the heatmap; usage for all and for month.

Footprint (phys_footprint, what Activity Monitor shows), cold start on a
copy of the real history, two runs each, alternating:
  f5b015742  peak 483 / 541 MB  end RSS 530 / 600 MB  CPU 1:44.7 / 1:47.7
  this       peak 465 / 463 MB  end RSS 511 / 509 MB  CPU 1:45.7 / 1:47.1
At rest both settle at 188-197 MB.

Tests: TestRowsOfOneSessionShareAShape fails when packedRow grows past
216 bytes (red at 328 with 112 bytes of padding put in by hand: "a
packed row is 328 bytes"), and checks that 200 rows of two models keep
2 shapes and read back equal after pack and unpack.
go test ./... -timeout 45m at this head: 65 packages ok; agent, gateway
and library failed only with "no space left on device" (the disk filled
mid-run) and, run again once there was room, are ok (agent 208s,
gateway 342s, library 115s).
GOOS=linux and GOOS=windows go vet -tags nogui ./... clean; gofmt clean.
2026-10-21 23:21:41 +08:00

168 lines
5.0 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 uint16
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][2]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][2]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
}
// agent is reportedAs's answer for a client, the agent counted and the
// client's own name when the user's counting changed it.
func (b *blockPricer) agent(ua string) (string, string) {
a, ok := b.agents[ua]
if !ok {
a[0], a[1] = reportedAs(ua)
b.agents[ua] = a
}
return a[0], a[1]
}
// 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
}
// a shape's names are priced once, and the row takes the shape they
// make: the agent, the client and the provider are all a shape's
c.Shapes, c.shapeIDs = slices.Clip(c.Shapes), nil
type ids struct {
id uint32 // the provider's string, or the row's shape
flags uint16
price *catalog.Price
}
names := map[[4]uint32]ids{}
agents := map[uint32][2]uint32{}
shapes := map[uint32]ids{}
for i := range c.Rows {
p := &c.Rows[i]
got, ok := shapes[p.Shape]
if !ok {
t := c.Shapes[p.Shape]
k := [4]uint32{t[1], t[5], t[7], t[8]}
named, ok := names[k]
if !ok {
a := b.as(c.Strings[k[0]], c.Strings[k[1]], c.Strings[k[2]], c.Strings[k[3]])
named = ids{intern(a.provider, k[0]), a.flags, a.price}
names[k] = named
}
agent, ok := agents[t[0]]
if !ok {
a, client := b.agent(c.Strings[t[0]])
agent = [2]uint32{intern(a, t[0]), intern(client, t[rowClient])}
agents[t[0]] = agent
}
t[0], t[1], t[rowClient] = agent[0], named.id, agent[1]
got = ids{c.shape(t), named.flags, named.price}
shapes[p.Shape] = got
}
p.Shape = got.id
p.Flags = p.Flags&^(1|2|32) | got.flags
if p.Flags&rowOwnCost != 0 {
// a reported call that said what it cost costs that (#1874)
if p.Tokens[0]+p.Tokens[1] > 0 {
p.Flags |= 1
}
continue
}
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
}