Commit Graph
10 Commits
Author SHA1 Message Date
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 32f5c33692 usage: a chunk without calls is read back from requests-v1.bin without a Latest, so a new version pairs its history on one start (#2278)
diskEntry wrote a chunk's Latest as c.Latest.UnixNano(). For a chunk
without calls Latest is the zero time, whose UnixNano is out of int64's
range and is written as another time; readDiskEntry read it back as a
call on 1969-12-31. heatSplit and effortSplit count a chunk with a zero
Latest as recent, but one read back so as settled, so the settled set
after a build (14426 chunks on the real history) differed from the one
after a read (15677). The key heat-v1.json and effort-v1.json were
written under on a new version's first start missed on its second, and
the whole history was paired again: two cold peaks, not one.

A zero Latest is now written as 0 and read back as the zero time.
Old data: requests-v1.bin is rewritten under the new binary (its key
holds requestDiskBinary()), so nothing old is read by the new reader.

Run:
- TestDiskEntryKeepsNoLatest round-trips a zero Latest and
  time.Unix(1790000100,5). Red on the old reader ("Latest 0001-01-01
  ... read back as 1969-12-31 16:00:00 -0800 PST"), green with the fix.
- Real history on mote (sandbox HOME, copy of the owner's sessions and
  requests): the first start wrote heat-v1.json and effort-v1.json, the
  second and third didn't rewrite them (both hit), and the heatmap's
  JSON had the same md5 on all three starts.
- Rebased onto 244d80e23; at the pushed tree on mote:
  go test -count=1 ./internal/usage ok (53.3s), gofmt clean,
  go vet -tags nogui ./internal/usage for windows ok (linux, darwin ok
  before the rebase, which touched no file of this commit).
Not tried: a full ./... suite.
2026-10-30 15:16:30 +08:00
yetone 8e1b1b26d0 usage: the request file's first write makes each entry on the last one's bytes (#2278)
After a cold start's first pages, nothing is held under GOGC 25 while
requestIndex.save writes requests-v1.bin, and the heap grew from 436 MB
to 764 MB before a collection, the footprint's peak. A heap profile
diffed from 13 s to 17 s gave save 444 MB of 465 MB allocated: each
entry grew its bytes from nil (appendDiskString 166 MB, the archive's
append 137 MB), and onDisk decoded every entry it had just written
with readDiskEntry, strings and all, to compare three fields (~95 MB).

Now toDisk hands diskEntry the last entry's bytes, onDisk reads the
size, mtime and archive with diskEntryArchive, which copies nothing,
and diskEntryPath gives bytes, looked up without a copy.

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.2112): phys_footprint_peak 835 / 863 / 860 MB,
  CPU 2:02.78–2:05.86
- after: 794 / 783 MB, CPU 2:01.55 / 2:01.12
- gctrace: between the first and second polls the heap now reaches
  499 MB (live 470), where it reached 764.

Tests at this head, through mote-run:
- go vet -tags nogui ./internal/usage/ ./internal/gui/, GOOS linux,
  windows and darwin: ok
- go test -timeout 45m ./internal/usage/: ok
- TestDiskEntryArchive (reads back what readDiskEntry reads, with zones
  and actors, and no cut entry) and TestDiskEntryAllocatesOnce: pass.
  With diskEntry's b set to nil again, TestDiskEntryAllocatesOnce is
  red: "an entry on the last one's bytes allocated 5 times".
2026-10-30 06:42:35 +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 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 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 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 42ab935516 usage: requests-v1.bin is of the code that makes rows, not of the binary
The file of the session files' chunks was named by the binary's own
stat key, so every upgrade, and magpie ships several a day, read every
session file again on its first Requests page: on a 15.6k-shard history
warm-up step 2 went from ~0.8-0.9s (read from the file) to 1.6-1.9s and
~1.3GB more allocation. It is named now by the call shards' version
(sessions.CallCacheVersion, which already decides whether a shard of the
calls is read) and a SHA-256 of this package's non-test source, which
the binary carries (go:embed *.go, ~750KB with the tests, which the name
leaves out). Of the last 99 releases, 17 changed that source; the other
82 keep the file. Prices, names and settings are in the file's meta as
before. When the embedded source can't be read the name is the binary's,
as it was.

Measured (real history, sbpairs): one test binary wrote the file, a
second binary at another path (the old key differs) read it: step 2
0.79s and 1001MB alloc, against 1.63s and 2285MB cold.

Run at this tree (89dc16476 + this change):
- go test -race -count=1 ./internal/usage: ok
- go test -count=1 ./internal/sessions ./internal/gui: ok
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage
  ./internal/sessions, and go build -tags nogui .: ok; gofmt -l clean
- TestRequestDiskNamesItsSource hashes the package's files from disk
  and wants the same name. Broken by hand (embed request_*.go only):
  red; restored: green.

Not tried: an upgrade of the real app from one release to the next.
2026-10-25 07:23:45 +08:00
yetone 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