6b3ee5a03bd32bdf584e793de79c8dabfea463dc
5
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
6d19988416 |
usage: a provider the log names but that isn't set up now goes by its name, "Claude Code", not "claude" (@ByronVon1 on X)
The Requests page's Provider filter listed "claude" between named providers. The usage log keeps the id of every provider a call went to, and usageapi named those only from provider.All(). The Claude Code subscription is in that list only while its account is discovered, so after a sign-out, with account discovery off, or for a preset provider removed since, the bare id showed. This happened in the filter, each row's Provider column, the split-by-provider and model-at-provider legends, the Account filter's provider notes, and the summary's model and account subtitles (stateOf had its own copy of the same lookup). - provider.KnownFace(id): the name and icon magpie knows an id by while it isn't set up. It covers the built-in subscriptions' card faces (accountCard: Claude Code, Codex, Copilot, Gemini, Antigravity, moved ones) and then the presets. A custom provider removed since stays its id, since nothing else knows its name. - usageapi.providerFaces: one lookup for LedgerPage and stateOf, in order: the provider set up, "Local session" for session-unknown, then KnownFace, then the id. Run: - TestProvidersNotSetUpAreNamed (new, internal/usageapi). Fails on the old code with 13 errors across the filter, rows, both splits, the Account filter and the summary; passes with the fix. - gofmt -l: clean. go vet for usageapi, provider, gateway, gui on darwin, and usageapi, provider on GOOS=linux and windows: clean. - go test ./internal/usageapi ./internal/usage: ok. - go test ./internal/provider ./internal/gateway ran at load average ~300 with other sessions' suites. Three timing tests went red, and each passes 3/3 alone (-count=3 -run): TestCopilotSecretToolUsername (#1627, commented), TestOTelFastRequestTranscriptDiscovery (#1811), and TestTranslatedStreamKeepsClientAlive (filed as #2169). TestUsageOverGateway and the gateway's TestUsage* pass. - GUI: usage-ledger.test.cjs and usage-ledger-chart.test.cjs in chromium and webkit, 52/52 (playwright 1.62.0). app.js is unchanged, since the page already shows the name the API sends. Not tried: the real GUI with a signed-out Claude account. |
||
|
|
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.
|
||
|
|
47269f448f |
usage, gateway, gui: the Requests card counts requests once, a try handed on to the next isn't a failure, and says how many were answered on a retry (小一 on Discord)
小一's Codex-on-credits ledger read "5,482 · 1,094 failed" while many rows said "2 tries/3 tries" and had been answered. "Failed" counted usage rows, not requests: besides each request's final row, the gateway writes a row for every try a vendor refused or turned away (hw.refused/hw.turnedAway), and each of those was counted as a call and a failure even when a later member answered. (Ordinary failovers write no row; 499 cancels and the agent's own client-side retries are separate requests.) In the owner's own usage.jsonl, 24 of the 71 "failed" rows were such refusals a later member answered. Now a request counts once, by how it ended: - usage.Record gains `tries` (final row, when the route took more than one) and `handed_on` (the row of a try that failed and handed the request on). Totals.count skips handed-on rows; a failure is a request whose agent got an error (LostRequest); one answered after a failed try is Totals.Retried (RetriedRequest), with a `retried=1` filter. - Logs written before this are read the same way: the log index marks a failed, non-rejected row followed by another of the same route id as handed on and raises the later row's tries (routeRows); the packed row and its snapshot carry both. - Panel card, Usage overview tile, ledger card, rankings and group rows, `magpie usage` and the TUI say "N answered on a retry"; the CSV adds `tries` and `handed_on` at the end. A row says "· handed on" (with why in its title) or "· N tries". - On the ledger's Requests card "N failed" and "N answered on a retry" are buttons that switch the list to the Failed / new Retried filter, and back when pressed again. The lines wrap rather than cut a button off (German). zh, zh-TW, ja, de strings added. - Docs: reference.md (counting, filter, CSV columns), gateway-routing.md. Run: - go test -tags nogui ./internal/usage ./internal/usageapi ./internal/tui ./internal/gateway . : ok. New TestRequestsCountedOnceWithTheirRetries (JSONL fixture: legacy refused row + 200, handed_on + 200 tries 3, 502 tries 2, plain 200, routeless 429 → 5 calls, 2 failed, 2 retried, across Ledger, QueryPage, Summarize, heatmap, filters, CSV) and TestRetriedRequestCountsOnce (group a refuses, b 500s, c answers → 1 call, 0 errors, 1 retried; a lone 400 → 1 error). - Broke each by hand (count without the HandedOn skip, gateway without HandedOn, log index without routeRows): each test went red; restored. - go test -tags nogui -timeout 40m ./... under the gotest lock, rebased on origin/main |
||
|
|
99fcddeeba |
usage: the Requests tab, its filters and refresh, the charts, the TUI and magpie usage answer at once over a long history (Vantiboo1ean)
Vantiboo1ean (Discord, macOS M2, v0.1.1157) has ~750,000 requests in usage.jsonl. On Usage > Requests every filter, model pick and refresh spun forever and the page never updated. Reproduced in a sandbox HOME with 750k generated records in the real format (400 MB usage.jsonl, ~84k sessions), on magpie web and in process. The cause: the #563 budget dropped the index's blocks once they passed 24 MB (60 MB here), so every read, of any period, parsed the whole file again (6 s CPU) and priced every call again; All took 12 s of CPU, the heatmap 13 s, and the page read both at once. What changed: - log_index: the gateway's blocks are always kept (about 80 bytes a call, S2-compressed instead of flate); the file is parsed once, then only what was appended. - block_price: the gateway's blocks are priced per query, once per set of provider/model/served/effort names rather than per call, into pooled buffers; range loops go by pointer (a packed row is 264 bytes). - request_page: pages are always cached (16 at most), session-file chunks stay in the budget, and a page asked again while it is worked out (the refresh button, the timer) waits for that one instead of starting a second scan. - Siblings that read the same history: - The heatmap names each day once. - A day filter no longer allocates per call. - The ledger behind the TUI, magpie usage, the CSV export and sync (LedgerOf, OwnDays) reads the gateway's calls from the index instead of Load parsing the whole file. - Direct/Summaries matches the session files' calls against the index's blocks without pricing all 750k gateway calls. - A summary of more than 1024 sessions is now cached with its top 1024 (it was not cached at all). The Usage page's /api/usage gets the top 100 (it was sent all 84k, 19 MB, which it never draws) plus a new sessionCount. /v1/magpie/usage still lists every session, and magpie usage says "top 10 of <sessionCount>". Timings, CPU (the box was at load 130-190 on 14 cores, so wall is inflated; min of repeated runs), before -> after: Requests today 6.0 s -> 20 ms Requests 7d 5.8 s -> 93 ms Requests 30d ~6 s -> 362 ms Requests all 12.4 s -> 2.4 s first, ~8 ms again all, model filter 12.3 s -> 1.5 s all, agent filter 11.3 s -> 1.8 s 30d, search "opus" 6.7 s -> 353 ms day filter 6.0 s -> ~0.1 s heatmap 13.7 s -> ~2.3 s first summary today / all 6.0 / 9.2 s -> 25 ms / 1.6 s first, <1 ms again /api/usage?period=all 1.6 s + 19 MB JSON each time -> <1 ms, 53 KB TUI Summaries(all) ~8.5 s (Load + ledger) -> 1.1 s first, <1 ms again TUI Summaries(today) ~6 s -> 29 ms Visit 7d (budget, codex) 5.9 s -> 10 ms The first read of the file after start costs ~5 s of CPU, once. Tests (each seen red with its guarantee broken by hand): - TestUsageOverBudgetHistoryIsReadOnce - TestUsageSessionChunksStayInBudget - TestUsageOverBudgetPageIsCached - TestUsagePageAskedTwiceIsWorkedOutOnce - TestUsageLedgerReadsTheIndexNotTheFile - TestUsageLargeSummaryIsCompleteAndKeptTrimmed (was ...ButNotCached) - TestDirectCountsOnlySessionFileCalls, now with a request-id match, checks that Direct/Summaries equal the ledger's. Run: go test -tags nogui ./... (temp HOME), gofmt -l, GOOS=linux and GOOS=windows go vet on the touched packages. |
||
|
|
b6a263b9fd |
gateway, usage: the Usage page's numbers are read over the gateway, and a Claude Code subagent's call says which subagent and which started it (HoGee_xxl on X)
HoGee_xxl wants their own usage app to read magpie over the gateway, which had no /api/usage counterpart, and asked for subagents' parent ids. - GET /v1/magpie/usage (the /api/usage summary, ?period=) and GET /v1/magpie/usage/requests (the /api/usage/requests ledger page, same filters, offset/limit) on the gateway. The builders moved out of gui into internal/usageapi so both serve the same JSON; gui keeps aliases and sets usageapi.Clients for agent names (gateway can't import agent). Guard as /v1/magpie/quotas: this machine, or another with an enabled gateway key, behind the same Host check. A key held to a budget, models or accounts is refused the summary (403) and gets the ledger filtered to its own CallerKey, with callerKeys/agents/providers/accounts cut to its own rows (usageapi.OwnPage): those facets are drawn from every call in the period. `path` is left out for another machine. - usage.Record gains subagent and parent_agent; session stays the parent conversation. Gateway rows take them from x-claude-code-agent-id and x-claude-code-parent-agent-id; session-file rows from the file name (<session>/subagents[/workflows/<run>]/agent-<id>.jsonl, no cache version bump) and the parentAgentId of the agent-<id>.meta.json beside it. Both packed into the request page's text columns (now 29, msg at 29). Codex sub-threads: only kind, as before; no spawned thread on disk to take a parent shape from. Run: real Claude Code 2.1.296 under a sandbox CLAUDE_CONFIG_DIR against a local fake Anthropic endpoint that made it spawn a subagent from a subagent: the nested request carried X-Claude-Code-Agent-Id=a143287ac46b82a96 and X-Claude-Code-Parent-Agent-Id=a99ca20c03d1813d8, the first-level one the agent id only, Session-Id the parent's throughout; the nested meta.json had parentAgentId. Tests use those bytes. TestUsageOverGateway goes red with OwnPage, the CallerKey pin, or the header read removed (each tried). gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...; set -o pipefail; go test ./... green. |