Commit Graph
181 Commits
Author SHA1 Message Date
yetone 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 1360689ef, Append into an
existing folder, -count 5: 3070 B and 25 allocs per call before, 2445 B
and 20 allocs after. Wall time is the write itself, ~45-60µs, and at
machine load ~160 the run-to-run noise was bigger than the saved stat,
so no time saving is claimed. A scratch test with XDG_CONFIG_HOME under
two missing folders checked the first Append still creates them and the
file.

Run at 1360689ef plus this change: gofmt -l clean; GOOS=linux and GOOS=windows
go vet -tags nogui ./internal/usage ok; go test -count=1 -timeout 45m
./internal/usage ok.
2026-10-27 01:58:09 +08:00
yetone 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 (cbbf3163c) and new, 4 rounds each:
  phys_footprint_peak old 396 353 346 352 MB, new 319 322 329 329 MB
  peak live (gctrace) old 209-259 MB, new 188-205 MB
  at rest unchanged (184-205 MB), warm-up time in the same range.
  gctrace: cold max live after mark is now 187MB against warm's 173MB; what
  is left of the gap is allocation churn (1.2GB allocated in the cold
  build against 280MB warm), not held data.
go test ./internal/usage ./internal/gui ok; -race -count=3 of the disk and
spill tests ok; GOOS=linux and windows go vet -tags nogui ok; gofmt clean.
Broken by hand: no spill put -> TestRequestDiskBuildSpills red; done not
making a chunk again -> TestArchiveSpillFailedMadeAgain red; the spill
ranked as the file -> TestRequestDiskBuildSpills red after the save.
Not tried: Windows (no mapping, path unchanged), a disk that fills while
spilling (the made-again path is covered by the unit test only).
2026-10-25 16:56:02 +08:00
yetone 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 (67a137744 + this change):
- go test -count=1 -timeout 45m ./internal/usage/ ./internal/sessions/:
  ok. go test -run 'Warm|Session|Request|Usage' ./internal/gui/
  ./internal/gateway/: ok.
- go test -race -count=4 -run TestRequestDisk ./internal/usage/: ok,
  six times in a row.
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage/: ok;
  gofmt -l clean.
- TestRequestDiskBuiltChunksMapped holds the write while a second page
  copies the chunks and a third copies them before the write and keeps
  them after it. It went red (0 of 4 mapped) with the swap matched by
  pointer instead of serial, and with keep not carrying the mapping.
- The real warm-up (gui warmSteps in sessions.Warm) on a copy of the
  owner's ~/.claude and ~/.codex sessions, cold (requests-v1.bin
  removed), parent and change alternating, 3 runs each, measured 5s
  after the warm-up:
  - heap at rest: 200/200/198MB before, 154/148/152MB after;
  - phys_footprint at rest: 233/234/237MB before, 198/197/205MB after;
  - phys_footprint_peak: 361/396/347MB before, 335/367/378MB after,
    the same within noise (the build itself is unchanged).

