Commit Graph
106 Commits
Author SHA1 Message Date
yetone 5bb252c8f3 usage: a poll's small pairing lets a whole history's scratch go (#2278)
The matcher, the response picks and visibleLocal's set of ids seen are
kept for the next pairing, and each pairing that puts one back holds it
scratchLinger more. A poll's pairing of its last few days put back the
scratch the cold start's pairing of the whole history made, sized for
every call, so ~140 MB of maps and slabs stayed while the window polled:
the heap profiles at 44, 50, 56, 62 and 68 s were alike to the MB, all
of it under codexEffortOfIndex, with no pairing of the history running.

Each scratch now records the rows of the largest call it served, and a
call over a quarter of that or less (and over 4096 rows' floor) makes its
own; the large one goes with the collection. A call alike in size takes
what is kept, as before, so the polls while an agent works still reuse
it. holdBigBuild counts its rows through the same rowsOfAll.

Run on mote at this head (parent 7d4a63148, rebased; usage ok 21.4s, usageapi ok 1.6s there):
- go vet ./internal/usage: ok
- go test ./internal/usage ./internal/usageapi: ok 18.0s, ok 0.8s
- TestSmallPairingLetsLargeScratchGo with scratchFits always true: red
  ("a small pairing kept the match scratch of a large one"); green with
  it back, beside TestPairScratchGoesWhenUnused, -KeepsNothingBetweenCalls
  and TestVisibleLocalSeenKeptEmpty.
- gofmt -l clean.

Real history (the owner's full ledger and session files, sandbox HOME,
caches deleted, the GUI's polls for 120 s), footprint every 5 s:
- this head: peak 532 and 539 MB; after the peak 367–374 MB while it
  polled; CPU 3:29 both.
- e31ccf230 in the same session: peak 556 MB (548–566 before); after the
  peak 416–419 MB; CPU 3:38.

The peak itself is the pairing of the whole history while it runs, beside
the Month page and the session stats; this change doesn't cut that.
Not tried: Windows and Linux runs.
2026-10-30 23:20:35 +08:00
yetone 18b63fe5f8 usage: a cold start's builds find the pairing the build before them made (#2278)
On a cold start the page of the month, the page of All, Codex's effort
and the heatmap read the history side by side and pair it in turn
(holdBigBuild). Each one missed the pairing the one before had kept
(pairMemo), and paired the whole history again beside it. On the real
history (469 gateway blocks, 16619 session chunks) every big build
missed; the warm All page's miss had a memo whose session serials all
differed (16619 of 16619).

Three things kept them apart:

- A session file's chunk got a serial from a counter each time a read
  built it. The builds read the same files together and share one build
  of each (sharedBuild), but each named its copy apart. A chunk's
  serial is now made from what it is made of: the file's path, size
  and mtime under the index's root and meta (sourceSerial), the same
  in a build and in a chunk read back from requests-v1.bin. The top
  bit keeps it apart from a counted serial (gateway blocks, other
  computers' days). The caches keyed by serial (cells, fold ids, match
  hints, message keys) hold what a chunk's rows give, so a chunk of
  the same file and meta reads the same from them.
- A build took the last pairing when it began, before waiting its
  turn. It now takes it once it has the turn (lastPairs).
- A build kept its pairing after it let the turn go, so the build
  that waited took its turn first and found none. It now keeps it
  while still holding the turn (keepPairsFor). The memo is kept
  though the build's index isn't: it stands only for chunks of its
  serials.

TestBigBuildsBegunTogetherPairOnce starts the page of All and the
heatmap together over a gateway log and eight session files, both
having read their rows before either pairs: two pairings, every row
once and the heatmap's recent days.

Broken by hand, the test is red (3 pairings) with any one of the three
undone: the counted serial back, the memo taken before the turn, the
memo not kept.

Run at this head, rebased on e31ccf230, on mote: go test -timeout 45m
./internal/usage/ (ok 16.3s; 52.9s at 2f65a33aa) and ./internal/usageapi/ (ok); gofmt -l
clean; GOOS=linux, windows and darwin go vet ./internal/usage/
./internal/usageapi/ ok. ./internal/gui/ was run at 2f65a33aa: the AppKit
real-window tests (TestMainWindowCorners, TestPanelCloseHidesIt, the
Dock and tray ones) hit their 20-80s deadlines on mote, which has no
window session for them (#4125, #2645); nothing in the GUI changed.
GOOS=linux go vet ./internal/gui/ stops in Wails' cgo files, as a cross
build without cgo does.

On mote, the real history, a true cold start (caches deleted), 240 s
polled as the Usage page polls: phys_footprint_peak 551, 553, 548 MB
against v0.1.2213's 607 (592-628 in earlier runs), CPU 3:50-4:08 against
3:40, under load ~27 from other sessions. An instrumented build logs
one pairing of All, then hits for the rest (30d, then All miss, All
hit, All hit). A restart with the caches kept: 317 MB against 341, CPU
10.5 s against 10.5 s. The peak left is Codex's effort pairing All
(~150 MB) while the page of the month, under bigBuildRows, pairs its
own beside it (~80 MB); not changed here.
2026-10-30 22:49:35 +08:00
yetone a6e7d40421 usage: the heatmap pairs its year through All's pairing, not a third time (#2278)
A cold start paired the whole history three times in turn: the page of
All, Codex's effort through All's memo, and the heatmap's 53 weeks on
their own. The year covers the same chunks as All for most histories,
and its pairing was the last and highest of the footprint's peaks
(fp 503 -> 565 -> 574 -> 582 -> 592 MB as each pairing ran, e18 on
the real history).

heatSplit's cold path now pairs through pairEvery: All's window and
All's memo (cache.pairs), visited from the heatmap's since on. Whichever
of the page of All, the effort and the heatmap comes first pairs every
row; the others take the memo. A call is paired to its session row as
the whole history pairs it, so a call early in the year can match a
session row from before it, as the page of All already counts it.
Only the heatmap's recent days are paired again for it.

On a cold start this alone moved no peak (597/619/595/611 MB against
e18's 592-628): every build missed the memo, for the reasons the next
commit fixes. With it, the effort, the page of All and the heatmap take
one pairing.

TestHeatmapPairsAsAllDoes counts the pairings with the page first and
with the heatmap first; both orders are red on the old code.

Run at this head, rebased on e31ccf230, on mote: go test -timeout 45m
./internal/usage/ (ok 16.3s; 52.9s at 2f65a33aa) and ./internal/usageapi/ (ok); gofmt -l
clean; GOOS=linux, windows and darwin go vet ./internal/usage/
./internal/usageapi/ ok. ./internal/gui/ was run at 2f65a33aa: the AppKit
real-window tests (TestMainWindowCorners, TestPanelCloseHidesIt, the
Dock and tray ones) hit their 20-80s deadlines on mote, which has no
window session for them (#4125, #2645); nothing in the GUI changed.
GOOS=linux go vet ./internal/gui/ stops in Wails' cgo files, as a cross
build without cgo does.
2026-10-30 22:49:35 +08:00
yetone 0606e03702 usage: a settled chunk's message keys are read for a pairing, not kept (#2278)
msgKeysOf kept every chunk's message keys by serial, for the next
pairing of the same chunks. A cold start pairs the whole history (the
warm-up's page of All, then the heatmap's year and Codex's effort when
page-v1, heat-v1 and effort-v1 miss), so it kept every session file's:
67 MB of the 460 MB live heap 30s after the footprint passed 400 MB
(heap profile of a cold start of the real history on mote), while
polls pair only the days since the split's cut.

A chunk whose rows end before settledBefore(now) is now left nil by
msgKeysOf, and visibleLocal reads its keys into one buffer as it
reaches it. Such a chunk is paired only when a split page's, the
heatmap's or the effort's kept cells are missed. What is left out is
the same: TestVisibleLocalSettledNotKept pairs a settled and a recent
chunk three times and checks the copy left out each time and that only
the recent chunk's keys are kept.

Cold start of the real history (fullcold.sh on mote, caches deleted):
phys_footprint_peak 613 and 603 MB with this change, against 638, 648,
654, 660, 663 and 682 MB before it.

Run at the rebased tree (on origin/main 387e8572a, on mote): gofmt -l clean;
go vet -tags nogui ./internal/usage/ for linux, windows and darwin ok;
go test ./internal/usage/ ok (34.5s), ./internal/usageapi/ ok;
-run 'VisibleLocal|Pair|PageSplit|Heat|Effort|QueryPage' ok.
Broken by hand (msgKeysOf keeping settled chunks again):
TestVisibleLocalSettledNotKept red, "settled chunk's keys kept true".
2026-10-30 20:21:52 +08:00
yetone 3bce283df4 usage: visibleLocal keeps its set of ids seen for the next pairing, not made again each time (#2278)
visibleLocal made a map of every Claude message id (~400k on the bench
HOME) to size for every pairing: 212 MB of the ~2 GB 90 s of polls
allocated, the largest single site left after the decode buffers were
kept (70d9996c5).

The set is now kept empty between calls as the matcher's scratch is
(keptSeen, an atomic pointer): a call takes it, a cleared map keeps its
buckets, and it goes with the scratch on ReleaseScratch or scratchLinger
after the last pairing. A call while another has it makes its own.

Run on mote at this tree, rebased on origin/main:
- go test -count=1 ./internal/usage/ ./internal/usageapi/: ok, at df09470d0 on 99ad38b7c
- GOOS=linux|windows|darwin go vet -tags nogui ./internal/usage/
  ./internal/usageapi/ ./internal/gui/: ok
- TestVisibleLocalSeenKeptEmpty (new): the set is kept empty, a call on
  other chunks after leaves out what a first call does, ReleaseScratch
  drops it. Broken by hand, red each time: the set not cleared before
  it is kept; ReleaseScratch not dropping it.

Bench (hmw.sh, 90 s), second runs: visibleLocal 266 MB -> 71 MB
(msgKeysOf and the duplicates left), fp_peak 347 -> 348 MB. The run's
total (2030 -> 2702 MB) moved with the sessions list, which this run
built again (sessionRoutes +782 MB, QueryPage -277 MB); that list is
the next thing to look at.
2026-10-30 18:36:13 +08:00
yetone 70d9996c57 usage: a pass's decode buffer is kept past a collection, not grown again after every GC (#2278)
chunkRows decoded each chunk into a rowBuffer from a sync.Pool. A poll
while an agent works collects several times a second, and each
collection emptied the pool, so the next pass grew a buffer to the
largest session chunk again. In 90 s of polls on the 65 GB bench HOME,
unpackReusing allocated 779 MB (486 MB flat), 553 MB of it under
matchedBlocks.

The buffers are now kept as the matcher's scratch is: up to four in
keptRows (atomic pointers), taken by chunkRows.of and put back by
release, and let go with the scratch, on ReleaseScratch or scratchLinger
after the last pass.

Run on mote at this tree, rebased on origin/main:
- go test -count=1 ./internal/usage/ ./internal/usageapi/: ok, at ae906d4df on df31059d6
- GOOS=linux|windows|darwin go vet -tags nogui ./internal/usage/
  ./internal/usageapi/ ./internal/gui/: ok
- TestRowBufferKeptPastCollections (new): a buffer survives two
  runtime.GC() between passes, two passes at once get two and both are
  kept, ReleaseScratch drops them. Broken by hand, red each time: release
  not putting the buffer back; ReleaseScratch not calling releaseRows.

Bench (hmw.sh, 90 s, gateway calls appended every 3 s, 10 endpoints
polled), second runs, mote load ~32:
- v0.1.2193 (e11): 2742 MB allocated, unpackReusing 779 MB,
  matchedBlocks 553 MB, pairRowsIn 858 MB, late GCs 26, fp_peak 333 MB.
- this (e12): 2030 MB, unpackReusing 199 MB, matchedBlocks 48 MB,
  pairRowsIn 346 MB, late GCs 16, fp_peak 347 MB (within noise).

Not tried: a real session file growing during the bench (the bench only
appends gateway calls).
2026-10-30 18:27:57 +08:00
yetone 4023a2e999 usage: a page's newest rows are kept on each chunk's part, not decoded again for every page (#2278)
A Usage page read again after a call picked its newest rows by decoding
the few newest chunks again, then decoded them once more for the rows
themselves (rowsOf). Under an agent at work that is the long session's
own file among them (57k calls): in the writer bench (a call every 3s,
the GUI's 10 endpoints polled) pairedRows.newest was 392 MB of 90s.

newest now keeps what a chunk gave on the chunk's part: its newest rows
the filter keeps, up to take, each with its row (strings copied, as the
chunk is decoded lent), and whether that was all of them. The part is
the cell cache's: its chunk serial and pairing sig, under the page's
period and filter, dropped with the rest when the clears, names or
prices change (meta). A page that wants more rows than the chunk gave
reads it again. The page's rows come from newest, and rowsOf is not
called for them.

Run at the pushed head, on mote:
- TestNewestKeptOnPart: pages of take 2, 2, 1, 4, 4, 6 decode 1, 0, 0,
  2, 0, 0 chunks with the same refs and rows; new parts decode again;
  rows read stay as they were after the chunks are decoded again over
  the lent block. Broken by hand, red each way: the kept rows never
  used; the take check dropped; the lent strings not copied.
- go test ./internal/usage/ ./internal/usageapi/: ok
- go vet -tags nogui, GOOS linux, windows, darwin: ok
- Writer bench, second start of each binary, 90s, load ~25:
  newest 392 MB and rowsOf 88 MB (v0.1.2190) -> 6 MB and none.
  Everything allocated: 3698 MB with only the refs kept -> 2742 MB.
  fp_peak 312 -> 333 MB, late GCs 46 -> 26.
  Not changed: the decode buffers are a sync.Pool, emptied at each GC,
  so the big chunk's buffer is now grown by matchedBlocks (18 -> 553 MB)
  where newest and rowsOf grew it before. That is the next change.
2026-10-30 18:17:09 +08:00
yetone 819aad1bc1 usage: a chunk's Claude message ids are read once per serial, not on every pairing (#2278)
visibleLocal leaves out a Claude message written again in another file.
To do it, every pairing decoded every local chunk of the period and
hashed each row's message id. While an agent worked (a call appended
every 3s, the GUI's endpoints polled every 5s), that was 1.1 GB of the
4.5 GB allocated in 90s; 840 MB of it was decoding.

Each chunk's message keys (the two hashes and the row) are now kept by
the chunk's serial, as matchedBlocks' hints are, with the same pruning
(hintsKept turns). Only a chunk with no serial, or none kept, is
decoded. The keys are read in the order the chunks are passed, so what
is left out is the same as before.

Run at this head, on mote:
- go vet ./internal/usage/; GOOS=linux, windows, darwin go vet -tags
  nogui ./internal/usage/ ./internal/usageapi/: ok
- go test -count=1 ./internal/usage/ ./internal/usageapi/: ok
- TestVisibleLocalKeptBySerial: three chunks, two with serials. The
  calls decode 3, then 1, then 1 chunk, with the same rows left out each
  time, and in reverse order too.
- Broken by hand: ignoring the kept keys made it red (call 1 decoded 3
  chunks); shifting each kept row index made it and
  TestVisibleLocalLeavesOutRepeatedMessages red.
- Writer bench (hmw.sh: the real 109 MB usage.jsonl history, calls
  appended every 3s, 10 endpoints polled), at the second start, heap
  profile at 90s, against v0.1.2188's code:
  - visibleLocal: 1111 MB -> 259 MB (msgKeysOf 53 MB);
  - pairRowsIn: 1394 MB -> 331 MB;
  - total allocated: 4537 MB -> 3908 MB;
  - fp_peak: 544 MB -> 315 MB.
  mote was at load ~26 from other work, so the times are noisy.

Not changed: the seen map is still built on every pairing (206 MB of
the 259 MB left).
2026-10-30 17:57:52 +08:00
yetone f8088cb2d1 usage: a page whose settled days are kept leaves the gateway's older blocks unpriced (#2278)
Every query of All priced and unpacked every gateway block of the history
before it looked at what it needed. With the page's cells, the heatmap's
days and Codex's effort kept from earlier days (page-v1, heat-v1,
effort-v1), a cache hit reads only the last days' rows. Pricing the rest
was still 53 MB of the 219 MB heap at 18s on the real history
(blockPricer.priceBlock: 38 MB of pooled rows, 14 MB of unpacking).

readRequestBlocks now leaves a packed, named block whose newest call is
before settledBefore(now) (the splits' edge) as a stub: its serial, count
and latest time, the raw block and the pricer. priceStubs prices stubs in
place, and every pairing calls it first (pairRowsIn, pairRowsMemo,
heatBefore). So a miss, a page of older rows, or a period the splits don't
cover prices them as before. rowsIn counts a stub by its raw block.
heatSettledKey names a gateway block by its raw rows, which requestState's
meta prices, so a priced block and a stub get one key. That changes the
keys once; this binary's own keys already change.

Run at 0414bbedd plus this change (origin/main fetched, no newer commits), on mote:
- go test -count=1 ./internal/usage ./internal/usageapi: ok
- go test ./internal/gui: the AppKit tests time out at 30s, the same set
  as #4125 (TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
  TestMainWindowCorners and 7 more); nothing else red
- GOOS=linux/windows/darwin go vet -tags nogui on the three packages: ok
- Broken by hand: with the stub turned off,
  TestKeptPageLeavesSettledBlocksUnpriced fails with "started again, 2
  blocks priced"

Real history on mote (~/r2278, a copy of the real ~/.codex, ~/.claude and
gateway log), 120s with the GUI's polls:
- v0.1.2183 at a cache hit: fp_peak 368 MB (356-374 before), peaklive
  262 MB
- this change at a hit: fp_peak 301 and 308 MB, peaklive 226 and 219 MB
- the first start of a new binary misses as before: 510-512 MB
- the five pages (all, 7d, all at offset 0 limit 100, all for codex, 30d)
  are the same as v0.1.2183's apart from float rounding in the sums
  (largest relative difference 5e-14)

Not tried: Windows and Linux runs. The change is in the usage package,
which has no OS-specific code.
2026-10-30 16:45:53 +08:00
yetone 4650e1e3c4 usage: this computer's zone is one page key, so the warm-up builds the page the Usage page reads (#2278)
The warm-up and the tray ask QueryPage with Filter{} (no zone); the
Usage page asks with Zone: time.Local (usageapi.FilterIn, usage.Zone("")
is time.Local). Both read their days in time.Local, but the pages cache,
the parts cache, pageOld and the page-v1.json/heat-v1.json keys took
them as two filters. So the warm-up's pairing of the whole history
warmed nothing the page read: the page built its own beside it, and
page-v1.json held two All pages. Found by logging the page key of every
start on the real history: the warm-up's key had zone "" and the page's
"Local", with everything else the same. queryPageOf now treats Zone ==
time.Local as no zone, before any key is made.

Real history on mote (~/r2278), 120s each, the build with this and the
next commit:
  new-binary miss  fp_peak 518 MB, peaklive 378 MB (v0.1.2180: 587/408)
  hit              fp_peak 374 MB / 356 MB, peaklive 271/266 MB
The hit after the five pg.sh pages (all, 7d, 30d, all with offset,
codex) started with the page cached on disk.

Test: TestLocalZoneIsTheWarmUpsPage (the page in time.Local after the
warm-up's pairs nothing more and is equal). Broken by hand (the
normalisation off): red, "the page in time.Local paired [6 6]".
TestPageSettledFromDisk's setup moved into pageHistory, which the new
test shares.

Run at this head, on mote:
  go test -count=1 ./internal/usage ./internal/usageapi: ok, ok
  GOOS=linux/windows/darwin go vet -tags nogui ./internal/usage: ok
  go test ./internal/gui: 8 AppKit window tests time out at 30s
  (TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt, TestMainWindowCorners
  and others): mote's AppKit hang, #4125. This change is internal/usage only.
Not run: the full suite.
2026-10-30 16:14:45 +08:00
yetone c7171a2561 usage: a page's cells before its last days are kept in page-v1.json, so a start pairs only the recent chunks for All (#2278)
A start's first page of All (the warm-up's, and the Usage page's own)
paired the whole history for the page's cells, every gateway call with
its session row: ~85 MB of a ~316 MB heap at 18s after the heatmap's days
and Codex's effort were kept (v0.1.2172). The cells of the rows before
cut (local midnight two days back) are now kept as heatSplit keeps its
days, in memory and in page-v1.json beside the sessions cache, under a
key from heatSettledKey plus the page's until, names and hours. A start
pairs only the chunks since the edge. A page whose rows are older than
cut (an offset past the recent rows) falls back to the full pairing.

Real history on mote (~/r2278, a copy of the owner's), 120s each,
three starts in a row:
  v0.1.2165       fp_peak 451-471 MB, peaklive 326-364 MB
  this, miss      fp_peak 587 MB, peaklive 408 MB (a new binary's first start)
  this, hit       fp_peak 361/366 MB, peaklive 265 MB, gcs 150 (was ~150)
page-v1.json is ~240 KB.
The output is the same: /api/usage/requests for period all, 7d, 30d,
all with offset/limit and all filtered to codex, from a start that hit
page-v1.json and from a cold one (file moved away): 0 differences, each
float within 1e-6, on two hit runs.

Test: TestPageSettledFromDisk (first page pairs once and writes the file;
after a restart fewer chunks are paired and the page is equal; an older
offset falls back and equals the cold page; a changed settled file pairs
everything, then hits again). Broken by hand (pageSplit always false):
it goes red at "first page: pairings []".

Run at this head (rebased on ace8ee1e1), on mote:
  go test -count=1 ./internal/usage ./internal/usageapi: ok, ok
  GOOS=linux/windows/darwin go vet -tags nogui ./internal/usage ./internal/usageapi: ok
Not run: the full suite. TestCoveredWindowStaysUp (internal/gui) is red
on mote even alone, "signal: killed", the AppKit hang under #4125; this
change touches internal/usage only.
2026-10-30 15:44:59 +08:00
yetone cd5df81ecd usage: Codex's effort before the last days is kept on disk, so a start pairs only the recent chunks (#2278)
After the heatmap's settled days were kept (heat-v1.json, fixed in the
commit before), the cold start's largest part was codexEffortOfIndex:
a pairing of the whole history, every gateway call with its session
row, for the effort column, ~90 MB of a ~310 MB heap at 18 s on the
real history bench.

effortSplit does for it what heatSplit does for the heatmap: the effort
of rows before cut (local midnight two days back) comes from memory
while the settled chunks' serials match (10 min), else from
effort-v1.json under a key built by heatSettledKey (the settled chunks,
the recent chunks' rows before cut, the identities, the code, root and
meta); only the chunks since edge are paired again. When neither
stands, the full pairing is used as before and the part before cut is
kept. Old data: no file yet means one full pairing, as today, then the
file. A write that fails only means the next start pairs again.

Real history (mote ~/r2278/full, heap at 18 s, three starts of this
build): CodexModelEffort 14 MB, effortSplit 3.6 MB on the third start
(v0.1.2156: 91 MB); /api/usage/heatmap at 40 s byte-identical to
v0.1.2156's (md5 7e458920...) on all three. The first two starts of a
new binary write the files (the settled chunks differ once between a
fresh build and requests-v1.bin's read), the third reads them.

TestCodexEffortSettledFromDisk: a restart pairs fewer chunks with the
same sums; a changed settled file pairs all with the changed input; a
cold run without the file equals it. Red with effortDiskRead disabled
by hand ("started again, paired 6 of 6").

Run at this tree, on d05482bab + the commit before (mote): go test
-count=1 ./internal/usage ok (86.1s); rebased onto 70a0c387c (an agent
change) and ran again: ok (16.8s); gofmt -l clean; go vet -tags
nogui ./internal/usage ./internal/gui for linux, windows, darwin ok.

Not done here: queryPageOf, the warm-up's QueryPage(All) page 0, is now
the largest part (111 to 227 MB at 18 s), a full pairing for 50 rows.
2026-10-30 14:47:05 +08:00
yetone 8d4c07ffed usage: the heatmap's settled days are kept on disk, so a start pairs only the last days (#2278)
The heatmap's days before the cut (two days ago) came from heatOld, a
full pairing of the whole history kept in memory. A started magpie made
it again on its first heatmap, and again every heatOldFresh (10 min):
on the 52G Codex + 13G Claude bench history that was heatSplit's 88 MB
of the cold start's ~325 MB in-use heap at 18 s.

The days are now kept in heat-v1.json beside the sessions cache, under
a key (heatSettledKey) naming what they were counted of: the request
code and the index's root and meta (prices, names), the cut, since,
zone, filter, the recent chunks' rows before the cut, the Codex thread
identities, and each settled chunk (a session file's by path, size and
mtime, like requests-v1.bin; any other chunk by its rows). The file is
written through a temp file renamed over the last. A key that can't be
named (a chunk with no serial) pairs as before; after heatOldFresh a
same-named key keeps the days without pairing again.

Measured on mote, ~/r2278/full, cold start + the page's 10 endpoints
polled every 5 s:
- heap at 18 s: v0.1.2149 324.6 MB in use, heatSplit 88.3 MB,
  HeatmapOf 135.8 MB; this 310.1 MB, no heatSplit, HeatmapOf 44.1 MB.
- /api/usage/heatmap at 40 s: byte-for-byte the same as v0.1.2149's.
- gcpeak 120 s, 3 rounds each, alternated (mote under other load):
  live 360/393/414 vs 378/404/387 MB, gcs 148/174/168 vs 201/209/160.
  The peak moves to CodexModelEffort's own full pairing (91 MB), next.
- First start, no file yet: pairs as before and writes 7.9 KB.

Tests: TestHeatmapAfterACallPairsOnlyTheLastDays now removes the file
for its cold oracle, and past heatOldFresh with nothing changed pairs
less than all, then a new settled file pairs all and equals cold.
TestHeatmapSettledDaysFromDisk: restarted with memory cleared pairs
less than all and gives the same heatmap; another filter, a rewritten
settled file, and no file each pair all.

Run at this tree (mote): go test ./internal/usage ok (71s);
go test -tags nogui ./internal/gui -run 'Heat|Usage' ok, usageapi ok;
go vet -tags nogui ./internal/usage/... ./internal/gui/... on linux,
windows, darwin ok; gofmt -l clean. Rebased onto e8d42c02d, then cae785a37 (no
internal/usage change in either); at e8d42c02d go test ./internal/usage ok
(100s) and linux vet ok again. Not run: the full suite.
2026-10-30 14:19:41 +08:00
yetone fddd7ff08f usage: pairing keeps its rows as bits and its groups by sums, and lets its pairs go (#2278)
A cold start pairs the whole history, and pairing held its row sets as
map[rowRef]bool, ~40 bytes a row, several sets of most rows at once.
They are now refSet: a bitset a chunk, a bit a row. matchScratch's
groupOf was keyed by the whole matchKey (a session string and its
tokens); it is keyed by a 128-bit maphash sum of them now, and the
sessions map is filled when a group is made. pairedRows' pairs and
compactions maps were filled and never read; they are gone.

Measured on mote, a copy of the real full history (52G Codex, 13G
Claude), GODEBUG=gctrace=1, 120s of /api polls, 3 rounds each,
alternating, v0.1.2143 (807048470) against this change:
  peak live heap  459 -> 439 MB (512/426/440 vs 470/433/413)
  heap at GC      543 -> 517 MB
  footprint peak  677 -> 641 MB
The inuse profile at the peak shows groupOf 28.7 -> 11.8 MB and the
matched set gone from matchedBlocks. This is a small part of the peak;
the rest is the full re-pair itself, which is next.

Run at this tree (rebased onto dca3e2d71 from 807048470), on mote:
go vet ./internal/usage; GOOS=linux|windows|darwin go vet -tags nogui
./... all ok; go test -count=1 ./internal/usage ok (30.1s), with the
new TestRefSet and TestMatchKeySum (no allocation).
Not run: the full suite, the GUI suite.
2026-10-30 13:42:11 +08:00
yetone 807048470e usage: a row keeps its times in ms in 32 bits, 184 bytes where it was 216 (#2278)
A page holds every row of its period at once, and at a cold start over
the full history the rows held were most of what the footprint's peak
held: on mote's copy of the real history (52G Codex, 13G Claude Code),
the inuse heap 20s into a polled start had 48.5 MB of decoded session
rows (unpackReusing) and 42.9 MB of priced gateway rows (pricedRows),
both packedRow.

Millis, TTFT, FirstText, FirstReasoning, Sent, Flow, Own, Retried and
Queued are ms (Record's *_ms) and go in an int32, as Masking already
did. One past 24 days, which no call takes, is kept as the longest an
int32 holds (msOf), not wrapped. The snapshot's encoding is unchanged:
each is written as the int64 it was and read back through msOf.
unsafe.Sizeof(packedRow{}) goes from 216 to 184, 15% of every row held:
~14 MB of the 91 MB above.

Run at this head (rebased on 46aa7e6b8, which touches providers and
the GUI only), on mote:
- go build ./... ok
- go test -count=1 ./internal/usage ./internal/usageapi ok (and before
  the rebase, on eadeb89c4)
- GOOS=linux, windows, darwin go vet -tags nogui ./internal/usage ok;
  gofmt -l clean
- TestRowsOfOneSessionShareAShape now wants 184 bytes at most.

Broken by hand: msOf as a plain int32(ms) turns the new
TestRowTimesPastWhatARowKeeps red ("read back Millis -1702967296").

Not measured: a whole-app footprint A/B. Two rounds of peakheap.sh ran
at mote load ~220, with most polls timing out (3 to 12 of 80 answered)
and each run higher than the last whatever the binary (202, 248, 270,
318 MB), so they say nothing either way.
2026-10-30 12:41:24 +08:00
yetone 99c2567cfa usage: the matcher's scratch goes 30s after the last pairing used it (#2278)
With nothing new to pair, every poll of the window is answered from the
pairings kept (pairMemo) and pairs nothing, so the scratch of one pairing
of the whole history (keptMatch's groupOf/calls/ends/byID maps, keptPicks'
picks and slab) sat unused while the window polled, until pageRest's
ReleaseScratch 30s after polling stopped. On the real 65 GB history
(52 GB Codex, 13 GB Claude) that was ~120 MB of the ~270 MB live heap
over 60s of polls. Now each release of either scratch (re)arms one timer,
and scratchLinger (30s) after the last pairing put it back both are let
go. While an agent works, every poll pairs again inside 30s and finds it
kept, as before.

Run at this head (origin/main 430005726 + this commit), on mote:
- go test -count=1 -timeout 45m ./internal/usage/: ok 19.6s.
- TestPairScratchGoesWhenUnused broken by hand (both lingerScratch calls
  removed): FAIL "the scratch was kept with no pairing using it" at
  30.55s; green with them.
- go test -count=1 -timeout 45m ./internal/gui/: one red,
  TestMainWindowCorners/macOS_26_SDK, which is #3949 (macOS 27, open,
  untouched by this change); everything else ok.
- GOOS=linux/windows/darwin go vet -tags nogui ./internal/usage/
  ./internal/gui/: clean. gofmt -l: clean.
- A/B on the real full history, KEEP=1 warm start, 10 endpoints polled
  every 5s for 120s (fullwarmh.sh), baseline 430005726 vs this commit,
  back to back on mote at load ~45:
  footprint 60s/100s/120s: 507/506/500 MB -> 384/389/382 MB
  footprint peak: 602 MB -> 567 MB
  CPU: 29.9s -> 30.6s (same within load noise); poll avg 0.172s -> 0.159s
  A first round at load ~80 gave 442/437/434 -> 347/342/355 MB.

Rebased onto eed140c4d (no internal/usage changes since 430005726);
at the rebased head go test ./internal/usage/ ok 22.5s, linux vet clean.

Not tried: the startup peak (~4s, first poll burst during warm-up) is
the pricedRows pool and the chunks of a whole-history build; this commit
doesn't change it.
2026-10-30 09:37:19 +08:00
yetone c8095d1101 usage: pages of 131k rows or more pair one at a time (#2278)
On a cold start the Usage page's requests (All) and heatmap (a year),
and the warm-up's Codex effort, each paired the whole history side by
side, and the live heap reached 624–630 MB at ~10–12 s: the peak. Now
a page's build, or Codex effort's pairing, of bigBuildRows (1<<17) rows
or more holds bigBuilds; a smaller page, Today's, goes beside them, and
its IO never waits (TestQueryPageIOOutsideCacheLock passes). Nothing
under the gate takes requestCache's lock or waits on a flight.

Measured on mote (M5 Pro), cold start with no caches, 390k calls,
a growing Codex rollout, 10 endpoints polled every 5 s, 60 s each:
- before (v0.1.2113): phys_footprint_peak 794 / 783 MB, CPU
  2:01.55 / 2:01.12
- after: 610 / 646 MB, CPU 2:01.08 / 2:03.22
- the first round's slowest usage answers, before 7.9 / 10.3 s and
  7.9 / 10.3 s, after 7.9 / 11.5 s and 6.4 / 8.7 s
On v0.1.2111 plus the warm-up fix alone, the gate cut the max live heap
from 624/630 to 473/480 MB but not the peak, which the request file's
write then set (8e1b1b26d).

Tests at this head, through mote-run:
- go vet -tags nogui ./..., GOOS linux, windows and darwin: ok
- go test -count=1 -timeout 45m ./internal/usage/ ./internal/gui/
  ./internal/sessions/: usage, sessions ok; gui only
  TestMainWindowCorners/macOS_26_SDK, #3949.
- TestBigPagesPairInTurn (two big pages, a 200 ms pairing each): 1 at
  once; with bigBuildRows at 1<<40 it was red, 2 at once.
2026-10-30 06:48:56 +08:00
yetone 839e606575 usage: a read marks a published chunk used without copying it (#2278)
requestIndex.use copied every chunk another read had published, only to
set its Used tick for trim, and readRequestBlocks, trim and visibleLocal
grew their maps and slices by appending. Under 80s of polls while a
session was written (ab17) the copies were 255 MB of 5.4 GB allocated,
visibleLocal's seen map 246 MB, readRequestBlocks' on map 96 MB and
trim's kept 107 MB, all garbage the GC then marked through.

A chunk's use is now a counter of its own (*atomic.Uint64, raised to the
read's tick by CAS, never lowered), shared by the map and every page
that holds the chunk, so use returns the chunk itself. A chunk from
elsewhere with no counter yet is copied once to get one. keep and trim
read lastUse. The maps and slices are made at their size.

TestRequestBlocksKeepOneChunkASource asserted the copy; it now asserts
the same chunk comes back with the later read's tick.

Run at this head (mote, Go 1.26.8):
- GOOS=linux/windows/darwin go vet -tags nogui ./internal/usage/: clean.
- go test -timeout 45m ./internal/usage/: ok.
- go test -race -count=3 -run 'RequestBlocks|RequestIndex|Ledger|Heatmap'
  ./internal/usage/: ok.

Rebased onto origin/main f982e46f2 after the run above; the three #2278
commits were run again together there (see the last commit's body).
2026-10-30 05:57:12 +08:00
yetone 926ef769ff usage: a priced gateway block is kept 30s past its last query, so the next poll reads it (#2278)
The queries reading at once already shared each gateway block's priced
copy (sharedPriced), but let it go when the last of them was done. Its
rows' sync.Pool was emptied by the collections between polls, so every
Usage poll decoded and priced the whole history again: priceBlock was
~960 MB, the pool's New ~720 MB, of 6.1 GB allocated in 80s of polls.

A block no query holds now stays pricedLinger (30s, past the 10s and 15s
polls) and is then let go by a timer; ReleaseScratch, which the window
calls once its reads rest, lets them all go at once. The key is the same
as for the sharing (requestState root|meta, the frozen block), so what a
block is priced as is no less current than when two queries share it.

Measured on mote (~/r2278 run2278d, 10 endpoints every 5s, gateway feed
from 60s), against 936bdccfa:
  allocated 120s-200s  6151 -> 5071 MB, priceBlock and the pool gone
  60s CPU profile: madvise 1.40 -> 0.85s, GC mark 4.68 -> 4.29s
  avg CPU after feed   32.9 -> 30.3%
  footprint peak 765.6 -> 769.8M, avg RSS after 60s 967 -> 966 MiB
  ps RSS peak 1010 -> 1192 MiB (footprint, what Activity Monitor
  shows, the same)
Latency is not comparable: mote's load was ~43, and the Sessions
endpoints this doesn't touch were as much slower (1.16 -> 2.01s) as
the Usage ones in the same run.
Same output: eq2.sh asked each binary heatmap, requests and usage
30d/7d/all twice; every reply byte for byte the same across binaries
and between the first and the second (kept) ask.

Rebased onto 0e2739743 (redact, codex resets); run again after it.
Run at the pushed head on mote: GOOS=linux/windows/darwin go vet -tags
nogui ./internal/usage/ ./internal/gui/ ok; go test ./internal/usage/
./internal/usageapi/ ok; ./internal/gui/ red only in
TestMainWindowCorners/macOS_26_SDK, the open #3949.
Broken by hand: release letting go at once again (the old code) turns
TestPricedBlocksSharedWhileHeld red ("0 blocks kept after every query
was done, want 2").
2026-10-29 08:19:54 +08:00
yetone d7e9c37454 usage: a call pairs again only the heatmap's last days, not its year (#2278)
Each call through magpie changes the gateway's newest block, so the
heatmap's 30 s reuse missed and HeatmapOf paired a year of gateway rows
against every session file again: 15% of magpie's CPU on real history
(HeatmapOf -> pairRows 5.2 s of 32.7 s sampled), ~2.3 s a refresh, and a
large share of the allocation the GC marks.

heatSplit keeps the days before cut (00:00 two days ago) from the last
full pairing, with the serials of the chunks that can't reach past cut
(newest row more than heatReach = 48 h before it). A call then pairs only
the recent chunks, from cut on (pairRowsIn), and adds their days to the
kept ones. Every chunk is paired again when:
- a settled chunk changed or went (its serials differ), or
- the recent chunks' rows before cut changed: a session file copied in or
  a rollout forked from an old one holds calls of then (heatBefore, a
  count, time and token sum of those rows), or
- cut moved (a new day), or the kept pairing is heatOldFresh (10 min) old.
heatReach covers a call paired across cut: a full gateway block whose
newest call is before cut is still paired with the session row after it.

TestHeatmapAfterACallAddsUpOnlyWhatChanged's gateway now has a call of
the last days before its first build, as a gateway in use does: with
only a call of 40 days ago its block went from settled to recent at the
call, which is a full pairing by design.

Run on mote, heat2278 at this head (based on fb5959553, rebased on
b2d005bf3, which changes internal/gateway and nothing under usage):
- GOOS=linux/windows/darwin go vet -tags nogui ./internal/usage/...
  ./internal/usageapi/... ./internal/gui/...: ok
- go test -count=1 -timeout 45m ./internal/usage/... ./internal/usageapi/...: ok,
  and again with vet after the rebase
- ./internal/gui/...: TestMainWindowCorners/macOS_26_SDK red, #3949
  (mote's macOS 27; nothing here reaches it); every other test ok
- broken by hand, TestHeatmapAfterACallPairsOnlyTheLastDays goes red:
  recent days after cut+1 dropped; heatReach 0 (the cross-cut gateway
  block); the heatBefore check removed (both the rewritten mixed file and
  the forked file, each alone)

Real history on mote (the owner's usage.jsonl and session files copied
into a sandbox HOME, GUI polled every 5 s, the gateway fed 4 calls/s,
load ~30 from other sessions), v0.1.1956 build vs this one:
- /api/usage/heatmap mean 2.35 s -> 1.53 s; all polls 0.93 s -> 0.74 s
- HeatmapOf 0.89 s of 28.35 s sampled (3.1%), heatSplit itself 0.25 s,
  from 15%
- average CPU after the feed starts 61.2% -> 59.0%; peak RSS 1103 -> 1065 MiB
What is left of the heatmap's wait is readRequestState and the pages it
shares a lock with, not its pairing.
2026-10-29 05:04:50 +08:00
yetone 49d4d0f7ab usage: the request matcher keeps its maps for the next call, and gives them back once the window rests (#2278)
Every poll while an agent works matches a year's history again:
matchedBlocks and codexChunkResponsePairs grew their maps (byID,
reserved, used, groupOf, picks, picked, ...) and slices from nothing on
each call. They were ~3.0 GB of the ~40 GB a poll-heavy 80 s allocated
on the real-history harness (d1951 heap diff, 120 s to 200 s).

A sync.Pool was tried first and kept nothing in real use: under
tightenGC a poll collects 4-5 times a second (1029 GCs in 230 s), each
collection empties the pool, and the matcher's flat allocation went
only from 2241 to 1840 MB. So one scratch of each is kept in an
atomic.Pointer, emptied after a call (clear() keeps the maps' buckets,
and drops every chunk the call saw), and let go by usage.ReleaseScratch,
which releaseIfPagesRest calls before FreeOSMemory: once the window's
reads have rested 3 s, what the matching kept goes back with the rest.
A call that finds the scratch taken makes its own, sized as before.
matchedBlocks' result map is now made once the id matches are known,
not grown from the response pairs alone.

Measured on mote (Apple M5 Pro), at aeacc6358 + this change:
- BenchmarkPairRows (2000 files x 100 calls), -count 3: 100.8 MB/op,
  7,056 allocs/op at aeacc6358; 48.4 MB/op, 5,458 allocs/op after.
- Real history (copy of the user's usage.jsonl, sandbox HOME, polls +
  appended calls, run2278d.sh 230 s), heap alloc 120 s to 200 s:
  matchedBlocks flat 2241 -> 1295 MB, codexChunkResponsePairs flat
  806 -> 143 MB, of a total about the same (39.8 vs 39.3 GB). That run
  was before the result-map change. Its CPU and peak RSS (974 MiB vs
  936) aren't comparable: mote's load went from ~25 to 50-88 from other
  sessions during it.

Tests:
- New TestPairScratchKeepsNothingBetweenCalls (pairRows on one history
  after another matches what a first call does; ReleaseScratch lets go)
  and TestMatchScratchForgetsTheLastCall (a gateway call one call used by
  id or reserved by a response pair is matched in the next; ids the last
  call looked up in another gateway aren't).
- Broken by hand, each red: without clear of byID (index out of range),
  used ("the last call's id match held the gateway's call"), reserved
  ("the last call's response pair held"), groupOf and picks (index out
  of range). ids, named and picked only choose which chunks are opened,
  so a stale entry there costs a read, not a match.
- go test -count=1 -timeout 45m ./internal/usage/ ./internal/usageapi/
  ./internal/sessions/ ./internal/gui/ at aeacc6358 + this change: usage,
  usageapi, sessions ok; gui red in TestMainWindowCorners/macOS_26_SDK
  alone, mote's macOS 27 (#3949). An earlier gui run there had ten
  AppKit window tests killed at their 20-40 s deadlines at load ~40-88
  (#2645).
- GOOS=linux, windows, darwin go vet -tags nogui ./internal/usage/
  ./internal/gui/ ./internal/usageapi/: ok.

Rebased onto origin/main fe05f0a72 (library and Claude-account changes,
nothing in internal/usage or page_memory.go); after the rebase
./internal/usage/ and ./internal/usageapi/ ran again at the pushed
tree: ok, and go build . ok.
2026-10-29 04:33:14 +08:00
yetone 06469694b7 usage: pairing a poll's calls allocates 40% less, in a few slabs (#2278)
Under polls, with calls coming in, GC was ~35% of magpie's CPU and
madvise another 16%, both driven by how much a poll allocates. The
pairing that the heatmap and every page run did most of it: in an 80 s
heap diff on a year's history, matchedBlocks allocated 3.2 GB and
codexChunkResponsePairs 2.6 GB.

- matchedBlocks: a match key holds a call or two, so each key's ends
  and range counts were two slices of their own. They are now one ends
  slab and one counts slab, a group an offset into them, and groupOf is
  made the size of the calls it keeps. The candidates and unique maps
  are a slice and a []bool over slab positions.
- codexChunkResponsePairs: picks and their slab are made the size of
  the gateway's response ids, and a gateway call is judged from its
  packed strings (codexGatewayCall) instead of being made a whole Row.

What a call pairs with is unchanged.

BenchmarkPairRows (new; 2,000 session files of 100 calls, half Codex by
response id, half Claude Code by session and tokens), on mote:
  e0ea15b8e: 170,154,300 B/op, 208,673 allocs/op
  this:      100,846,208 B/op,   7,056 allocs/op
(ns/op isn't comparable: mote was at load 20-35, both ~0.7-1.0 s/op.)

Not yet measured: the poll-and-feed A/B against a real build on mote
(load 86 from other runs); its numbers go on #2278.

Run at this head on mote: go test ./internal/usage ./internal/usageapi
ok; go test ./internal/sessions ok; ./internal/gui: TestMainWindowCorners/
macOS_26_SDK red only, #3949 (macOS 27 AppKit, untouched here); go vet
-tags nogui ./internal/usage/... ./internal/gui/... ./internal/usageapi/...
for linux, windows and darwin ok.

Broken by hand: the counts slab without the group's +k offset (groups'
range counts overlap) failed TestIndexedExportMatchesExhaustiveOracle,
TestRequestMatchIndexEquivalent, TestMatchOpensOnlyNamedChunks and
TestCodexCacheWriteMatchesGatewayCall; codexGatewayCall taking a
rejected call failed TestCodexRejectedGatewayDoesNotPairWithNativeCall.

Not run: the full ./... suite.
2026-10-29 03:40:18 +08:00
yetone 655f8dbd1c usage: matching by request id keeps no slice an id (#2278)
matchedBlocks kept each request id's gateway calls in a map of slices,
the local calls that named it in a second map of slices with the id
cloned, and each match group behind a pointer. Over a year's calls the
alloc profile of v0.1.1928 on mote (34k session files, 240k gateway
rows, two minutes of polls while an agent worked) had matchedBlocks at
2.5 GB: groups 598 MB, byID 547 MB, byRequest 504 MB, matched/used
463 MB. Now:
- an id is a place in one slice of calls, its first call held in place
  and only repeats in a slice; the map of ids is sized by a count pass;
- the local calls that name an id are one slice, each linked to the one
  found before it, read back in the order they were found, so the order
  (and newestIDs' sort) is what it was;
- the id is looked up, not cloned, and a call with no id is skipped
  before the lookup;
- groups are a slice the map points into.

TestMatchByIDAllocatesNoSliceAnID: 4000 gateway calls with ids, a third
of the locals naming an earlier id again, match as matchedLocalLegacy
does, and the second match makes at most n/10 allocations. Red on the
old code (11,334 allocations), green on the new (168).

Run on mote at the pushed head (rebased onto origin/main 3ec9babe7, no
change to internal/usage since its base 87a983423; rebased again onto
1319a44bb, four plugin and provider commits that touch neither
internal/usage nor internal/sessions):
  go test -count=1 -timeout 45m ./internal/usage/ ./internal/sessions/
    ok (25.9s, 32.2s)
  go test ./internal/gui/: FAIL only in TestMainWindowCorners, the open
    macOS 27 red #3949
  GOOS=linux/windows/darwin go vet -tags nogui ./internal/usage/ ok
Not run: an A/B of the page on mote; it follows with the Codex pairs
change.
2026-10-29 00:52:47 +08:00
yetone b5d2858f41 usage: matching gateway calls decodes only the session files they can match (#2278)
matchedBlocks paired the gateway's calls with the session files' by
request id, then by session, tokens and time, and decoded every session
file of the period for each pass: twice per poll, for the few sessions
the gateway had calls of. In a 24s heap profile of a fed sandbox it was
0.77 GB of the 5.3 GB allocated, and 5.4s of a minute's 42s of CPU.

Each local chunk's hints are now kept by its serial (match_chunks.go,
as chunkIDs keeps Codex's response ids): a 32-bit hash of each request
id it names, a hash of each session a call of it can be matched in
(agy's as agyMatchSession, rows of no tokens and no failure left out,
as the pass does), and its last call's time. A pass decodes a chunk
only when one of its ids or sessions is the gateway's and its last call
is in the period. A hash that matches only decodes the chunk, so the
matches are exact. Hints live 8 matchings past their last use.

Run at this head (cb167fcbd + this change), on mote:
- TestMatchOpensOnlyNamedChunks (new): 20 seeds of 12 session files, the
  gateway naming four sessions and one id in a fifth file; the matches
  equal matchedLocalLegacy's and only named files are decoded. Red with
  namesAny always true ("matching decoded /local/session-4").
- TestMatchOpensAgyChunks (new): an agy step is matched with its file
  alone decoded.
- go test ./internal/usage -timeout 45m: ok (26.9s).
- go vet -tags nogui ./internal/usage for darwin, linux and windows:
  clean.

A/B on mote, the sandbox of #2278's synthetic history (34k sessions,
3000 with gateway records), 10 page endpoints polled every 5s and 4
gateway appends a second, 230s each, old = dc6f6d902 (v0.1.1927):
                       old        new
  all polls mean     4.93s      3.15s
  heatmap mean      11.86s      7.24s
  footprint peak    707.2M     632.4M
  avg CPU after feed  90.0%      79.6%
mote's load was ~100 from other sessions' suites through both arms, so
the times are slower than an idle machine's; the arms ran back to back.
Then rebased onto b119f8777, which changes an internal/gateway test and
LESSONS.md only.

Not tried: the user's own history.
2026-10-29 00:25:57 +08:00
yetone b69f8e96af usage: a call through magpie adds up the heatmap only for the chunks it changed (#2278)
A call through magpie changes the gateway's log, so the heatmap's kept
page (heatFresh) is no use and the Requests tab's refresh read every
row of the year again: unpacked each session file's chunk and summed its
days. While an agent worked through magpie that was every refresh.

The heatmap now keeps each chunk's day sums (chunkPart.days, in
requestIndex.heatParts, apart from the pages' cells so neither pushes
the other's out), under the same pairing signature the cells use, and
adds up again only a chunk whose rows or pairing changed. A call is
still counted at once. pairedRows.visit had no other caller and is gone.

Measured on mote at #2278's scale (synthetic HOME: 15 GB of Codex
rollouts, 1.9 GB of Claude sessions, 240k-row usage.jsonl), the GUI's
polls every 5s and 4 gateway records appended a second, against
v0.1.1920:
- CPU of a 60s profile while appending: 57.9s -> 42.1s;
  HeatmapOf 11.5s -> 6.7s, of it the visit 4.8s -> ~0
- /api/usage/heatmap mean 2.79s -> 1.69s; process CPU average
  107% -> 83%
- peak footprint unchanged (579 MB, 607 MB this run: noise; what is
  left is pairRows' pairing of the year, next)

Test: TestHeatmapAfterACallAddsUpOnlyWhatChanged (8 session files and
a gateway call: after one more call, at most 1 chunk is added up again,
the call is counted, and the sums equal a cold build). Broken by hand
(old sums never taken): red, "a call added up 9 chunks again".

Run at the pushed head (rebased on fc6f1d5e8, no internal/usage change
in between, rerun after): go test ./internal/usage ok; GOOS=linux,
windows, darwin go vet -tags nogui ./internal/usage ./internal/gui ok;
go test ./internal/gui before the rebase: ok except
TestMainWindowCorners, #3949 (macOS 27 on mote). Not run: the whole
suite.
2026-10-28 23:44:37 +08:00
yetone 6104e88aa9 usage: a session file two queries read at once is made once (#2278)
At a cold start with the app open, the warm-up's request page and the
GUI's heatmap each read every session file at the same time. Each one
decoded and priced its own chunk of each file. That is twice the CPU,
and the GUI's requests queued behind it. sharedBuild keys a build by
the request state (root and meta, hashed) and by the file's path, size
and time. A query that finds the same file already being made waits
for that build, then takes its own shallow copy, because a query writes
its chunk's serial, use and archive place. The rows and the archive are
shared and only read. If the build panics, the waiter builds its own.
Only QueryPage and the effort index share builds; queryPage's other
callers build as before. blockPricer.share now takes the hashed state
directly.

Measured on mote with synthetic history at #2278's scale (25k Codex
rollouts, 9k Claude sessions, a 115 MB usage.jsonl), with a cold
`magpie web` and 10 GUI endpoints polled every 5 s for 150 s. Built on
v0.1.1903 before the rebase:
- slowest GUI response: 61 s on v0.1.1903, 15.3 s with this change
- footprint peak: 591 MB on v0.1.1903, 609 MB with this change, so no
  memory gain; the peak is a transient spread over the page, heatmap,
  effort index and session stats (heap profile at 15 s: QueryPage
  145 MB, HeatmapOf 87 MB, buildEffort 51 MB, StatsAndNative 43 MB)

TestSharedBuildMakesAFileOnce checks several things:
- a second query waits for the first one's build
- each query gets its own copy, and the copies share one archive
- a change to one copy doesn't show in the other
- the map is empty afterwards
- after a panicked build, the waiter builds its own
With the join broken by hand (the lookup disabled), it failed with "a
file made again while another query was making it".

Run at the pushed tree (rebased onto ca499953e, after b7b817116 and
84a6a2c42 changed request_page.go), on mote:
- go test -race -tags nogui ./internal/usage ./internal/sessions: ok
- go vet -tags nogui ./internal/usage for linux, windows and darwin: ok
Not run: the full suite, and the footprint run at the rebased tree.
2026-10-28 21:40:12 +08:00
yetone aafbe575ce usage: queries reading at once share one priced copy of a gateway block (#2278)
A query over the gateway's history decodes and prices every block it
reads and holds them until it is done. At a cold start with the GUI
open, the warm-up's page, the heatmap and Codex's model/effort each ran
such a query at the same time, and each held its own copy: 105 MB of
pooled rows between them at the peak, and the app's footprint went to
737-760 MB where it is 388 MB with nothing asking.

A priced block is now kept in sharedPriced, by the frozen block and a
hash of what prices and names a call (requestState.meta and root), while
any query holds it; the last release hands its rows back to the pool.
A block is never changed once frozen, and a priced copy is only read:
pairing clones a chunk before it writes a row's thread. A pricer that
was not given a meta (the tests' own) keeps its blocks to itself, as
before. Both callers release on a panic too (defer), so a block is never
held for good.

Run on mote (M5 Pro), rebased onto 012c584cc, then 29181eb78 (a gateway
test only), and run again after each:
- go test -race -count=1 -timeout 45m ./internal/usage: ok (38s at the
  pushed head, 42s and 70s before). ./internal/gui: TestMainWindowCorners/macOS_26_SDK
  red only, #3949 (macOS 27, untouched here).
- TestPricedBlocksSharedWhileHeld (new): ok. Broken by hand (block()
  never sharing): red, "two queries of one meta priced 0x...080 and
  0x...380".
- GOOS=linux/windows/darwin go vet -tags nogui ./internal/usage: ok;
  gofmt -l clean.
- #2278's reproduction: a synthetic HOME of 25k Codex rollouts (40 of
  them ~120 MB), 9k Claude sessions and a 115 MB usage.jsonl; cold
  `magpie web` for 150s with every GUI usage/sessions endpoint polled
  every 5s from 2s on:
    before (v0.1.1900 tree): footprint peak 760.4 MB, RSS peak 1018 MiB,
      heap before GC peak 663 MB
    after:                   footprint peak 591.1 MB, RSS peak 867 MiB,
      heap before GC peak 513 MB
  The pool's live rows at 33s: 104.7 MB before, 49.5 MB after.

Not tried: the reporter's own history; a Windows or Linux run (no
OS-specific code).
2026-10-28 21:25:04 +08:00
yetone 012c584cc1 usage: clear a model's usage, or all of it, from the Usage page
CrazyMouse_TT on X asked for a way to clear usage, all of it or one
model's, to measure a local model fresh after deploying it.

The Usage page's Models list has a "…" on each row (and a right-click
menu) with "Clear usage…", and "Clear all usage…" sits under the lists
below the "Counted from…" note. Each asks first, in a confirmation that
says what is deleted, that it can't be undone, and that key spending
limits and allowances still count the calls.

A clear is a mark in settings (usageCleared: provider, model, unix ms),
read at read time; usage.jsonl is never rewritten. The Overview hides
calls up to the mark in summarizeFrom; the Requests page, heatmap and
ledger/CSV hide them in Filter.keepsRow, their one choke point, and the
request index's meta carries the marks so its cache is dropped. Key
budgets, window holds and Codex reads go through usage.Visit and the raw
log, so a clear never resets a key's spending limit or a quota. A later
clear of the same model or of everything takes the place of an earlier
one. The marks ride the settings part of a sync (sync-backup.md) and a
save of the Settings page keeps them (api.go's keep list; the guard
test TestSettingsSaveKeepsWhatItDoesNotSend caught it missing).
gateway-sessions.md and sync-backup.md say so.

Run on mote (mote-run) at this tree, rebased on origin/main c26b2992e
(the Go packages and usage-clear.test.cjs; vet and the 68 GUI files
ran at the earlier base f835bd713, four commits behind):
- go test -tags nogui -timeout 45m ./internal/usage ./internal/settings
  ./internal/usageapi ./internal/gui: all ok after the
  keep-list fix (before it, TestSettingsSaveKeepsWhatItDoesNotSend red).
- gofmt -l: clean. GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: exit 0. (Linux vet without nogui fails in
  wails' cgo, as on main.)
- usage-clear.test.cjs: 32/32 in Chromium and WebKit, en/zh/zh-TW/ja/de,
  at 1200, 560 and 390 (web). With the old page.js/client.js/i18n.js it
  fails (TimeoutError).
- 68 GUI files the change can reach (every usage-*, gui-de/ja/zh-tw,
  i18n-keys, click-scroll, idle-ticks, mobile-web, panel-usage,
  sessions-purge): 941/980. The reds are filed and red on main
  (usage-ledger run alone at origin/main 84a6a2c42 too): i18n-keys "masking…" (#4053), mobile-web
  (#3952), usage-agents-hide (#2276, #3414), usage-ledger "newest live
  route needs no return-to-live button" (#3104, run alone at main too).
  i18n-keys first also named "Clear usage…" in Go comments of this
  change; reworded.
Broken by hand, each red: hides() always false (usage and gui tests),
keepsRow's clear check removed ("Requests after the clear: 5 rows"),
clearedKey out of the request meta ("after clearing everything: 3"),
the api.go keep line removed (UsageCleared [] after a save).

Not tried: the full go ./... suite and the whole GUI suite (mote was
busy with other sessions' full suites), the real app, a sync between
two computers. usage.jsonl doesn't shrink, and the Sessions tab's
figures are not cleared.
2026-10-28 21:13:09 +08:00
yetone b7b8171165 usage: a source's chunk is kept once, the index's and the page's both (#2278)
readRequestBlocks copied every source's chunk twice, one for the index
and one for the page, on every read: 13.5 MB of the 176 MB live heap
after 34k sessions' cold start (synthetic history at #2278's scale on
mote, 240k gateway records in usage.jsonl). Nothing writes a published
chunk in place (pairRows and pairMemo.apply clone, keep copies, the
spill gives an archive back before the read returns), so both now take
one chunk. A chunk this read built or read from disk is its own and is
not copied at all; one an earlier read published is copied once, for
its Used, since that read's page may still hold it. The other
computers' days are kept the same way.

TestRequestBlocksKeepOneChunkASource: a built chunk is the map's and
the page's one pointer, with this read's tick; read again after keep, it
is one new copy and the published one is unchanged. Broken by hand
(the index given its own copy again) it failed with "a built chunk is
copied".

Run at this change on 0dc4cec85 (mote): go vet -tags nogui of
internal/usage and internal/sessions for linux, windows and darwin ok;
go test -tags nogui ./internal/usage ./internal/sessions ok. Rebased
onto 60561129f (GUI and codexcat changes), then go test -tags nogui
./internal/usage ./internal/sessions ./internal/codexcat ok again at
the pushed tree.
Not measured apart: the cold-start footprint run on mote ran beside a
full suite (load ~40) and isn't comparable; the heap line above is from
the profile before this change.
2026-10-28 20:53:36 +08:00
yetone 0dc4cec85d usage: a row's Codex thread is kept as a 4-byte place, not a string (#2278)
Every row of a chunk had a 16-byte string header for its Codex
thread. A day's rows are a few hundred threads, one after another. At
the scale of #2278 (34k session files, 1M Codex rows), these headers
were the largest single holder in the heap, 24.5 MB of 184 MB live.
codexActors now keeps a []uint32 into the chunk's thread names. The
row before's thread is checked first, then the names. A clone shares
the names clipped, so adding a name to one never writes into the
other. The disk format is unchanged: each row's thread is still
written as a string.

Measured on mote, at 7e58591dc's parent with this change. The history
is synthetic: 25,000 Codex rollouts and 9,000 Claude Code sessions, 40
turns each (13 GB), plus a 115 MB usage.jsonl of 240k gateway calls on
the newest 3,000 of each. Cold `magpie web --no-open` in a sandbox
HOME, with `magpie heap` taken at 130 s:
- main: live heap 195.2 MB (both runs), physical footprint peak 389 to
  417 MB.
- this change: live heap 175.6 MB, physical footprint peak 366 MB.
The reporter's 0.1.1318 peaked at 2.85 GB RSS on such a history.

Run at the pushed head (rebased onto 7e58591dc, rerun after):
- GOOS=linux, windows and darwin go vet -tags nogui ./internal/usage/...
  ./internal/sessions/... ./internal/gateway ./internal/cli: ok.
- go test ./internal/usage/... ./internal/sessions/...: ok.
TestCodexActorsTakeFourBytesARow: 100k rows of 200 threads hold at
most 5 bytes a row, read back, and a clone keeps its own rows. Broken
by hand (no lookup of a name already held) it goes red.
Not run before the push: the full suite. It runs next.
2026-10-28 20:43:10 +08:00
yetone 396e0e4638 usage: a deleted provider's requests merged into another, or named, from the Requests filter
CyberCaius on Discord: a deleted provider's requests sat under its old id
("<date> 已删除"), and the only way to put them under a provider they
have was renaming that provider onto the old id. Now, with a deleted
provider picked in Usage › Requests' Provider filter, a "…" beside it
offers Merge into… (an app menu of the providers there are now) and
Rename… (the filter's button turns into a name field; Enter or leaving
it saves, Escape keeps it). With the merged-into provider picked, the
same "…" lists Separate <name> for each, the undo.

Nothing in the log is rewritten. Both live on the deletion's own record
in providers.json (Deleted.Into/MergedAt, Deleted.Label), so a provider
added later under the old id inherits neither: it is a different
provider, and its record of its own is what it has. Renaming the target
carries the merge (Rename rewrites Into); deleting the target ends it.

Renames.Both(id, time) gives the id a call is shown under and the one it
was made to (Own). Listing, filtering, the summary and vias go by the
shown id; pricing (Record.priceID, block_price's as), window holds and
the gateway's loggedAnswers go by the own one, so a merge moves no cost
or token, only whose name they sit under. The target's face lists what
was merged into it (Named.Merged). Routes: GET /api/usage/deleted/into,
POST /api/usage/deleted {id, into?, name?}; a field not sent stays.

Run (mote, at this tree on d50f84c9f):
- go test -tags nogui -timeout 45m ./... : every package ok, exit 0.
- GOOS=linux and GOOS=windows go vet -tags nogui on usage, usageapi,
  provider, gui, gateway: ok. gofmt -l clean.
- New: TestDeletedProviderMergedIntoAnother (usage: cost 306 before and
  after the merge, 3 calls under main, coster/pricer price a relay call
  at its own price, a new "relay" keeps only its own call, rename and
  delete of the target, undo), TestDeletedProviderNamedAndMerged
  (usageapi), TestUsageDeletedProviderRoutes (gui).
- GUI: usage-ledger-deleted-merge.test.cjs, chromium and webkit, en zh
  zh-TW ja de at 1400 and 760px: ok. All 63 usage-*/ledger-* files and
  i18n-keys, both engines: 923 of 954 ok. The reds are red the same on
  origin/main c3b0484a9 run alone: usage-agents-hide (#3414),
  usage-fold (#3415), usage-ledger's "newest live route needs no
  return-to-live button" (#3104), and i18n-keys' "a plugin's words are
  its own" on library's "Runs as" (#3897).

After rebasing on origin/main 3e96197da (i18n.js merged with c3b0484a9's
balance keys): go build ./..., go test of internal/usage/...,
usageapi/..., provider/..., gui/... ok; the new GUI file in both
engines and every language ok; i18n-keys only #3897's red.

Broken by hand:
- Both returning (to, to): TestDeletedProviderMergedIntoAnother red,
  "cost 900, before 306".
- renamesOf not setting into: both Go tests red (relay still listed).
- ledProviderMore returning at once: the GUI test red (timeout waiting
  for the …), 5 of 5 subtests in chromium.
- On the old code the new tests don't compile (no MergeDeleted).

Not tried: the real app on a real providers.json with a deleted
provider; Linux/Windows GUI. gateway_sessions still prices by the raw
id, and a deleted provider's per-provider price stops applying once its
id is reused (both before this change, unchanged by it).
2026-10-28 11:15:57 +08:00
yetone 841bcf8da7 usage: a reply under the name its provider's list gives the model is not a swap
jzing.draw (Discord #general, 10-27) had a Usage row for Qoder's free
Qwen model, sent as qfmodel, tagged "actual Qwen3.8-Flash". Since
plugins#412/#413 (qoder 0.2.38) the plugin answers under the model list's
display name, and Qoder's list names qfmodel Qwen3.8-Flash, so it is the
model asked for. Swapped compares names alone and can't know that.

usage.ListedAs(provider, model, served) reads the provider's own list
(Provider.Available, once a minute per provider, only once a reply already
reads as swapped) and holds when served is the name it gives the model,
spelled however (SameSpelled). Every place a swap is set or read again
asks it: the gateway's try, the ledger and request-page rows, block
pricing, a kept row read back (request_page unpack) and a kept route
(history routedAgain), so old rows lose the false tag too.

Run at this tree (base ca8a6f346):
- go vet ./internal/usage ./internal/gateway on darwin, linux (nogui)
  and windows; gofmt -l clean
- go test -count=1 -timeout 45m -p 1 ./internal/usage ./internal/gateway:
  usage ok 146s, gateway ok 887s
- the new tests (TestListedNameIsTheModelAskedFor, TestListedNamesReadOnceAMinute,
  TestKeptRowListedNameNotSwapped, TestBlockPricerListedNameNotSwapped,
  TestRouteKeptListedNameNotSwapped) pass

Broken by hand: with the call sites put back (served.go's ListedAs kept),
TestKeptRowListedNameNotSwapped, TestBlockPricerListedNameNotSwapped and
TestRouteKeptListedNameNotSwapped fail.

Real use: a binary built from this tree, under a sandbox HOME holding a
copy of the owner's ~/.config/magpie, reads the real Qoder list:
qoder/qfmodel answered as Qwen3.8-Flash and dmodel as DeepSeek-V4-Pro are
listed (not swaps), qfmodel answered as GLM-5.3 is not.

Not tried: a live gateway call through the Qoder plugin; the full
go test ./... (other packages don't call ListedAs); the gateway try's line has no test of its own beyond the kept-route
read, which uses the same ListedAs.
2026-10-27 18:54:31 +08:00
yetone 94c2aaecba usage: a deleted provider's tests stay listed under it, not its host (cybercaius)
cybercaius on Discord: one custom provider (example, on api.example.me)
was listed in the Requests page's provider filter under its id and its
host, and the host stayed after the provider was deleted.

The Add sheet's Detect, model-list and Test requests are sent before the
provider has an id, so probelog records them under the host asked
("a provider being added has no id yet"). 8e2ba36de (v0.1.1697, yyddbds)
lists those under the provider saved on that host now (Renames.ProbeOf),
but a deleted provider is on no host any more, so its probes went back
to the host beside the id its calls are kept under.

Now the log's index notes, as it reads each line, the provider each
host's calls went to (logSnapshot.hosts; "" once two providers were on
one host). probeProvider lists a probe recorded under its host by the
provider saved on that host, and with none there, by the one the log's
calls to that host were made under. A host two providers are or were
on, or none, stays the host, lowercased, so one typed in two cases is
listed once. It is done when the log is read, so rows written before
this release are merged too. Renames.OnHost tells "no provider on this
host" from "two providers on it", so a host shared now is never given
to a deleted one.

Not added: deleting a provider's usage rows. usage.jsonl is the record
budgets, windows and totals are read from, and probe rows are counted in
none of them; with them under one name there is nothing left to clean.

Run:
- go test -tags nogui ./internal/usage ./internal/usageapi
  ./internal/probelog: ok, at the pushed head (rebased on 56de2d192).
- ./internal/provider, skipping the reds open on main
  (TestUnreadLoginsWriteErrorsKeepCredentials #3632, TestFetchAsksASharedBaseOnce
  and its two siblings #3854): the disk was full from other sessions'
  temp files, and TestLoginUsageEachAccount failed on "no space left on
  device"; it and the Rename tests passed on a rerun.
- New TestProbesOfADeletedProviderStayWithIt: probes under
  api.example.me and API.example.me before provider.Add, a Test after,
  a gateway call with the provider's Where, and twice.example used by two
  providers; after provider.Delete the list is [example one
  twice.example two] and example's filter has its 4 rows.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.

Broken by hand: probeProvider without the log's hosts fails it with
"deleted: providers [API.example.me api.example.me example one
twice.example two]", the reporter's extra names.

Not tried: the reporter's own usage.jsonl; a host typed in the Add sheet
and changed before saving (its probes went to another host and stay
under it); the GUI suite (no GUI file changed; the filter lists what
QueryPage returns); the full go test ./... (disk full).
2026-10-27 18:32:44 +08:00
yetone f3c4d7b7a7 usage: Codex effort reads only the session chunks that have Codex threads
CodexModelEffort (the Usage page's model and effort per Codex thread,
read again each minute) unpacked every chunk of the ledger, Claude
Code's and every other agent's too, to sum the few rows a Codex actor
owns. codexEffortOfIndex now visits only chunks with a Codex actor
(pairedRows.visitActors), and effortSums.add clones the model and
effort it keeps, since lentRows lends its strings.

Run at this head (d5f86d991 + this): go test ./internal/usage
./internal/usageapi ./internal/gui ok; TestCodexModelEffort* -race
-count=3 ok; gofmt clean; GOOS=linux and GOOS=windows go vet -tags
nogui ./internal/usage clean. TestCodexModelEffortIsTheWholeLedgers
now checks a chunk was read and the Claude Code session's wasn't: red
with the skip taken out by hand, and red with the clone taken out
(the sums read the next chunk's strings).
A/B on real session files, 8 sequential polls of state, sessions,
stats, usage, usage/requests, quotas and providers, 15 s apart, the
previous commit's build vs this: CodexModelEffort 305 -> 245 MB,
codexEffortOfIndex 238 -> 176 MB; against v0.1.1661 twice, 304 -> 253
and 308 -> 245 MB. Totals moved with live sessions being written
beside the runs (the sandbox HOME links ~/.codex/sessions and
~/.claude/projects): ReadCallSource read 46 to 398 MB a run on the
same binaries, so the totals don't measure this change.
Not changed: pairRowsMemo's misses in buildRequestBlocksIn and
readRequestState's listing, the next hotspots.
Rebased on 33ccc6188 (library, not usage) and run again at the pushed
head: usage and usageapi ok.
2026-10-27 09:33:42 +08:00
yetone 8fba65d0bc gateway: what masking took a request is kept, and shown as Masking in its time
fremontdango on Discord asked, after the request that sat as "routing…"
while it was masked, how long masking took. Now each request keeps it.

noteRedacting adds up the time from the first masking at once to the
last's end (redaction.spent); maskingMs gives it in ms, at least 1 when
there was any, never more than Own, magpie's own time before the request
went out (splitSent), since masking happens inside it. It goes on the
route (Route.Masking, /api/gateway/trace) and in the usage record
(Record.Masking, masking_ms; packedRow's int32 fits in its padding, so
TestRowsOfOneSessionShareAShape's 216 bytes are unchanged, and the
process-private snapshot carries it). It is a duration, no text.

The Routing page shows it as magpie's "Masking" part, first in where the
first try's time went (timeParts, renderSteps); the Usage page's detail
splits it out of "In magpie" (page.js). Both use the core "Masking"
string every language already has (脱敏, 脫敏, マスク, Maskierung).

Why masking can be slow, measured on this machine (go1.27, M-series):
the rules are linear, ~0.25 ms/KB. redact.MaskJSON over a Claude Code
shaped body: 283 KB 35 ms (secrets) / 63 ms (+ personal data); 511 KB
70 / 122 ms; a dense 402 KB with 7,821 hits 173 ms with personal data,
144 ms with the user's words too. Through the gateway (redactedHits,
secrets + personal, 402 KB dense) 145 ms the first time, 123 ms again;
noteMasked ~2.6 ms. Doubling the body doubles the time; nothing
quadratic or repeated per hit. So a request held "routing…" for 15 s or
more (unroutedShow) while masked is the local model (Settings → Privacy
→ Find with a local model, internal/pii): it reads each text it hasn't
seen (a new turn's tool results are the misses), one model turn at a
time, so requests queue behind each other (#3682: 480 KB took 90 s on an
RX 470/580). No change to masking's speed here; the phase and the time
now say which it was.

Run at this head, on origin/main 9ae791221 (Go, M-series macOS):
- go test -timeout 45m ./internal/gateway ./internal/gui ./internal/redact
  ./internal/usage: ok (gateway 425s, gui 99s); ./internal/masking and
  ./internal/pii ok at the pre-rebase head 3a4a13d04
- gofmt -l internal: clean; go vet ./..., GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean; go build: ok
- go test -race -count=3 TestMaskingIsAPhaseWithItsTime,
  TestNoMaskingNoMaskingTime: ok
- GUI, chromium and webkit: routing-masking (every language) 10/10,
  usage-ledger-detail 6/6, i18n-keys and routing-levels green. The whole
  routing-*, panel-routing*, usage-ledger* and i18n-keys set: 1,824
  tests, 96 red at load ~47, in 15 files. The first run's i18n-keys red
  was this change's (a Go comment quoting the core word), fixed in the
  commit before. The other 14 files, rerun two at a time at this head
  and at origin/main 9ae791221: the same files red on both (89 here, 86
  there; routing-rule-remove alone 5 red here, 7 on main). Each has an
  issue: #2115, #3410, #3411, #1905, #3593, #3408, #3096, #3094, #3001,
  #3104, #3786.

Broken by hand, each red: spent not added (route and record Masking 0),
no t.Masking on the route, no Masking in the usage record, the snapshot's
put/take of Masking (TestRowsOfOneSessionShareAShape), timeParts without
Masking or renderSteps without the first try's masking
(routing-masking), the Usage page without the Masking line
(usage-ledger-detail, 3 red).

Not tried: a real local model (Settings → Privacy → Find with a local
model) on the reporter's Windows box or any GPU, so a long masking was
only held by a fake masker; the Codex backend's usage record has no
Masking yet; the Windows test box wasn't used.

Reported by fremontdango on Discord.
2026-10-27 08:08:23 +08:00
yetone c2c08850f6 usage: a request state hashes Codex's thread identities without encoding them
readRequestState json.Marshal()ed every Codex thread's identity (~20k
over a real history) into a new buffer only to write it into the key's
hash, on every requests page and effort ask: every 15 s poll. They are
now written into the hash directly, each field length-prefixed, in the
order of their keys. The key lives in memory only (the disk index is
keyed by meta), so the changed form costs nothing on upgrade.

Benchmark, 20k identities (a throwaway benchmark, not committed):
json.Marshal + hash 7.06 ms, 6.49 MB, 40012 allocs an ask; now 3.36 ms,
0.36 MB, 3 allocs. In a 12-poll real-history run json.Marshal under
readRequestState was 116 MB.

Test: TestCodexIdentitiesHashed (same identities in another order hash
the same; a thread turning subagent changes it; ab|c is not a|bc; none
is not one). It fails with the length prefixes taken out by hand. The
rest of the package's tests passed with this hash removed altogether:
an identity changes only with a rollout, whose size and time are in the
key too.

Run at this tree: go test ./internal/usage/ ok (8 runs; one earlier run
of this change printed a bare FAIL whose test I lost to a tail, not
seen again in 8 package runs and 30 of the effort tests); gofmt -l
clean; go vet, GOOS=linux and GOOS=windows go vet -tags nogui
./internal/usage ok.
2026-10-27 08:04:30 +08:00
yetone 61d656c696 usage: a Codex thread's consumption is built again at most once a minute
The Sessions page asks CodexModelEffort(All) on every 15 s poll. It
built the ledger of all history again whenever any session file or the
gateway log had changed, and with Codex and Claude Code at work they
change between nearly every two polls. In a 3.5-minute real run that was
2.49 GB allocated, the largest single cost of a poll. An answer now
stands for effortFresh (a minute) before a change is built into it, and
an ask inside the minute is answered before the sources' state is read
(that listing and hashing is most of an unchanged ask's cost). Another
home's answer is never held (requestRoot). The page's own rows, totals
and the requests page are read as they change; only this per-thread
model/effort breakdown can be up to a minute behind.

Tests: TestCodexModelEffortHeldForAMinute holds the answer inside the
minute (no build, the old value), builds the change after it, and
builds for a new home at once. It fails with the check turned off by
hand ("inside the minute: builds 2 ... want 1"). The package's TestMain
sets effortFresh to 0, so every other test still sees a change at once.

Measured on a copy of the owner's real history, 12 poll cycles 15 s
apart after a warm start, origin/main a3d4f8c5c against this tree:
CodexModelEffort's allocation over the polls 754 MB -> 548 MB (Codex
was quieter in this window than in the 3.5-minute run above);
api/sessions 280 ms -> 237 ms mean.

Run at this tree: go test ./internal/usage/ ./internal/sessions/ ok;
./internal/cli ./internal/davsync ./internal/gui ./internal/middleware
./internal/otlp ./internal/tui ./internal/tune ./internal/usageapi ok;
gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui of usage
and sessions ok. Not run: internal/agent and internal/gateway, which
don't call CodexModelEffort.
2026-10-27 07:46:32 +08:00
yetone d03779cc10 usage: the Requests page's seen message ids are hashes, not copies
visibleLocal leaves out a Claude message written again in another file
(a resumed or forked session's copy). It kept every id it had seen as a
strings.Clone of the decoded chunk's string, so a long history's ~400k
ids were copied on each page build: ~7MB held at the start's peak and
27MB more allocated per run. It now keeps two maphash values of each id
(seeds made per process); two ids alike in both are ~1e-28 likely.

Measured with the real ~/.codex and ~/.claude histories (sandbox HOME,
fp3 harness), base bbb4fd478 vs this change, two alternating runs:
  visibleLocal allocated   81MB -> 55MB per run (the clones gone)
  footprint at the end     170 / 174MB -> 166 / 170MB
  footprint peak           275 / 278MB -> 252 / 277MB (noisy)

No test guarded the dedupe: breaking it by hand left ./internal/usage
green. TestVisibleLocalLeavesOutRepeatedMessages is new; with the
seen check turned off by hand it went red ("left out map[]").

Run at this head: gofmt clean; GOOS=linux and GOOS=windows go vet
-tags nogui ./internal/usage; go test -timeout 45m -count=1
./internal/usage ./internal/gui ok.
Not run: the full ./... suite (only internal/usage changed).
2026-10-27 04:58:22 +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 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 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