diff --git a/docs/integrating.md b/docs/integrating.md index 3429d15ac..868cb3206 100644 --- a/docs/integrating.md +++ b/docs/integrating.md @@ -70,7 +70,12 @@ user's subscription allowances, and `GET /v1/magpie/usage` and `/v1/magpie/usage/requests` the Usage page's numbers and its requests (with `session`, and `subagent`/`parent_agent` for a Claude Code subagent's call). They answer only this machine, or another with a gateway -key; a key held to a budget, models or accounts sees its own calls alone. [Connecting anything else](reference.md#connecting-anything-else) +key; a key held to a budget, models or accounts sees its own calls alone. +Calls your app makes to its vendor itself can be reported with `POST +/v1/magpie/usage/requests` (one record or up to 5000 a post, in +`usage.jsonl`'s shape, each with a `rid`; past times are kept, so a +history can be backfilled). They show on the Usage page as reported, and +never count against a key's limit. [Connecting anything else](reference.md#connecting-anything-else) has the details. **Keep the user's providers.** Add magpie as one more provider (named diff --git a/docs/reference.md b/docs/reference.md index a30c01079..c78111613 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1566,6 +1566,42 @@ only with a gateway key. A key held to a budget, to some models or to some accounts is told its own calls alone: `/v1/magpie/usage` refuses it with a 403, and `/v1/magpie/usage/requests` keeps only its rows and filter lists. +An app that calls its vendor itself, not through magpie, can report those +calls so the Usage page counts them: `POST /v1/magpie/usage/requests` with +`Content-Type: application/json`. The body is one record or an array of up +to 5000 (32 MiB at most), shaped like a `usage.jsonl` line: + +```sh +curl -s http://127.0.0.1:3425/v1/magpie/usage/requests \ + -H 'Content-Type: application/json' \ + -d '[{"t":"2026-10-13T08:00:00Z","agent":"my-app","provider":"anthropic", + "model":"claude-sonnet-4-6","in":1200,"out":340,"cache_read":9000, + "cache_write":0,"ms":2400,"ttft_ms":610,"status":200,"rid":"req_01"}]' +``` + +- **Fields:** `t` (RFC 3339), `agent`, `provider`, `model` and `rid` are + required. `in`, `out`, `cache_read`, `cache_write`, `cache_write_1h`, + `reasoning`, `ms`, `ttft_ms`, `status`, `cost` (USD), `effort`, + `session` and `err` may be left out. +- **Pricing:** a record without `cost` is priced at magpie's prices for + its provider and model. +- **Past times:** `t` is taken as given, however far back, so a history + can be backfilled; it may not be before 2000-01-01T00:00:00Z or more + than an hour ahead. +- **Repeats:** a `rid` already reported is skipped, after a restart too, + so a batch can be sent again. +- **Refusals:** a bad record refuses the whole post with a 400 naming it, + as `error.index` and `error.param` (`record 3: in: must not be + negative`), and nothing is written. +- **The reply:** `{"accepted":1,"skipped":0,"records":[{"index":0,"rid":"req_01","status":"accepted"}]}`. +- **Showing:** reported rows carry `source: "reported"`, count in every + total, and can be listed alone with `via=reported` (`reported` in the + GET's reply has their totals). +- **Nothing live:** they never count against a gateway key's limit or a + budget, a subscription window, an alert, a rate limit or routing. +- **Who may post:** the same as the GETs: this machine, or another with a + gateway key. A web page needs a key even on this machine. + A row's `session` is the conversation it belongs to. A Claude Code subagent's call keeps its parent conversation there and adds `subagent`, its agent id (the `agentId` of its lines and its diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index 64e0e29d4..e4fe2f2f2 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -207,6 +207,65 @@ lists cut to its own rows (`usageapi.OwnPage`): the ledger's facets are drawn from every call in the period, so without the cut they would name other keys. `TestUsageOverGateway` covers both, and a red when either cut is removed. +### Calls an app reports itself + +`POST /v1/magpie/usage/requests` +([`internal/gateway/usage_ingest.go`](../../internal/gateway/usage_ingest.go), +#1874) takes calls that never went through magpie, from an app that sends +them straight to its vendor, so the Usage page covers them too. The body is +one record or an array of up to 5000 (32 MiB at most), in `usage.jsonl`'s +shape: `t`, `agent`, `provider`, `model` and `rid` are required; `in`, +`out`, `cache_read`, `cache_write`, `cache_write_1h`, `reasoning`, `ms`, +`ttft_ms`, `status`, `cost`, `effort`, `session` and `err` are optional. +Any other field, a quoted number, a negative or out-of-range count, a time +more than an hour ahead or before 2000-01-01T00:00:00Z refuses the whole +post with a 400 that names the record (`error.index`) and the field +(`error.param`), and nothing is written. A past `t` is taken as given, +however old, so a client's history can be backfilled. + +- **Who may post:** the GET routes' rule, through the same `lanGuard`: + this machine, or another with an enabled gateway key while shared. On + top of that a browser page (`fromBrowser`) needs a key wherever it is, + since `corsGuard` lets a localhost page and `Origin: null` through, and + a held key is refused. `TestUsageIngestAccess`. +- **Writing:** `usage.IngestReported` + ([`internal/usage/reported.go`](../../internal/usage/reported.go)) + appends under the same mutex and to the same file as `usage.Append`, + each row with `source: "reported"` and no caller key. A `rid` the log + already has as reported, or one repeated in the post, is skipped. The + set of reported rids is read from the log itself, so it survives a + restart: the first post after one scans the log once, keeping only + lines that carry the reported mark, and each later post reads only what + was appended since. The reply counts `accepted` and `skipped` and gives + each record's `index`, `rid` and `status`, so a re-run of a batch is + safe. +- **Pricing:** a record with `cost` keeps it (`Record.OwnCost`, the + `rowOwnCost` flag on a packed row). Without one it is priced at magpie's + own prices, like a gateway row. +- **Showing:** reported rows count in every total. They also have a source + of their own (`SourceReported`): `RequestPage.Reported`, `?via=reported`, + and a fourth cell and a "Reported" badge on the Requests tab. +- **Nothing live:** a reported row only shows on the Usage page. + `Record.IsReported` keeps it out of a gateway key's budget and spend + limit (`budget.counts`), a subscription window's holds (and the log's + start that decides whether a window can be reckoned, `firstOwn`), the + Sessions page's gateway sessions, what a session was routed to (`Vias`), + and Codex's sealed answers and remembered model. Nothing else is done + for it: no OTel span, no rate limit, no rest, no alert. + +`TestUsageIngest*` and `TestIngestReported*` cover these, including +concurrent posts beside the gateway's own writes, and a backfill of a full +5000-record batch landing on the right 7d/30d/all days. +`TestReportedTouchesNothingLive` and `TestUsageIngestTouchesNoLimit` go red +when any of the live guards is removed. Browser: +`usage-ledger-reported.test.cjs`. + +With 200k reported rows (a 47 MB log), 40 posts of 5000 took 0.4 s in all. +The first post after a restart took 0.45 s to read the rids back, and a +later one about 2 ms. The Usage page's first read builds the log index +(2.1 s, as it does for the gateway's own rows); after that, a page of all +took 27 ms and the all-time summary 215 ms. + A usage record's `Session` stays the conversation. A Claude Code subagent's record adds `Subagent` and `ParentAgent`. Through the gateway they come from the `x-claude-code-agent-id` and `x-claude-code-parent-agent-id` headers diff --git a/internal/budget/budget.go b/internal/budget/budget.go index 3c96a1ed8..bf3ef605a 100644 --- a/internal/budget/budget.go +++ b/internal/budget/budget.go @@ -90,7 +90,9 @@ var state = struct { func slot(keyID string) string { return usage.Path() + "\x00" + keyID } // counts reports whether r is a call a key's budget counts. -func counts(r usage.Record) bool { return !r.IsRejected() && r.Computer == "" } +// A call an app reported itself (#1874) never counts: it didn't go through +// magpie, and may be a backfill of calls long past. +func counts(r usage.Record) bool { return !r.IsRejected() && !r.IsReported() && r.Computer == "" } // sumsFor is keyID's sums for the window starting at start, read from // usage.jsonl the first time. Called with state held. diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index f44ea1b9e..2c9e4615b 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -308,7 +308,7 @@ func loggedAnswers(convs ...string) []loggedAnswer { } var all []loggedAnswer usage.Visit(time.Now().Add(-sealerKeep), func(r usage.Record) { - if r.Provider == "" || r.Provider == "magpie" || r.IsRejected() || r.Status <= 0 || r.Status >= 400 || r.Computer != "" || isTitleKind(r.Kind) { + if r.Provider == "" || r.Provider == "magpie" || r.IsRejected() || r.IsReported() || r.Status <= 0 || r.Status >= 400 || r.Computer != "" || isTitleKind(r.Kind) { return } if r.Provider == "openai" && strings.HasPrefix(r.Endpoint, CodexPath) { diff --git a/internal/gateway/codex_memory.go b/internal/gateway/codex_memory.go index 12c1cc077..5f2b7f769 100644 --- a/internal/gateway/codex_memory.go +++ b/internal/gateway/codex_memory.go @@ -83,7 +83,7 @@ func (s *Server) codexMemoryStandIn(r *http.Request, who, agent, kind, asked str keyID := access.Caller(r.Context()).KeyID var last usage.Record usage.Visit(time.Now().Add(-7*24*time.Hour), func(rec usage.Record) { - if rec.Agent != who || rec.CallerKeyID != keyID || rec.Kind != "" || rec.Rejected || rec.Failed() || rec.Requested == "" { + if rec.Agent != who || rec.CallerKeyID != keyID || rec.Kind != "" || rec.Rejected || rec.IsReported() || rec.Failed() || rec.Requested == "" { return } if rec.Time.After(last.Time) { diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 244306ef2..7936ff00f 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -534,6 +534,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("GET /v1/magpie/quotas", s.quotas) mux.HandleFunc("GET /v1/magpie/usage", s.usageSummary) mux.HandleFunc("GET /v1/magpie/usage/requests", s.usageRequests) + mux.HandleFunc("POST /v1/magpie/usage/requests", s.usageIngest) mux.HandleFunc("GET /v1/magpie/quotas/history", s.quotasHistory) mux.HandleFunc("GET "+provider.RemoteCardsPath, s.quotaCards) mux.HandleFunc("POST "+provider.RemoteRefreshPath, s.quotaCardsRefresh) diff --git a/internal/gateway/usage_ingest.go b/internal/gateway/usage_ingest.go new file mode 100644 index 000000000..81881ec79 --- /dev/null +++ b/internal/gateway/usage_ingest.go @@ -0,0 +1,346 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "mime" + "net/http" + "slices" + "strings" + "time" + "unicode/utf8" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// POST /v1/magpie/usage/requests (#1874): a client that calls its vendor +// itself, not through magpie, tells magpie of its calls, so the Usage page +// counts them with the rest. It takes one record, or an array of them, in +// the shape usage.jsonl has, and writes each beside the gateway's own, +// marked source "reported": counted in the totals, and told apart, and +// filtered (?via=reported), on the page and over GET. +// +// A record's rid is required, and one already reported is skipped, after +// a restart too, since what was reported is read from the log itself. A +// record with no cost is priced at magpie's prices, as a gateway call is. +// A batch is all or nothing: one bad record answers 400, naming it and its +// field, and none is written. +// +// It writes into what this computer's usage says, so it is let in as +// GET /v1/magpie/usage is: this computer, or another with an enabled +// gateway key while magpie is shared. A request with a browser's marks +// needs an enabled gateway key even from this computer: corsGuard lets +// a page on localhost or 127.0.0.1 (any port) and an opaque origin +// through, and none of them should be able to write what the page counts. + +const ( + // ingestMaxBody is the most a post may carry: a full batch of + // ingestMaxRecords at a few hundred bytes each is a few MiB, so this + // leaves room for records that carry an err text too. + ingestMaxBody = 32 << 20 + // ingestMaxRecords is the most records one post may carry: a few + // thousand, for a backfill of a client's history (#1874) sent in + // batches, each answered record by record. + ingestMaxRecords = 5000 + // ingestMaxTokens is the most of any token count one call may say: + // more than any model's context, so a larger number is a mistake. + ingestMaxTokens = 100_000_000 + // ingestMaxMillis is the longest a call may say it took: a day. + ingestMaxMillis = int64(24 * time.Hour / time.Millisecond) + // ingestMaxCost is the most one call may say it cost, in USD. + ingestMaxCost = 10_000.0 + // ingestMaxText is the longest a name (agent, provider, model, rid…) + // may be. + ingestMaxText = 256 + // ingestFuture is how far ahead of this computer's clock a call's + // time may be, for a client's clock that runs ahead. + ingestFuture = time.Hour +) + +// ingestEarliest is the earliest a call may be dated. A past time is taken +// as given, so a client's history can be backfilled and lands on its own +// day; this bound only stops a zero or mistyped year. +var ingestEarliest = time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC) + +// ingestFields are the fields a reported record may carry, of the ones +// usage.jsonl has: what a client can know of a call it made itself. +var ingestFields = []string{"t", "agent", "provider", "model", "in", "out", "cache_read", "cache_write", "cache_write_1h", "reasoning", "ms", "ttft_ms", "status", "rid", "cost", "effort", "session", "err"} + +// ingestFault is what is wrong with one record of a post. +type ingestFault struct { + index int + field string + msg string +} + +func (f *ingestFault) Error() string { + return fmt.Sprintf("record %d: %s: %s", f.index, f.field, f.msg) +} + +func (s *Server) usageIngest(w http.ResponseWriter, r *http.Request) { + if !local(r) && !sharedWith(r) { + writeError(w, provider.Chat, http.StatusForbidden, usageRefused) + return + } + who := access.Caller(r.Context()) + if fromBrowser(r) && who.KeyID == "" { + // lanGuard identified only a remote or managed key; a page on this + // computer with a key is looked up here + for _, k := range callerKeys(r) { + if id, ok := access.Authenticate(k); ok { + who = id + break + } + } + if who.KeyID == "" { + writeError(w, provider.Chat, http.StatusForbidden, "a browser page may report usage only with an enabled magpie gateway key (Authorization: Bearer ): a page has no say in what this computer's usage counts") + return + } + } + if heldKey(who) { + writeError(w, provider.Chat, http.StatusForbidden, "this gateway key is held to a budget, models or accounts, so it may not report usage") + return + } + if mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")); err != nil || mt != "application/json" { + writeError(w, provider.Chat, http.StatusUnsupportedMediaType, "send the records as JSON, with Content-Type: application/json") + return + } + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, ingestMaxBody)) + if err != nil { + var tooBig *http.MaxBytesError + if errors.As(err, &tooBig) { + writeError(w, provider.Chat, http.StatusRequestEntityTooLarge, fmt.Sprintf("the body is over %d bytes: send at most %d records a post", ingestMaxBody, ingestMaxRecords)) + return + } + writeError(w, provider.Chat, http.StatusBadRequest, "the body could not be read") + return + } + recs, fault := parseIngest(body, time.Now()) + if fault != nil { + v := map[string]any{"message": fault.Error(), "type": "invalid_request_error", "param": fault.field} + if fault.index >= 0 { + v["index"] = fault.index + } + writeJSON(w, http.StatusBadRequest, map[string]any{"error": v}) + return + } + took, err := usage.IngestReported(recs) + if err != nil { + writeError(w, provider.Chat, http.StatusInternalServerError, "the records could not be written: "+err.Error()) + return + } + type result struct { + Index int `json:"index"` + RID string `json:"rid"` + Status string `json:"status"` + } + out := struct { + Accepted int `json:"accepted"` + Skipped int `json:"skipped"` + Records []result `json:"records"` + }{Records: make([]result, len(recs))} + for i, rec := range recs { + st := "skipped" + if took[i] { + st = "accepted" + out.Accepted++ + } else { + out.Skipped++ + } + out.Records[i] = result{i, rec.RequestID, st} + } + writeJSON(w, 200, out) +} + +// parseIngest reads a post's records: one object, or an array of them. +// The first bad one is the answer, with its index (-1 for the body as a +// whole) and its field. +func parseIngest(body []byte, now time.Time) ([]usage.Record, *ingestFault) { + body = bytes.TrimSpace(body) + var raws []json.RawMessage + switch { + case len(body) > 0 && body[0] == '[': + if err := json.Unmarshal(body, &raws); err != nil { + return nil, &ingestFault{-1, "body", "not a JSON array of records: " + err.Error()} + } + if len(raws) == 0 { + return nil, &ingestFault{-1, "body", "the array has no records"} + } + if len(raws) > ingestMaxRecords { + return nil, &ingestFault{-1, "body", fmt.Sprintf("%d records: send at most %d a post", len(raws), ingestMaxRecords)} + } + case len(body) > 0 && body[0] == '{': + raws = []json.RawMessage{body} + default: + return nil, &ingestFault{-1, "body", "send a JSON record, or an array of them"} + } + out := make([]usage.Record, 0, len(raws)) + for i, raw := range raws { + rec, fault := parseReported(i, raw, now) + if fault != nil { + return nil, fault + } + out = append(out, rec) + } + return out, nil +} + +// parseReported reads one record, field by field, so what is wrong with it +// is said by the field's name. +func parseReported(i int, raw json.RawMessage, now time.Time) (usage.Record, *ingestFault) { + var rec usage.Record + var fields map[string]json.RawMessage + if err := json.Unmarshal(raw, &fields); err != nil || fields == nil { + return rec, &ingestFault{i, "record", "not a JSON object"} + } + keys := make([]string, 0, len(fields)) + for k := range fields { + keys = append(keys, k) + } + slices.Sort(keys) // the same field is named for the same body every time + for _, k := range keys { + if !slices.Contains(ingestFields, k) { + return rec, &ingestFault{i, k, "not a field a reported record takes (" + strings.Join(ingestFields, ", ") + ")"} + } + } + text := func(k string, need bool) (string, *ingestFault) { + v, ok := fields[k] + if !ok || string(v) == "null" { + if need { + return "", &ingestFault{i, k, "required"} + } + return "", nil + } + var s string + if json.Unmarshal(v, &s) != nil { + return "", &ingestFault{i, k, "must be a string"} + } + s = strings.TrimSpace(s) + switch { + case need && s == "": + return "", &ingestFault{i, k, "required"} + case utf8.RuneCountInString(s) > ingestMaxText && k != "err": + return "", &ingestFault{i, k, fmt.Sprintf("longer than %d characters", ingestMaxText)} + case strings.ContainsFunc(s, func(r rune) bool { return r < 0x20 || r == 0x7f }) && k != "err": + return "", &ingestFault{i, k, "has a control character"} + } + return s, nil + } + whole := func(k string, max int64, need bool) (int64, *ingestFault) { + v, ok := fields[k] + if !ok || string(v) == "null" { + if need { + return 0, &ingestFault{i, k, "required"} + } + return 0, nil + } + var n json.Number + // a Number takes a quoted one too, which is a string here + if v[0] == '"' || json.Unmarshal(v, &n) != nil { + return 0, &ingestFault{i, k, "must be a number"} + } + x, err := n.Int64() + if err != nil { + return 0, &ingestFault{i, k, "must be a whole number"} + } + if x < 0 { + return 0, &ingestFault{i, k, "must not be negative"} + } + if x > max { + return 0, &ingestFault{i, k, fmt.Sprintf("over %d, more than one call can be", max)} + } + return x, nil + } + var f *ingestFault + if rec.RequestID, f = text("rid", true); f != nil { + return rec, f + } + if rec.Agent, f = text("agent", true); f != nil { + return rec, f + } + if rec.Provider, f = text("provider", true); f != nil { + return rec, f + } + if rec.Model, f = text("model", true); f != nil { + return rec, f + } + if rec.Effort, f = text("effort", false); f != nil { + return rec, f + } + if rec.Session, f = text("session", false); f != nil { + return rec, f + } + if rec.Error, f = text("err", false); f != nil { + return rec, f + } + if len(rec.Error) > 4096 { + rec.Error = strings.ToValidUTF8(rec.Error[:4096], "") + } + t, ok := fields["t"] + if !ok || string(t) == "null" { + return rec, &ingestFault{i, "t", "required"} + } + var ts string + if json.Unmarshal(t, &ts) != nil { + return rec, &ingestFault{i, "t", "must be an RFC 3339 time, as a string"} + } + when, err := time.Parse(time.RFC3339Nano, ts) + if err != nil { + return rec, &ingestFault{i, "t", "must be an RFC 3339 time (2026-10-13T08:00:00Z)"} + } + if when.After(now.Add(ingestFuture)) { + return rec, &ingestFault{i, "t", "is in the future"} + } + if when.Before(ingestEarliest) { + return rec, &ingestFault{i, "t", "is before 2000-01-01T00:00:00Z, the earliest a call may be dated"} + } + rec.Time = when + counts := []struct { + k string + to *int + }{{"in", &rec.Input}, {"out", &rec.Output}, {"cache_read", &rec.CacheRead}, {"cache_write", &rec.CacheWrite}, {"cache_write_1h", &rec.CacheWrite1h}, {"reasoning", &rec.Reasoning}} + for _, c := range counts { + n, f := whole(c.k, ingestMaxTokens, false) + if f != nil { + return rec, f + } + *c.to = int(n) + } + if rec.CacheWrite1h > rec.CacheWrite { + return rec, &ingestFault{i, "cache_write_1h", "more than cache_write, which counts it"} + } + if rec.Millis, f = whole("ms", ingestMaxMillis, false); f != nil { + return rec, f + } + if rec.TTFT, f = whole("ttft_ms", ingestMaxMillis, false); f != nil { + return rec, f + } + st, f := whole("status", 599, true) + if f != nil { + return rec, f + } + if st < 100 { + return rec, &ingestFault{i, "status", "must be an HTTP status, 100 to 599"} + } + rec.Status = int(st) + if v, ok := fields["cost"]; ok && string(v) != "null" { + var c float64 + if json.Unmarshal(v, &c) != nil { + return rec, &ingestFault{i, "cost", "must be a number of USD"} + } + if math.IsNaN(c) || math.IsInf(c, 0) || c < 0 { + return rec, &ingestFault{i, "cost", "must not be negative"} + } + if c > ingestMaxCost { + return rec, &ingestFault{i, "cost", fmt.Sprintf("over %g USD, more than one call can cost", ingestMaxCost)} + } + rec.OwnCost = &c + } + return rec, nil +} diff --git a/internal/gateway/usage_ingest_test.go b/internal/gateway/usage_ingest_test.go new file mode 100644 index 000000000..a6f1bc42b --- /dev/null +++ b/internal/gateway/usage_ingest_test.go @@ -0,0 +1,342 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "math" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/budget" + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/usage" + "github.com/yetone/magpie/internal/usageapi" +) + +type ingestReply struct { + Accepted, Skipped int + Records []struct { + Index int + RID, Status string + } + Error *struct { + Message, Param string + Index *int + } +} + +func ingestServer(t *testing.T) func(from, body string, hdr ...string) (int, ingestReply, string) { + t.Helper() + fresh(t) + t.Setenv("MAGPIE_ADDR", "") + os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755) + os.WriteFile(catalog.CachePath(), []byte(`{"anthropic":{"id":"anthropic","models":{"claude-opus-5-5":{"id":"claude-opus-5-5","cost":{"input":4,"output":20,"cache_read":0.2,"cache_write":5}}}}}`), 0o644) + catalog.Reset() + t.Cleanup(catalog.Reset) + h := lanGuard(New().Handler()) + return func(from, body string, hdr ...string) (int, ingestReply, string) { + r := httptest.NewRequest("POST", "/v1/magpie/usage/requests", strings.NewReader(body)) + r.RemoteAddr = from + r.Host = "127.0.0.1:3425" // the address a client on this computer uses + r.Header.Set("Content-Type", "application/json") + for i := 0; i+1 < len(hdr); i += 2 { + if hdr[i] == "Host" { + r.Host = hdr[i+1] + continue + } + r.Header.Set(hdr[i], hdr[i+1]) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + var out ingestReply + json.Unmarshal(w.Body.Bytes(), &out) + return w.Code, out, w.Body.String() + } +} + +func reportedRecord(rid string, extra string) string { + t := time.Now().Add(-time.Hour).UTC().Format(time.RFC3339Nano) + return `{"t":"` + t + `","agent":"my-app","provider":"claude","model":"claude-opus-5-5","in":1000000,"out":100000,"cache_read":1000000,"cache_write":0,"ms":1200,"ttft_ms":300,"status":200,"rid":"` + rid + `"` + extra + `}` +} + +func reportedLines(t *testing.T) int { + t.Helper() + b, _ := os.ReadFile(usage.Path()) + return bytes.Count(b, []byte(`"source":"reported"`)) +} + +// POST /v1/magpie/usage/requests (#1874): this computer reports a call +// it made itself and it is counted, priced at magpie's prices, as +// reported; the same rid again is skipped; a call's own cost is kept; and +// the page and GET tell the reported ones apart and filter them. +func TestUsageIngest(t *testing.T) { + do := ingestServer(t) + c, out, b := do("127.0.0.1:5000", reportedRecord("r-1", "")) + if c != 200 || out.Accepted != 1 || out.Skipped != 0 || len(out.Records) != 1 || out.Records[0].Status != "accepted" || out.Records[0].RID != "r-1" { + t.Fatal(c, b) + } + c, out, b = do("127.0.0.1:5000", "["+reportedRecord("r-1", "")+","+reportedRecord("r-2", `,"cost":0.25`)+","+reportedRecord("r-2", "")+"]") + if c != 200 || out.Accepted != 1 || out.Skipped != 2 || out.Records[0].Status != "skipped" || out.Records[1].Status != "accepted" || out.Records[2].Status != "skipped" { + t.Fatal("again:", c, b) + } + if n := reportedLines(t); n != 2 { + t.Fatal("lines:", n) + } + + h := lanGuard(New().Handler()) + get := func(q string) usageapi.Ledger { + r := httptest.NewRequest("GET", "/v1/magpie/usage/requests?period=all"+q, nil) + r.RemoteAddr = "127.0.0.1:5000" + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + var l usageapi.Ledger + if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &l) != nil { + t.Fatal(w.Code, w.Body.String()) + } + return l + } + l := get("") + priced := (1e6*4 + 1e5*20 + 1e6*0.2) / 1e6 + if l.Total != 2 || l.Reported.Calls != 2 || l.Through.Calls != 0 || math.Abs(l.Cost-(priced+0.25)) > 1e-9 { + t.Fatalf("total %d, reported %+v, through %+v, cost %v", l.Total, l.Reported, l.Through, l.Cost) + } + for _, r := range l.Rows { + if r.Source != usage.SourceReported || !r.Priced { + t.Fatalf("row %+v", r.Row) + } + if want := map[string]float64{"r-1": priced, "r-2": 0.25}[r.RequestID]; math.Abs(r.Cost-want) > 1e-9 { + t.Fatalf("%s cost %v, want %v", r.RequestID, r.Cost, want) + } + } + if l := get("&via=reported"); l.Total != 2 { + t.Fatal("via=reported:", l.Total) + } + if l := get("&via=through"); l.Total != 0 || l.Reported.Calls != 2 { + t.Fatal("via=through:", l.Total, l.Reported) + } +} + +// A backfill (#1874): a full batch of a client's history, however old, is +// taken as dated, each record answered, and lands on its own day for the +// 7d, 30d and all views; sent again, it is skipped whole. +func TestUsageIngestBackfill(t *testing.T) { + do := ingestServer(t) + now := time.Now() + ages := []time.Duration{3 * 365 * 24 * time.Hour, 20 * 24 * time.Hour, 3 * 24 * time.Hour} + recs := make([]string, ingestMaxRecords) + for i := range recs { + at := now.Add(-ages[i%len(ages)]).UTC().Format(time.RFC3339Nano) + recs[i] = fmt.Sprintf(`{"t":%q,"agent":"my-app","provider":"claude","model":"claude-opus-5-5","in":10,"out":5,"status":200,"rid":"old-%d"}`, at, i) + } + body := "[" + strings.Join(recs, ",") + "]" + c, out, b := do("127.0.0.1:5000", body) + if c != 200 || out.Accepted != ingestMaxRecords || len(out.Records) != ingestMaxRecords || out.Records[4999].Index != 4999 || out.Records[4999].Status != "accepted" { + t.Fatalf("%d %.300s", c, b) + } + if c, out, b := do("127.0.0.1:5000", body); c != 200 || out.Accepted != 0 || out.Skipped != ingestMaxRecords { + t.Fatalf("again: %d %.300s", c, b) + } + by := make([]int, len(ages)) + for i := range recs { + by[i%len(ages)]++ + } + want := map[usage.Period]int{usage.Today: 0, usage.Week: by[2], usage.Month: by[1] + by[2], usage.All: ingestMaxRecords} + for p, n := range want { + page := usage.QueryPage(p, usage.Filter{}, 0, 1) + if page.Total != n || page.Reported.Calls != n { + t.Errorf("%s: %d rows, %d reported; want %d", p, page.Total, page.Reported.Calls, n) + } + if s := usage.Summarize(p); s.Calls != n { + t.Errorf("%s summary: %d calls; want %d", p, s.Calls, n) + } + } +} + +// A reported call never touches a key's limit (#1874): not one posted with +// the key (the key only lets the post in), and not a line that names the +// key itself. Nor is it an answer Codex's sealed reasoning was given by. +func TestUsageIngestTouchesNoLimit(t *testing.T) { + do := ingestServer(t) + now := time.Now() + if c, out, b := do("127.0.0.1:5000", reportedRecord("r-1", `,"session":"conv-1"`)); c != 200 || out.Accepted != 1 { + t.Fatal(c, b) + } + usage.Append(usage.Record{Time: now.Add(-time.Minute), Agent: "my-app", Provider: "claude", Model: "claude-opus-5-5", Input: 5000, Output: 5000, Status: 200, RequestID: "r-2", Source: usage.SourceReported, CallerKeyID: "k1", Session: "conv-1"}) + st := budget.Of(access.Key{ID: "k1", Limit: &access.Limit{Period: "day", Tokens: 700}}, now) + if st == nil || st.Calls != 0 || st.Tokens != 0 || st.Spent { + t.Fatalf("a reported call counted against the key: %+v", st) + } + if a := loggedAnswers("conv-1"); len(a) != 0 { + t.Fatalf("a reported call answered a Codex conversation: %+v", a) + } + // the gateway's own call of the key still counts + usage.Append(usage.Record{Time: now.Add(-time.Minute), Agent: "my-app", Provider: "claude", Model: "claude-opus-5-5", Input: 500, Output: 500, Status: 200, CallerKeyID: "k1", Session: "conv-1"}) + if st := budget.Of(access.Key{ID: "k1", Limit: &access.Limit{Period: "day", Tokens: 700}}, now); st.Calls != 1 || !st.Spent { + t.Fatalf("the key's own call: %+v", st) + } + if a := loggedAnswers("conv-1"); len(a) != 1 { + t.Fatalf("the gateway's own answer: %+v", a) + } +} + +// Who may report: this computer; another only with an enabled key while +// shared; a browser page, from anywhere, only with a key, since corsGuard +// lets a page on localhost and an opaque origin through; never a key held +// to a budget. Nothing refused is written. +func TestUsageIngestAccess(t *testing.T) { + do := ingestServer(t) + rec := reportedRecord("r-1", "") + // not shared: another machine is refused outright + if c, _, b := do("192.168.1.9:5000", rec); c != http.StatusForbidden { + t.Fatal("not shared:", c, b) + } + _, secrets := newCaller(t, "Laptop") + if c, _, b := do("192.168.1.9:5000", rec); c != http.StatusUnauthorized { + t.Fatal("another machine with no key:", c, b) + } + if c, _, b := do("192.168.1.9:5000", rec, "Authorization", "Bearer sk-magpie-wrong-wrong-wrong"); c != http.StatusUnauthorized { + t.Fatal("another machine with a wrong key:", c, b) + } + pages := [][]string{ + {"Origin", "https://evil.example", "Sec-Fetch-Site", "cross-site", "Sec-Fetch-Mode", "cors"}, + {"Origin", "http://localhost:5173", "Sec-Fetch-Site", "same-site", "Sec-Fetch-Mode", "cors"}, + {"Origin", "null", "Sec-Fetch-Mode", "cors"}, + {"Sec-Fetch-Site", "cross-site", "Sec-Fetch-Mode", "no-cors", "User-Agent", "Mozilla/5.0"}, + } + for _, hdr := range pages { + if c, _, b := do("127.0.0.1:5000", rec, hdr...); c != http.StatusForbidden && c != http.StatusUnauthorized { + t.Fatal("a page with no key:", hdr, c, b) + } + // a rebound name, a page that thinks it is its own origin + if c, _, b := do("127.0.0.1:5000", rec, append([]string{"Host", "rebound.example:3425"}, hdr...)...); c != http.StatusForbidden && c != http.StatusUnauthorized { + t.Fatal("a rebound page:", hdr, c, b) + } + } + if n := reportedLines(t); n != 0 { + t.Fatal("a refused post wrote", n) + } + // with a key: another machine, and a page on this computer + if c, out, b := do("192.168.1.9:5000", rec, "Authorization", "Bearer "+secrets[0]); c != 200 || out.Accepted != 1 { + t.Fatal("another machine with the key:", c, b) + } + if c, out, b := do("127.0.0.1:5000", reportedRecord("r-2", ""), "Origin", "http://localhost:5173", "Authorization", "Bearer "+secrets[0]); c != 200 || out.Accepted != 1 { + t.Fatal("a local page with the key:", c, b) + } + // a JSON body is required, so no form post can carry one + if c, _, b := do("127.0.0.1:5000", rec, "Content-Type", "text/plain"); c != http.StatusUnsupportedMediaType { + t.Fatal("text/plain:", c, b) + } + if n := reportedLines(t); n != 2 { + t.Fatal("lines:", n) + } +} + +// A batch with one bad record answers 400 naming the record and its field, +// and writes none of them. +func TestUsageIngestValidation(t *testing.T) { + do := ingestServer(t) + good := reportedRecord("ok-1", "") + future := time.Now().Add(3 * time.Hour).UTC().Format(time.RFC3339) + cases := []struct { + bad, field string + }{ + {strings.Replace(reportedRecord("b", ""), `"in":1000000`, `"in":-5`, 1), "in"}, + {strings.Replace(reportedRecord("b", ""), `"out":100000`, `"out":1e12`, 1), "out"}, + {strings.Replace(reportedRecord("b", ""), `"cache_read":1000000`, `"cache_read":1.5`, 1), "cache_read"}, + {strings.Replace(reportedRecord("b", ""), `"in":1000000`, `"in":"10"`, 1), "in"}, + {strings.Replace(reportedRecord("b", ""), `,"rid":"b"`, ``, 1), "rid"}, + {strings.Replace(reportedRecord("b", ""), `"model":"claude-opus-5-5"`, `"model":""`, 1), "model"}, + {strings.Replace(reportedRecord("b", ""), `"status":200`, `"status":42`, 1), "status"}, + {strings.Replace(reportedRecord("b", ""), `"ms":1200`, `"ms":999999999999`, 1), "ms"}, + {reportedRecord("b", `,"cost":-1`), "cost"}, + {reportedRecord("b", `,"cost":1e9`), "cost"}, + {reportedRecord("b", `,"source":"through"`), "source"}, + {reportedRecord("b", `,"callerKeyId":"k1"`), "callerKeyId"}, + {`{"t":"` + future + `","agent":"a","provider":"p","model":"m","status":200,"rid":"b"}`, "t"}, + {`{"t":"yesterday","agent":"a","provider":"p","model":"m","status":200,"rid":"b"}`, "t"}, + {`{"t":"1999-12-31T23:59:59Z","agent":"a","provider":"p","model":"m","status":200,"rid":"b"}`, "t"}, + {`[1]`, "record"}, + } + for _, c := range cases { + code, out, b := do("127.0.0.1:5000", "["+good+","+c.bad+"]") + if code != 400 || out.Error == nil || out.Error.Param != c.field || out.Error.Index == nil || *out.Error.Index != 1 || !strings.Contains(out.Error.Message, "record 1: "+c.field) { + t.Errorf("%s: %d %s", c.bad, code, b) + } + } + for _, body := range []string{"[]", "", "42", `[` + strings.Repeat(good+",", ingestMaxRecords) + good + `]`} { + if code, out, b := do("127.0.0.1:5000", body); code != 400 || out.Error == nil || out.Error.Param != "body" { + t.Errorf("body %.40q: %d %.200s", body, code, b) + } + } + big := `[` + good + `,` + reportedRecord("big", `,"err":"`+strings.Repeat("x", ingestMaxBody)+`"`) + `]` + if code, _, b := do("127.0.0.1:5000", big); code != http.StatusRequestEntityTooLarge { + t.Errorf("a body over the limit: %d %.200s", code, b) + } + if n := reportedLines(t); n != 0 { + t.Fatal("a refused batch wrote", n) + } + // the same batch, fixed, is taken whole + if code, out, b := do("127.0.0.1:5000", "["+good+","+reportedRecord("ok-2", `,"cost":null,"effort":"high","session":"s1","err":"","reasoning":10,"cache_write_1h":0`)+"]"); code != 200 || out.Accepted != 2 { + t.Fatal(code, b) + } +} + +// Posts at once, beside the gateway's own calls: each rid once, every line +// whole. +func TestUsageIngestConcurrent(t *testing.T) { + do := ingestServer(t) + const posts, each = 12, 30 + var wg sync.WaitGroup + var mu sync.Mutex + accepted := 0 + for p := range posts { + wg.Add(2) + go func() { + defer wg.Done() + var recs []string + for i := range each { + rid := fmt.Sprintf("shared-%d", i) + if i%2 == 1 { + rid = fmt.Sprintf("own-%d-%d", p, i) + } + recs = append(recs, reportedRecord(rid, "")) + } + c, out, b := do("127.0.0.1:5000", "["+strings.Join(recs, ",")+"]") + if c != 200 || out.Accepted+out.Skipped != each { + t.Error(c, b) + } + mu.Lock() + accepted += out.Accepted + mu.Unlock() + }() + go func() { + defer wg.Done() + usage.Append(usage.Record{Time: time.Now().Add(-time.Hour), Agent: "claude", Provider: "claude", Model: "claude-opus-5-5", Input: 1, Output: 1, Status: 200}) + }() + } + wg.Wait() + if want := each/2 + posts*each/2; accepted != want { + t.Fatalf("accepted %d, want %d", accepted, want) + } + f, _ := os.Open(usage.Path()) + defer f.Close() + b, _ := io.ReadAll(f) + lines := strings.Split(strings.TrimSuffix(string(b), "\n"), "\n") + if len(lines) != accepted+posts { + t.Fatalf("%d lines, want %d", len(lines), accepted+posts) + } + for _, line := range lines { + if !json.Valid([]byte(line)) { + t.Fatalf("a torn line: %.200s", line) + } + } +} diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 86899f44d..2dc264ad2 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1171,9 +1171,10 @@ body.window .field.solo { grid-column: auto; } /* over the requests: their sum, and at its right the request archive's switch */ .led-head { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 8px; margin: 0 2px 7px; min-width: 0; } .led-head .led-sum { margin: 0; min-width: 0; } -/* the two sources the request page counts and their total, in the same block - of cells as the totals above them, each one clickable to filter by it */ -.led-vias { grid-template-columns: repeat(3, minmax(0, 1fr)); margin: 0 0 9px; } +/* the sources the request page counts and their total, in the same block + of cells as the totals above them, each one clickable to filter by it; a + fourth, the calls apps reported (#1874), only once there are some */ +.led-vias { grid-template-columns: repeat(var(--vias, 3), minmax(0, 1fr)); margin: 0 0 9px; } .led-vias[hidden] { display: none; } .led-vias .blk { cursor: pointer; text-align: left; border: 0; font: inherit; color: inherit; background: none; } .led-vias .blk:hover { background: var(--pill-hover); } @@ -1274,6 +1275,7 @@ body.window .field.solo { grid-column: auto; } .led .src.access-api { --badge-ink: var(--tk-f); } .led .src.access-subscription { --badge-ink: var(--tk-k); } .led .src.proto { --badge-ink: var(--muted); font-weight: 500; } +.led .src.reported { --badge-ink: var(--tk-o); } .led .duration { font-weight: 550; } .led .duration-fast { color: var(--tk-s); } .led .duration-slow { color: var(--amber); } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 4aaaee72b..d5496e851 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -18410,14 +18410,14 @@ function renderLedger() { // are counted with the pick cleared (usage.RequestPage), so all three stay // switchable whichever is on. const via = $("#ledVia"); - const thru = l.through || { calls: 0 }, dir = l.direct || { calls: 0 }; - if (thru.calls + dir.calls > 0) { + const thru = l.through || { calls: 0 }, dir = l.direct || { calls: 0 }, rep = l.reported || { calls: 0 }; + if (thru.calls + dir.calls + rep.calls > 0) { // the total is the two sources added up, not the page's own totals: those // are the rows the filter keeps, so with one source picked the total cell // would read that one's figures under the whole period's count const all = {}; for (const k of ["calls", "errors", "input", "output", "cache_read", "cache_write", "cost", "timed", "ttft_ms", "decode_ms", "decode_out"]) { - all[k] = (thru[k] || 0) + (dir[k] || 0); + all[k] = (thru[k] || 0) + (dir[k] || 0) + (rep[k] || 0); } const tile = (b, label, calls, tot, pick) => { const on = ledVia === pick; @@ -18439,16 +18439,22 @@ function renderLedger() { }; return b; }; - // the three cells are the same elements from one redraw to the next, so + // the calls apps reported themselves (#1874) are a fourth cell, once + // there are some, or while they are the ones picked + const n = rep.calls > 0 || ledVia === "reported" ? 4 : 3; + // the cells are the same elements from one redraw to the next, so // one being pressed or focused is never swapped out from under a reader let cells = [...via.children]; - if (cells.length !== 3) { - cells = [el("button"), el("button"), el("button")]; + if (cells.length !== n) { + cells = cells.slice(0, n); + while (cells.length < n) cells.push(el("button")); via.replaceChildren(...cells); } - tile(cells[0], "all requests", thru.calls + dir.calls, all, ""); + via.style.setProperty("--vias", String(n)); + tile(cells[0], "all requests", thru.calls + dir.calls + rep.calls, all, ""); tile(cells[1], "through magpie", thru.calls, thru, "through"); tile(cells[2], "not through magpie", dir.calls, dir, "direct"); + if (n === 4) tile(cells[3], "reported by apps", rep.calls, rep, "reported"); via.hidden = false; } else { via.replaceChildren(); @@ -18553,6 +18559,12 @@ function renderLedger() { : t("Read from the agent's session file. The account is shown only when local metadata identifies it; no service provider is inferred."); badges.append(k); } + // a call an app reported itself (#1874): it went straight to its vendor + if (r.source === "reported") { + const k = el("span", "src reported", t("Reported")); + k.title = t("Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie."); + badges.append(k); + } if (badges.childElementCount) wc.append(badges); // the model sent is what the gateway sent the vendor: a session file has none // The log names a model, but does not capture the outbound HTTP request. @@ -24508,7 +24520,7 @@ if (mode === "window" && params.get("view") === "usage") { ledPurpose = params.get("purpose") || ""; ledComputer = params.get("computer") || ""; const v = params.get("via") || ""; - ledVia = v === "through" || v === "direct" ? v : ""; + ledVia = v === "through" || v === "direct" || v === "reported" ? v : ""; const u = new URL(location.href); for (const k of ["tab", "provider", "agent", "computer", "card", "purpose", "via"]) u.searchParams.delete(k); history.replaceState(null, "", u); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 5430dccaf..0590cc498 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2400,6 +2400,9 @@ const I18N = { "{n} cache read": "缓存读取 {n}", "through magpie": "经过 magpie", "not through magpie": "不经过 magpie", + "reported by apps": "由应用上报", + "Reported": "上报", + "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "由发起请求的应用通过 POST /v1/magpie/usage/requests 上报:这次请求直接发给了服务商,没有经过 magpie。", "all requests": "全部请求", "Show only these requests": "只看这些请求", "Show every request again": "重新显示全部请求", @@ -6924,6 +6927,9 @@ const I18N = { "{n} cache read": "快取讀取 {n}", "through magpie": "經過 magpie", "not through magpie": "不經過 magpie", + "reported by apps": "由應用程式回報", + "Reported": "回報", + "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "由發出請求的應用程式透過 POST /v1/magpie/usage/requests 回報:這次請求直接送往服務商,沒有經過 magpie。", "all requests": "全部請求", "Show only these requests": "只看這些請求", "Show every request again": "重新顯示全部請求", @@ -11449,6 +11455,9 @@ const I18N = { "{n} cache read": "キャッシュ読み取り {n}", "through magpie": "magpie 経由", "not through magpie": "magpie を経由しない", + "reported by apps": "アプリからの報告", + "Reported": "報告", + "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "リクエストを送ったアプリが POST /v1/magpie/usage/requests で報告したものです。このリクエストは magpie を経由せず、直接ベンダーに送られました。", "all requests": "すべてのリクエスト", "Show only these requests": "これらのリクエストだけを表示", "Show every request again": "すべてのリクエストを再表示", @@ -15973,6 +15982,9 @@ const I18N = { "{n} cache read": "{n} Cache-Lesen", "through magpie": "über magpie", "not through magpie": "nicht über magpie", + "reported by apps": "von Apps gemeldet", + "Reported": "Gemeldet", + "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "Von der App gemeldet, die die Anfrage gestellt hat (POST /v1/magpie/usage/requests): Die Anfrage ging direkt an den Anbieter, nicht über magpie.", "all requests": "alle Anfragen", "Show only these requests": "Nur diese Anfragen zeigen", "Show every request again": "Wieder alle Anfragen zeigen", diff --git a/internal/gui/tests/usage-ledger-reported.test.cjs b/internal/gui/tests/usage-ledger-reported.test.cjs new file mode 100644 index 000000000..56d0d306f --- /dev/null +++ b/internal/gui/tests/usage-ledger-reported.test.cjs @@ -0,0 +1,154 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The calls an app reported itself, through POST /v1/magpie/usage/requests +// (#1874), are a fourth source on the Requests tab, beside the gateway's and +// the session files': a cell of their own, there only once there are some, +// that lists only them when picked (via=reported, which a link can carry +// too), counted in the total; and each such row says it was reported. In +// every language, Chromium and WebKit, wide and narrow, light and dark; no +// backend, the API is faked. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { reach } = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); +const tot = (calls, tokens, cost) => ({ calls, errors: 0, input: tokens * 0.2, output: tokens * 0.1, cache_write: 0, cache_read: tokens * 0.7, cost }); +const ROW = { t: new Date().toISOString(), agent: "claude", agentName: "Claude Code", icon: "claudecode-color", provider: "anthropic", providerName: "Claude", model: "claude-sonnet-5", in: 2, out: 600, cache_write: 0, cache_read: 3900, ms: 2380, status: 200, cost: 0.08, priced: true }; +const REPORTED = { ...ROW, agent: "my-app", agentName: "my-app", icon: "", rid: "r-1", source: "reported", cost: 0.25 }; + +function page(q, reported) { + const via = q.get("via") || ""; + const all = [ROW, ...(reported ? [REPORTED] : [])]; + const rows = via === "reported" ? all.filter((r) => r.source === "reported") : via === "through" ? all.filter((r) => !r.source) : via === "direct" ? [] : all; + return { + period: "today", rows, offset: 0, total: rows.length, ...tot(rows.length, 4500 * rows.length, 0.33), reasoning: 0, unpriced: 0, + bucket: "hour", series: [], by: { provider: [], agent: [], model: [] }, + agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }], providers: [{ id: "anthropic", name: "Claude", icon: "claudecode-color" }], + through: tot(8, 4e6, 4), direct: tot(12, 6e6, 6), ...(reported ? { reported: tot(5, 1e6, 1.25) } : {}), + }; +} + +function server(lang, theme, reported, asked) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"${theme}",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme }, fx: { rate: 7.2, at: new Date().toISOString() } }); + if (url.pathname === "/api/usage/requests") { asked.push(url.searchParams); return json(page(url.searchParams, reported)); } + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/usage") return json({ calls: 1, errors: 0, input: 1, output: 1, cache_read: 0, cache_write: 0, reasoning: 0, unpriced: 0, cost: 1, bucket: "day", series: [], agents: [], models: [], path: "~/.config/magpie/usage.jsonl" }); + if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] }); + if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} }); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +// the four cells, and the row's badge, as each language says them +const L = { + en: { cells: ["all requests", "through magpie", "not through magpie", "reported by apps"], badge: "Reported", reqs: "requests" }, + zh: { cells: ["全部请求", "经过 magpie", "不经过 magpie", "由应用上报"], badge: "上报" }, + "zh-TW": { cells: ["全部請求", "經過 magpie", "不經過 magpie", "由應用程式回報"], badge: "回報" }, + ja: { cells: ["すべてのリクエスト", "magpie 経由", "magpie を経由しない", "アプリからの報告"], badge: "報告" }, + de: { cells: ["alle Anfragen", "über magpie", "nicht über magpie", "von Apps gemeldet"], badge: "Gemeldet" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": reported calls are a source of their own", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const shots = process.env.ARTIFACT_DIR; + if (shots) await fs.mkdir(shots, { recursive: true }); + + const open = async (lang, { theme = "light", width = 1180, reported = true, query = "" } = {}) => { + const errors = [], asked = []; + const context = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" }); + t.after(() => context.close()); + const p = await context.newPage(); + p.setDefaultTimeout(5000); + p.on("pageerror", (e) => errors.push(e.message)); + await p.route("**/*", server(lang, theme, reported, asked)); + await p.goto("http://magpie.test/" + query); + if (!query) { + await p.locator('[data-view="usage"]').first().click(); + await p.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click(); + } + await p.locator("#ledVia .blk").first().waitFor(); + return { p, errors, asked }; + }; + const lastAsked = async (asked, want) => { + for (let i = 0; i < 60 && !(asked.length && want(asked.at(-1))); i++) await new Promise((r) => setTimeout(r, 40)); + assert(asked.length && want(asked.at(-1)), "asked: " + (asked.at(-1) || "")); + }; + const labels = (p) => p.locator("#ledVia .blk .k").allTextContents(); + const fits = (p) => p.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1 && + [...document.querySelectorAll("#ledVia .blk")].every((b) => { const r = b.getBoundingClientRect(); return r.left >= -1 && r.right <= innerWidth + 1 && b.scrollWidth <= b.clientWidth + 1; })); + + for (const lang of Object.keys(L)) { + const w = L[lang]; + for (const width of [1180, 420]) { + await t.test(`${lang} at ${width}`, async () => { + const { p, errors, asked } = await open(lang, { width, theme: width < 600 ? "dark" : "light" }); + assert.deepEqual(await labels(p), w.cells); + // the total is the three sources together + const counts = await p.locator("#ledVia .blk .v").evaluateAll((vs) => vs.map((v) => parseInt(v.firstChild.textContent.replace(/\D/g, ""), 10))); + assert.deepEqual(counts, [25, 8, 12, 5]); + // in a row at a wide window, stacked at a narrow one, and either way inside it + const tops = await p.locator("#ledVia .blk").evaluateAll((bs) => bs.map((b) => Math.round(b.getBoundingClientRect().top))); + if (width > 600) assert.equal(new Set(tops).size, 1, "four in a row: " + tops); + else assert.equal(new Set(tops).size, 4, "stacked: " + tops); + assert(await fits(p), "the cells fit and the page doesn't scroll sideways"); + // no native select, and no coloured stripe down a cell's or the badge's side + assert.equal(await p.locator("#ledVia select, #view-usage select").count(), 0); + const sides = await p.locator("#ledVia .blk, .led .src.reported").evaluateAll((bs) => bs.map((b) => parseFloat(getComputedStyle(b).borderLeftWidth))); + assert(sides.every((s) => s <= 1), "no left accent: " + sides); + + // the reported row says so + const badge = p.locator(".led .src.reported"); + await badge.first().waitFor(); + assert.equal(await badge.count(), 1); + assert.equal(await badge.textContent(), w.badge); + assert((await badge.getAttribute("title")).includes("POST /v1/magpie/usage/requests")); + if (shots) await p.screenshot({ path: path.join(shots, `reported-${engine}-${lang}-${width}.png`) }); + + // picking it lists only them, and the total is the way back + // stacked at a narrow window, the fourth is under the window's + // foot: the reader scrolls down to it + await reach(p, p.locator("#ledVia .blk").nth(3)); + await p.locator("#ledVia .blk").nth(3).click(); + await lastAsked(asked, (q) => q.get("via") === "reported"); + await p.locator("#ledVia .blk:nth-child(4).on[aria-pressed=true]").waitFor(); + assert.equal(await p.locator("#ledVia .blk.on").count(), 1); + assert.deepEqual(await labels(p), w.cells, "the cells stay while one is picked"); + await reach(p, p.locator("#ledVia .blk").nth(0)); + await p.locator("#ledVia .blk").nth(0).click(); + await lastAsked(asked, (q) => !q.has("via")); + await p.locator("#ledVia .blk:nth-child(1).on").waitFor(); + assert.deepEqual(errors, []); + }); + } + } + + await t.test("none reported: three cells, as before", async () => { + const { p, errors } = await open("en", { reported: false }); + assert.deepEqual(await labels(p), L.en.cells.slice(0, 3)); + assert.equal(await p.locator("#ledVia").evaluate((v) => getComputedStyle(v).gridTemplateColumns.split(" ").length), 3); + assert.equal(await p.locator(".led .src.reported").count(), 0); + assert.deepEqual(errors, []); + }); + + await t.test("a link with via=reported opens on them", async () => { + const { p, errors, asked } = await open("en", { query: "?view=usage&tab=requests&via=reported" }); + await lastAsked(asked, (q) => q.get("via") === "reported"); + await p.locator("#ledVia .blk:nth-child(4).on[aria-pressed=true]").waitFor(); + assert.deepEqual(errors, []); + }); + }); +} diff --git a/internal/usage/block_price.go b/internal/usage/block_price.go index f1c7f1209..3028815da 100644 --- a/internal/usage/block_price.go +++ b/internal/usage/block_price.go @@ -16,7 +16,7 @@ const swapKnown = 64 // one provider, model, served model and effort. type pricedAs struct { provider string - flags uint8 + flags uint16 price *catalog.Price } @@ -115,7 +115,7 @@ func (b *blockPricer) block(packed *rowChunk) *rowChunk { } type ids struct { provider uint32 - flags uint8 + flags uint16 price *catalog.Price } names := map[[4]uint32]ids{} @@ -136,6 +136,13 @@ func (b *blockPricer) block(packed *rowChunk) *rowChunk { } 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 diff --git a/internal/usage/gateway_sessions.go b/internal/usage/gateway_sessions.go index bba445b7e..5467e314c 100644 --- a/internal/usage/gateway_sessions.go +++ b/internal/usage/gateway_sessions.go @@ -179,7 +179,7 @@ func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map daily := map[dayKey]*GatewayDayUsage{} perSession := map[key]map[dayKey]*GatewayDayUsage{} snapshot.visit(since, func(r Record) { - if r.IsRejected() || r.Session == "" { + if r.IsRejected() || r.IsReported() || r.Session == "" { return } a := AgentOf(r.Agent) diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go index 33b6655dc..71fb40145 100644 --- a/internal/usage/ledger.go +++ b/internal/usage/ledger.go @@ -64,8 +64,8 @@ type Filter struct { // Computer narrows to the calls of one computer (#542): ThisComputer, // OtherComputers, or another's id; "" is every computer's Computer string - // Through narrows to one of the two sources a row can be of - // (SourceGateway, SourceSession); "" keeps both. It is what the requests + // Through narrows to one of the sources a row can be of + // (SourceGateway, SourceSession, SourceReported); "" keeps all. It is what the requests // page's source cells filter by, and, as with the other dimensions, the // cells themselves are counted with it cleared so all three stay // switchable. Not Record.Via, which is the computer that forwarded the @@ -74,13 +74,17 @@ type Filter struct { } // SourceGateway and SourceSession are the two sources a request row is of, -// which Row.Source spells "log" and "": the calls magpie's own gateway +// which Row.Source spells "" and "log": the calls magpie's own gateway // served, and the ones read from the agents' own session files, which it // never saw. They are the requests page's source cells, and the values its // via= takes. const ( SourceGateway = "through" SourceSession = "direct" + // SourceReported is the third: the calls a client reported through + // POST /v1/magpie/usage/requests (#1874), which went straight to their + // vendor. Record.Source and Row.Source spell it the same, as does via=. + SourceReported = "reported" ) // SourceOf is the source a row is of, as the page's cells name them: the @@ -92,8 +96,11 @@ func SourceOf(r Row) string { if r.IsRejected() { return "" } - if r.Source == "log" { + switch r.Source { + case "log": return SourceSession + case SourceReported: + return SourceReported } return SourceGateway } @@ -376,7 +383,7 @@ func ledgerMatched(since, until time.Time, f Filter, recs []Record, logs []sessi if r.Provider != "" && !slices.Contains(providers, r.Provider) { providers = append(providers, r.Provider) } - if !f.keeps(r) { + if !f.keepsRow(Row{Record: r, Source: source}) { return } if !r.IsRejected() { @@ -401,7 +408,7 @@ func ledgerMatched(since, until time.Time, f Filter, recs []Record, logs []sessi if id, ok := renamed[r.Provider]; ok { r.Provider = id } - add(r, priceOf(r), "") + add(r, priceOf(r), r.Source) } for i, c := range logs { if (!since.IsZero() && c.Time.Before(since)) || after(until, c.Time) || matched[i] { @@ -432,6 +439,11 @@ func ledgerMatched(since, until time.Time, f Filter, recs []Record, logs []sessi return rows, sum, agents, providers } +// ownPrice is what pricer answers for a reported call that said what it +// cost: a price, so the call counts as priced, which Record.CostAt passes +// over for the call's own cost. +var ownPrice catalog.Price + // pricer uses the same effective price as the model CLI and session totals: // explicit provider/model or provider-wide prices (including zero), then the // provider catalog, then the maker catalog. Settings are read once per query. @@ -446,6 +458,9 @@ func pricer() func(Record) *catalog.Price { prices := map[[3]string]*catalog.Price{} s := settings.Load() return func(r Record) *catalog.Price { + if r.OwnCost != nil { + return &ownPrice // CostAt answers its own cost (#1874) + } served := strings.TrimSpace(r.Served) if served == r.Model { served = "" diff --git a/internal/usage/log_index.go b/internal/usage/log_index.go index 22f8054e6..402858334 100644 --- a/internal/usage/log_index.go +++ b/internal/usage/log_index.go @@ -29,16 +29,20 @@ const ( // for 750k calls, on every refresh and filter of the Requests page. type logSnapshot struct { - bytes int64 - settled bool - path string - info os.FileInfo - off int64 - hash string // SHA-256 of the log's first off bytes, the ones parsed - digest []byte // the hash's running state, which the next parse continues - version uint64 - blocks []*rowChunk - first time.Time + bytes int64 + settled bool + path string + info os.FileInfo + off int64 + hash string // SHA-256 of the log's first off bytes, the ones parsed + digest []byte // the hash's running state, which the next parse continues + version uint64 + blocks []*rowChunk + first time.Time + // firstOwn is the first call magpie carried itself, leaving out what + // apps reported (#1874): a backfill reaching back doesn't make the log + // reach back to a subscription window's start. + firstOwn time.Time keyProviders map[string]bool } @@ -102,7 +106,7 @@ func readLogSnapshot() *logSnapshot { // the old snapshot's hash when it continues its blocks. sum := sha256.New() if continued && resumeLogHash(sum, old.digest) { - next.off, next.first = old.off, old.first + next.off, next.first, next.firstOwn = old.off, old.first, old.firstOwn next.blocks = slices.Clone(old.blocks) next.keyProviders = maps.Clone(old.keyProviders) } @@ -140,11 +144,14 @@ func readLogSnapshot() *logSnapshot { tail = &rowChunk{} } routes.handedOn(tail, &r) - tail.add(Row{Record: r}, "", next.off, false) + tail.add(Row{Record: r, Source: r.Source}, "", next.off, false) routes.seen(tail, len(tail.Rows)-1) if !r.IsRejected() && (next.first.IsZero() || r.Time.Before(next.first)) { next.first = r.Time } + if !r.IsRejected() && !r.IsReported() && (next.firstOwn.IsZero() || r.Time.Before(next.firstOwn)) { + next.firstOwn = r.Time + } if r.ProviderKeyID != "" { next.keyProviders[r.Provider] = true } diff --git a/internal/usage/reported.go b/internal/usage/reported.go new file mode 100644 index 000000000..c49b5bd4e --- /dev/null +++ b/internal/usage/reported.go @@ -0,0 +1,147 @@ +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 +} diff --git a/internal/usage/reported_test.go b/internal/usage/reported_test.go new file mode 100644 index 000000000..5a9fc5244 --- /dev/null +++ b/internal/usage/reported_test.go @@ -0,0 +1,220 @@ +package usage + +import ( + "bytes" + "fmt" + "math" + "os" + "path/filepath" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +func reportedHome(t *testing.T) { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755) + os.WriteFile(catalog.CachePath(), []byte(`{"anthropic":{"id":"anthropic","models":{"claude-opus-5-5":{"id":"claude-opus-5-5","cost":{"input":4,"output":20,"cache_read":0.2,"cache_write":5}}}}}`), 0o644) + catalog.Reset() + t.Cleanup(catalog.Reset) + forgetReported() + t.Cleanup(forgetReported) +} + +// forgetReported is a restart, as far as what was reported goes. +func forgetReported() { + reported.ingest.Lock() + reported.path, reported.info, reported.off, reported.rids = "", nil, 0, nil + reported.ingest.Unlock() +} + +// A reported call (#1874) is written beside the gateway's own, marked +// reported: priced at magpie's prices when it said no cost, at its own +// when it did; counted in the totals and in a source of its own, which +// via=reported narrows to and the gateway's "through" leaves out. A rid +// already reported is skipped, in one batch, in a later one, and after a +// restart, which reads the log again. +func TestIngestReported(t *testing.T) { + reportedHome(t) + now := time.Now().Add(-time.Hour) + Append(Record{Time: now.Add(-time.Minute), Agent: "claude", Provider: "claude", Model: "claude-opus-5-5", Input: 1000, Output: 100, Status: 200, RequestID: "gw-1"}) + own := 0.25 + recs := []Record{ + {Time: now, Agent: "my-app", Provider: "claude", Model: "claude-opus-5-5", Input: 1_000_000, Output: 100_000, CacheRead: 1_000_000, Status: 200, RequestID: "r-1"}, + {Time: now.Add(time.Second), Agent: "my-app", Provider: "claude", Model: "claude-opus-5-5", Input: 10, Output: 1, Status: 200, RequestID: "r-2", OwnCost: &own}, + {Time: now.Add(2 * time.Second), Agent: "my-app", Provider: "claude", Model: "claude-opus-5-5", Input: 10, Output: 1, Status: 200, RequestID: "r-1"}, + // a gateway call's rid is no reported call's + {Time: now.Add(3 * time.Second), Agent: "my-app", Provider: "nowhere", Model: "mystery", Input: 5, Output: 5, Status: 200, RequestID: "gw-1"}, + } + took, err := IngestReported(recs) + if err != nil || fmt.Sprint(took) != "[true true false true]" { + t.Fatal(took, err) + } + if took, err := IngestReported(recs[:2]); err != nil || fmt.Sprint(took) != "[false false]" { + t.Fatal("again:", took, err) + } + forgetReported() + if took, err := IngestReported(append(recs[:2:2], Record{Time: now, Agent: "my-app", Provider: "claude", Model: "x", Status: 200, RequestID: "r-3"})); err != nil || fmt.Sprint(took) != "[false false true]" { + t.Fatal("after a restart:", took, err) + } + b, _ := os.ReadFile(Path()) + if n := bytes.Count(b, []byte(`"source":"reported"`)); n != 4 { + t.Fatalf("%d reported lines:\n%s", n, b) + } + + priced := (1e6*4 + 1e5*20 + 1e6*0.2) / 1e6 + page := QueryPage(All, Filter{}, 0, 50) + if page.Total != 5 || page.Reported.Calls != 4 || page.Through.Calls != 1 || page.Direct.Calls != 0 { + t.Fatalf("total %d, reported %+v, through %+v", page.Total, page.Reported, page.Through) + } + byRID := map[string]Row{} + for _, r := range page.Rows { + byRID[r.RequestID+"/"+r.Source] = r + } + if r := byRID["r-1/reported"]; !r.Priced || math.Abs(r.Cost-priced) > 1e-9 || SourceOf(r) != SourceReported { + t.Fatalf("priced at magpie's prices: %+v", r) + } + if r := byRID["r-2/reported"]; !r.Priced || r.Cost != own || r.OwnCost == nil || *r.OwnCost != own { + t.Fatalf("its own cost: %+v", r) + } + if r := byRID["gw-1/reported"]; r.Priced || r.Cost != 0 { + t.Fatalf("an unknown model is unpriced: %+v", r) + } + if r := byRID["gw-1/"]; r.Agent != "claude" || SourceOf(r) != SourceGateway { + t.Fatalf("the gateway's own: %+v", r) + } + if want := priced + own + (1000*4+100*20)/1e6; math.Abs(page.Sum.Cost-want) > 1e-9 { + t.Fatalf("sum cost %v, want %v", page.Sum.Cost, want) + } + if p := QueryPage(All, Filter{Through: SourceReported}, 0, 50); p.Total != 4 || p.Reported.Calls != 4 || p.Through.Calls != 1 { + t.Fatalf("via=reported: %d rows, %+v / %+v", p.Total, p.Reported, p.Through) + } + if p := QueryPage(All, Filter{Through: SourceGateway}, 0, 50); p.Total != 1 || p.Rows[0].RequestID != "gw-1" { + t.Fatalf("via=through: %+v", p.Rows) + } + if s := Summarize(All); s.Calls != 5 || math.Abs(s.Cost-page.Sum.Cost) > 1e-9 { + t.Fatalf("summary %d calls, cost %v; the page %v", s.Calls, s.Cost, page.Sum.Cost) + } + if rows, _, _ := Ledger(All, Filter{Through: SourceReported}); len(rows) != 4 { + t.Fatalf("ledger via=reported: %d", len(rows)) + } +} + +// Posts at once, and the gateway's own calls between them, keep every +// line whole, and a rid posted by several at once is written once. +func TestIngestReportedConcurrent(t *testing.T) { + reportedHome(t) + now := time.Now().Add(-time.Hour) + const posts, each = 16, 40 + var wg sync.WaitGroup + accepted := make([]int, posts) + for p := range posts { + wg.Add(2) + go func() { + defer wg.Done() + var recs []Record + for i := range each { + // half the rids every post sends, half its own + rid := fmt.Sprintf("shared-%d", i) + if i%2 == 1 { + rid = fmt.Sprintf("own-%d-%d", p, i) + } + recs = append(recs, Record{Time: now, Agent: "my-app", Provider: "claude", Model: "claude-opus-5-5", Input: 1, Output: 1, Status: 200, RequestID: rid}) + } + took, err := IngestReported(recs) + if err != nil { + t.Error(err) + } + for _, ok := range took { + if ok { + accepted[p]++ + } + } + }() + go func() { + defer wg.Done() + Append(Record{Time: now, Agent: "claude", Provider: "claude", Model: "claude-opus-5-5", Input: 1, Output: 1, Status: 200}) + }() + } + wg.Wait() + total := 0 + for _, n := range accepted { + total += n + } + if want := each/2 + posts*each/2; total != want { + t.Fatalf("accepted %d, want %d", total, want) + } + recs := Load(time.Time{}) + if len(recs) != total+posts { + t.Fatalf("%d lines, want %d", len(recs), total+posts) + } + seen := map[string]bool{} + for _, r := range recs { + if r.Source != SourceReported { + continue + } + if seen[r.RequestID] { + t.Fatal("written twice:", r.RequestID) + } + seen[r.RequestID] = true + } +} + +// What apps report (#1874), backfilled or not, is shown on the Usage page +// and nowhere that acts on live traffic: not as a gateway session, not in +// what a session was routed to, not in a subscription window's holds, and a +// backfill reaching back doesn't make the log reach back to a window's start. +func TestReportedTouchesNothingLive(t *testing.T) { + reportedHome(t) + now := time.Now() + gw := Record{Time: now.Add(-time.Hour), Agent: "claude", Provider: "claude", ProviderAccount: "dee@example.com", Model: "claude-opus-5-5", Input: 100, Output: 100, Status: 200, Session: "s-gw"} + Append(gw) + if took, err := IngestReported([]Record{ + {Time: now.Add(-30 * 24 * time.Hour), Agent: "claude", Provider: "claude", Model: "claude-opus-5-5", Input: 9000, Output: 9000, Status: 200, RequestID: "old", Session: "s-rep"}, + {Time: now.Add(-2 * time.Hour), Agent: "claude", Provider: "claude", Model: "claude-opus-5-5", Input: 9000, Output: 9000, Status: 200, RequestID: "new", Session: "s-rep"}, + }); err != nil || fmt.Sprint(took) != "[true true]" { + t.Fatal(took, err) + } + // a row that says it was reported and names an account, as an older or + // hand-made line might + Append(Record{Time: now.Add(-3 * time.Hour), Agent: "claude", Provider: "claude", ProviderAccount: "dee@example.com", Model: "claude-opus-5-5", Input: 9000, Output: 9000, Status: 200, RequestID: "acct", Source: SourceReported}) + + s := readLogSnapshot() + if math.Abs(s.firstOwn.Sub(gw.Time).Seconds()) > 1e-3 { + t.Fatalf("the log's own first call %v, want %v", s.firstOwn, gw.Time) + } + if s.first.After(now.Add(-29 * 24 * time.Hour)) { + t.Fatalf("the chart's first call %v is after the backfill", s.first) + } + for _, g := range GatewaySessions(time.Time{}, nil) { + if g.ID == "s-rep" { + t.Fatalf("a reported session is a gateway session: %+v", g) + } + } + if v := Vias(time.Time{})["claude|s-rep"]; len(v) != 0 { + t.Fatalf("a reported session was routed: %+v", v) + } + if !(Record{Source: SourceReported}).IsReported() || (Record{}).IsReported() { + t.Fatal("IsReported") + } + reset := now.Add(3 * 24 * time.Hour) + qs := []provider.SubscriptionQuota{{Provider: "claude", User: "dee@example.com", Windows: []provider.QuotaWindow{ + {Name: "7 days", Used: 40, ResetsAt: &reset, Span: 7 * 24 * time.Hour}}}} + if h := WithWindowHolds(qs, now)[0].Windows[0].Holds; h != nil { + t.Fatalf("the gateway's log began an hour ago, and the week was reckoned: %+v", h) + } + // with the gateway's own log reaching back, the week counts its call only + Append(Record{Time: now.Add(-20 * 24 * time.Hour), Agent: "claude", Provider: "claude", Model: "claude-opus-5-5", Input: 1, Output: 1, Status: 200}) + h := WithWindowHolds(qs, now)[0].Windows[0].Holds + if h == nil || h.Routed.Calls != 1 || h.Routed.Tokens != 200 { + t.Fatalf("the week holds %+v, want the gateway's one call", h) + } +} diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index 97262f13e..a618c5bbd 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -39,6 +39,9 @@ type RequestPage struct { // is the two together; the page shows the three beside each other so a // reader can tell what magpie carried from what it only read about. Through, Direct Totals + // Reported are the calls a client told magpie of (#1874), which went + // straight to their vendor: counted in Sum, apart from both of those. + Reported Totals // Accounts are the subscription accounts that answered calls in the // period, by provider and account, for the Account filter (#557) Accounts []Group @@ -67,12 +70,17 @@ type packedRow struct { RouteID int64 Cost float64 Status, Tries int32 - Flags uint8 + Flags uint16 } // rowHandedOn is the Flags bit of Record.HandedOn const rowHandedOn = 128 +// rowOwnCost marks a reported call that said what it cost (#1874): Cost is +// that, which the block pricer keeps, and reading the row back gives +// Record.OwnCost again. +const rowOwnCost = 256 + type rowChunk struct { Archive []byte Locations []*time.Location @@ -139,6 +147,10 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) { if r.HandedOn { p.Flags |= rowHandedOn } + if r.OwnCost != nil { + p.Flags |= rowOwnCost + p.Cost = *r.OwnCost + } c.Rows = append(c.Rows, p) c.Count = len(c.Rows) if r.Time.After(c.Latest) { @@ -155,6 +167,13 @@ func (c *rowChunk) row(i int) Row { if r.Swapped && p.Flags&swapKnown == 0 && (SameSpelled(r.Model, r.Served) || ServingName(r.Model, r.Served) || RelayRenamed(r.Model, r.Served)) { r.Swapped = false // kept before a name spelled otherwise, a vendor's serving name or a relay's rename was the same } + if r.Source == SourceReported { + r.Record.Source = SourceReported + if p.Flags&rowOwnCost != 0 { + own := p.Cost + r.OwnCost = &own + } + } r.Computer = c.Computer return r } @@ -829,9 +848,12 @@ func buildRequestBlocks(p Period, f Filter, offset, limit int, now time.Time, ga // while another is picked, or one of them would read 0 and // there would be no way back. if !r.IsRejected() && viaFilter.keepsRow(r) { - if r.Source == "log" { + switch r.Source { + case "log": out.Direct.addRow(r) - } else { + case SourceReported: + out.Reported.addRow(r) + default: out.Through.addRow(r) } } @@ -1015,9 +1037,12 @@ func pageFromLedgerAt(p Period, f Filter, offset, limit int, all Ledgered, now t if r.IsRejected() || !viaFilter.keepsRow(r) { continue } - if r.Source == "log" { + switch r.Source { + case "log": out.Direct.addRow(r) - } else { + case SourceReported: + out.Reported.addRow(r) + default: out.Through.addRow(r) } } diff --git a/internal/usage/request_snapshot.go b/internal/usage/request_snapshot.go index acbc3d077..8b3a2a6b8 100644 --- a/internal/usage/request_snapshot.go +++ b/internal/usage/request_snapshot.go @@ -154,7 +154,7 @@ func (c *rowChunk) unpackInto(into []packedRow) *rowChunk { p.RouteID = int64(take()) p.Sent, p.Flow = int64(take()), int64(take()) p.Own, p.Retried, p.Queued = int64(take()), int64(take()), int64(take()) - p.Cost, p.Status, p.Flags = math.Float64frombits(take()), int32(take()), uint8(take()) + p.Cost, p.Status, p.Flags = math.Float64frombits(take()), int32(take()), uint16(take()) p.Tries = int32(take()) } if !valid || len(data) != 0 { diff --git a/internal/usage/usage.go b/internal/usage/usage.go index dab43a9ae..3f368a35c 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -166,6 +166,16 @@ type Record struct { // a call brought here by sync (#542); "" for one made here, as every // call in usage.jsonl is Computer string `json:"computer,omitempty"` + // Source is SourceReported for a call a client told magpie of through + // POST /v1/magpie/usage/requests (#1874), one that went straight to its + // vendor and that magpie never saw; "" for the gateway's own. Reported + // calls count in the totals and are told apart, and filtered, on the + // page. + Source string `json:"source,omitempty"` + // OwnCost is what such a client said the call cost, in USD. nil when it + // said nothing: the call is then priced at magpie's own prices, as the + // gateway's calls are, and priced again when those change. + OwnCost *float64 `json:"cost,omitempty"` // OTel is transient trace context; SkipOTel avoids exporting ledger records // when the gateway exports its attempts separately. Neither is persisted. OTel *OTelSpan `json:"-"` @@ -220,6 +230,14 @@ func Append(r Record) { // IsRejected also recognizes local rejections written before the explicit flag. func (r Record) IsRejected() bool { return r.Rejected || r.Provider == "" && r.Status >= 400 } +// IsReported is a call an app reported itself (#1874), which never went +// through magpie. It is shown and counted on the Usage page only: nothing +// that acts on live traffic (a key's budget, a window's holds, the Sessions +// page's gateway sessions, what a session was routed to, Codex's sealed +// answers or remembered model) reads it, since it may be a backfill of +// calls long past and none of them were magpie's to route. +func (r Record) IsReported() bool { return r.Source == SourceReported } + // Load streams complete records from the log. Historical request bodies are // not retained by a global cache after the caller finishes with this snapshot. func Load(since time.Time) []Record { @@ -328,8 +346,12 @@ const ( var Periods = []Period{Today, Week, Month, All} // CostAt is what the call costs at a price: at the tier its input reaches, -// its 1-hour cache writes at theirs. +// its 1-hour cache writes at theirs. A reported call that said what it +// cost costs that, at any price. func (r Record) CostAt(p catalog.Price) float64 { + if r.OwnCost != nil { + return *r.OwnCost // a reported call's own cost (#1874) + } return p.CostSplit(r.Input, r.Output, r.CacheRead, r.CacheWrite, r.CacheWrite1h) } @@ -920,7 +942,7 @@ func Vias(since time.Time) map[string][]Via { func buildVias(snapshot *logSnapshot, since time.Time) map[string][]Via { out := map[string][]Via{} snapshot.visit(since, func(r Record) { - if r.IsRejected() || r.Session == "" || r.Model == "" { + if r.IsRejected() || r.IsReported() || r.Session == "" || r.Model == "" { return } k := AgentOf(r.Agent) + "|" + r.Session diff --git a/internal/usage/window_holds.go b/internal/usage/window_holds.go index c3cf12f22..24caa706b 100644 --- a/internal/usage/window_holds.go +++ b/internal/usage/window_holds.go @@ -25,7 +25,7 @@ func WithWindowHolds(qs []provider.SubscriptionQuota, now time.Time) []provider. return qs } s := readLogSnapshot() - return windowHolds(qs, now, s.first, apiPricer(), provider.Renamed(), func(fn func(Record)) { s.visit(since, fn) }) + 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. @@ -96,7 +96,7 @@ func windowHolds(qs []provider.SubscriptionQuota, now, first time.Time, priceOf sums := map[slot]*provider.WindowHolds{} unpriced := map[slot]bool{} read(func(r Record) { - if r.IsRejected() || r.Input+r.Output == 0 { + if r.IsRejected() || r.IsReported() || r.Input+r.Output == 0 { return } if next, ok := renamed[r.Provider]; ok { diff --git a/internal/usageapi/usageapi.go b/internal/usageapi/usageapi.go index db4271429..92525a418 100644 --- a/internal/usageapi/usageapi.go +++ b/internal/usageapi/usageapi.go @@ -155,7 +155,7 @@ func FilterOf(q url.Values) usage.Filter { // viaOf is the source a request's ?via= names, "" for both. func viaOf(s string) string { switch s { - case usage.SourceGateway, usage.SourceSession: + case usage.SourceGateway, usage.SourceSession, usage.SourceReported: return s } return "" @@ -196,6 +196,9 @@ type Ledger struct { // the two together, so the page can show all three (#the usage report). Through usage.Totals `json:"through"` Direct usage.Totals `json:"direct"` + // Reported: the calls a client told magpie of through POST + // /v1/magpie/usage/requests (#1874), which went straight to their vendor + Reported usage.Totals `json:"reported"` // Agents, Providers and Purposes: those with calls in the period, for the filters Agents []Named `json:"agents"` Providers []Named `json:"providers"` @@ -264,7 +267,7 @@ func LedgerPage(p usage.Period, f usage.Filter, offset, limit int) Ledger { return a } out := Ledger{Period: p, Rows: make([]Row, 0, len(page)), Offset: offset, Total: l.Total, Totals: l.Sum, Agents: []Named{}, Providers: []Named{}, Accounts: []Account{}} - out.Through, out.Direct = l.Through, l.Direct + out.Through, out.Direct, out.Reported = l.Through, l.Direct, l.Reported out.Bucket, out.Series = l.Bucket, l.Series out.Purposes = l.Purposes out.Day = f.Day @@ -276,10 +279,10 @@ func LedgerPage(p usage.Period, f usage.Filter, offset, limit int) Ledger { for _, r := range page { a := who(r.Agent) lr := Row{Row: r, AgentName: a.Name, Icon: a.Icon, ProviderName: names[r.Provider]} - if r.Source != "log" { + if r.Source != "log" && r.Source != usage.SourceReported { lr.Access = access[r.Provider] } - if r.Priced { + if r.Priced && r.OwnCost == nil { if model := provider.PricedNameFor(r.Provider, r.Model); model != r.Model { lr.PricingModel = model } diff --git a/site/public/docs/integrate.html b/site/public/docs/integrate.html index 90d549bf0..bfae5ed75 100644 --- a/site/public/docs/integrate.html +++ b/site/public/docs/integrate.html @@ -116,7 +116,7 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"GET /v1/models lists what the user has turned on: id (provider/model, or a routing group’s name, sent as it is), display_name, owned_by (the provider), reasoning and supported_reasoning_levels ([{"effort":"low"},…]), context_window and max_output_tokens when known, and modalities when magpie knows whether it takes images. List them from there rather than shipping a list: the user adds and removes providers in magpie. Reasoning is asked in your API’s own field (reasoning_effort, reasoning.effort, Anthropic’s thinking or output_config.effort). ?format=text gives the ids one a line.

