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

148 lines
4.5 KiB
Go

package usage
import (
"bufio"
"bytes"
"encoding/json"
"io"
"os"
"path/filepath"
"sync"
)
// reported holds the request ids of the reported calls usage.jsonl already
// has (#1874), so a client that sends a call twice, or again after a
// restart, adds it once. It is read from the log itself, never kept apart:
// the log is what the page counts, so it is what says what was counted.
// Only reported rows are looked at, so the set is as big as what clients
// have reported, not as the gateway's history.
var reported struct {
// ingest is held for a whole IngestReported: two posts of one rid at
// once must not both find it new.
ingest sync.Mutex
path string
info os.FileInfo
off int64
rids map[string]bool
}
// reportedMark is how a reported row's line spells its source, which the
// scan looks for before it parses a line.
var reportedMark = []byte(`"source":"` + SourceReported + `"`)
// catchUpReported reads the lines written to the log since the last look
// and notes the request ids of the reported calls among them. A log that
// is now another file, or shorter, is read again from the start. Called
// with reported.ingest held.
func catchUpReported(path string) error {
f, err := os.Open(path)
if os.IsNotExist(err) {
reported.path, reported.info, reported.off, reported.rids = path, nil, 0, map[string]bool{}
return nil
}
if err != nil {
return err
}
defer f.Close()
info, err := statLogHandle(f)
if err != nil {
return err
}
if reported.rids == nil || reported.path != path || reported.info == nil || !sameLogFile(reported.info, info) || info.Size() < reported.off {
reported.path, reported.off, reported.rids = path, 0, map[string]bool{}
}
reported.info = info
if _, err := f.Seek(reported.off, io.SeekStart); err != nil {
return err
}
rd := bufio.NewReaderSize(f, 64<<10)
for {
line, err := rd.ReadBytes('\n')
if err != nil {
break // an unfinished last line is read again once it ends
}
reported.off += int64(len(line))
if !bytes.Contains(line, reportedMark) {
continue
}
var r struct {
RID string `json:"rid"`
Source string `json:"source"`
}
if json.Unmarshal(line, &r) == nil && r.Source == SourceReported && r.RID != "" {
reported.rids[r.RID] = true
}
}
return nil
}
// IngestReported writes the calls a client reported (#1874) to the log
// the gateway writes its own to, under the same lock, each marked
// SourceReported. A call whose request id the log already has as reported,
// or that came earlier in recs, is skipped. It answers, for each record,
// whether it was written. The records must already be checked: each has
// a RequestID.
//
// Nothing else the gateway does on a call happens: no OTel span (the call
// is the client's, which can send its own), and no caller key's budget is
// spent, since the call didn't go through magpie.
func IngestReported(recs []Record) ([]bool, error) {
reported.ingest.Lock()
defer reported.ingest.Unlock()
path := Path()
// most of the catching up is done before the gateway's lock is taken,
// so a long log doesn't hold its calls up; what it wrote meanwhile is
// read under the lock below
if err := catchUpReported(path); err != nil {
return nil, err
}
mu.Lock()
defer mu.Unlock()
if err := catchUpReported(path); err != nil {
return nil, err
}
took := make([]bool, len(recs))
var buf []byte
batch := map[string]bool{}
for i, r := range recs {
if r.RequestID == "" || reported.rids[r.RequestID] || batch[r.RequestID] {
continue
}
r.Source = SourceReported
r.CallerKeyID, r.CallerKeyName = "", ""
b, err := json.Marshal(r)
if err != nil {
return nil, err
}
buf = append(append(buf, b...), '\n')
batch[r.RequestID] = true
took[i] = true
}
if len(buf) == 0 {
return took, nil
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return nil, err
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
return nil, err
}
defer f.Close()
before, _ := statLogHandle(f)
if _, err := f.Write(buf); err != nil {
// what part of it reached the file is read back by the next scan
return nil, err
}
after, _ := statLogHandle(f)
noteLogAppend(path, before, after)
// the lines are the log's now: the next scan starts after them
for rid := range batch {
reported.rids[rid] = true
}
if after != nil && reported.info != nil && sameLogFile(reported.info, after) && before != nil && before.Size() == reported.off {
reported.info, reported.off = after, after.Size()
}
return took, nil
}