Not tried: Windows (it maps no file, so it is unchanged there).
2026-10-25 16:19:18 +08:00
yetone 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 defbb1a15): go test ./internal/usage
./internal/sessions ./internal/gui ok; -race -count=3 of the chunkRows,
Pack and Archive tests ok; GOOS=linux and windows go vet -tags nogui
./internal/usage ok; gofmt clean. TestChunkRowsReuseReadsEachBlock now
runs 4 passes, lent and not, in both orders, through one pool; broken
by hand (a reused rows slice cut to its cap, not the block's count) it
fails "pass 0 block 1: 0 rows, want 3".

Not tried: Linux and Windows real-data runs.
2026-10-25 15:10:47 +08:00
yetone 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 894603bcd (GUI-only,
none of these files) and provider, usage, usageapi, the build and the
Rename/Answer/Lead tests of gateway and gui run again there: ok.
- TestRenamesByWhenTheIDWasTaken (provider), TestRenamedProviderShownOnce
  (usage), TestRenamedProviderAnsweredItsLead (gateway): each red with its
  piece broken by hand (Save's giveID, freeID's Was, the last-good renames,
  probe rename, vias rename, block pricer's timed path, summarize's time,
  loggedAnswers' rename), green with it.
- go test -timeout 45m provider usage usageapi budget middleware cli agent
  gui gateway sessions profile tui: all ok.
- gofmt -l, go vet ./internal/..., GOOS=linux/windows -tags nogui vet of
  provider/usage/gateway and build of the binary: clean.
- Sandbox: rebuilt binary on the same HOME; /api/usage/requests lists only
  newrelay, the probe row included.

Not tried: the GUI suite (no JS or asset changed; /api/providers gains an
omitempty "gave"), Windows tests run on the Windows box, a real account,
and the full ./... suite (other sessions' suites were running).
2026-10-25 10:53:45 +08:00
yetone 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 (b1f44d099), load 26-32:
- phys_footprint_peak: 285-298MB -> 232-259MB
- phys_footprint at rest: 221-227MB -> 176-179MB
- peak live heap 200MB -> 157MB, heap at rest 198MB -> 147MB
- step 2 (QueryPage All): 771-952ms -> 754-814ms; warm-up 1.68-1.96s
  -> 1.54-1.89s
- every one of the 15624 mapped chunks unpacks to the same rows
  (reflect.DeepEqual, 359553 rows) as its archive copied to the heap
- mmap of the file alone and a CRC pass: 6.5ms, read+CRC 8-10ms

Tests: go test -timeout 45m ./internal/usage ./internal/sessions
./internal/gui ok; -race on the usage request/chunk/page/disk tests ok;
gofmt clean; go vet -tags nogui with GOOS=linux and GOOS=windows ok.
TestRequestDiskChunksMapped checks every chunk read from the file is of
the mapping and that it is unmapped once forgotten; it is red with the
mapping turned off. TestRequestDiskMappingCutShort is red ("fatal error:
fault SIGBUS") with SetPanicOnFault off.

Not tried: a Linux or Windows real-data run (Linux vet only; Windows
keeps the old path); a file truncated under a running magpie outside
the test.
2026-10-25 08:29:23 +08:00
yetone 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 e1f5f9c16, which origin/main still was):
- TestCodexEffortReusesPagePairing (new): the page pairs once, the
  effort after it pairs 0 times, and equals an effort that pairs on its
  own. Broken by hand (memo -> nil): red, "the effort after the page
  paired again (2 pairings)".
- go test ./internal/usage ./internal/gui ./internal/sessions: ok.
  -race ./internal/usage: ok. go vet -tags nogui GOOS=linux and
  GOOS=windows for usage and gui, gofmt: clean.
- Real data (a copy of the owner's sessions, 421,292 calls), warm-up
  three runs each after one to write the cache file, e1f5f9c16 -> this:
  step 3 0.52-0.58s -> 0.24s; warm-up alloc 1.24-1.29GB -> 1.06GB;
  warm-up 1.80-1.85s -> 1.50s (one 1.77s). Max RSS unchanged (~310-333MB).
- CodexModelEffort(All)'s JSON hash on that data, four runs alternating
  base and this: identical every time (78f93906...).

Not tried: the effort of a period whose page was not built first (it
pairs as before, from nil).
2026-10-25 08:05:33 +08:00
yetone 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).
2026-10-25 07:57:24 +08:00
yetone 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 13f907013, and the packages again rebased on 73d17f90c
(usage, gui, sessions ok; vet and gofmt clean):
- real history in a sandbox HOME (the sbpairs copy of the caches), a
  page in each of three processes: before, 9 files (84,625 calls) read
  at each of two starts; after, a start that made every chunk (the
  source changed) and then 0 files read, then 2 (live sessions).
- the rows rule alone on the real history (requestDiskLeast raised past
  15.6k): with no file, a start wrote it (44,275,132 bytes), and the
  next start read it and made 2 files' chunks.
- TestRequestDiskRowsWrittenOnce: red with the rows rule removed ("no
  file of them") and red with the once guard removed ("written again
  for 4 rows").
- go test -count=1 ./internal/usage ./internal/gui ok; go test -race
  -run 'TestRequest|TestQueryPage|TestChunk' ./internal/usage ok;
  GOOS=linux and GOOS=windows go vet -tags nogui on both ok; gofmt -l
  clean.

Not tried: a full go test ./... (one suite per machine).
2026-10-25 07:47:12 +08:00
yetone 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 (89dc16476 + this change):
- go test -race -count=1 ./internal/usage: ok
- go test -count=1 ./internal/sessions ./internal/gui: ok
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage
  ./internal/sessions, and go build -tags nogui .: ok; gofmt -l clean
- TestRequestDiskNamesItsSource hashes the package's files from disk
  and wants the same name. Broken by hand (embed request_*.go only):
  red; restored: green.

Not tried: an upgrade of the real app from one release to the next.
2026-10-25 07:23:45 +08:00
yetone 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 = 2a3d9f5ae, alternated, two rounds each):
- total alloc through step 3, cold: base 3171/2994MB, new 2610/2626MB
- warm (requests-v1.bin read): base 1763/1751MB, new 1399/1408MB
- times within noise: cold step 2 base 1.86/1.61s, new 1.56/1.85s;
  step 3 0.55-0.79s both

Run at this tree (2a3d9f5ae + this change):
- go test -race -count=1 ./internal/usage: ok
- go test -count=1 ./internal/gui ./internal/sessions: ok
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage
  ./internal/gui: ok; gofmt -l clean
- TestChunkRowsReuseReadsEachBlock reads blocks of 400, 3, 120, 1 and
  400 rows through one chunkRows against their unpacked rows. Broken by
  hand (keep a string the earlier block left in the buffer): red; restored:
  green.

Not tried: a Windows or Linux run of the warm-up.
2026-10-25 07:06:36 +08:00
yetone 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 (432393217): 3.24 s / 448 MB maxrss, 2.18 s / 433 MB
- after: 1.85 s / 417 MB, 1.84 s / 410 MB
The readers are now mostly in syscalls (shard and meta.json reads).

Run at this head (432393217 + this):
- go test -count=1 -timeout 45m ./internal/usage: ok; with -race: ok
- go test -count=1 -timeout 45m ./internal/gui: one red,
  TestRestartHandsTheGatewayOver (18 of 19 requests answered, EOF), the
  open #3451; alone -count=5 it passes. Load was ~45.
- TestPrefetchEachMakeIsAReadersOwn: 9 makes (8 readers, the loop's
  own) and no race. Broken by hand: one make shared by every reader ->
  -race reports DATA RACE, red.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/usage ok.
2026-10-25 06:58:27 +08:00
yetone 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).
2026-10-25 06:20:17 +08:00
yetone 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 500aa7096 (origin/main, fetched): go test -timeout 45m of usage
(14.7s), usageapi (6.5s) and gui (143.5s, before the idle-save removal,
which touches no GUI path) ok; TestRequestChunksFromDisk -race -count=3
ok. gofmt clean; GOOS=linux and GOOS=windows go vet -tags nogui
./internal/usage/ clean.

TestRequestChunksFromDisk (new): a start reads no session file, a file
written over to the same size is read again for its mtime, new prices read
every file, a file cut short stands for the entries before the cut, and
garbage reads every file; every page equals the ledger's. Red with the
header compare taken out, with the size/mtime check taken out, and with
the write skipped.
2026-10-25 05:54:24 +08:00
yetone 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 a6399dd49 (= origin/main, fetched):
- TestRequestPairsReusedAcrossPages (new): a gateway call paired with
  its rollout, a fork copying another file's call and a Claude call,
  every page of All/Today/Week at limit 1 and the whole page against
  pageFromLedger. Broken by hand three ways, each red on the memo hit:
  apply without matched ("all page 1: 4 rows, 157 input"), without skip
  ("4 rows, 127 input"), without compactions (page differs).
- Real data, same process (scratch test, not committed), fresh pairRows
  vs the memo applied over a second read: sandbox with the live
  rollouts (symlinked, read only) and a copy of usage.jsonl: All 15607
  chunks, 4801 skip, 1469 matched, 2 actor sets; Today 58 matched; 7d
  1075 matched. Actors, compactions, skip, matched equal, and pages
  equal for 3 filters per period. Without the gateway log: All 15600
  chunks, 4801 skip, all periods equal.
- Timing on that sandbox (load 110-143), page turns after the first:
  v0.1.1449 mean 407 / 460 ms, this change 154 / 145 ms.
- go test -count=1 -timeout 45m ./internal/usage/... ./internal/usageapi/...
  ./internal/sessions/...: usageapi and sessions ok; usage red only on
  TestUsageReadAfterAppendHashesNothingOnAFineClock/whole-second_stamp,
  which is #3511 (taken by another session). At -count=20, load 154,
  it fails 3/20 here and 2/20 at the base 1313b047f; it builds no page.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ok.

Not tried: the GUI against a live gateway; the page reads the same
QueryPage the tests and the real-data run used.
2026-10-25 05:18:41 +08:00
yetone 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 1313b047f and this change: 0
  differences over 18 pages (floats at rel 1e-9).
- zzbench timing at load 170: warm pages 1.15s / 1.36s mean -> 0.45s /
  0.41s; first page 3.1s / 2.8s -> 2.4s / 2.6s.
- New TestRequestCellsFollowIdentityAndFiles: a child chunk whose
  parent's file changes (its root moves to top-z) without the child
  being read again, a changed child file, a gateway append, compared
  to pageFromLedger for All and Week. Broken by hand: reusing a part
  whatever its signature turns it red ("a cached part kept the old
  root: 0 rows, 0 input"). Passes in TZ=UTC too.
- go test -count=1 -timeout 45m ./internal/usage/... ./internal/usageapi/...
  ./internal/sessions/...: usageapi and sessions ok; usage red only on
  TestUsageReadAfterAppendHashesNothingOnAFineClock/whole-second_stamp,
  #3511 (taken by another session). -count=10 of it: 2 FAIL on this
  change and 2 FAIL on the base 1313b047f, at load ~100-145. Every
  other usage test passes.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/usage/.

Not done here: the pairing setup (unpacking unchanged chunks for
visibleLocal, matchedBlocks and foldCodexRows) is now most of a warm
page, ~0.18s each; it is next.
2026-10-25 05:02:18 +08:00
yetone 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 dbbe97991 (its parent ffe493773 adds
rows for magpie's own probes, none in this sandbox), on a sandbox copy of real data (sbmem: 12,069 Codex
rollouts, ~416k rows), base 22a7f86c9 against this, /api/sessions then
the Requests page then /api/sessions, one CPU profile over each run:
  total CPU          16.75s -> 9.40s  (first run 20.10s -> 8.32s)
  CodexModelEffort    4.21s -> 1.65s
  sessions.loadCalls  5.61s -> 1.22s  (now only under the first build;
                                       the page that follows reads none)
  wall, first run: sessions 4.97s -> 2.84s, requests 7.72s -> 2.01s
  (load average 78-133 from other sessions' suites, so wall is noisy)
/api/sessions of both binaries: 4,930 Codex sessions, 4,604 model/effort
entries, every token count equal and every cost equal within 1e-9
(summation order).

Tests, at this head after the rebase: go test ./internal/usage ./internal/sessions ./internal/usageapi;
./internal/gui -run 'Session|Codex|Effort'; ./internal/usage -race -run
'Codex|Effort|RequestPage'; gofmt; GOOS=linux and windows go vet -tags
nogui ./internal/usage ./internal/gui. TestCodexEffortRowsAreTheWholeLedgers
now also holds codexEffortOfIndex to the whole ledger's sums for All,
Today and Week; it goes red with a gateway call's actor broken by hand.

Not tried: a live Codex session writing while the list polls (the build
after a call is the page's incremental read, measured in 22a7f86c9).
2026-10-25 04:28:31 +08:00
yetone 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 22a7f86c9): gofmt -l clean; go vet
./..., GOOS=linux -tags nogui and GOOS=windows clean; go test -count=1
usage, probelog, netproxy, usageapi, provider and gui packages ok (the
rebase over 22a7f86c9 applied cleanly; upstream's 8b460833e chunk
cache leaves probeChunk, built per query, alone).

Run one rebase earlier (on origin/main 0b72ccbef; request_page.go
merged by hand onto 7d67910f7/66b6d6ade's per-row Totals, with
uncounted rows skipping the caller and account groups too):
- go test -tags nogui -timeout 45m ./... in a sandbox HOME, log tee'd:
  every package ok (gateway 640s, agent 514s, provider 278s, usage 77s)
  but internal/gui's TestRestartHandsTheGatewayOver (7 of 8 requests
  answered during the restart), 3 of 3 green alone after (#3451).
- gofmt -l clean; go vet ./..., GOOS=linux -tags nogui and GOOS=windows
  go vet ./... clean.
- GUI usage-ledger-probe, usage-ledger-reported, i18n-keys,
  purpose-filter, quota-pool-model: 72/72. usage-ledger's "newest live
  route needs no return-to-live button" is red on origin/main 0b72ccbef
  alone too (#3104).
- Whole GUI suite, both engines, at the pre-rebase base 761904b5a:
  1313 tests; reds, each also red on origin/main 7b1faf99f alone:
  account-discovery "agents' sign-ins read" (#3497), builtins
  "Plugins > Built-in" (Masking page in the list, #3518 filed), and
  context-map "two tiles overlap" chromium ja 420 (#3488; 1 of 2 red on
  main alone, 3 of 3 green on this branch alone). Earlier package run:
  TestRestartHandsTheGatewayOver red under load, passes alone (#3451).
- No size budget raised.

Not tried: no real vendor account (fake servers only); a plugin's model
list, fetched in the JS plugin host, isn't written down; the real GUI
app wasn't launched (Playwright only).
2026-10-25 04:12:06 +08:00
yetone 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).
2026-10-25 04:07:20 +08:00
yetone 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).
2026-10-25 03:58:02 +08:00
yetone 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 (7d67910f7): user 20.84 / 20.39 / 20.61 s, sys 2.69-2.93 s
  after:              user 15.33 / 15.74 / 15.75 s, sys 2.80-2.97 s
In the profile, buildRequestBlocksOf's row closure went from 5.56 s to
1.59 s cumulative. Wall time per page is too noisy at this load to quote
(1.9-3.1 s both ways). What remains per rebuild is mostly evicted shards
being read again (prefetchSources -> loadCalls, ~1.7 s over the seven
builds) and the walk of the Codex folders.

Tests: TestTotalsPlusAddsEveryField fails when a Totals field is left
out of plus (broken by hand: dropping FloorN fails it).
TestPartPlusIsAdd compares Part.plus with Part.add over measured,
reasoning, failed, handed-on and retried rows. TestCompactPageMatchesLedger
already compares the page with the per-row ledger path over 13 filters.
Making every dimension group reuse keep fails 60 of its subtests.

Run at this head: go test -count=1 ./internal/usage ./internal/gui ok
(36.5s, 150.0s); go build -tags nogui ./... ok; 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) and the gateway
package (it only calls usage's exported API, which is unchanged).
2026-10-25 03:31:55 +08:00
yetone 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 = 2009d33a6):
- peak footprint 452-481 MB -> 351-389 MB; peak RSS 577-616 -> ~495-505
- live heap at 6s ~306 MB -> 203-229 MB
- settled footprint 246 -> 226-239 MB; settled live heap 142-143 ->
  147-148.6 MB. ~4 MB of one block's text is still held from the chart
  loop; its holder wasn't found (keyer, Row fields, Locations,
  EffortFamily ruled out). Cloning every chart row reached 143.8 MB but
  costs CPU per row, so it was left out.
- process CPU over 15s: 8.25/8.35s -> 9.29/11.65s at load 77-95; the
  profile puts most of it in syscalls and CodexModelEffort's reads, and
  the page's own work at queryPage 1.61 -> 1.97s, unpackInto 0.17s.

Tests: TestRequestPageSameFromPackedLocalChunks builds the same page
from packed and unpacked chunks (Codex pairs, compactions, actors, Claude
duplicates, request-id and fallback matches); red with chunkRows' cache
never refreshed (r.c == nil) and with an empty decode.
TestRequestPageOwnsItsStrings is red with ownStrings' clone removed.

Run: go test -tags nogui -timeout 45m -count=1 ./internal/usage
./internal/gui ./internal/gateway ok at this head (gateway run after
rebase onto 3133f6343); gofmt clean; GOOS=linux and GOOS=windows go vet
-tags nogui ./internal/usage ok. Not run: the full ./... suite (other
sessions' suites are on this machine).
2026-10-25 03:11:41 +08:00
yetone 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); d08b6118b had already moved the
  masking page's maskWho, maskProv and stillMotion out to
  plugins/redact, which an earlier version of this change did too.
- Strings in zh, zh-TW, ja and de. docs/subsystems/provider-plugins.md
  now describes the ledger side and what is not covered.

Not covered, filed: hit rates read from the agents' own session files
(the TUI and CLI session lists, the Sessions tab's totals) still count
Kiro's 0 as a miss (#3470). Found on the way: System One's calls are
recorded without their cache tokens (#3471).

Run at this tree (on origin/main e57e78563, fetched just before; the
54-file GUI run was at a84d2ec80, and the 14 files that main's
redact page change since could reach were run again here):
- gofmt -l . prints nothing. go build ./... ok. go vet ./... ok,
  GOOS=linux go vet -tags nogui ./... ok, GOOS=windows go vet ./... ok.
- go test -count=1 -timeout 45m ./internal/usage ./internal/gui
  ./internal/gateway: all ok (gateway 388s), TestCoreScriptBudget
  included.
- GUI, 54 files (ledger-*, panel-*, i18n-*, context-*, request*,
  usage-card*, usage-ledger and the masking/redact files),
  concurrency 2: WebKit 439/452, Chromium 444/457. The new
  ledger-cache-unknown test passed in both. Again here (ledger-*,
  masking-*, redact-*, mask-*, usage-ledger): WebKit 104/117,
  Chromium 109/122, the same reds. The reds, both already
  red alone on main before this change:
  - redact-words-any-case, 10/10 in each engine (#3500)
  - usage-ledger "newest live route needs no return-to-live button",
    en and zh in each engine (#3104)
- At earlier bases, with the same change: usage-agents-hide (#3414),
  usage-checkin's WebKit Qoder tab (#3091), usage-fold (#3415),
  usage-focus-steady (#3501) were red, each red alone on main too;
  usage-card-refresh read a row before it was laid out, under load
  (#3509); context-picks (#3483) and
  context-map's tile overlap (#3488) in Chromium. Filed while doing
  this: TestUsageReadAfterAppendHashesNothingOnAFineClock goes red
  about 1 in 20 on main aa3112f4e (#3511); it passed in this run.
- Red on the old code: the new Go tests in usage, gateway and gui, and
  ledger-cache-unknown.test.cjs (the old page shows "hit rate 6%"
  where this shows 90%). Each changed piece was broken by hand and
  turned a test red. The exception is the OTel attempt path in
  observe.go, which no test reaches.

Not tried: a real Kiro account through the GUI.
2026-10-25 01:23:42 +08:00
yetone 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 3b5a2f612): go test -tags nogui
-timeout 45m ./internal/usage ./internal/gui ok (TestCoreScriptBudget
included, no budget raised; app.js 1,317,465 of 1,317,486). GUI files
panel*, tray*, i18n-keys, routing-sessions (27 files, chromium and
webkit): 336 pass, 0 fail. gofmt clean. Earlier, at 7571ebc93: full
GUI suite 1095 pass; the 4 reds are two tests red on main too (#3497,
removed by hand gives "changed height 630 !== 561".
2026-10-24 23:49:08 +08:00
yetone 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.
2026-10-24 22:58:26 +08:00
yetone 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).
2026-10-24 22:58:26 +08:00
yetone 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 63c0c354a plus this): gofmt clean,
go test ./internal/usage ok. GOOS=linux and windows go vet -tags nogui of
internal/usage and internal/gui ok, and internal/gui and usageapi ok,
with the heatmap change after this one on top.
2026-10-24 22:58:25 +08:00
yetone 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.
2026-10-24 21:00:05 +08:00
yetone 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).
2026-10-24 17:07:35 +08:00
yetone 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 3e9efe1d5:
- gofmt -l, go vet (darwin), GOOS=linux and GOOS=windows go vet of
  ./internal/usage ./internal/gateway: clean.
- go test -count=1 -timeout 45m ./...: ok, 70 packages, no FAIL (internal/gateway 544.996s)

Broken by hand (ClineServing returning false), each red:
TestSwappedClineServingName, TestKeptRowClineServingNameNotSwapped,
TestRouteKeptClineServingNameNotSwapped; and the scratch real-plugin run
marked all four routes Swapped.

Not tried: a real ClinePass request (no Cline sign-in on this machine),
so whether zRain's four rows had "上游:deepseek" after the vmc/ name is
the reporter's to say; the GUI suite (no GUI file changed).
2026-10-24 16:29:44 +08:00
yetone 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 f4640c0ae, rebased onto 2b4c0664e with no overlap):
- gofmt -l: clean. go vet ./... darwin, GOOS=linux -tags nogui, GOOS=windows: ok.
- go test -count=1 -timeout 45m (sandbox HOME) internal/usage,
  sessions, provider, cli, settings, gui, tui: all ok.
- Real binary in a sandbox HOME: two usage.jsonl calls priced $2 and
  $100 per M: `magpie usage` showed two model rows ($2.00, $100), and
  after `magpie model alias` one row, 2.0M, 2 calls, $102; the session
  row too. alias/aliases/--reset/loop/self output checked by hand.

Broken by hand, each red then restored:
- no alias in summarizeFrom: TestUsageAlias* red
- nil alias into the gateway projection: TestUsageAlias* red
- statsIn without aliasStats / List without aliasSession:
  TestSessionsCountAliasedModelsAsOne red
- merged usage row keeps Priced true: TestAliasStatsLeavesItsInputAlone red
- loop check off / self check by == / last-good read off / flag check off:
  TestUsageAliasRefusesSelfAndLoops, TestUsageAliasUnreadSettings,
  TestModelAliasCmd red
- GUI save drops UsageAliases: TestSettingsSaveKeepsWhatItDoesNotSend red

Not tried: the GUI pages in a browser (no app.js change; the Usage and
Sessions pages read the same rows), the full go test ./... before push,
Windows box.
2026-10-24 02:48:50 +08:00
yetone 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 e435b8867 + this change:
- gofmt -l and go vet on internal/usage, internal/usageapi and
  internal/gui: darwin, GOOS=linux -tags nogui, and GOOS=windows. The
  vet ran before the new _test files were added.
- go test ./internal/usage ./internal/usageapi and
  -tags nogui ./internal/gui: ok with TZ=UTC and with
  TZ=Asia/Shanghai.
- New tests:
  - TestUsageReadsTheViewersZone and TestZoneNames (internal/usage).
  - TestUsageRoutesReadTheViewersZone (internal/gui) asks the routes
    with ?tz= naming a zone other than the server's.
  - Each holds usage.Clock and checks the hour label, today's
    membership, the Day filter, the week chart's day label and the
    heatmap's days. With no ?tz=, the server's days are kept.

Broken by hand:
- Clock().In(zone) / Clock().In(f.loc()) back to Clock(): red in both
  zones (Summary, Requests, ledger, heatmap, /api/usage,
  /api/usage/requests, /api/usage/heatmap).
- The Day filter read in time.Local: red under TZ=UTC.
- The summary's and chart's bucketing in time.Local: the week-day label
  check goes red under TZ=UTC. Under TZ=Asia/Shanghai the chosen
  moment falls on one date in both zones, so it can't tell there.
Each was restored after.

Not tried:
- A Playwright GUI test with timezoneId in Chromium and WebKit was
  not written. The GUI suite and usage-stale-answer.test.cjs (which got
  a usageZoneQ stub) were not run: the disk was at ~350 MB free.
- TestCoreScriptBudget was not run again after the change. app.js is
  untouched, and page.js is a plugin page outside the core budget.
- A real remote `magpie web` from another zone, and the Windows box.
- Siblings left alone:
  - The Sessions tab buckets by the server's days and hours in its
    cached rollups, and its "By hour" card labels them with the
    browser's zone name.
  - The Routing history's day files are the server's days.
  These need issues of their own.
2026-10-23 10:54:27 +08:00
yetone 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: f5b015742 and this build served byte-identical bodies on
the real history for 14 endpoints, signed in: requests.csv of every row
(94,292,195 bytes); the requests page for all, offset 20000, month,
week, day, agent=codex, agent=claude, failed=1, q=opus and
provider=anthropic; the heatmap; usage for all and for month.

Footprint (phys_footprint, what Activity Monitor shows), cold start on a
copy of the real history, two runs each, alternating:
  f5b015742  peak 483 / 541 MB  end RSS 530 / 600 MB  CPU 1:44.7 / 1:47.7
  this       peak 465 / 463 MB  end RSS 511 / 509 MB  CPU 1:45.7 / 1:47.1
At rest both settle at 188-197 MB.

Tests: TestRowsOfOneSessionShareAShape fails when packedRow grows past
216 bytes (red at 328 with 112 bytes of padding put in by hand: "a
packed row is 328 bytes"), and checks that 200 rows of two models keep
2 shapes and read back equal after pack and unpack.
go test ./... -timeout 45m at this head: 65 packages ok; agent, gateway
and library failed only with "no space left on device" (the disk filled
mid-run) and, run again once there was room, are ok (agent 208s,
gateway 342s, library 115s).
GOOS=linux and GOOS=windows go vet -tags nogui ./... clean; gofmt clean.
2026-10-21 23:21:41 +08:00
yetone 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 5c557c793):
gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ./...
clean; go test -race -tags nogui ./internal/usage/ ./internal/sessions/
ok; go test -tags nogui -timeout 45m ./... with pipefail: 68 packages
ok, no FAIL.
Warm start in a sandbox HOME, magpie serve --web (ps RSS / footprint /
heapSys at 30s): origin/main 650 / 213 / 649 MB, all three 606 / 208 /
598 MB. Allocated in the first 30s: 2557 MB before, 1878 MB after.
2026-10-21 09:41:29 +08:00
yetone 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 5c557c793):
gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ./...
clean; go test -race -tags nogui ./internal/usage/ ./internal/sessions/
ok; go test -tags nogui -timeout 45m ./... with pipefail: 68 packages
ok, no FAIL.
Warm start in a sandbox HOME, magpie serve --web (ps RSS / footprint /
heapSys at 30s): origin/main 650 / 213 / 649 MB, all three 606 / 208 /
598 MB. Allocated in the first 30s: 2557 MB before, 1878 MB after.
2026-10-21 09:41:29 +08:00
yetone 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 33dbdcc52.
- agent and gateway in full, -p 2 -timeout 120m: gateway ok (2996s).
  agent failed four tests that still expected the old ids
  (TestOmp/PiModelsAskedOnTheirNativeAPI, TestReseatFoundGroupsOff,
  TestReseatKeepsAFoundGroupWithAProviderOff); updating them showed the
  Reseat bug above. After the fix, go test -count=1 -timeout 120m
  ./internal/agent/: ok (1000s, load ~160-220).
- GUI files the change reaches, chromium and webkit: group-found-off and
  the routing files pass, except routing-bodies, routing-model-rest,
  routing-keys-fold and routing-request-metrics, which fail the same with
  33dbdcc52's JS.

Broken by hand and watched red, then restored: CanonicalRef in
validateModel (both-ids routing test), allows() (key tests both ways),
the Save refusal and AutoRefsOn checks in Ref/CanonicalRef (provider
named auto), catalog.Lists' preference (models.dev lookup of the part
after auto/), renameFoundGroups' applied.json check and its SyncCatalog
call (user values kept), PublicRef in visible.go, the codexcat prefix,
samePick in Reseat (TestReseatFoundGroupsOff: opus left on the gone
group).
TestBareModelIDsShared was red before the bare.go fix.

Not verified: no real agent, vendor or models.dev client run; no run on
the Windows box. Settings pickers (vision, title model) holding a saved
group/auto-... value may show it as saved. codexcat can't tell a stored
"auto" provider apart, so its models lose the "text only" hint. The
pre-existing reds above are not filed.
2026-10-20 00:18:51 +08:00
yetone 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 f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:19 +08:00
yetone 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 f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:18 +08:00
yetone 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 f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:18 +08:00
yetone 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 f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:18 +08:00
yetone 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 f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:18 +08:00
yetone 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 2ceff7370 with all four #2776 commits' changes
(this one and the three beside it), load average 291-568 (nine agents
running suites), macOS:
- go test -p 4 ./... -timeout 45m, 09:35-10:49: 62 packages ok,
  among them agent (2310s), gateway (1707s), provider (764s), usage
  (83s). Red:
  - internal/sessions: TestWSLOmpProfiles, TestWSLStoppedDistroKept,
    TestWSLStoppedSinceNotOpened, TestWSLNoneWithoutHomes, each
    "TempDir: mkdir ...: no space left on device" (the disk filled
    mid-run). After space was freed, ./internal/sessions alone: ok
    (139s).
  - internal/gui: TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
    TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow,
    TestDockReopenKeepsTheWindowsSpace (each killed at 30s) and
    TestMainWindowCorners (86s): the real-window AppKit tests under
    load, already filed as #2645 and #1936. Rerun alone at load ~335:
    all pass, with TestSetAnswersWhileDevinAndProvidersHang (17s).
- gofmt -l: none. go vet: darwin, GOOS=linux -tags nogui and
  GOOS=windows all exit 0.
- No internal/gui/assets file changed, so the GUI Playwright suite was
  not run.
2026-10-19 11:33:00 +08:00
yetone 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 ccb2eea15, the same Usage/Sessions/Routing views opened by
Playwright, after GC via /v1/magpie/heap; footprint from `footprint`):
- after the views: live heap 618 MB -> 466 MB, footprint 801 -> 670 MB
- after warm-up only: live heap 467 -> 390 MB
- CPU over the same 9m40s: ~22.4 s both
Go is the process that holds memory: on a live v0.1.1208 app the Go
process's footprint was 1045 MB, the Bun plugin host 51 MB, the two
WebKit WebContent processes 70 and 83 MB.

No single commit in v0.1.1225..HEAD is the cause: the shared-slab decode
(99fcddeeb) and both caches (c9b826337, 60f896031) predate v0.1.1225.
Idle with no page open, HEAD used 1.04 s CPU per 5 min against
v0.1.1225's 0.56 s.

Not fixed here: the gateway projection is kept once per window (up to
4), the startup heap peaks ~1.5 GB from GOGC doubling the warm-up's live
heap, and a synthetic 11k-session history did not reproduce the 1 GB
reported.

Run at this change on ccb2eea15 (load average ~275-500 from other
sessions):
- go test ./... -timeout 45m, sandbox HOME: 61 packages ok;
  internal/agent timed out at 45m; 4 reds in gateway
  (TestClaudeAccountsSpentFallBackToCodex,
  TestCodexServedNamesTheAccountThatSigned) and gui
  (TestPluginPageReadsWhatItDeclared,
  TestSetAnswersWhileDevinAndProvidersHang).
- Those 4 alone: gateway ok 40.8s, gui ok 13.7s.
- internal/agent alone (-timeout 45m): timed out again at 2732s under
  load ~500; the stacks left include a netproxy.Bridge accept loop.
  internal/agent never calls GatewaySessions or Vias, the only code
  changed. Not filed from here: the run kept only its last 25 lines,
  so the test that hung is not named.
- internal/usage: ok 123s.
- gofmt -l: clean. go vet ./internal/usage/ for darwin, linux
  (nogui) and windows: clean.
2026-10-19 03:01:38 +08:00
yetone 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 d9b943555 (head 663db0ecf), with the #2517,
#2521 and #2522 changes, load ~240:
- gofmt -l clean; go vet -tags nogui for darwin, linux and windows: ok.
- go test -timeout 120m -count=1 ./... (pipefail): exit 0, every package
  ok (gateway 1416.8s, agent 1535.5s). Before the rebase, on 63be47717:
  - The 45m run had agent and gateway past 45m (#2544, #2108).
  - TestMainWindowCorners was killed at its deadline (#1936).
  - TestSkillRelinkKeepsUnreadableCopy failed (#2555; it passes alone).
  - gateway alone with 120m was ok.
- GUI, the 41 Requests/Usage files in serial, both engines, before the
  rebase: 493 pass, 3 fail. The 3 were usage-refresh "not yet 2 !== 1",
  the same on 63be47717 alone (1 of 3); seen again on #2184.
- Rebased, these all pass, 102/102: i18n-keys, usage-ledger-ttft,
  usage-ledger-key-split, usage-ledger, usage-speed, usage-ledger-detail,
  gui-ja, gui-de and gui-zh-tw.
- Rebased again onto 9b04c4e20, which touches ledger.go, request_page.go
  and gateway.go:
  - vet ×3: ok.
  - internal/usage, internal/usageapi and internal/cli: ok.
  - internal/gateway -run 'NativeCompaction|UsageOverGateway|Capped|Cap':
    ok.
  - usage-ledger-ttft, usage-ledger-key-split, usage-ledger and
    usage-speed: 86 pass. i18n-keys was red from main's own words (#2586,
    fixed in the next commit).
2026-10-16 21:59:33 +08:00
yetone 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 63be47717, with #2511's commit):
- gofmt -l clean; go vet ./... (darwin), GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean; go build: ok.
- go test -timeout 45m ./... with pipefail, sandbox HOME: 63 packages ok,
  usage (200s), cli, tui, gui among them; agent, gateway and library timed
  out at load ~270 (see the #2511 commit); library ok alone, agent and
  gateway ok with -timeout 150m: agent ok (5529s); gateway red only in TestIntentClassifierGroup (#1813), TestMaxRPMWaitsForRoomInTheMinute (#1791) and TestMaxRPMGroupPrefersMemberWithRoom (#2520), known timing reds under load, each passing alone here -count=3 (19s).
- New: TestPlanCreditsReachTheLedger (chat stream, whole reply,
  translated /v1/messages, free 0, none), TestPlanCreditsSummed,
  TestPlanCreditsPacked, TestFormatCredits, TestUsageSaysCredits, and
  plan-credits.test.cjs (en, zh, zh-TW, ja, de; Chromium and WebKit;
  420px fit) 12/12.
- Broken by hand: dropping Credits at the record site turns the gateway
  test red; skipping it in unpack turns the usage tests red; dropping the
  ranking's ledCredits turns plan-credits red in every language.
- GUI reds elsewhere: see the #2511 commit (#2536, #2552, a
  provider-detect-draft load timeout that passes 3/3 alone).
- Rebased onto origin/main ba132d68b (13 commits; chat.go, gateway.go, app.js, i18n.js among theirs): gofmt and go vet ./internal/... clean; Credits/DeepSeek/Balance/Ledger/RowFlags tests in usage, gateway, provider, cli, tui ok; plan-credits 12/12, balance-parts 4/4, i18n-keys 3/3 in both engines.
2026-10-16 20:11:34 +08:00
yetone 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
2026-10-15 23:08:03 +08:00
yetone 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
2026-10-15 23:08:02 +08:00
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
yetoneandNorethSea 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 707fbb249. Filed as #2228.
  - The GUI break-check (main's !sub.history gate put back) turns the new
    quota-curve test red.
- Full suite: SUITE_LINE

Co-authored-by: NorethSea <963979204@qq.com>
2026-10-15 23:08:00 +08:00
yetoneandggbdpq 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>
2026-10-15 09:36:26 +08:00