Files
magpie/internal/usage
yetone 8a1b5916f3 sessions, usage, gui: one read of every call at a time, the Codex effort built once and kept, and the Sessions page asks for an overview once, so the app no longer grows to 85 GB (#2278)
On a long history (the reporter's: 68k call files in calls-v15, 415 MB;
42 MB usage.jsonl; 75k calls in 7 days), the app's main process grew to
85 GB in about 90 minutes and the gateway froze. `magpie serve` alone held
83-153 MB for 20 minutes (the reporter's follow-up), so the growth is in
the app's Sessions path:
/api/sessions/overview -> usage.CodexModelEffort -> LedgerOfAt ->
sessions.Calls(all history).

Why it grew:
- CodexModelEffort's cache key changes on every gateway write, and it
  never kept an answer when usage.jsonl was missing or grew during the
  build. So every /api/sessions, overview, /one and /manage ask with a Codex
  session rebuilt the all-history ledger, gob-decoding every shard (only
  64 stay in memory).
- Nothing joined concurrent asks.
- The page's 15s reload asked for an overview again while the last one
  was still under way, so slow asks piled up.

What changes:
- sessions.Calls and the new AgentCalls go through sharedCalls. An ask
  while the same read is under way waits for it and gets a copy, and
  reads run one at a time.
- AgentCalls(since, "codex") reads Codex's files only. pruneCalls still
  sees every file.
- CodexModelEffort is built from Codex's calls plus the gateway's records.
  Only those name a Codex actor, and TestCodexModelEffortIsTheWholeLedgers
  checks the answer equals the whole ledger's on a mixed Claude + Codex +
  gateway fixture.
  - One build per period at a time. An ask during a build gets the last
    answer for the same home (root), or waits if there is none.
  - The answer is kept when usage.jsonl is missing or grows during the
    build.
  - At most 8 periods are kept.
- page.js: sessOverview shares one promise per query, so the filter's ask
  and the 15s reload's ask for the same overview send one request.
- docs/subsystems/gateway-sessions.md says this.

Reproduced (temporary test, not committed): a sandbox HOME with 62k
Claude Code session files, 5.9k Codex rollouts and 100k gateway records.
Sessions routes in-process, 4 rounds x 6 concurrent asks
(overview?days=0 and /api/sessions), a usage record appended every 300ms:
  before (2b0037f41): 7m39s total, slowest ask 2m01s; 66264 MB allocated
    (2761 MB per ask); peak heap in use 4620 MB, peak Go sys 6274 MB,
    peak RSS 5325 MB
  after:              20.4s total, slowest ask 7.1s; 20728 MB allocated
    (863 MB per ask); peak heap in use 1168 MB, peak Go sys 1487 MB,
    peak RSS 1415 MB
Cold warm-up (index plus every shard) was 21m before and 18.5s after on the
same home. The after run reused the shards on disk, so it is not a
comparable number.

Tests, each red on the old code:
- TestConcurrentCallsShareOneRead: 8 reads, not 1. It also goes red when
  the join is broken by hand.
- TestCodexModelEffortConcurrentAsksBuildOnce: 8 builds.
- TestCodexModelEffortAnswersLastWhileBuilding: 3 builds.
- TestCodexModelEffortKeptWithoutLogAndAcrossAWrite: 2 builds.
- sessions-overview-once.test.cjs: 2 overview requests, not 1. That is
  chromium and webkit; en, zh, zh-TW and ja at 1100/900px, de at 420px.
  It was red with the old page.js served.
TestAgentCallsReadsOneAgent and TestCodexModelEffortIsTheWholeLedgers pass
on both versions.

Run:
- gofmt -l: clean.
- go vet -tags nogui for darwin, linux and windows: sessions, usage,
  gui. Before that, the whole tree for linux and windows.
- go test -race on ./internal/sessions/ and ./internal/usage/.
- go test of internal/sessions, internal/usage and internal/gui at the
  rebased head (on 95e7c6bcc): green. gui was red once, in a run whose
  output was cut, at load ~100; it was green on two reruns.
- Full suite: SUITE_LINE
- GUI: the 13 files that ask for sessions/overview, at the rebased head,
  in chromium and webkit: 198/198. Before the rebase, those plus every
  usage*.test.cjs,
  in chromium and webkit: 749 pass. The 24 failures are usage-fold
  (#2163) and usage-agents-hide (#2276). The same 24 fail with the old
  page.js on 2b0037f41, and both are filed.

Not tried: the real app on the reporter's data; an hour-long run.
2026-10-15 23:08:00 +08:00
..
usage: each subscription account's tokens and cost, by the account that answered (#557: 希望用量账本能按订阅账号统计,每个 Codex / Claude 账号各用了多少 token、多少钱) — a call's record named the upstream key it went out on (ProviderKeyID/Name, #500) but never the subscription account, so with two Codex accounts signed in, or a Claude account that took over after a failover, the ledger could say what Codex cost and not what each account did. A record now carries providerAccount, the account that answered as the Routing trace names it (Account.User: its email or login, never a token), set by the gateway at the try that went out (the candidate loop's last try, so a failover's answer is the account that took over and the refused try stays the first account's; an X-Magpie-Account pin is the pinned one), and on the decide, draw and video paths too. Record.Account() gives it, or for a record written before the field the account its host named (Where() has long written "chatgpt.com as dee@example.com" for an account), and otherwise "" — shown as "account not recorded", never inferred from today's sign-in. The summary groups calls by provider and account (Summary.Accounts, the same email on Codex and on Claude being two accounts), priced as every other group; the ledger's Filter has Account, the search finds a call by its account, the CSV has a provider_account column beside provider_key_name (the provider's identity columns together, the caller's still last), and the Requests page's packed rows keep it and offer the period's accounts. magpie usage prints an accounts table after the provider keys, and magpie usage --csv --account <name> keeps one account's calls. The app's Usage page lists Accounts on the Overview (tokens and cost per account, the provider under its name, an unrecorded one in the faint colour, no stripe down a row's side) and has an Account filter on Requests, each account noting the providers it answered for, which asks for and exports that account's calls without moving the page. OTLP export is an allowlist and does not carry the account. TestUsageNamesPinnedAccount (both pinned accounts on magpie's endpoint and on Codex's own, the trace's Who and the record agreeing, no token in usage.jsonl) and TestUsageNamesAccountThatTookOver (Ordered routing, the first account refusing: the answer recorded as the spare, the refusal as the first) fail without the gateway change; TestSummaryByAccount, TestLedgerByAccount and TestRequestPageByAccount cover the grouping, the host fallback, "not recorded", keyed providers kept out, the filter, the search, the CSV column and the packed rows; TestLedger and TestLedgerWithSessionLogCalls take the new column. usage-accounts.test.cjs (WebKit and Chromium, en and zh: the Overview's accounts and costs, the Account picker's notes, its request and export, All accounts clearing it, scrollTop unchanged) fails without the asset change; api-key-usage, click-scroll, panel-usage, request-archive-usage, tray-usages, claude-usage-asked and every usage-* test pass in WebKit. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass (TestFXInState failed once on its TempDir cleanup, passes alone).
2026-10-02 20:15:33 +08:00
archive: a request the archive kept is opened and downloaded from the Usage page, with its bodies whole (jorben, #447: 请求存档 reachable from usage history, full bodies, download) — the archive's name was only on the Gateway page's recent calls, gone once a call left the list or the gateway restarted, and the archive kept the first 256 KB of each body, the recent list's cut. The usage ledger's row now names the call's archive (archive in usage.jsonl, kept through the Requests page's packed rows), and its details on Usage → Requests show the Request archive panel, Fetch from archive and Download; with the archive on, a request it has no copy of says "Not archived". The bodies are kept whole up to requestArchiveMaxMB in settings.json (32 MB unless set, at most 1024): the response is teed to a temp file as it is sent, the request body written to one when the call ends, so the upload queue holds file handles, not bodies, and one upload at a time reads them; a body past the limit is kept to it and marked cut, with its whole size. What goes upstream is unchanged, the archive stays off unless turned on, headers and bodies are scrubbed as before, and the temp files are removed after the upload or when the queue is full. The page is sent a body to show only when it is 256 KB or less (a longer one is said by its size), an archive over 80 MB is only said to be; Download streams the object whole, to Downloads in the app (archive/export, -2, -3… for a name taken) and as the browser's download in magpie web (archive/file). TestArchiveWholeBodies, TestArchiveLimit, TestRowKeepsArchive and TestArchivePreviewAndDownload fail without the change; TestArchiveOffUsage, TestArchiveTooLargeToPreview, TestArchiveOldPreview keep the rest. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass; request-archive-usage (new), request-archive, click-scroll, old-webkit, usage-ledger, usage-ledger-detail, usage-ledger-content, web-page, sse-body pass.
2026-10-02 00:57:51 +08:00
usage, gateway: a model the vendor spells with other separators isn't marked as another one (vincentzhang on Discord: 这个说明有点奇怪。看不明白。) — Volcengine Ark answers deepseek-v4.1-flash as deepseek-v4-1-flash, the dots written as hyphens, and the Usage page's Requests and the Routing page marked every such row amber 「实际 deepseek-v4-1-flash」, saying another model had answered, not the one asked for under a dated name. Swapped now compares the bare names without their separators (. - _ and spaces) and case, so deepseek-v4-1-flash, deepseek_v4_1_flash, GLM-4-6 for glm-4.6 and gpt-4-1-2025-04-14 for gpt-4.1 are the model asked for, while deepseek-v4-flash or deepseek-v4.1-pro for deepseek-v4.1-flash still are another. Rows and routes kept marked swapped before are read back as not swapped when the names differ only so (usage.SameSpelled, in rowChunk.row and Route.routedAgain). The tag's explanation says it in plainer words: asked for {sent}, the reply says {served} answered, likely another model; the same model under a dated name or spelled otherwise isn't marked (zh, ja, de). TestSwappedIgnoresSeparators fails on the old code; TestKeptRowSameSpelledNotSwapped, TestRouteKeptSpelledOtherwiseNotSwapped. usage-ledger (its expected title updated), remote-group-served, panel-routing, gui-ja and gui-de pass on WebKit. go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass (TestCodexVersion timed out once under load and passes alone).
2026-10-05 12:49:59 +08:00