Optional

-

Send X-Magpie-Session: <id> with a conversation’s requests and GET /v1/magpie/route?session=<id> says which model a routing group picked for the turn and the fallbacks it tried, before the first token (long-poll with after=<seq>&wait=<s>). GET /v1/magpie/quotas lists the user’s subscription allowances, and GET /v1/magpie/usage and /v1/magpie/usage/requests the Usage page’s numbers and its requests (with session, and subagent/parent_agent for a Claude Code subagent’s call). They answer only this machine, or another with a gateway key; a key held to a budget, models or accounts sees its own calls alone. The reference has the details.

+

Send X-Magpie-Session: <id> with a conversation’s requests and GET /v1/magpie/route?session=<id> says which model a routing group picked for the turn and the fallbacks it tried, before the first token (long-poll with after=<seq>&wait=<s>). GET /v1/magpie/quotas lists the user’s subscription allowances, and GET /v1/magpie/usage and /v1/magpie/usage/requests the Usage page’s numbers and its requests (with session, and subagent/parent_agent for a Claude Code subagent’s call). They answer only this machine, or another with a gateway key; a key held to a budget, models or accounts sees its own calls alone. Calls your app makes to its vendor itself can be reported with POST /v1/magpie/usage/requests (one record or up to 5000 a post, in usage.jsonl’s shape, each with a rid; past times are kept, so a history can be backfilled). They show on the Usage page as reported, and never count against a key’s limit. The reference has the details.

