Files
magpie/internal/usage/window_holds.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

179 lines
5.7 KiB
Go

package usage
// What a whole subscription window holds (Chiao on Discord): the Usage
// page's account cards show each window's share used, as the vendor reads
// it; magpie knows what it routed through the account since the window
// began, so the whole is about that over the share. It is told only where
// that is honest: the window's start and the account's calls are known,
// magpie's log reaches back to the start, and enough of it is used for a
// rounded percent to scale up (provider.HoldsFloor).
import (
"math"
"strings"
"time"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// WithWindowHolds is qs with each window's Holds reckoned from the log, as
// it stood at now. qs itself, which the caller may share, is left as it is.
func WithWindowHolds(qs []provider.SubscriptionQuota, now time.Time) []provider.SubscriptionQuota {
since, ok := holdsSince(qs, now)
if !ok {
return qs
}
s := readLogSnapshot()
return windowHolds(qs, now, s.firstOwn, apiPricer(), provider.Renamed(), func(fn func(Record)) { s.visit(since, fn) })
}
// holdsSince is the earliest start of a window that could be reckoned.
func holdsSince(qs []provider.SubscriptionQuota, now time.Time) (time.Time, bool) {
var since time.Time
found := false
for _, q := range qs {
at := readAtOf(q, now)
for _, w := range q.Windows {
if start, _, ok := holdsBounds(q, w, at); ok && (!found || start.Before(since)) {
since, found = start, true
}
}
}
return since, found
}
func readAtOf(q provider.SubscriptionQuota, now time.Time) time.Time {
if q.ReadAt != nil && !q.ReadAt.After(now) {
return *q.ReadAt
}
return now
}
// holdsBounds is the window of q's account to reckon w's whole over, ok
// only where w can be: an account's own card, a window that runs out and
// starts again on a known clock, counts a whole account's or some named
// models' calls, and is used enough, and a reading not past its reset.
func holdsBounds(q provider.SubscriptionQuota, w provider.QuotaWindow, at time.Time) (time.Time, time.Time, bool) {
if q.Error != "" || q.From != "" || q.User == "" || q.Balance != "" {
return time.Time{}, time.Time{}, false
}
if w.Unlimited || w.Aside || w.Family != "" || w.Pool != "" || math.IsNaN(w.Used) || w.Used < provider.HoldsFloor {
return time.Time{}, time.Time{}, false
}
start, end, ok := w.Bounds(at)
if !ok || !end.After(at) || !start.Before(at) {
return time.Time{}, time.Time{}, false
}
return start, end, true
}
// windowHolds fills in each window's Holds from the calls read gives: the
// calls of the card's provider (by the id it has now) answered by its
// account, to a model the window counts, from the window's start to when
// its share was read. first is the log's first call: a window begun before
// it has calls magpie can't see, and isn't reckoned.
func windowHolds(qs []provider.SubscriptionQuota, now, first time.Time, priceOf func(Record) *catalog.Price, renamed map[string]string, read func(func(Record))) []provider.SubscriptionQuota {
type slot struct{ q, w int }
type span struct{ start, end time.Time }
want := map[slot]span{}
byAccount := map[string][]slot{}
for i, q := range qs {
at := readAtOf(q, now)
for j, w := range q.Windows {
start, _, ok := holdsBounds(q, w, at)
if !ok || first.IsZero() || first.After(start) {
continue
}
k := q.Provider + "\x00" + strings.ToLower(q.User)
byAccount[k] = append(byAccount[k], slot{i, j})
want[slot{i, j}] = span{start, at}
}
}
if len(want) == 0 {
return qs
}
sums := map[slot]*provider.WindowHolds{}
unpriced := map[slot]bool{}
read(func(r Record) {
if r.IsRejected() || r.IsReported() || r.Input+r.Output == 0 {
return
}
if next, ok := renamed[r.Provider]; ok {
r.Provider = next
}
for _, s := range byAccount[r.Provider+"\x00"+strings.ToLower(r.Account())] {
b := want[s]
if r.Time.Before(b.start) || r.Time.After(b.end) || !qs[s.q].Windows[s.w].Counts(r.Model) {
continue
}
h := sums[s]
if h == nil {
h = &provider.WindowHolds{Since: b.start}
sums[s] = h
}
h.Routed.Calls++
h.Routed.Tokens += int64(r.Input + r.Output)
h.Routed.CacheRead += int64(r.CacheRead)
h.Routed.CacheWrite += int64(r.CacheWrite)
if pr := priceOf(r); pr != nil {
h.Routed.Cost += r.CostAt(*pr)
} else {
unpriced[s] = true
}
}
})
if len(sums) == 0 {
return qs
}
out := make([]provider.SubscriptionQuota, len(qs))
copy(out, qs)
cloned := map[int]bool{}
for s, h := range sums {
if h.Routed.Tokens <= 0 {
continue
}
q := &out[s.q]
if !cloned[s.q] { // the caller's windows are left as they are
q.Windows, cloned[s.q] = append([]provider.QuotaWindow(nil), q.Windows...), true
}
w := &q.Windows[s.w]
h.Used = w.Used
scale := 100 / w.Used
h.Tokens = int64(math.Round(float64(h.Routed.Tokens) * scale))
if !unpriced[s] && h.Routed.Cost > 0 {
h.Priced = true
h.Cost = h.Routed.Cost * scale
}
w.Holds = h
}
return out
}
// apiPricer is each call's model at its API list price: its maker's, else
// the provider's own list, never a price the user set for the
// subscription (which may well be nothing) nor a rate it bills at. A price
// of nothing at all is no API price.
func apiPricer() func(Record) *catalog.Price {
prices := map[[2]string]*catalog.Price{}
return func(r Record) *catalog.Price {
k := [2]string{r.Provider, r.Model}
if pr, ok := prices[k]; ok {
return pr
}
var pr *catalog.Price
v, ok := provider.MakerPrice(r.Model)
if !ok || v.Cost(1e6, 1e6, 0, 0) == 0 {
ok = false
if p, err := provider.Find(r.Provider); err == nil {
v, ok = p.ListPrice(r.Model)
}
}
if ok && v.Cost(1e6, 1e6, 0, 0) > 0 {
pr = &v
}
prices[k] = pr
return pr
}
}