Files
magpie/internal/usage/block_price.go
T
yetone d4c2512d2d usage: apps report their own calls with POST /v1/magpie/usage/requests, backfill included (#1874)
What changed
- POST /v1/magpie/usage/requests (internal/gateway/usage_ingest.go) takes
  one record or an array, in usage.jsonl's shape:
  - the post may carry up to 5000 records and 32 MiB;
  - t, agent, provider, model and rid are required.
  Each field is checked: unknown fields, quoted numbers, negative or absurd
  counts, a status outside 100-599, a cost over 10000 USD, and a t more
  than an hour ahead or before 2000-01-01T00:00:00Z. Any fault refuses the
  whole post with a 400 that names error.index and error.param, and nothing
  is written. A past t is otherwise taken as given, so history can be
  backfilled. The reply gives accepted and skipped counts and each
  record's index, rid and status.
- Access: lanGuard's rule (this machine, or another with a key while
  shared, behind the Host check). A browser page also needs a key, since
  corsGuard lets localhost pages and Origin null through. A held key is
  refused.
- usage.IngestReported writes under usage.mu to the same file as
  usage.Append. Rows carry source "reported" and no caller key. A rid
  already reported is skipped, as is one repeated in the post. The set of
  reported rids is read back from the log: one scan after a restart (lines
  without the reported mark aren't parsed), then only what was appended.
- Pricing: a record with cost keeps it (Record.OwnCost, the rowOwnCost
  flag; packed flags widened to uint16). Otherwise it is priced at
  magpie's prices.
- Display:
  - SourceReported is a source of its own: RequestPage.Reported,
    ?via=reported, and Ledger now honours via.
  - The Requests tab gains a fourth cell "reported by apps", shown once
    there are some, and a "Reported" badge (en, zh, zh-TW, ja, de).
- Nothing live: Record.IsReported keeps reported rows out of:
  - a key's budget/spend limit (budget.counts);
  - window holds, and the log start that decides whether a window can be
    reckoned (logSnapshot.firstOwn);
  - gateway sessions and Vias;
  - Codex's sealed answers and remembered model.
  There is no OTel span, rate limit, rest or alert for them.
- Docs: gateway-sessions.md, reference.md (with a curl), integrating.md,
  site integrate.html (en, zh).

Why: the reporter's apps call vendors directly, and their usage (and
history) should show on the Usage page without becoming live traffic.

Run, in a worktree with sandbox HOME and a private GOCACHE
- gofmt -l: clean.
- go vet ./...: darwin, GOOS=linux -tags nogui, and GOOS=windows.
- go test internal/usage, usageapi, budget, gateway, gui: ok.
- -race -count=3 of the new usage/gateway tests: ok.
- GUI with playwright 1.62.0:
  - usage-ledger-reported.test.cjs, 26/26 in chromium and webkit (5
    languages, 1180 and 420 wide, light and dark);
  - usage-ledger*.test.cjs, ledger-*.test.cjs, usage-sum-whole,
    usage-unpriced-sum and i18n-keys: all pass.
- Timings with 200k reported rows (47 MB log, darwin):
  - 40 posts of 5000 took 0.40 s (worst batch 18 ms);
  - the first post after a restart took 0.45 s (rid rescan), a later one
    1.6 ms;
  - the cold index build took 2.1 s (as for gateway rows);
  - page all took 27 ms warm, page 30d 39 ms, all via=reported 0.53 s;
  - summary all took 215 ms, 30d 20 ms.

Broken by hand, each went red, then restored
- Go: dedupe against stored rids; the restart scan; CostAt ignoring own
  cost; the block pricer overwriting own cost; the Reported split;
  fromBrowser's key rule; skipping bad records instead of refusing; the
  max-records and body limits; the ingest lock (race); both locks;
  firstOwn -> first; the IsReported guards in windowHolds,
  buildGatewaySessions, buildVias, budget.counts and loggedAnswers.
- GUI: the fourth cell, the --vias column count and the badge class.

Not shown red on its own: the remote-no-key and evil.example refusals come
from lanGuard and corsGuard before the handler, so breaking only the
handler's own check stays green. The codex_memory guard is not tested
alone: a reported row has no Requested there anyway. Not tried: a real
client against a live gateway, Windows/Linux runs of the tests, the full
GUI suite.
2026-10-13 06:32:03 +08:00

154 lines
4.4 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]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 uint16
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
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
}