Keep the user’s providers. Add magpie as one more provider (named Magpie) beside the ones the user set up in your app, rather than replacing them, so turning magpie off is picking another provider.
diff --git a/site/public/docs/zh/integrate.html b/site/public/docs/zh/integrate.html index 2e22afcee..3fb0e7c20 100644 --- a/site/public/docs/zh/integrate.html +++ b/site/public/docs/zh/integrate.html @@ -116,7 +116,7 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"GET /v1/models 列出用户打开的模型:id(provider/model,或路由组的名字,原样发送即可)、display_name、owned_by(供应商)、reasoning 与 supported_reasoning_levels([{"effort":"low"},…]),已知时还有 context_window、max_output_tokens,以及 magpie 知道是否支持图片时的 modalities。请从这里读取,而不是内置一份列表:用户会在 magpie 里增删供应商。推理强度用你所用 API 自己的字段传(reasoning_effort、reasoning.effort、Anthropic 的 thinking 或 output_config.effort)。?format=text 每行一个 id。

可选

-

在同一会话的请求里带上 X-Magpie-Session: <id>,GET /v1/magpie/route?session=<id> 就能在第一个 token 之前告诉你路由组为这一轮选了哪个模型、尝试过哪些后备(用 after=<seq>&wait=<s> 长轮询)。GET /v1/magpie/quotas 列出用户各订阅的额度,GET /v1/magpie/usage 和 /v1/magpie/usage/requests 给出用量页的统计和逐条请求(带 session;Claude Code 子代理的调用还有 subagent/parent_agent)。它们只回答本机,或带网关密钥的其他机器;限了额度、模型或账号的密钥只看得到自己的调用。细节见参考文档。

+

在同一会话的请求里带上 X-Magpie-Session: <id>,GET /v1/magpie/route?session=<id> 就能在第一个 token 之前告诉你路由组为这一轮选了哪个模型、尝试过哪些后备(用 after=<seq>&wait=<s> 长轮询)。GET /v1/magpie/quotas 列出用户各订阅的额度,GET /v1/magpie/usage 和 /v1/magpie/usage/requests 给出用量页的统计和逐条请求(带 session;Claude Code 子代理的调用还有 subagent/parent_agent)。它们只回答本机,或带网关密钥的其他机器;限了额度、模型或账号的密钥只看得到自己的调用。你的应用直接发给厂商、不经过 magpie 的调用,可以用 POST /v1/magpie/usage/requests 上报(每次一条,或最多 5000 条,格式同 usage.jsonl 的一行,每条带 rid;过去的时间照原样保留,所以可以补录历史)。它们在用量页上标为上报,且从不计入密钥的限额。细节见参考文档。

保留用户自己的供应商。把 magpie 作为又一个供应商(名为 Magpie)加在用户已有的供应商旁边,而不是替换它们,这样关掉 magpie 就只是换选另一个供应商。