31da93ccdca03073513d2e1d73efdfd50bd14f6a
181
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
e1709ab42e |
usage: Append makes the log's folder only when it is missing (#3725)
Every request appends one line to usage.jsonl, and Append ran os.MkdirAll on the folder first each time: a stat, and on its error path a walk up the tree. Now the file is opened first, and the folder is made (then the open tried again) only when that open says it doesn't exist. Measured with a scratch benchmark (not committed) at |
||
|
|
9dc7d6eb84 |
usage: a large build's archives are held in a spill file as they are made (#3493)
A cold build (first start, or after an update that changes internal/usage)
kept every chunk's archive on the heap until save had written
requests-v1.bin and swapped them for the file's pages: 31MB for 15.7k
sessions, the largest thing a cold peak held over a warm start's.
Now a build that wants requestDiskLeast or more files written writes each
archive to requests-*.spill as the chunk is made, lets go of the heap copy,
and maps the file once the build is done (unlinked at once). save then
swaps the spill's pages for requests-v1.bin's as before: pagesRank orders
heap < spill < file, and keep and save take the later. A spill that can't
be written or mapped has each of its chunks made again from its source, so
none is left without an archive. Windows maps no file, so nothing changes
there.
Run, real data (15.7k Claude Code + Codex sessions, sandbox HOME, copies of
the call shards, requests-v1.bin removed before each run), the gui warm-up
harness alternating old (
|
||
|
|
cbbf3163cb |
usage: a cold build's chunks are of the file's pages once it is written (#3493)
A start that reads requests-v1.bin keeps each chunk's archive in the
file's mapped pages, not on the heap. A start that builds the chunks
(a cold one: no file, or one of another build) kept the archives it
encoded on the heap until the next start, after writing the very same
bytes to the file: 32-40MB for 15.7k sessions, and a resting heap
~50MB over a warm start's.
Once save has written the file, onDisk maps it and makes, for each
chunk whose archive is of the heap, a copy whose archive is the same
bytes of the mapping (checked equal). save swaps it in for the chunk
of the same serial: a read since has copied the chunk with a use of
its own, so the pointer it wrote is gone by then. A read that copied
the chunks before the swap and finishes after it keeps the mapped
archive (keep), or it would put the heap one back. Nothing changes
where no file is mapped (Windows).
diskUnmapped, the tests' hook, is an atomic.Pointer: a mapping's
cleanup reads it on its own goroutine while the next test sets it,
which -race -count=4 caught once the new test let go of mappings.
Run at this tree (
|
||
|
|
ba301e98e2 |
usage: a page's passes over the chunks decode into buffers kept between them (#3493)
Each pass of a Requests page over every chunk (foldCodexRows, the
response pairs, visibleLocal, matchedBlocks, visit, partsOf, newest,
rowsOf) started a chunkRows with no buffers and grew its rows, strings,
shapes and decode buffer from nothing. A warm start's All page and
Codex's effort after it read the same rows pass after pass, ~30 MB a
pass. chunkRows now takes a rowBuffer from a pool, unpacks into it
(unpackReusing gets a dst chunk too, so the open chunk isn't allocated
each block), and gives it back on release, its strings cleared so no
row text is held.
Measured on the real data copy (sbpairs: 12k Codex rollouts and the
Claude projects), warm-up harness TestZZWarm, each binary run 3 times
in a row and the first run dropped (the chunk file is named by this
package's source, so alternating binaries rebuilds it):
step 2 (QueryPage All) allocated 835 MB -> 666 MB
allocated through step 3 (effort) 994 MB -> 820 MB
unpackReusing in step 2 163 MB -> 34 MB
peak footprint ~240 MB, unchanged
Run at this head (base
|
||
|
|
42976f9a08 |
usage: a renamed provider is shown once, by the id it has now
cybercaius on Discord (#help, 10-25): "已经更改供应商 id 的也没有变更过来反而
分开显示了". Reproduced in a sandbox HOME (magpie web on 3582, fake upstream
on 3583): after renaming myrelay to newrelay in the editor, the Requests
page's provider list had both myrelay and newrelay, each named "myrelay",
because the model-list probe row was still under myrelay. The summary was
already folded; the probe chunk, the Sessions tab's vias and the gateway's
loggedAnswers (lead-first routing) were not renamed at all.
What changed
- provider.Renames (UsageRenames): Of(id, time) is the id a call recorded
under id at that time belongs to now. Every usage reader goes through it:
summarizeFrom (and its historical-key set), ledgerMatched, NewPricer,
NewCoster, the Requests page's gateway blocks, probe rows and other
computers' days, window holds and their history, buildVias, and
gateway loggedAnswers. Visit stays as recorded so Of is taken once.
The summary, Requests and vias caches key on Renames.Key.
- An id reused by another provider no longer pulls the new one's calls
into the old one. Rename onto, or Save of a new provider under, an id in
another's Was moves it into that one's Gave with the time (giveID):
calls before then stay the old provider's. freeID treats Was ids as
taken, so adding the vendor again gets "-2". Renamed() (refs) skips ids
a provider or subscription holds now.
- A providers.json that can't be read keeps the last renames read instead
of none (a failed read is unknown), so usage doesn't split meanwhile.
- History: nothing in usage.jsonl is rewritten. Calls from before this
release under a renamed id show under the new id at once. An id that was
reused before this release has no hand-over time, so its calls show under
whoever holds the id now, as before.
Siblings checked: budget keys by caller key; per-key limits, RPM and
concurrency count live requests by the current id; tray totals go through
QueryPage; codex_memory reads Requested refs. None needed a change.
Run at the tree before the rebase; rebased onto
|
||
|
|
115ca34343 |
usage: the chunks' file is mapped, not read into the heap (#3493)
A start read requests-v1.bin's 44MB of chunk archives into the heap,
where they stayed: a fifth of the heap at rest, and with GOGC 25 a
larger heap goal through every warm-up step. They are pointer-free and
only ever decoded, so on unix the file is now mapped read-only
(MAP_SHARED, PROT_READ) and each chunk's Archive is a capped slice of
the mapping. A cleanup unmaps it once no chunk refers to it. The file is
only replaced by a rename (toDisk), never written in place; a read past
its end, if another program cut it short, is caught by readMapped
(SetPanicOnFault) as a failed read, not a crash: the chunk unpacks as
nil and reads as no rows, as a corrupt archive did before, until its
session file changes or magpie starts again. Windows can't
rename over a mapped file, so it reads the file as before
(request_disk_map_other.go).
decodeMapped keeps the decode's closure out of unpackReusing: with the
closure there, data escaped to the heap and every row's take() through
it was slower, which made step 2 0.12-0.2s slower than before (found by
profile: unpackReusing.func2 0.28s -> 0.64s over three runs).
Run at this tree, on the owner's real data (sandbox HOME with
.claude/projects and .codex/sessions linked read-only, ~421k rows), warm
runs interleaved with v0.1.1471 (
|
||
|
|
b1f44d099e |
usage: Codex's effort reuses the pairing the page of its period just made (#3493)
The warm-up builds the Requests page of All and then Codex's model and effort over All. The page keeps its pairing of the calls (pairMemo, by chunk serials), but the effort paired every session file's calls again from nothing, the warm-up's step 3. It now reads requestIndex.pairs[p] before taking its private copy and pairs through pairRowsMemo, so unchanged chunks keep their pairing, and it keeps the new pairing for the next page or effort. Storing a period's pairing is one helper, keepPairs, that queryPage uses too. Run at this head (on |
||
|
|
e1f5f9c164 |
usage: the passes that pair a page's calls read a chunk's strings in place (#3493)
A Requests page decodes each packed session chunk in five passes, one chunk at a time (chunkRows). Every decode copied the chunk's whole string section out of the pooled buffer, though four of the passes (folding Codex's repeated calls, pairing Codex response ids, Claude's repeated message ids, request-id matching) only look strings up and clone the few they keep. That copy was the largest allocation of a warm start's page. Those four passes now read through lentRows: the chunk is decoded into a buffer the reader owns, and its strings are of that buffer until the next chunk is decoded over it. The cell pass and every reader that keeps rows still copy. What was run, at this head: - Real data (sbpairs: 421,206 calls, 15.6k session files), warm-up steps three runs each, before / after: step 2 (first Requests page): 0.88-1.03s / 0.76-0.79s, ~560 MB / 446 MB allocated; whole warm-up 1.41-1.45 GB / 1.21 GB allocated; maxrss 320-336 MB / 318-319 MB. - Real pages, base and this change alternately: QueryPage of All, today, 7d and 30d at offsets 0 and 500, and CodexModelEffort(All). Totals, rows and every string are the same; the only differences are float costs' last digits, from summation order, which differ between two base runs as well (and one new live call). - Broken by hand: storing the lent message id and request id without their clones turns TestRequestPageSameFromPackedLocalChunks red. - go test ./internal/usage ./internal/gui ./internal/sessions ok; -race -run 'TestRequest|Codex|Packed|Visible|Match' ./internal/usage ok; GOOS=linux and GOOS=windows go vet -tags nogui of usage and gui clean; gofmt clean. Not tried: the full ./... suite (one suite per machine; only the packages this reaches were run). |
||
|
|
ac149224f9 |
usage: many rows made since the last write have it written once a run (#3493)
The file of the session files' chunks (requests-v1.bin) was written only once 64 files' chunks had been made since the last write. Long sessions that ended since then are few files with many rows: on the real history (sbpairs) two starts in a row each made 9 files' chunks again, 84,625 calls (one Claude Code session alone is 52,191), and neither wrote them, so every start did it again, and the sessions that ended next joined them until they were 64 files. noteBuilt also counts the rows made, and writes the file once a run when they are 20,000 or more. Once, as a session still at work is made again after each of its calls; the 64-file write is as it was. Run on |
||
|
|
42ab935516 |
usage: requests-v1.bin is of the code that makes rows, not of the binary
The file of the session files' chunks was named by the binary's own
stat key, so every upgrade, and magpie ships several a day, read every
session file again on its first Requests page: on a 15.6k-shard history
warm-up step 2 went from ~0.8-0.9s (read from the file) to 1.6-1.9s and
~1.3GB more allocation. It is named now by the call shards' version
(sessions.CallCacheVersion, which already decides whether a shard of the
calls is read) and a SHA-256 of this package's non-test source, which
the binary carries (go:embed *.go, ~750KB with the tests, which the name
leaves out). Of the last 99 releases, 17 changed that source; the other
82 keep the file. Prices, names and settings are in the file's meta as
before. When the embedded source can't be read the name is the binary's,
as it was.
Measured (real history, sbpairs): one test binary wrote the file, a
second binary at another path (the old key differs) read it: step 2
0.79s and 1001MB alloc, against 1.63s and 2285MB cold.
Run at this tree (
|
||
|
|
3767addd4d |
usage: a block's strings and shapes are read into buffers the next block reuses
Each Requests pass (warm-up step 2's whole-history page, step 3's Codex effort pairs) decodes every packed block through chunkRows, which already reused the rows' buffer. Each block still made its strings slice, its shapes slice and a []int of every string's offset and length, ~170MB of the ~450MB a pass allocated on a 15.6k-file history. chunkRows now keeps the strings' and shapes' slices too (unpackReusing), and the offsets are found by walking the copied section's length prefixes a second time instead of being stored. The strings themselves still point into one copy per block, so a row taken from a block keeps its text after the buffer moves on; only the slices are reused, and nothing holds a block's slices past the next of(). Measured (real history, sbpairs: 15,656 call shards, gui warm-up steps, zzbase = |
||
|
|
2a3d9f5aeb |
usage: a session file's rows are made by the reader that read it (#3493)
A cold Requests build (every upgrade) read the call shards eight at a time, but turned every call into a row on the one loop that takes them: logRecord, the account resolver, pricing, interning and packing, ~1 s of serial CPU over a real history, with the readers waiting on the window behind it. prefetchSources becomes prefetchEach: each reader has a make of its own from newMake, and the loop has its own for a source not wanted. Request rows are made there. Each make has its own Pricer and Swapped memo, so neither needs a lock; the session resolver is made once (sync.OnceValue) and only read after. The serial number is still given in the loop, in source order. The window now holds packed chunks, smaller than the calls it held. Measured on a copy of real data (15,656 shards, 3,451 Claude Code subagent meta files), GUI warm-up step 2 (QueryPage(All)), cold (requests-v1.bin written for the other binary), alternating runs: - before ( |
||
|
|
31bff66be3 |
usage: a session file's few calls are kept packed too
pack left a chunk of fewer than 64 rows as rows. Most session files hold a handful of calls, so a cold build (the first start after an update, or with no requests-v1.bin) kept 13,972 of 15,624 local chunks unpacked: 98,320 rows. The same chunks read back from requests-v1.bin are all archives, so the cold build alone held them as rows. Now every chunk with a row is packed when its archive is smaller, as the file's entries already were. Measured on the real history copy (sbpairs: 15.6k session files, 420k calls), one QueryPage(All) from cold under GOGC=25 as the GUI's warm-up runs it, three runs each, old then new: - heap in use after: 267/267/269 MB -> 229/227/232 MB - peak heap in use: 357/367/341 MB -> 308/338/336 MB - max RSS: 454/462/448 MB -> 420/424/449 MB - page: 2.95/2.41/2.52 s -> 3.66/2.19/2.42 s (no change past noise) A page after a new call, packed chunks read from the file: 120-143 ms, as before. TestFewRowsArePacked packs three rows and reads them back. It is red with the old 64-row floor. Run at this head: go test ./internal/usage (ok); go test -run 'Usage|Request|Tray|Session' ./internal/gui ./internal/gateway (ok); go vet ./internal/usage, GOOS=linux and GOOS=windows -tags nogui; gofmt -l. Not run: the full suite (one per machine). |
||
|
|
5d2260d3e6 |
usage: the Requests page's chunks are kept on disk, so a start doesn't open every call shard again
A started magpie opened every session file's call shard (~15.6k on a busy
machine) and turned each call into a row again before its first Requests
page could show (#3493). requests-v1.bin (beside sessions.json) now keeps
each session file's chunk as the page packs it: an entry stands while its
file's size and mtime are the same, as a call shard does, and the whole
file while the binary that wrote it and the index's root and meta (prices,
names, providers) are the same. Each entry has a length and CRC-32; a bad
one ends the read and the entries before it stand.
- The file is read when 64 or more session files want reading (a start, a
change of prices), and written behind the lock once 64 or more chunks
were made since the last write; fewer are a few shard reads next start,
not worth writing the whole file again. The idle trim does not write.
- A chunk of another computer's day is not kept; times keep their zone
(Local, UTC, a tz-database name or a fixed offset).
Real data (sandbox HOME with the live ~/.codex/sessions and
~/.claude/projects symlinked read only, 15,603 sources, 420k rows, load
~90 to 130): a cold All page 3.6s; written in 76 to 168ms behind the lock,
44MB. A start from the file: fromDisk 50ms for 15,602 chunks, then the
blocks 100ms, against the shard reads before; the whole page 1.5s, most of
it now readRequestState (0.65 to 1.1s), which is next. Same total, cost
and input as the cold page.
Run at
|
||
|
|
4982ded8a6 |
usage: a turned page reuses the last pairing while its chunks are the same
A Requests page paired every Codex session file's calls with the
gateway's again on each query: clone, fold forks, match response ids.
That unpacked every session chunk three times and was about half of a
warm page (#3493). pairRowsMemo names the chunks of a pairing by their
serials (the probe chunk, which has none, by its rows' log offsets and
times) and keeps what the pairing found: the rows left out (skip,
matched), the actors it changed and each chunk's compactions. The next
query over the same chunks and window applies that to fresh clones
instead of pairing again. A changed file gets a new serial, a new
window or period misses, and adopt drops the memos with the parts.
Run at
|
||
|
|
a6399dd494 |
usage: a Requests page sums each chunk once and reuses it while the chunk is the same
Turning a page, or the 15s refresh of the open page, built every sum, chart and share from every row of history again. On the owner's real history that was 1.15-1.36s a page (load 170) after the chunks were already cached. Each chunk's rows are now folded into cells: one per provider, agent, model, kind, caller, account, computer, source, filter bits and chart bucket, with its totals. A page merges the cells. The cells of a chunk are kept per (period, filter, since, until, zone), up to 4 such sets, keyed by the chunk's serial (a new one every time a chunk is read or frozen) and a signature of what pairing gave it: rows skipped or matched, Codex actors and their identities (with the parent's role), and compactions. A changed file, a gateway tail block or an identity change from another file sums that chunk again. The newest rows are taken from chunks in Latest order, stopping once the heap holds rows newer than the next chunk. Cell strings are unique handles, so the cache holds no chunk's string block. Totals and Part sums are linear, so merged cells equal the row-by-row sums; date-mode buckets store the day number and are placed against the chart's first day at merge time. What was run (macOS, arm64): - Real history (sbmem sandbox HOME, read-only links to the owner's data), zzbench dump of 9 cases x 2 pages (offset 0/50 after a warm 7/50 call, and 120/30) with the base |
||
|
|
1313b047f5 |
usage: a Codex thread's model and effort are read through the request index
CodexModelEffort, which the Sessions list asks for, read the ledger again on every build: sessions.AgentCalls(since, "codex") opened all of Codex's shards (12k rollouts, 15.6k shards on the reporter-sized sandbox) after any new call, beside the Requests page reading the same files into its own index (#3493). It now reads through the request index as a page does: readRequestBlocks (moved out of queryPage), the page's pairing and visit (pairedRows, moved out of buildRequestBlocksOf), and the sums added row by row as they are visited (effortSums), so a build after a call reads only the files that changed, and the first of the Sessions list and the Requests page reads them for both. The LogCalls path still builds from codexEffortRows. The visit's row is one per visit now: as a returned closure's local it was moved to the heap, one allocation a row, which TestRequestPageAppendDoesNotRepriceHistory caught (10890 allocations over 8000 records against 2000). Measured before the rebase onto |
||
|
|
ffe493773c |
usage: magpie's own Test, Detect APIs and model list requests are rows of the request log, counted nowhere
neiko and gys619 on Discord: a provider's Test or Detect APIs left no
trace in Usage > Requests, so a failing test couldn't be read back.
The provider package marks the context of the editor's Test, Detect APIs
(and per-model detection) and a model list's refresh with a kind
(internal/probelog). Each request sent under the mark is written once:
by the provider's Do, or by probelog.Transport under http.DefaultClient
(netproxy.Install), whichever sends it first; the Claude Code run and
the gateway's translated test write theirs from their result. A row
keeps time, provider, account, model, host, path (no query, no
user:password), method, status, ms and the first 500 bytes of the error.
The row is usage.SourceProbe, agent "magpie", Kind provider_test /
api_detect / model_list ("Test", "Detect APIs", "Model list" in Called
for; purposes.js regenerated). The log index keeps probes apart
(logSnapshot.probes), so Visit, Load, Summarize, budgets, Vias, heatmap,
shared days, LastSeen and observers never meet one. The request page
lists them (probeChunk) and counts none: Row.IsProbe, since a packed row
keeps the row's Source and not its record's. The page shows a muted
badge "magpie's own · not counted in any total" (en, zh, zh-TW, ja, de);
no new control, no layout change.
Tests, each red on the old code:
- usage TestProbeRowsListedNotCounted: listed, clipped, and absent from
Sum, Through, every By group, Summarize, Load, LastSeen, OwnDays and
the observer; a provider filter lists it and sums 0.
- provider TestTestWritesItsRequestsDown / TestDetectWritesItsRequestsDown:
every request the fake server saw is exactly one row, with the right
kind, model and 401 text; an unmarked Do writes nothing.
- probelog TestNoteKeepsNoSecret, TestTransportOnce.
- GUI usage-ledger-probe: badge per language, both engines, 1180/420,
light and dark, no left border, no sideways scroll.
- gui TestProviderDetectDraft now expects the log line (source probe,
kind api_detect, no key) and leaves usage.jsonl out of the unchanged
config comparison.
Broken by hand, each went red: request_page's uncounted check,
log_index's probe skip, Append's observer skip, Do's Taken (6 rows for
4 requests), Test's and Detect's marks, probelog's query strip,
page.js's badge (11 GUI fails).
Run at this head (on origin/main
|
||
|
|
22a7f86c9b |
sessions: the Requests page walks the Codex folders once a rebuild
readRequestState asked CallSources and then CodexIdentities, and each walked ~/.codex/sessions and archived_sessions, lstat()ing every rollout. Over the 12,069 rollouts of a real Codex folder that was two walks of ~75ms on every rebuild, which runs on each 5s refresh while an agent works. CallSourcesAndCodexIdentities walks once and hands the list to both; CallSources and CodexIdentities stay as they were for their other callers. Run at this head: - go test -timeout 45m ./internal/sessions ./internal/usage ./internal/usageapi: ok. TestCodexIdentityParentChainsAndSummaryCache now checks the one-walk pair equals CallSources and CodexIdentities. - GOOS=linux and GOOS=windows go vet -tags nogui on both packages, gofmt. - Real data (sandbox HOME over the owner's ~/.codex, 12,069 rollouts, ~416k rows): CPU profile of two rebuilds, codexFiles 0.31s before, 0.12s after. Wall times on a loaded machine were 1.0-2.1s both ways, too noisy to compare. Not tried: Windows or WSL folders (wslFiles is still walked as before). |
||
|
|
8b460833e0 |
usage: the Requests page keeps its chunks while it is open
Every new call is a new page key, so the open Requests tab works its
page out again on each 5s refresh. The session files' packed chunks
were held to 24 MB. A history of 416,000 calls has 63 MB of them, so
each rebuild read 2,679 shards again (39 MB), gob-decoded them, priced
each call and packed it again, and dropped them again after.
Now the chunks are held to 128 MB while the page is asked for. After 2
minutes with no ask (requestIdle), a timer cuts them back to the 24 MB
they were held to before (requestIdleBytes), so an unopened page holds
what it held before.
Measured on the real sandbox data (sbmem, 416,665 rows):
- zzbench, one QueryPage of period=all and six rebuilds at new offsets,
alternated with v0.1.1439's code at load ~150-200: user CPU
17.26 / 16.09 s before, 10.79 / 10.21 s after; sys 3.41 / 3.01 ->
1.98 / 2.14 s; peak RSS 604 / 664 MB -> 566 / 543 MB. A debug count
showed 2,679 shards read per rebuild before and 1-2 after (the
files that grew).
- A running magpie (`web --gateway` under sbmem), /api/usage/requests
period=all at offsets 1-5, warm file cache, load ~175: rebuilds
1.98 / 1.99 / 1.50 / 1.69 / 1.52 s on v0.1.1439, 1.30 / 1.18 / 1.09 /
1.07 / 1.07 s now. Cold (the first run after building), one rebuild
took 23 s; v0.1.1439's cold rebuilds took 5.5-8.0 s, and the warm
reruns didn't show it again.
- Heap in use on that server, by /v1/magpie/heap: after the builds
175.7 MB (v0.1.1439) and 199.1 MB (now); after 140 s unasked 161.7
and 149.8 MB. Footprint 339 -> 286 MB and 302 -> 254 MB.
Tests: TestRequestChunksTrimmedWhenIdle checks that three chunks over
the idle bound are kept while the page is asked for, and dropped once
it goes unasked. It waits for that state, not for a time. Broken by hand
both ways: without the idle trim it fails ("3 chunks kept after the
page went unasked"), and with the build trimming to the idle bound it
fails ("0 chunks kept while the page is asked for"). It also passes
with -race -count=3.
Run at this head: go test -count=1 ./internal/usage ./internal/gui ok
(16.1s, 201.8s); go vet -tags nogui for GOOS=linux and windows on
internal/usage ok; gofmt -l clean. Not run: the full suite (other
sessions' suites hold the machine).
|
||
|
|
66b6d6ade9 |
usage: the Requests page sums each row once, not once per group
Every Requests page build (each 5s refresh of the newest page, each page
turn, each filter) walks the whole period. Over all of it each row went
into about 17 sums: the page's own, a source cell, five chart series
groups, five dimension groups, the caller key and account groups, the
computers' share, and the chart point with its five parts. Each one
copied the 896-byte Row and worked out Decode and Floor again, and
each dimension rebuilt f.Without(d) and ran keepsRow on another copy.
Now each row's sums are made once (Totals.addRow into d) and added to
each group (Totals.plus, Part.plus). The filters with a dimension, or
the computer and day, cleared are built once. A filter that clearing
leaves unchanged reuses the row's own keep, and with no pick that is
every dimension. keepsRow, keepsRecord, computer, Row.key and keyer.key
take pointers.
Measured on the real sandbox data (sbmem, 416,665 rows), with zzbench:
one QueryPage of period=all, then six rebuilds at new offsets. Process
CPU at load ~110-127, three runs each, alternated with the old binary:
before (
|
||
|
|
7d67910f74 |
usage: the Requests page reads packed chunks in place, and owns its strings
The first Requests page after a start unpacked every local and shared chunk whole and held them all while it built the page, so a cold page on the owner's real usage peaked at ~450-480 MB footprint (#3493 follow-up: "发版后把 RSS 峰值也修了"). queryPage now keeps chunks packed. visibleLocal, matchedBlocks, the Codex identity fold, the chart and rowsOf read a packed chunk through chunkRows, a one-entry cache that decodes into one reused buffer. The Codex response pairs are read per chunk (codexChunkResponsePairs), and pack records Count so a packed chunk's length is known without a decode. An unpacked block's strings are substrings of one text, so a row or name the page kept would hold that whole block (~9 MB, kept by the request cache): buildRequestBlocksWithCodex now copies every string of the finished page (ownStrings). Measured (owner's real usage copied into a sandbox HOME, warm caches, first /v1/magpie/requests page, base = |
||
|
|
3a47e377e0 |
usage: a call whose vendor counts no cache is left out of every hit rate (#3464)
#3464 (zeewell on X): Kiro caches on its side, but its replies give only credits and a context share, never cache tokens. Every hit rate outside the Routing page read those calls' CacheRead of 0 as a miss. A Kiro-heavy day showed "hit rate 6%" when the counted calls hit 90%. The plugin already says so (opencode-kiro-auth 0.1.16 sends usage.magpie_cache_unknown), and the gateway already kept it as RouteUsage.CacheUnknown for Routing. This carries it the rest of the way: - gateway: Usage.cacheNotCounted() (the vendor said so and no try reported a cache token) goes into usage.Record.CacheUnknown on every path that records a call: the gateway's own record, the OTel attempt path in observe.go, and trace's routeUsage. - usage: Record.CacheUnknown is kept as ledger row flag 8192 (rowCacheUnknown; grepped, no other flag uses that bit). Totals sums such calls' prompt into cache_unknown and counts them in cache_unknown_calls. Totals.HitRate leaves that prompt out of its denominator, and gives no rate when nothing is left. - Old records: calls kept before the plugin said so carry no flag. A Kiro call (provider kiro or kiro-plugin) with no cache counted is read as uncounted (usage.CountsNoCache): in the ledger's row read, in Totals, and for Routing's history in internal/gui/trace.go (cacheCounted). The rule is scoped to Kiro's two ids, so another vendor's 0 stays a miss (tested). - GUI: cacheHitOf in app.js drives the tray panel's card, the Usage page's agent rows and cache tile, the requests' Cache hit rate card and each ranking row. When only uncounted calls are left it shows "—" or nothing instead of 0%. Otherwise it says "{n} requests left out: their vendor doesn't count the cache". A request row's cache cells show "—", and its details say the vendor doesn't count the cache. The Context page (context.go, context.js) shows no cache for such a call and doesn't score it as a miss. - No budget raised. This adds 625 bytes to app.js (1,320,224 to 1,320,849, under its 1,321,336); |
||
|
|
1f589e3f4f |
usage: read today's usage ahead at startup
CyberCaius (Discord, Windows): "今天 N 次调用" is slow on the first
panel open after a start. The first usage?period=today parses
usage.jsonl: 0.33s for 2MB, 0.43s for a 40MB sandbox log here, more
on a slower disk. startBackend now runs usage.ReadAhead() in the
background, which works out today's summary into the summary cache,
so the panel's first ask finds it.
Parallel parsing was not done: with the read ahead, a request 1s
after start answers in 1-2ms, so there is nothing left to win there.
Test: TestReadAheadLeavesTodayNothingToRead. After ReadAhead, a
SummarizeTopIn(Today) parses nothing and works nothing out. Red with
ReadAhead's body emptied ("parsed the log 1 more times and was
worked out 1 more").
Run at tree 53ae48f72 (on origin/main
|
||
|
|
3be1f14ebb |
usage: a re-read source asks Swapped once per model pair (#3493)
Swapped's regexps ran for every call of every file read again: a few hundred sent/served pairs over ~289k calls on the owner's real history, about a third of the re-read's pricing cost in a CPU profile. queryPage now keeps each pair's answer for the read. Measured at internal/usage with the owner's real ~/.codex and ~/.claude in a sandbox HOME: a heatmap read whose key changed, 3.0s -> 1.4s together with the heatmap's own page. Run at this tree: go test -count=1 -timeout 45m ./internal/usage ./internal/usageapi ok; GOOS=linux and windows go vet -tags nogui ./internal/usage ok. |
||
|
|
cf8b1e9338 |
usage: the heatmap works out only its days, kept 30s while only session files change (#3493)
The Requests tab asks for the year's heatmap on every ledger refresh. A live agent writes its session file all the time, so the page's key changed for every ask and the whole year was worked out again: groups, shares and series the heatmap never reads, over ~289k calls on the owner's real history. - buildRequestBlocks returns at once for the heatmap's period with only HeatmapOf's days, from the rows the chart filter keeps. - queryPage keeps a heatmap page 30s (heatFresh) while the gateway log's snapshot version is the same; a meta change (prices, names, wires) drops it, and a call through magpie shows at once. Measured at the handler (internal/gui, sandbox HOME with the owner's real ~/.codex and ~/.claude, 15,553 sources, 59.9 GB): heatmap steady refresh 2.99s -> 0.15s, cold 5.5s -> 4.5s. Run at this tree: go test -count=1 -timeout 45m ./internal/usage ./internal/usageapi ok. TestHeatmapKeptWhileOnlySessionsChange is red with the throttle taken out (builds counted twice). |
||
|
|
57a70aaf10 |
usage: a new Codex thread keeps the chunks read before (#3493)
Codex's thread identities were in the request index's meta, so every new
Codex thread, each subagent's included, dropped every chunk, and the next
Usage page read the whole history again: 7s on the reporter-sized
history here (15,553 session files, 418k calls). A chunk's rows don't
hold the identities; the page gives them to its rows as it is built
(cloneCodexChunks, codexIdentities). They now go in the key alone, which
drops only the built pages.
TestCodexNewThreadKeepsReadChunks writes a child thread, reads the page,
then writes its parent: only the parent's file is read again, and the
child's row names the parent's session. Red with the identities put back
in meta (both files read again).
Run at this head (origin/main
|
||
|
|
f6a96b2f0b |
usage: a change time with a fraction settles in 100ms, so a read after an append hashes no log (#3394)
readLogSnapshot checks its snapshot against a SHA-256 of the log's whole prefix whenever the log's change time is under a second old. Under steady traffic every read came within a second of the gateway's last append, so each one hashed the whole usage.jsonl again: 1.8 times the log for each append and read. A stamp with a nonzero fraction of a second comes from a clock that ticks in milliseconds (APFS in ns, Linux's coarse clock 1-10 ms, NTFS ~15.6 ms), so it settles in logFineSettle = 100ms. A stamp in whole seconds (HFS+, FAT, a share) keeps the one-second settle. Run: - go test -count=1 -timeout 45m ./internal/usage/ ./internal/budget/: ok. - TestUsageReadAfterAppendHashesNothingOnAFineClock (20000-row log, 5 appends, each followed by two reads): fine stamp 0 bytes hashed; whole-second stamp 50.7 MB. Broken by hand (logFineSettle = time.Second): 54 MB hashed, red. - Real account, sandbox HOME, a deepseek-only providers.json and a 98 MB usage.jsonl (the owner's own log, repeated 50 times). magpie serve took 30 real /v1/responses calls with a Codex user agent to deepseek/deepseek-flash, all answered, while /v1/magpie/usage?period=today (the Usage page's read) was polled every second. Process CPU time, two runs each: before 3.11 s and 3.05 s, after 1.95 s and 2.25 s. The same calls with /v1/magpie/quotas polled cost 0.2 s on both binaries, since that path never reads the log. - gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage/ clean. Not tried: an HFS+ or FAT volume (the test skips when the file system gives whole-second stamps, and covers that case by truncating the stamp); the full suite at this head runs after the push. |
||
|
|
24f24abde3 |
usage: a ClinePass contributor-fallbacks route still shows as a swap (plugins#351)
woyin's Routing rows show cline-pass/deepseek-v4.1-flash-1017 served as vmc/deepseek-v4p1-flash-1017-contributor-fallbacks. Third-party Cline Pass tools record that name as a private contributor deployment (finalProvider "openai-compatible-private"), not DeepSeek's own API. So the row has to keep saying it was served elsewhere. 6db5e9d59's ClineServing already does this, because only the exact model maps. This commit is tests only: they hold the rule, so a looser match (a prefix, say) can't hide the route later. - TestSwappedClineServingName: -contributor-fallbacks (with and without the -1017 date), -contributor and -fallbacks are swaps. - TestRouteKeptClineServingNameNotSwapped: a kept row served as ...-contributor-fallbacks stays swapped when it is read again. Run at 616c87256's tree: - go test ./internal/usage: ok. - go test ./internal/gateway -run 'Clin|Swap|Served|routedAgain|History': ok. - go vet on darwin, linux and windows: ok. gofmt -l: clean. Broken by hand: ClineServing changed to a prefix match. Three usage cases and the history case went red. Restored afterwards. Not run: the full suite (tests only, in two packages). |
||
|
|
6db5e9d593 |
usage: ClinePass's vmc/ name for the model asked is not a swap (zRain on Discord)
zRain (Discord, 10-24) sent Snow CLI through magpie to
cline/cline-pass/deepseek-v4.1-flash-1017 and read the Routing row's
"vmc/deepseek-v4p1-flash-101…" as the upstream, so the DeepSeek pin
(cline plugin 0.1.11) looked ignored. That text is magpie's swap tag
("实际 vmc/…", "likely another model"): ClinePass answers a cline-pass/
model under its virtual model config's name, the version's dot written
"p", and Swapped read deepseek-v4p1-flash as another model than
deepseek-v4.1-flash. hy125245's pinned requests (finalProvider deepseek,
X 10-23) carried the same vmc/ name, so the name says nothing about the
upstream; the upstream is the "上游:…" tag after it, which the swap tag
pushed out of a narrow row.
Changed: usage.ServingName now includes ClineServing: served "vmc/<name>"
for a sent model with a cline-pass/ path, equal once "<d>p<d>" reads as
"<d>.<d>". Scoped to ClinePass: the same vmc/ name for deepseek/… (not
cline-pass/), another model (v4-pro answered as v4p1-flash, v4p1 vs v4p2,
glm-5.3 vs glm-5p3-flash) and another prefix stay swaps. ServingName is
what routedAgain and the ledger's kept rows already re-read, so routes
and Requests rows kept marked swapped read as not swapped too.
Facts checked, not changed:
- The pin reaches ClinePass on every path. The real opencode-cline-auth
0.1.11 index.mjs, loaded in magpie's plugin host against a fake
api.cline.bot (scratch wrapper over fetch, not committed), got
providerOptions {gateway:{only:["deepseek"],has:["vision",
"implicit-caching"]}} for a Snow-shaped streamed /v1/responses, a
non-streamed one, /v1/chat/completions and /v1/messages, and the
route's Upstream was the reply's finalProvider.
- With the fake refusing the pin ("no matching upstream"), the plugin's
one unpinned retry went out and the route showed the fallback's
finalProvider as Upstream: a fallback would show as another "上游".
- Vercel's AI Gateway lists deepseek for deepseek-v4.1-flash-1017 with
vision and implicit-caching, so the has filter doesn't rule it out;
"vmc" is not one of its providers.
- @magpie-community plugins update by themselves hourly; npm has 0.1.11
since 10-23 14:18 UTC.
Run at this commit, rebased on origin/main
|
||
|
|
ea9454d2d8 |
usage: count two ids of one model as one, magpie model alias (SlouchyQuill507 on Discord)
A vendor names one model two ways (deepseek-v4.1-flash and deepseek-flash),
and Usage, Usage > Sessions and `magpie usage` showed two rows. Now:
magpie model alias deepseek-v4.1-flash deepseek-flash
magpie model alias deepseek-v4.1-flash (what it is counted as)
magpie model alias deepseek-v4.1-flash --reset
magpie model aliases
kept as settings.json "usageAliases" {from: to}. Off until one is written.
Ids match as routing groups match them (provider.sameModel: vendor/ prefix,
case, "_", snapshot date), at every provider; a chain is followed to its
end; an alias to itself, a loop, or a flag as an id is refused. A loop
written into the file by hand counts each model under its own id.
Display only: requests, agents' model lists, /v1/models, routing groups,
Same as and prices never read it. Each call is priced by the id it was
made under and only then counted under the alias; the alias's own price
is never put on the other id's calls, and a merged row is priced only
when every id in it is. Applied in usage summarize/direct (Models
groups), the gateway sessions projection (alias read before
gatewayCache's lock; the cache key hashes usageAliases), and
sessions.List/Get/Find/Stats (read before storeMu/mu, merged into new
slices so the memo is untouched; ModelEffort rows merged too). A failed
settings.json read keeps the last aliases read, and SetUsageAlias refuses
to write over an unreadable file (EditUsageAliases under fileMu). The GUI
settings save carries usageAliases. No GUI control.
Not aliased: the Requests ledger's per-request model and its model
filter, which show each call's own id.
Run (worktree at
|
||
|
|
e00fbdbbc7 |
usage: times and days follow the viewer's time zone, not the server's (Outvi V, Discord)
Outvi V reads a remote magpie through `magpie web`. The Usage page
bucketed calls by the server's days and hours, so a call at 9:00 in
UTC+8 showed under 1:00.
What changed:
- The Usage page (plugins/usage/page.js) names its browser's IANA zone
in ?tz= on /api/usage, /api/usage/requests, /api/usage/heatmap, the
CSV link and the export.
- usage.Zone turns the name into one cached *time.Location per name, so
a Filter holding it stays a comparable cache key. An empty or unknown
name, or a zone that keeps this computer's clock, is time.Local, so
the desktop page, the tray and the TUI see no change and share caches.
- Filter.Zone carries the zone. Today/7d/30d, the chart's hour and day
buckets and labels, the Day filter and the heatmap's days are all
read in it (Clock().In(zone)). The summary cache is keyed by period
and zone, and the request-page cache by the reader's date.
- Shared days from other computers are read with a 2-day margin, not
1, since two zones can be 26h apart.
- Limit and quota resets are unchanged. The gateway's
/v1/magpie/usage stays on the computer's zone.
Run at
|
||
|
|
4042aa4d1d |
usage: a row keeps the strings its chunk shares once, in Shapes
The usage page holds every row of the period at once, and a packed row was 328 bytes, 140 of them 35 string ids. On the owner's real history (364,013 calls in 6,445 chunks) only five of those vary call by call: the error, the request id, the archive, the response id and the message id. The other 30 (agent, provider, model, session, endpoint, client...) repeat for most rows of a chunk: 364k rows have 7,300 distinct sets. So a row keeps those five ids and a Shape, an index into its chunk's Shapes table, which holds every other set once. packedRow is 216 bytes. A snapshot (process-private, nothing on disk) writes the table once after the strings and per row the shape and the five ids, so archives shrink too. block() renames and re-prices per shape, not per row. Same output: |
||
|
|
80d32fd609 |
usage: a Claude Code call skips the desktop-root path arithmetic
sessionResolver.desktopIdentity ran filepath.Rel and strings.Split
against every desktop root for every claude call, though only a file
under a root's local-agent-mode-sessions can name a desktop identity.
In a warm start's heap profile (sandbox HOME, ~380k calls) that was
178 MB from Rel and 98 MB from Split in the first 30s, about a fifth
of what gui.warmUp's first Requests read allocated. A path without the
folder name can't produce a Rel whose first segment is that name, so
the guard is exact.
TestDesktopIdentityOfCLICallAllocatesNothing: 6 allocs per call on the
old code (red, run with the change stashed), 0 now.
go test -tags nogui ./internal/usage/: ok, TestDesktopSessionAccountMetadata
unchanged.
At 8b48dc5d6 (this commit and the two beside it, on
|
||
|
|
16d20c0b3d |
usage: a packed block keeps its compressed bytes, not S2's worst-case buffer
s2.Encode makes its output MaxEncodedLen(len(src)) long, more than the
rows' own bytes, and pack kept the archive as a slice of it
(slices.Clip trims the capacity, not the allocation). Every cached
session block and every gateway log block (log_index.go) so held its
whole uncompressed size plus S2's slack, while Bytes counted only the
compressed length, so the cache budget undercounted it too. pack now
encodes into pooled scratch (the rows' bytes and S2's output) and
copies the archive out at its own length.
Measured on a sandbox HOME (a clone of a 23 GB Codex + Claude Code
history, ~380k calls), magpie serve --web, warm call caches, heap
profile from /v1/magpie/heap:
- at rest (2 min): s2.Encode's archives 17.2 MB -> 9.2 MB (slices.Clone)
- at the warm-up's peak (6 s): archives 45.3 MB -> 30.6 MB
- liveHeap at 30 s 96.1 MB -> 90.3 MB, footprint 213 MB -> 203 MB
TestPackedArchiveHoldsOnlyItsBytes packs 100 blocks of 2000 rows and
measures what stays reachable after a collection. On the old pack it
fails: "100 packed blocks hold 16035 KB for 3887 KB of archives"
(3 of 3 runs); with the change it passes, and blocks packed through
the same scratch read back their own rows.
At 8b48dc5d6 (this commit and the two beside it, on
|
||
|
|
81a24cf8fe |
groups: a found group is listed as auto/<model id as the vendor spells it>
ZeroClover asked on X: Auto Group ids group/auto-<slug> can't be looked
up on models.dev. A found group is now listed and written as
auto/<model>, e.g. auto/claude-opus-5.5: /v1/models, the catalog, agent
configs, the GUI's Routing page and the CLI. Context and output limits
come from the model's metadata as before.
What stays the same:
- The internal id is still group/auto-<slug> (Group.Ref() gives the
public one). Every old form is still accepted as input forever:
provider.CanonicalRef turns auto/<model>[:level][[1m]] into it at the
gateway (validateModel), keys, stats, affinity and usage, so both ids
route to the same group and count as one.
- A key's model list allows a model by either id, group/* included
(allows() in key_models.go).
- Hand-made groups stay group/<id>.
- A provider whose stored id is "auto" keeps its models: while one
exists, found groups are listed by their old id (AutoRefsOn) and
auto/<x> means that provider's model. Documented in
docs/subsystems/gateway-routing.md.
Agent configs: SyncCatalog rewrites a field that holds a found group's
old id (renameFoundGroups), but only while the value is still what
applied.json says magpie wrote; a value the user set stays. A pick by
the old id written now is written as auto/<model> (Apply). Hidden,
picked and ordered model lists saved by the old id hold for the new one
(visible.go), and a bare model id still reaches its found group (bare.go).
Claude Code is given a dotted Claude version dashed (ClaudeSpelled), so
auto/claude-sonnet-4.5 sits in its settings as auto/claude-sonnet-4-5.
That routes to the same group, but with found groups off nothing reads
it back dotted, and Reseat took the field for changed and left the agent
on a group that was gone. Reseat now compares a group pick by its
canonical id (samePick). The old ids had no dots, so this is new with
auto/<model>.
Run at this tree (sandbox HOME, caches pinned):
- gofmt -l: clean. go vet ./...: clean on darwin, GOOS=linux -tags
nogui, GOOS=windows.
- go test -p 4 -timeout 45m ./...: every package ok except agent and
gateway, whose failures were the tests' expected ids (updated here)
and two regressions now fixed (bare ids; desktop models hiding groups
by prefix). Every failing test passes on rerun. Load average was
~210-290 from other sessions throughout.
- Reruns: provider, cli, codexcat ok. internal/gui: only
TestSetAnswersWhileDevinAndProvidersHang fails (set slow/slow-1 took
10.19s), and it fails the same in a git-archive export of
|
||
|
|
2fcd4b33c4 |
usage: one Vias index answers every since, instead of a rebuild from the whole log whenever the since changes (#2776)
Vias kept the lists for one since. The Sessions list asks from its
oldest listed session's start, each agent's manage page from that
agent's oldest, and a session's detail from that session's start, so
an open page's polls almost never asked the kept since, and each ask
read and grouped the whole log again. Idle with an open Sessions page
on the 720k-call sandbox, buildVias allocated 9.1 GB in 8 minutes,
78% of everything allocated, which is most of why the idle process
churned its heap and grew.
The cache now keeps one index from the whole log and each session's
first call. A session whose calls all came at or after the since is
answered from it. A session with calls before its since is answered
from one kept window for that since, built only when such a session
is read. Len counts the sessions with a call since the index's time.
Both are kept per log version and agent list, as before.
TestViasAnswerEverySinceFromOneIndex writes 20,001 sessions and asks
from three sinces in turn, as the three pages do: 2,677 bytes an ask.
On the old cache: red, 11,580,100 bytes an ask. It also checks that a
session with a call on each side of a since counts only the one after
it, and what Len says for a window and for every session.
TestGatewaySessionsCachePricesWindowsAndRewrite's window check and
TestUsageViasSkipsOldHistory stay green.
720k-call sandbox, idle with an open page's polls every 15 s (the
Sessions list, stats, Claude's manage page, Requests, state), before
and after side by side for 12 minutes, load ~170-250. Allocated from
minute 4 to minute 12: buildVias 9,100 MB before, 0 after (built once,
before minute 4). The faster answers let the poll loop run about twice
as often, so the totals (11.6 GB and 10.5 GB) aren't per poll. The
live heap ran 352-641 MB before and 514-724 MB after, and RSS 730-962
and 555-1217 MB; both swing with where a poll is when the snapshot is
taken and the machine's load, and neither shows a trend in 12 minutes.
Run: go test -p 4 -count=1 ./internal/usage/ -run
'Vias|KeptStrings|GatewaySessionsCachePrices|Incremental|Review': ok.
Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main
|
||
|
|
34b1757843 |
usage: the kept gateway projection's days and models are lists of their own size (#2776)
buildGatewaySessions grew each session's Daily and Models an item at a
time from empty. The projection is kept for as long as the log is
unchanged, and so was the spare room append had left each list (five
days took eight). slices.Clip in gatewayProjection hides that room from
callers but doesn't free it. On the 720k-call sandbox, that append was
the largest single allocation of the build (319 MB of 1.14 GB), and the
lists are most of what the start keeps for the Sessions page.
Each list is now made at the size its map already counts.
TestGatewayProjectionKeepsNoSpareRoom builds 3000 sessions x 5 days
with one to five models each, and measures the heap the projection
keeps. The bound is its days and models x1.3, plus the sessions' list
and index. Fixed: 9,233,056 bytes, against a bound of 10,478,400. With
the two makes taken out by hand: red, 12,754,488 bytes.
720k-call sandbox, cold start, the four first asks together, the live
heap 20 s after them, back to back: 541 MB before, 479 MB after. The
machine's load was ~250-290 and the answers took ~140 s in both runs,
so their peak RSS (1395 and 1891 MB) measured the load, not this.
Run: go test -p 4 -count=1 ./internal/usage/: ok.
Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main
|
||
|
|
43bd998b15 |
usage: GatewaySessions hands out the kept projection's lists instead of cloning every session's days for each ask (#2776)
GatewaySessions cloned every session's Models and Daily for each ask,
from the projection kept for exactly these asks. The start's first
asks (the Sessions list, each agent's manage page, the stats) each
cloned them all. In a heap snapshot at the 720k-call sandbox's peak,
cloneGatewaySession held ~447 MB live of the 1362 MB. Every caller
(gatewayExternal, listedGateway) only reads the lists, and copies them
again into its own ExternalSession anyway.
The lists are now the kept projection's, shared and read only, which
GatewaySessions' doc now says. This changes the old contract that a
caller owned its copy. The kept lists are clipped, so an append by a
caller makes a slice of its own and can't write into another's.
gatewaySessionFrom shares the days in a window the same way.
GatewaySessionByID still hands out a clone.
TestGatewaySessionsHandOutTheKeptProjection writes 2000 sessions x 10
days and asks 10 times: 435,215 bytes an ask, against the 368,000-byte
list itself. With the clone put back by hand: red, 3,669,150 bytes an
ask. TestGatewaySessionsCacheRefreshAndOwnership now checks that two
asks share the days, that two callers' appends don't alias each other
or the kept list, and that the kept data is unchanged after them. With
the clone put back it is red too ("each ask has a copy of the days of
its own").
Run: go test -p 4 -count=1 ./internal/usage/ ./internal/gui/: ok (load
~157).
Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main
|
||
|
|
6359b2c27c |
usage: Vias hands every caller the one copy it keeps, and a session's list is copied only when read (#2776)
Vias cloned every session's list for each ask, from a cache built for
exactly this. The Sessions list, the manage pages and a session's
detail each asked, and read the lists of the sessions they show, or of
one. Over ~720k calls one ask was ~66 MB.
Vias now answers a ViaIndex over the kept map. Of(key) is a session's
list as a copy of its own, so a caller still can't change the kept
one; Len is how many sessions have one. The three GUI callers and the
tests read through Of.
TestViasHandOutTheKeptCopy writes 20,000 sessions and asks 20 times,
reading one list each: 2,590 bytes an ask. With the clone of every
list put back by hand (under ViaIndex): red, 3,817,492 bytes an ask.
It also changes a list read through Of and checks the next ask still
says 1 call.
Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main
|
||
|
|
227b864a45 |
usage: CodexModelEffort keeps only the gateway calls a Codex session file's call can be matched to (#2776)
CodexModelEffort built the whole ledger of the period and kept the rows
that carry a Codex thread. Every gateway call became a Record (in
gatewayRecords' slice), a packed row (gatewayMatchesDetails' chunk) and
a priced Row (ledgerMatched), all held at once, though only a gateway
call paired with a Codex session file's call by its response id can
carry a thread. On the 720k-call sandbox this build was 7.6 GB of the
start's 18 GB allocated and most of its peak.
codexEffortRows visits the log once and keeps only the gateway calls
with a response id, request id or session (native, else magpie's) that
one of the session files' calls has, or an agy call when one is agy's.
No other gateway call can change gatewayMatchesDetails' answer: the
request-id match looks up only the locals' ids, the fallback groups are
looked up only by the locals' sessions, and a response id's uniqueness
is counted over every call that has it, all of which are kept. Only the
paired calls are priced into rows, and the rows are the whole ledger's
thread rows in the same order, so the sums (floats included) are the
same.
TestCodexEffortRowsAreTheWholeLedgers compares the rows with the whole
ledger's for All, Today and 7d, with Codex's reader and every agent's:
a pair by response id, an ambiguous response id, a session-and-tokens
match, a call two days old, and unrelated calls around them. With the
session test dropped from matchingRecords by hand it is red (all,
every agent: the session-matched call shows as a row of its own).
TestCodexModelEffortLetsUnrelatedCallsGo builds over 3000 unrelated
gateway calls and allows a visit of the log and a half. With the old
build put back (LedgerOf): red, 18,347,128 bytes against a visit's
1,198,680. With the fix: 1,321,824 against 1,321,744.
720k-call sandbox, cold start, the four first asks together, back to
back (load 48.7 then 14.7, so the times are not comparable; the memory
is what this measures):
before (beb9c40d5): peak RSS 4411 MB, heapSys 5513 MB, live 574 MB
after: peak RSS 2427 MB, heapSys 2413 MB, live 542 MB
manage?agent=codex answered in 41.5 s before, 23.1 s after.
Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main
|
||
|
|
e7114d3882 |
usage: one gateway session projection is kept, and a range of days is read out of it (#2776)
The gateway's sessions were projected and kept once per `since`, up to
four at once (all time, and each Sessions stats range: today, 7, 30
days...). With 600k calls the all-time projection alone is ~160 MB in
use (pprof inuse_space of buildGatewaySessions on the sandbox below),
and #2776 counted 148 MB for its copies.
Now only the all-time projection is kept. A range that starts at a
local midnight (every stats range does: combinedSessionStats parses
st.From in time.Local) is derived from it: each session's days from that
date on, with its tokens, models, cost and start/last summed from those
days. Each kept day now carries the first and last time of its requests
(unexported, two time.Time) so the derived start and last are exact.
Any other start is built from the log and not kept. The cache is keyed
on the zone too, since the days are local dates.
TestGatewayWindowsShareOneProjection: six days of calls over three
sessions, priced and unpriced models; the all-time read and five ranges
(0, 1, 2, 3 and 7 days back) build one projection between them, and each
range equals a direct build from its midnight (sessions, start, last,
tokens, models, cost within 1e-9, unpriced, days). Broken by hand:
- the midnight path turned off (a build per range, as before): red,
"built 6 projections for one log and 5 ranges, want 1".
- the derived start taken from the whole session: red, codex|even's
Start 2026-10-15 where the build says 2026-10-19.
Cost: the two times per kept day add ~13 MB to the one projection on the
sandbox below (158 -> 171 MB in use), against a whole second projection
(~160 MB) for each range a page asks for.
Measured: the sandbox runs (see the commits before) ask only the 30-day
range, so their heap shows one kept projection on both sides; the
saving is per extra range asked and is shown by the test's build count,
not by those runs.
Run on origin/main
|
||
|
|
db61143fe7 |
usage: the Sessions and Routing caches copy out the strings they keep, so they no longer pin every decoded block
An unpacked block's strings are cut from one allocation (unpackInto). The gateway-sessions projection (gatewayCache) and the vias cache kept a session id, model, agent, provider or effort from nearly every block, and each such substring held the block's whole decoded text: request and response ids and errors included. keptStrings clones each kept value once and interns it, so a cache holds only what it uses. TestSessionCachesHoldNoDecodedBlocks writes 16 blocks x 512 rows with a 1 KB error each, reads GatewaySessions and Vias, drops the snapshot and compares the live heap with and without the caches. Without the fix (both call sites reverted) it is red: "the caches hold 16651 KB for 16 sessions: the decoded text of their blocks (8192 KB)". With it, green -count=3. Measured (macOS, sandbox HOME seeded with 600k gateway calls, the fixed build vs |
||
|
|
2c72563dd1 |
usage: Requests splits and filters by gateway key, with "No gateway key" for the calls none made (#2521)
MauriceCarlo asked for two things on Usage → Requests. 1. The gateway-key filter should show even when one key has calls. The picker hides itself under two options, and with one key it had one, so calls made with that key couldn't be told from calls made with no key. A "No gateway key" choice (callerKey=none) now sits beside the keys whenever the period has calls with no key, or it is the current pick. A single key's picker therefore shows and separates the two. The hidden condition itself is left to #2499, which another session has. 2. The trend chart and the ranking can split by gateway key. LED_SPLITS gains "Gateway key". It's offered only while the period has a key's calls, and it falls back to Model otherwise. A click on a rank row picks that key, or none, and a second click lets go, as the other splits do. Server: - usage.Dimensions gains "callerKey". A row's key is its CallerKeyID, or NoCallerKey ("none") when it has none, and the filter takes "none" as calls without a key. - Filter.Without(d) is the one place that clears a dimension's own pick, so the by-split lists every value. RequestPage's fast and slow paths both use it now; they each had their own switch. - usageapi names the split's shares from the key labels: "No gateway key" for none, the ID if a key was deleted. - OwnPage keeps a held key's view to its own share in by and in the chart's split, so one key never learns another's name or numbers. The series was already only its own rows. - docs/reference.md documents callerKey=none and by.callerKey. "No gateway key" goes into the core i18n.js. The gateway keys page says "No gateway keys yet", and i18n-keys' "a plugin's words are its own" matches on substrings. Tests: - TestCallerKeySplitAndNone runs the fast and the slow path over {}, one key, none, and none+an agent, and checks by.callerKey. Broken by hand, it goes red: once with the none clause in the filter removed, and once with Without's callerKey case removed. - TestUsageOverGateway: on loopback the split names both keys. A held key's by.callerKey is only its own. With the OwnPage scrub skipped, it goes red (another key's name leaked). - usage-ledger-key-split is new, in both engines, all five languages, and 1400 and 760 px. It checks: - the picker's options with the none choice; - filtering on none; - the split's rows, and a click picking and letting go; - no sideways scroll; - that a period with no key's calls shows neither the picker nor the pill. 32/32 pass. With the none option removed by hand, 11 go red. Run on origin/main |
||
|
|
7170b5d8bd |
usage: the plan credits a reply says it cost are summed by model, agent and session (#2512)
wwcraft_ on Discord asked for the WorkBuddy credits spent on the Usage page, by model, agent and session. WorkBuddy's chat stream ends with usage.credit, the per-request figure its own app shows as "Credits Consumed". The built-in and the moved plugin both hand that chunk to the gateway's chat decoder (the plugin's renamed()/kept() pass usage on as it came), so cUsage reads `credit` into Usage.Credits and the three record sites keep it on the row. A reply that says nothing has no credits, not 0. - usage: Record.Credits; Totals/Via sum Credits and count Credited; the packed row keeps it under its own flag bit (4096, in TestRowFlagsApart); the ledger CSV gains a trailing "credits" column. - GUI: the Usage ranking's line says "0.7 credits" (积分, 積分, クレジット, Credits) beside the cost, its title how many requests said it; the Sessions page's Routed line says it per route. TUI usage page and `magpie usage` tables say it muted on the same line. No new layout. Real replies on workbuddy-ai, 10-16: gemini-3.5-flash "credit":0.01; deepseek-v4.1-flash, minimax-m3, kimi-k2.6 "credit":0; glm-5.3-flash refused (14003). The tests use those bytes. Run (at b07b518e7 on origin/main |
||
|
|
357ffac7be |
usage: a model's Same as prices its calls when no list does (#2344, liuweifeng)
A model a provider serves under its own id (a WorkBuddy kimi-k3-1, a relay's renamed gpt) had no price unless the user typed one, even when the user had already told magpie in the editor's "Same as" box which model it is. Its calls showed no API-price cost in Usage, window holds had no price to weigh, and `magpie model price` said unpriced. Now, when neither the user's prices, the provider's list nor models.dev's maker price covers a model, provider.SamePriceIn takes the maker's list price of the model it is the same as (settings.ModelSameAs), and the provider's price rate still applies. A price the user set, or a list that prices the model, always wins; nothing is inferred without a Same as. The same fallback is used by priceOf (Usage costs, re-priced when the ledger is read, so past calls pick it up), usage's apiPricer (window holds), the model editor's greyed list price, and `magpie model price`, which names where the price came from. The "Same as" tooltip says so in en, zh, zh-TW, ja and de. Run: - go test -p 1 -tags nogui ./internal/provider ./internal/usage ./internal/cli ./internal/gui (focused: TestSameAsPricesAnUnlistedModel, TestHoldsPriceTheModelItIsTheSameAs, TestModelEditorShowsTheSameAsPrice, TestModelPriceCmdSaysWhereThePriceCameFrom, plus the packages): ok - GUI (chromium + webkit): provider-same-as, i18n-keys, model-price-edit, 11/11 pass - gofmt -l clean; go vet -tags nogui for darwin, linux, windows: clean Broken by hand, each went red: - SamePriceIn dropped from priceOf: "kimi-k3-1 ... false; want $0.3" - usage's apiPricer fallback removed: "wasn't its API price: <nil>" - the GUI editor branch removed: "list <nil>" - the CLI source line disabled: TestModelPriceCmd... FAIL - the zh tooltip left untranslated: provider-same-as.test.cjs 0/2 A prefix-stripping branch passed when removed (MakerPrice already resolves vendor-prefixed ids like moonshotai/kimi-k3), so it was dropped. Not tried: a real WorkBuddy account's usage after the change. Full suite: SUITE_LINE |
||
|
|
0c0665126b |
quota: magpie quota --json and /v1/magpie/quotas tell each window's whole (holds / holdsWhy) as the Usage page does (#2333, zhenghaowen0967)
usage.WithWindowHolds reckoned a subscription window's whole (tokens, and cost at API list prices) from magpie's own calls, or why it can't, but only GET /api/usage/quotas and its refresh called it. magpie quota --json, GET /v1/magpie/quotas and its ?kept=1 list showed name, used, remaining and resetsAt only, so a script comparing plans had to rebuild the estimate from the log without its guards. Package provider can't import usage, so usage sets provider.ReckonHolds in an init (like the other provider hooks). quotaReport, which QuotaReport, KeptQuotaReport and RefreshReport share, runs it once over every card and QuotaSpan carries Holds and HoldsWhy. The log is read through usage's cached snapshot, so ?kept=1 (magpie statusline, every message) adds no full read after the first. A key held to a budget, models or accounts and told cards (#2216) is not told holds: they are reckoned from every call routed through the account, other keys' too, so quotaScope.quotas drops them; this machine and unheld keys get them. The Balance guard in holdsBounds (a Codex account holding credits gets no whole and no reason) is unchanged; it is answered on the issue. Docs: reference.md's /v1/magpie/quotas section names holds/holdsWhy and each reason; providers-accounts.md's Allowance row names the hook. Run (sandbox HOME, -tags nogui, -p 1): - New TestQuotaReportTellsWindowHolds (provider), TestQuotaReportsReckonByTheLog (usage, against a real usage.jsonl in the sandbox) and TestHeldKeyToldNoWindowHolds (gateway) pass. - Broken by hand: the ReckonHolds call in quotaReport skipped → provider test FAIL "reckoned 0 times over 0 cards"; Holds/HoldsWhy not copied into QuotaSpan → FAIL "5 hours told no whole"; usage's init removed → usage test FAIL "provider.ReckonHolds isn't set"; quotaScope not clearing them → gateway test FAIL "a held key was told 5 hours's whole". - go test ./internal/provider ./internal/usage ./internal/cli ./internal/gateway: ok. - gofmt -l clean; go vet -tags nogui darwin, GOOS=linux, GOOS=windows on provider, usage, gateway: ok. - Not run: the GUI suite (no GUI file changed), and against the owner's real accounts. Full suite: SUITE_LINE |
||
|
|
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 (
|
||
|
|
b00da3860c |
usage: a past cycle shows its own whole-window estimate, and a reset ends a dry run (#2009, #2010, NorethSea)
Ported from NorethSea's fork (abed2e224) and re-derived on main.
What it does:
- A known reset ends a dry run (a stretch where a window read 0% left), even
when the next poll sees the refill later. A stale dry reading taken after
its own reset no longer extends the run. Calls from the reset on are not
treated as "maybe paid from credits".
- A refill observed later than reset minus span
(QuotaPoint.StartsCycleAfter, the boundaries history sampling keeps)
starts what is reckoned. Calls before a fixed-deadline refill stay in the
cycle before it. A first reading is not a reset.
- Picking a past cycle in Usage > Allowances > Trends > Cycle asks
GET /api/usage/quotas/history/holds once per selection
(quotaCycleHoldsOf). The route asks no vendor. HistoricalWindowHolds
reckons each window at its own last reading in the cycle, using the
ledger and readings from before that reading. "Loading..." shows while it
is pending. An answer for a cycle no longer picked is dropped. The card's
Refresh, or an asked read, reckons again. The estimate's tooltip names the
window's start and the reading's time.
Changed from the fork:
- After a run closed at its reset, the fork reset lastLeft to zero. A
window that ran dry again before its next reset then opened a run from
time zero, which hid every window's estimate, the weekly one included.
The next run now starts no earlier than that reset.
TestWindowHoldsDryAgainAfterReset covers it (red with the fork's line).
- The fork narrowed the live card's Span to the observed refill. Span also
feeds provider.WithWindowStarts, so the window's Pace would have moved.
withSpansOf puts the card's spans back after reckoning. A span assertion
in TestWindowHoldsUsesObservedRefillStart covers it (red without it).
- The fork's historical snapshot dropped the card's Balance. That slipped
past the gate a live card has (holdsBounds), so a card that tells a
balance got past-cycle estimates. Balance is now kept. Covered in
TestHistoricalWindowHoldsUsesEachWindowsOwnReading (red without it). The
fork's fixture had a Codex card with a Balance, which no Codex card has.
- Main has since added HoldsWhy (#2045). The fork's own "Whole: not enough
reliable data" line and its .quota-holds-unknown CSS are left out. A past
cycle uses main's holdsUnknownLine and its reasons, as a live card does.
A window with neither an estimate nor a reason shows nothing, where the
fork showed its unknown line.
- withRecordedWindowStarts is ported to main's holdsBounds(start, end, why).
- quota-refresh-order.test.cjs's VM harness now stubs quotaCycleHolds,
which loadQuotas and quotaRefresh clear.
Left out: nothing else from the fork. Past prices aren't kept, so a past
cycle's cost uses today's API list prices (documented). Credits can't be
attributed per call, so none is attempted (documented).
What was run:
- gofmt -l: clean. go vet -tags nogui ./... for GOOS darwin, linux and windows.
- go test -tags nogui ./internal/usage ./internal/gui ./internal/provider:
ok.
- Each of the three fixes above was reverted by hand, and its test went red.
- GUI, Chromium and WebKit:
- quota-curve: 30/30. Also run at 1100 and 420 wide: 60/60 (all five
languages).
- Also: quota-*, i18n-keys, gui-de/ja/zh-tw, usage-card-refresh,
usage-refresh*, usage-stale-answer, usage-remote-cards,
usage-accounts*, usage-quota-head, usage-pack and usage-alert.
- Reds: quota-count-wrap and quota-name-translated are red in WebKit,
the same as on origin/main
|
||
|
|
58651568b3 |
agent, sessions, provider: a state file that doesn't parse is kept aside, not written over as empty (#2263, ggbdpq)
applied.json, wsl.json and sessions-wsl.json were read as empty when they didn't parse, and the next save wrote that emptiness over them. What magpie had applied to each agent, the WSL distros and the WSL session listing were lost with no copy. stash.json already kept a bad file aside as .bad-<time>. Each of these now does the same through one helper, lastgood.KeepUnparsed, instead of a copy per file: - It does nothing when the file is missing or empty. - When the file doesn't unmarshal into the reader's own type (lastgood.Into[T]), it copies the file aside (KeepBad). - It stops the write when the copy can't be kept. This also fixes the issue's claim about stash.json. Stash judged a file with json.Valid, so `[]`, which a map reader takes as empty, was written over unkept. Its failed copy was only logged, and the write went ahead anyway. Both are fixed (TestUnreadStashArrayKeptAside), and gateway-hidden.json uses the same helper. Siblings found by going through every single-file JSON reader that takes a bad file as empty and then writes it whole: - stepfun-auth - login-returns - quota-history - balance-history - credits-daily - Claude Desktop tiers - plugin updates - usage's computer id - davsync's sync state Each now keeps a bad copy. Caches that are rebuilt from the vendor are left alone; docs/subsystems/providers-accounts.md lists them. Run: - gofmt -l, go vet (darwin -tags nogui, GOOS=linux -tags nogui, GOOS=windows): clean. - go test -tags nogui -p 4 -timeout 40m ./... with the other three commits of this push: see the last one's body. Broken by hand: on the code before this, these fail: - the issue's applied_keep_test.go and wsl_keep_test.go - TestUnreadStashArrayKeptAside - TestUnreadStateKeptAside (10 subtests) - the gateway, usage, davsync and plugin _keep tests TestKeepUnparsed and TestKeepUnparsedFailsWhenItCantBeKept cover the helper. I dropped a test, "not written when it can't be kept", for stash. It passed on the old code too, because a read-only folder also stops the atomic write. Not tried: a real WSL distro. Co-authored-by: ggbdpq <ggbdpq@gmail.com> |