Commit Graph
259 Commits
Author SHA1 Message Date
yetone f2eb56c6bb usage: a first start pairs the history a few weeks at a time, not at once (#2278)
With no sums on disk (a first install, or a version that counts rows
otherwise), the page's cells, the heatmap's days and Codex's effort
before the cut were built from one pairing of the whole history. Every
gateway block was priced, every session row's message id went into one
set, and every call into one match map. On the owner's history that
was ~212 MB of the warm-up's 341 MB in use and the cold start's peak.

coldSpans builds them as a day's start advances them (pageAdvance),
14 days at a time. A span pairs the chunks with a row from heatReach
before it to heatReach after. Each chunk's oldest row is kept by its
serial. A gateway block not priced yet is priced by a pricer of the
span alone, and its rows go back to the pool after the span. The
recent days are then paired as on any kept start.

The page's cells come out in another order (by span, then chunk), so
TestSettledCountedAsVersioned now sorts them before it hashes. The
sorted hash is the same for a pairing at once and in spans, so
settledCountVersion stays. Tests that count a pairing of every chunk
use pairAtOnce (coldSpan 0).

Run on mote at the pushed head (rebased on b62fa332f): gofmt -l
clean; go vet ./internal/usage for darwin, linux and windows ok;
go test -count=1 ./internal/usage ok (20.0s); go build . ok.
Broken by hand: TestFirstBuildPairsSpans goes red when a span pairs
only its own days (lo, hi := from, to): the effort differs.
Bench, real history (a year), cold first start, against v0.1.2256,
two rounds each, on mote at load ~22:
  no GUI polls:  footprint peak 451, 407 MB (2256: 493, 484);
                 live heap max 318, 289 MB (2256: 367, 362)
  GUI polls:     footprint peak 483, 410 MB (2256: 534, 532);
                 live heap max 316, 290 MB (2256: 395, 406)
The heatmap's answers are byte-equal to 2256's. The request page's
differ only in float digits from the summation order (232 floats,
largest relative difference 6.5e-14); every other value is equal.
Not tried: a start on Windows or Linux.
2026-10-31 03:13:28 +08:00
yetone f45c3c96b6 usage: a day's first start advances the kept sums from the last cut, not a pairing of all history (#2278)
The page's cells, the heatmap's days and Codex's effort before the last
days are kept on disk (page-v1.json, heat-v1.json, effort-v1.json) under
a key that names the cut, today minus two days at midnight. The cut moves
each midnight, so each user's first start of a day found none of them,
and paired the whole history again three times. On the 240k-row bench
history that peak was 506-538 MB, against 235-325 MB for a start of the
same day.

Each file now also holds the cut and since its sums were counted at.
When the current key misses, the file's sums still stand if the key at
their own cut is the same: the chunks are split again at that cut, named
as heatSettledKey names them, and compared with the file's key. Then
only the chunks of the days since that cut are paired. The rows between
the two cuts are added to the kept sums, and the sum is written under
the current key. The heatmap also drops days before a since that moved
forward a week. A full pairing is left for a first install, a raised
version, or a settled chunk that changed.

settled_version_test blanks a page's cut and since, as it blanks its key
and at. They say when the cells were counted, not how, so
settledCountVersion stays at 1. Files written before this commit have no
cut, so the first day change after the upgrade still pairs everything
once.

Run at 9cd9cfed0 (rebased on cfb06e11c), on mote:
- go test -count=1 ./internal/usage: ok (16.8s)
- GOOS=linux and GOOS=windows go vet ./internal/usage: ok
- gofmt -l internal/usage: clean

New tests (cut_advance_test.go): TestHeatmapDaysAdvanceACut,
TestPageCellsAdvanceACut and TestCodexEffortAdvancesACut. Each holds the
clock at Sunday 2026-10-04, then at Monday, and checks that every
pairing on Monday is below all chunks and that the result equals a cold
pairing. The heatmap test includes a call 368 days back that leaves the
window when the week turns.

Broken by hand:
- With the days between the cuts left out (all three), all three tests
  are red.
- With the advance turned off (all three), all three tests are red on
  the pairing count.

Real history (mote, ~/r2278: 240k gateway rows and the full session
history, window endpoints polled every 5s, clock moved one day by a
temporary build-only env that is not in this commit, caches restored
with cp -Rp each run):
- day change, advance off: peak 506, 518 MB
- day change, this commit: peak 418, 398 MB
- the same day: peak 325 MB
- /api/usage/heatmap and /api/usage/requests were byte-identical with
  the advance on and off.

Not tried: a real overnight day change on a user's machine. The cold
first-install peak (~480-538 MB) is unchanged by this commit.
2026-10-31 01:48:43 +08:00
yetone 62a1dcdd79 usage: a start's log blocks are of log-v1.bin's pages, not the heap (#2278)
logDiskRead read log-v1.bin whole with os.ReadFile, and the kept blocks'
Archives were slices of that copy, so a 240k-call history held ~7 MB of
file bytes in the heap for good. GOGC then let the heap grow by about as
much again. Where the system maps the file, the blocks are now of its
pages, the same way requests-v1.bin's blocks already are (diskMapping,
readMapped, m.read()). Elsewhere it is read into the heap as before.

Run at the pushed head, on mote, through mote-run:
- go vet ./internal/usage: ok. GOOS=linux and GOOS=windows go vet
  ./internal/usage: ok.
- go test ./internal/usage: ok. go test ./internal/usageapi: ok.
- New TestLogDiskBlocksMapped: 2 full blocks plus a tail are written,
  the log is restarted and read again, and each full block's Archive
  must be inside the mapping. Broken by hand (c.mapped = m dropped): red,
  "block 0: read from the file into the heap". Green again restored.
- go test ./internal/gui: FAIL on the AppKit window tests only
  (TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
  TestMainWindowCorners and 7 others), killed at their deadline on mote
  under load ~24. These are #4125 and #2645, and the same tests fail
  without this change.

Bench on mote, with the real 240k-row history: a warm restart while
the Sessions tab polls, and the heap profiled at 200 s.
- In use: 174.1 and 175.0 MB with this change, 187.6 MB without.
- Footprint at 200 s: 290 and 297 MB with it, 297 MB without. mote's
  load (~24) makes this ±20 MB, so the footprint gain is not resolved.

Not tried: Windows, where the file is still read into the heap.
2026-10-31 00:28:43 +08:00
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 fb3aef575b usage: settled days are kept across an upgrade that counts them the same (#2278)
The settled summaries (heat-v1.json, page-v1.json, effort-v1.json)
were keyed by requestDiskBinary, which hashes this package's source.
14 of the last 39 releases changed that source. After each of those
upgrades, every user's first start paired the whole history three
times (page, heatmap, Codex effort), and that is the cold start's
footprint peak.

heatSettledKey now names the counting by sessions.CallCacheVersion and
a new settledCountVersion constant. requests-v1.bin and the gateway
log's disk file still use requestDiskBinary, so a session file is
still read again after any source change. Only the pairing is kept.

TestSettledCountedAsVersioned is the guard. It runs a cold page,
heatmap and effort build over a fixed fixture in UTC: five Codex calls
with their gateway calls, cache reads, five efforts, an unmatched
Claude call with cache writes, and a 500. It hashes what the three
files keep, with keys and times stripped, and compares the hash with a
golden value. A change that counts a row differently fails it until
settledCountVersion and the golden are raised together. It guards only
what the fixture reaches.

Run on mote at this tree (rebased onto da3c5e0c0): gofmt clean; GOOS
linux, windows and darwin go vet of ./internal/usage/ and
./internal/usageapi/ ok; go test ./internal/usage/ ./internal/usageapi/
ok (17.2s, 0.8s); TestSettledCountedAsVersioned, *SettledFromDisk and
TestHeatSettledKeyNamesTheZone ok again under TZ=Pacific/Kiritimati.
TestSettledCountedAsVersioned also ok on Windows (win-run).

Broken by hand, each red: a page cell's n doubled in cellsBefore,
effort before the cut leaving out one row, and a heatmap day's tokens
leaving out CacheWrite. A doubled heatBefore tokens count stays green,
since it only goes into the key.

Real full history on mote (fullcold.sh, then a start with the caches
kept, by a binary whose internal/usage source differs by one comment
line):
  old key: cold peak 616 MB; upgraded start peak 591 MB, fp 377 MB at 240s
  new key: cold peak 626 MB; upgraded start peak 449 MB, fp 258 MB at 240s
One run each.

Not tried: an upgrade across a real release pair.
2026-10-30 20:46:59 +08:00
yetone da3c5e0c0f gateway: Claude Desktop's connection check is tagged as one on the Routing page (cybercaius on Discord)
Also: the check follows a Desktop model switch made after the last turn.

cybercaius (#help): with gpt-6.1-sol on AnyRouter chosen in the
conversation, the Routing page showed "Claude Desktop requested
deepseek/deepseek-flash" while the answer came from gpt-6.1-sol. The route
was right; the row was not explained.

Those rows are Desktop's own connection check ({"max_tokens":1, content
"."}, app.asar 2.7032 lWt/YT). Desktop names its model itself: the
shortest listed id with haiku, else sonnet, else opus, else the FIRST
listed model. magpie lists no Claude-named ids to it, so the check names
the first one (deepseek-flash), whatever the conversation is on, and
magpie sends it to the model chosen in Desktop's menu (desktopChosen).

- The check is recorded with kind connection_check (KindDesktopCheck,
  usage purposeKinds "Connection check", purposes.js regenerated). The
  Routing page tags the row "Connection check" next to the requested id
  and its story says the id is the one Desktop named from its list, not
  the conversation's model, and where magpie sent it. zh/zh-TW/ja/de.
  The requested id itself stays what Desktop sent.
- desktopChosen: a turn sent after cowork_account_settings.json was last
  written wins over the menus (newer of the two). Before, the last
  session's model came first whenever any menu still held it, so the Code
  tab switched off DeepSeek with Cowork left on it kept the check on
  DeepSeek. desktopPicked now carries when that turn was sent (the
  file's mtime once read).

The two 400s were AnyRouter's own (the reporter says so); not changed.

Run (at 0013f990c, this tree before its rebase on e0ad48641 and the
version stamp v0.1.2208 -> v0.1.2212 in comments/doc):
- mote: go test -tags nogui -timeout 45m -count=1 ./... : 81 ok, exit 0.
- mote: go vet ./internal/gateway ./internal/usage for darwin, linux
  (nogui) and windows: ok. gofmt clean. go generate ./internal/usage
  gives the same purposes.js as committed.
- GUI: routing-desktop-check (new; en, zh, zh-TW, ja, de), routing-kind,
  i18n-keys: chromium on mote ok; WebKit could not launch on mote (90+
  hung pw_run.sh launches from other sessions), so both engines ran on
  the Linux box (wsl-run): 14/14 ok.
- Whole GUI suite (wsl-run, concurrency 4) still running at push; reds
  so far are in account-arrange, account-models and agent-expand-steady,
  files this change does not reach. Checked against main after.
Broken by hand:
- call.Kind = KindDesktopCheck turned off: TestClaudeDesktopProbeAsksNoClassifier
  red ('recorded as kind "" (unmarked)').
- the connection_check story removed from client.js: routing-desktop-check red.
- old desktop.go: the new "Code tab switched off the last session's
  model" case red; the at.After check turned off: red too.
Not tried: a real Claude Desktop. Whether Desktop sends a check on each
model switch, and whether its composer switch writes the menu file, are
read from its bundle, not seen live. AnyRouter's 400s not looked into.
2026-10-30 20:32:25 +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 17c90b6f2f usage: pairFixture's chunks take serials of their own (#2278)
TestPairScratchKeepsNothingBetweenCalls was red after any test that
paired another pairFixture of other sizes first: both fixtures named
their chunks 100, 101, ..., so msgKeysOf, which keeps a chunk's message
keys by its serial, read the other fixture's ids for this one's chunks
and left 18 of 108 calls out as copies ("a first call matched 90 of
108"). It passed alone and in the package's full order, so it showed
only under a -run of the pairing tests.

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 (serials 1 and 100+f again): that -run is red,
TestPairScratchKeepsNothingBetweenCalls "a first call matched 90 of 108".
2026-10-30 20:21:52 +08:00
yetoneandYangHonghang 9e73f69af4 providers: rate windows bill a provider's hours at its own rate (#2463)
A provider can have up to 8 rate windows: days, a span that may cross
midnight (on this computer's clock), and a rate. Inside a window a call
costs the base price times the rate. The base is the user's model price
as set, or the list price times PriceRate with the vendor's own peak
(DeepSeek, Command Code, OpenCode Go) already in it. The author gave
this order as the spec: a 0.8 window on a shared DeepSeek key takes 0.8
off the peak price at peak. The editor's hint says not to set the
official peak hours again as a window, in every language.

Each call is priced at its own time on the Usage page and its CSV, in
the Requests tab's rows, and against a gateway key's cost limit. The
Sessions page, group templates and the model list written into an
agent's own config use the base price. /v1/models prices at now.

Ported from YangHonghang's 2c9d459ff (rate-windows-2463-v2). The Go
pricing, its tests and the translations are theirs. Changed here:
- No budget raised. Their commit raised appScriptBudget and
  coreScriptBudget; core_budget_test.go is main's again. The editor's
  window rows, time menus, validation and hint moved to ratewindows.js,
  which app.js imports when the field is drawn (as signsheets.js is).
  The sliding-thumb and modalDepth comments were cut down to make room.
  The core is 1,535,528 of 1,536,586 and app.js 1,312,242 of 1,315,316.
  Until the script has loaded, a save leaves rateWindows out, and the
  server keeps the saved ones.
- Their unrelated TestAssetsHaveNoConflictMarkers is dropped (one
  commit, one goal).
- The row badge shows only for a provider with windows. Before, every
  provider with a price rate alone got a new ×badge. Its title is
  shorter, and so are its translations.
- AgentPricer (agent model files: Pi, omp, OpenCode cost) uses the base
  price. Nothing rewrites those files when a window opens or closes, so
  a price taken at Sync stayed on outside the window.
- internal/budget gets a TestMain through testenv, so the new test
  runs in a home of its own.
- old-webkit's list of lazily loaded scripts names ratewindows.js.
- The draft keeps each window as a shallow copy, and a day chip
  replaces its days array, so the saved provider is never changed.
- The GUI test waits for the lazy script's hint, not a fixed 300ms.
  It also checks the peak note in each language.

Run first on 2f5a3f1c0, then again after rebasing on 70d9996c5,
8acb0d3a7 and d609729cf. The rebase onto 70d9996c5 met main's ruleedit.js in
old-webkit's list, and both are listed.
- gofmt -l internal: clean at 8acb0d3a7 (129578c3d gofmt'd main's
  pi_api_test.go).
- mote, on 8acb0d3a7: go vet on usage, provider and gui
  ok; GOOS=linux and GOOS=windows go vet -tags nogui ./... ok.
  go test -tags nogui for internal/usage, provider, gui, budget and
  sessions: ok. The five internal/agent tests that are red on WSL
  (below) pass on mote there. On d609729cf (a one-line mover min in
  internal/provider), internal/provider again: ok.
- On 2f5a3f1c0: internal/provider, usage, budget and sessions, and the
  gui RateNow|PriceRate|CoreScript|Budget tests, each under TZ=UTC,
  Asia/Shanghai and America/Los_Angeles: all ok.
- wsl-run (magpie-desktop, Playwright chromium and webkit) on
  70d9996c5: provider-rate-windows, old-webkit, i18n-keys,
  provider-price-rate, provider-advanced-fold, agent-hides-editor,
  key-box-once, provider-many-keys, nokey-editor and
  editor-short-window: 200/200. On 2f5a3f1c0 the first five and
  model-price-edit: 132/132. On mote the same files hit WebKit launch
  timeouts (180s) under another session's full GUI suite (load 30), and
  that run was stopped.
- Full suite, wsl-run (mote was running another session's full suite),
  go test -tags nogui -count=1 -timeout 45m ./... at 6e534f546 (this
  change on 70d9996c5): every package ok except internal/agent.
  internal/agent fails TestInstalledVersion, TestGrokInstalled,
  TestCursorFolderFromTheEditorIsNotTheCLI, TestOmpDetectedWithPiDir
  and TestZedAppPath. This change doesn't touch internal/agent. At
  origin/main 8acb0d3a7 on the same box, TestInstalledVersion,
  TestGrokInstalled and TestOmpDetectedWithPiDir fail too: a fake CLI
  in /tmp exec'd with "Invalid argument". That is #4033 and #3548
  (WSL2 binfmt interop).
- Broken by hand, red each time:
  - Pricer without the window: TestPricerRateWindows,
    TestBlockRowsTakeTheirRateWindow, TestCostLimitCountsTheRateWindow.
  - Block rows without atWindow: TestBlockRowsTakeTheirRateWindow.
  - AgentPricer at now: TestAgentPricerLeavesTheRateWindowOut.
  - Badge for a price rate alone: TestRateNowOf.
  - Peak note removed: provider-rate-windows, 10 of 10 chromium
    layouts.
  - ratewindows.js not in old-webkit's list: old-webkit.

Not tried:
- A real relay billed by the hour.
- The real desktop app (WebKitGTK, WKWebView).
- The full GUI suite (mote was running another session's).
Known limits:
- No rate is stored per record, so changing the windows reprices
  history, as a changed PriceRate does.
- Windows follow this computer's zone, with no zone of their own.
- The Sessions page uses the base price.

Co-authored-by: YangHonghang <honghang.yang@qq.com>
2026-10-30 18:55:51 +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 8974836679 usage: a chunk's rows before the heatmap's cut are counted once, not on every read (#2278)
heatBefore summed the recent chunks' rows before the cut for heatSplit,
pageSplit and effortSplit, unpacking every recent chunk whole each time.
A long-lived session file is recent for weeks (one of the owner's Claude
sessions holds 57k calls), so each recompute of the Usage page while an
agent works unpacked ~200k rows three times. A named chunk's sum is now
kept by its serial and the cut, and dropped after hintsKept reads that
didn't ask for it, as hintsOf keeps a chunk's hints.

Run on mote at this tree:
- go test ./internal/usage ./internal/usageapi: ok
- GOOS=linux|windows|darwin go vet -tags nogui ./internal/usage: ok
- TestHeatBeforeKeptBySerial: sums equal a count of every chunk, a named
  chunk is unpacked once per cut, an unnamed one every time.
  Broken by hand (a kept sum used whatever its cut): red; restored, green.
- A debug build on a copy of the real history logged each call: the
  first reads of a start (concurrent) unpacked 766 non-empty chunks
  (207k rows) each; the next read unpacked none of them.
- Cold start bench, 120s of polls: fp_peak 321MB vs 309MB before, 103 vs
  96 GCs: no change outside noise, since polls answered 304 recompute
  nothing. A bench appending a call every 3s was too noisy on mote
  (load ~20 from other work) to show a difference either way.

Not tried: the GUI suite (no GUI file changed).
2026-10-30 17:42:08 +08:00
yetone 8f0d21a009 usage: a start reads the gateway log's full blocks from log-v1.bin, not the whole log again (#2278)
Every start parsed the whole of usage.jsonl with json.Unmarshal a line at
a time. On the owner's real history (109 MB) that was 622 MB of the first
18s's 1765 MB allocated, and most of the GC work of a cold start.

The full blocks the log index freezes are now kept in log-v1.bin beside
the sessions cache, with where they end in the log (offset, line count),
the SHA-256 of the log up to there and the hasher's state, first/firstOwn,
the provider keys and hosts seen, and the probe rows before that offset.
A start reads them and parses only the lines after. They stand only
while the log's bytes up to the offset hash the same and the code that
reads them is the same (requestDiskBinary); otherwise the whole log is
parsed as before. The file is written through a temp file and a rename,
at most every 10 minutes and only when it gains blocks.

Run on mote at this tree, rebased on origin/main:
- go test ./internal/usage ./internal/usageapi: ok
- GOOS=linux|windows|darwin go vet -tags nogui ./internal/usage: ok
- TestStartReadsKeptLogBlocks: a second start loads the kept blocks, and
  rows, probes, keys, hosts and hash equal a whole parse; a log edited
  before the offset is parsed whole.
- Broken by hand: accepting the kept blocks without resumeLogHash turns
  TestStartReadsKeptLogBlocks red (hash differs); restored, green.
- Bench on a copy of the real history (~/r2278, 109 MB log), cold start
  polled 120s, second start of each binary (caches hit):
  v0.1.2184: peaklive 217MB fp_peak 307MB, 156 GCs
  this:      peaklive 210MB fp_peak 315MB,  98 GCs
  readLogSnapshot alloc_space 622MB -> 8.6MB; total 1765MB -> 1095MB.
  The first start writes log-v1.bin (7.4 MB).

Not tried: the GUI suite (no GUI file changed); Windows and Linux runs of
the package (vet only).
2026-10-30 17:10:26 +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 0414bbeddb usage: page-v1.json holds eight pages and moves one read near its end first, so a reader's filters don't drop the warm-up's (#2278)
page-v1.json held four pages, newest written first, and a page read
from it was never moved. The warm-up's All, the Usage page's period,
the tray's periods and a few filters a reader picks are more than four,
so the warm-up's was dropped and every start after paired the whole
history again (the 587 MB start). Seen on the real history: after five
pg.sh pages the next start missed. It holds eight now, and a page read
from the second half is written again first.

Real history on mote (~/r2278), with the previous commit: a start
after the five pages hit (fp_peak 356 MB, peaklive 266 MB).

Test: TestPageReadAgainStaysOnDisk (the warm-up's page last of eight,
read, then one more page written: the next start still reads it).
Broken by hand (no move): red, "read again, then another page written".

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
Not run: the full suite. internal/gui's AppKit tests time out on mote
(#4125); this change is internal/usage only.

Rebased on 6d154ef1e (with the commit before this); go test
./internal/usage ./internal/usageapi and the three vets ran again at this
head: ok.
2026-10-30 16:15:28 +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 6d154ef1e1 context: scripts (curl, Bun, python-httpx…) are one Scripts card, not an agent each
A request whose User-Agent names only an HTTP library or an SDK (curl,
Bun, node-fetch, undici, python-httpx, requests, aiohttp, Go-http-client,
okhttp, the OpenAI/Anthropic SDKs, …) or nothing at all got a Context
scorecard of its own, as if it were an agent (theforeveriris on X: "Bun",
"curl", "python-httpx" cards). usage.IsLibrary names those clients;
contextOfRecs folds them and "other" into one "Scripts" card at read
time, so older history reads the same way, and the card's meta line and
tooltip list the libraries by count. The cached day records are not
changed. No setting: it works as is. The Usage page's Agents list still
shows each library by name, with its Hide and Count-as-agent controls.
i18n for zh, zh-TW, ja, de. Existing context.js comments were condensed
so TestCoreScriptBudget holds without a raise (core scripts -28 bytes).

Run, at this head (rebased on 40af66027):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  (mote) for usage and gui; earlier the whole tree on all three, exit 0.
- mote: go test -count=1 -tags nogui -timeout 45m ./internal/usage
  ./internal/gui: ok, ok.
- Windows box: context-scripts + i18n-keys 26/26 (chromium, webkit,
  5 languages, 360 and 1100px). Before the rebase, every reachable file
  (context-*, compact-one-value, group-context, routing-context-fold,
  routing-ctx-fold, routing-ctx-still, i18n-keys, gui-de/ja/zh-tw,
  header-relang): 333/349; the 16 reds are routing-ctx-still, red the
  same on origin/main 40af66027 on that box, listed in #4124.
Broken by hand: IsLibrary false and no fold -> TestIsLibrary and
TestContextScriptsAreOneCard red (cards python-httpx, claude, Bun, ...);
the JS label/clients removed -> context-scripts.test.cjs 0/22.
Not tried: a real app run with real curl/Bun traffic; Linux WebKitGTK;
GUI files on mote (its browsers were busy with another suite).
2026-10-30 16:05:58 +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 643b525469 usage: a DeepSeek call at peak hours costs double its off-peak list price
treeMan on Discord: DeepSeek bills off-peak at half the peak rate, and the
Usage page didn't follow it. The catalog's list prices for these models
are already the off-peak ones: models.dev's DeepSeek, Command Code and
OpenCode Go entries give the off-peak rate as the price and a factor-2
multiplier for peak hours, and api.json leaves the multiplier out
(deepseek-flash: $0.15/$0.60/$0.003, DeepSeek's page says $0.30/$1.20/
$0.006 at peak). So every peak call was counted at half its cost. Now a
call made from 01:00 to 04:00 or 06:00 to 10:00 UTC, Monday to Friday,
costs twice the list price. The call's own timestamp decides.

Which providers (provider.PeakOf, by base URL, or by preset/id only for a
provider with no URL, such as a plugin's or a removed one):
- DeepSeek's API (api.deepseek.com), every model, except on Chinese
  public holidays (catalog.PeakDeepSeek);
- Command Code (api.commandcode.ai, the commandcode preset and the
  commandcode-plan plugin): deepseek-v4.1-flash, -v4.1-flash-fast,
  -v4-flash, -v4-flash-vision-exp and -v4-pro, every weekday, since its
  docs name no holiday. deepseek-v4-flash-fast is one price at every hour;
- OpenCode Go (opencode.ai/zen/go): deepseek-v4.1-flash and
  deepseek-v4-pro, every weekday.
Unchanged: OpenCode Zen (a flat $0.30/$1.20), ZenMux, Cline Pass,
OrcaRouter and every other relay, a price the user set (ModelPrices
returns before a Peak is set), a "same as" price and every other model.
The provider's price rate still applies.

Holidays: catalog.cnHolidays has 2026 from the State Council's notice
(2025-11-04). TestCNHolidaysCoverThisYear fails on 2027-01-01 unless that
year's notice, due in November, is added. A year missing from the table
counts no holidays.

Where the hour is applied (catalog.Price.In): Record.CostAt (Usage's
totals and groups), the packed gateway blocks (priceBlock), OTLP's
exported cost and budget's estimate (now). The Sessions page sums per
model without per-call times and stays at the list price. The model
editor's price box says when a list price counts double (four languages;
app.js kept under its budget by shortening, not by a raise).

Run at the tree pushed (parent 32f5c3369), on mote:
- gofmt -l clean
- go vet on the six packages
- go test of catalog, usage and otlp whole, and provider and gui -run
  Peak|PriceIn|CNHolidays|Price|TestCoreScriptBudget, with TZ=UTC and
  with TZ=Asia/Shanghai: all ok
At 76b18f68d (the same change before the last two rebases), on mote:
- go vet ./internal/..., GOOS=linux -tags nogui and GOOS=windows vet of
  ./..., and the darwin, linux nogui and windows builds: ok
- catalog, provider, usage and otlp whole, in both zones: ok
- internal/gui: TestCoreScriptBudget was red (app.js 108 bytes over),
  fixed by shortening the hint. Ten AppKit window tests were killed at
  their 30s bar at load ~130 (TestDockJoinLeadsCommandTab,
  TestMainWindowCorners and others); this change doesn't touch them.
GUI:
- model-price-edit (now checks both peak hints and none on a plain list
  price), model-price-tiers, provider-price-rate and i18n-keys: Chromium
  ok on mote.
- WebKit on mote couldn't launch at all (browserType.launch timed out at
  180s, 69 WebKit processes from other runs), so the three price files ran
  in WebKit on Linux (wsl-run): 8 of 8 ok.
- The whole GUI suite (both engines) at ff23724f3 was still running at
  load 110 to 150 when this was pushed, 119 red of ~7200. Every file
  checked so far is a timeout under load or in #4304 / #3476.
  model-chip-steady is red the same way on origin/main 0911a65e7.

Broken by hand, each red:
- CostAt without .In(r.Time): TestCostAtTheCallsHour (0.753 at peak,
  want 1.506)
- priceBlock without .In(p.Time): its block half
- Peak.At ignoring holidays: TestPeakHours on 2026-10-05
- priceOf never setting Peak: TestPriceOfPeak
- OpenCode Go's model list dropped: TestPeakOf (kimi-k3 "weekdays")

Not tried: a real call to DeepSeek, Command Code or OpenCode Go at peak
and off-peak to compare against their bills; a full go test ./...; the
holiday rule's handling of the swapped working weekends (DeepSeek says
Monday to Friday, so a worked Saturday stays off-peak here); ZenMux,
whose own docs give no schedule.
2026-10-30 15:22:55 +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 1bbaded622 usage: an agent's call to magpie's own MCP tools is a row of Requests
ferock (Discord) asked to see calls to magpie's MCP tools, such as
magpie-image's generate_image, generate_video and generation_result, in
Routing > Requests.

Each tools/call to magpie's own MCP servers (image, vision, web search,
tools and the Library hub) is now a row of the request log. The row has
Source and Kind "mcp", the tool as its model, the server as its host,
how long the call took, and its error if it failed. The provider and
model it shows are those of the model requests the call made, collected
through the request's context in appendUsage. generation_result names
the model of the job it answers. The stdio Magpie Image server reports
each call it answered to the gateway as "magpie/toolCalled". That report
carries the tool, ms, model and error, never the prompt.

The arguments are never stored at all, so there is nothing to mask. The
rows go down the probe lane: they are listed, but no total, host list,
budget or key limit counts them. The model requests a call made are rows
of their own.

In the GUI the row reuses the Requests list. It gets a muted "MCP" badge
with a tooltip, the server beside the provider, and a Succeeded/Failed
status. The Purpose filter gains "MCP tool" in every language. There is
no new page, no <select> and no left border.

The core scripts went over their budget with the new purpose.
genpurposes now writes purposes.js as compact JSON, which makes the core
448 bytes smaller than main in all, and coreScriptBudget is lowered to
the new total, 1,538,975. No room is added.

Run on mote, at the rebased head:
- gofmt -l: clean. go vet -tags nogui ./... with GOOS darwin, linux
  and windows: ok.
- go test -tags nogui -timeout 45m: ./internal/usage, ./internal/imagemcp,
  ./internal/usageapi and ./internal/gui ok. internal/budget has no test
  files. ./internal/gateway (805s): every test ok except five Antigravity
  and Codex/Grok tests. They fail the same on a clean origin/main
  3bebc3839 and are filed as #4362.
- GUI, the usage-ledger*, routing-request*, purpose*, i18n* and
  gui-zh/ja/de files (25). On mote, Chromium: 32 of 32 ok; WebKit
  could not launch (10 other sessions' suites on mote). On Linux
  (wsl-run), both engines: 335 of 355 ok. The 20 reds are
  routing-request-model, usage-ledger, -ttft, -chart and
  -open-settled, which fail the same at the parent 1534474c8 (#4120).
  usage-ledger-mcp, purpose-filter and i18n-keys are ok in both.
  The whole GUI suite runs after the push, and each red it finds gets
  an issue.
- At the pushed head, rebased on 0804f2d97: ./internal/gui (the
  budget and purpose asset tests among them), ./internal/usage,
  ./internal/imagemcp and ./internal/usageapi ok, and ./internal/gateway
  -run "MCP|Purpose|Probe" ok.
- usage-ledger-mcp.test.cjs covers 5 languages, widths 1180 and 420,
  light and dark, with no sideways scroll.

Broken by hand. Each break went red:
- sawHost's MCP skip removed: TestMCPCallRowsListedNotCounted (the hosts
  list had magpie-image).
- Row/Record.IsProbe's MCP case removed: the same test (3 calls counted),
  and TestMCPCallCountsInNoKeyLimit (Calls: 1).
- The callMCPTool hook removed: TestMCPToolCallIsARequestRow and its
  siblings (no rows).
- The appendUsage hook removed: the row had no provider or model.
- imagemcp's report removed: TestToolCallsAreReported.
- The gateway's magpie/toolCalled case removed:
  TestMCPCalledFromStdioIsARow.
budget's in-memory counts() now skips these rows too. Breaking only that
stays green, because budget.Of reads the file through usage.Visit, which
already skips probes, and limits count tokens and cost.

Not tried:
- no real agent calling a real vendor's drawing;
- no test run on Windows or Linux;
- the page not checked in the real app or in WebKitGTK.
A generate call that answers while its drawing still runs has no model on
its row. The generation_result row that follows names it.
2026-10-30 15:00:16 +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 ceef9e9438 usage: the heatmap's settled-days key names the filter's zone, not its pointer (#2278)
8d4c07ffe (v0.1.2156) named the heatmap's settled days with %#v of the
Filter, and the page's filter carries Zone, a *time.Location: %#v
writes its address, another in each run. So heat-v1.json never matched
on a start and every start paired the whole history for the heatmap
again, the cost 8d4c07ffe was to take away. Its bench start matched by
chance.

The zone is now written by its name, the rest of the filter as before.

Found with a key-parts log on mote (~/r2278/full): two starts of one
binary wrote headers differing only in Zone:(*time.Location)(0x1089b81e0)
vs (0x105d8c1e0). After the fix three starts of a build with it: the
first (new binary) and second wrote heat-v1.json, the third read it,
and its heap at 18 s has no heatSplit (was 83 to 95 MB in each start
before).

TestHeatSettledKeyNamesTheZone: two FixedZone("Z", 3600) give one key,
nil or another zone a different one. Red at 8d4c07ffe's heat_disk.go
("one zone, two keys"), green here.

Run at this tree, cherry-picked onto d05482bab (mote; first
run on c28cc5c87 the same): go test -count=1 ./internal/usage ok (16.4s); gofmt -l clean; go vet -tags
nogui ./internal/usage for linux, windows, darwin ok.
2026-10-30 14:39:22 +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 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 442897f414 gateway: masking time is kept when magpie's own time is unknown
A masked request's "Masking" part on the Routing page comes from
Route.Masking, which maskingMs capped at Own, magpie's own time before
the request went out. Own is known only when magpie's client wrote the
request and a first token came back, so a request that was masked but
went through a plugin, through Claude Code for a Claude subscription,
failed, or had no first token had its masking time dropped to 0, and
the page showed nothing for it (Discord, lute: some requests show the
masking and model time and some don't). The Codex backend path never
set it at all.

maskingMs now keeps all of the masking time when Own is unknown, and
still caps it at Own when Own is known. The Codex backend path sets it
on its route and its usage record. The usage page still shows Masking
only beside a known Own, as before.

Run (mote, go1.26.8):
- TestMaskingTimeKeptWhenOwnIsUnknown (a masked request the vendor
  refuses): red on the old redact_phase.go ("masking 0 ms, held
  120ms"), green with it.
- TestCodexOwnSignInKeepsItsMaskingTime: red without the codex
  backend lines ("route's masking 0 ms, held 120ms"), green with them.
- TestMaskingIsAPhaseWithItsTime, TestNoMaskingNoMaskingTime: ok.
- go test ./internal/gateway ./internal/usage -count=1 -timeout 45m with
  this and the next commit: ok (gateway 502s, usage 16s).
- go vet ./internal/gateway ./internal/usage for darwin, linux
  (-tags nogui), windows: ok. gofmt -l: clean.
2026-10-30 01:54:40 +08:00
yetone c201fe2266 usage: Codex's auto-review through a ChatGPT sign-in costs nothing (silverzhou)
silverzhou (Discord): codex-auto-review has been free for a long time,
but magpie still estimates a cost for it. OpenAI's Codex lead
(thsottiaux, "Day 2.1"): "We have made Auto-review free for all users
signed in through a ChatGPT account."

provider.ListPrice now prices codex-auto-review at $0 on the "codex"
provider, the one that holds only ChatGPT sign-ins, unless that sign-in
is on the Free plan: cybercaius measured auto-review spending the Free
allowance, which is why the gateway's freeOnChatGPT already left Free
out. That rule now has one owner, provider.ChatGPTReviewFree, and
freeOnChatGPT calls it. The plan is read from Codex's current sign-in;
an unreadable plan or a Codex signed out since counts as a paid plan
(priceOf's unknown-model branch answers $0 for it too).

Still priced, since nothing says those are free: codex-auto-review sent
with an API key (openai, chatgpt-api), through a relay, or a review
magpie made follow the session's model (the row's served model is that
model). A price the user set for the model wins over the $0.
PricedNameFor names the model itself, so the Requests list no longer
says "priced as gpt-5.6-luna". The usage summary cache key carries the
Codex plan, so a plan change re-prices cached views.

Old rows: prices are applied when the log is read, so every past
codex-auto-review row through a ChatGPT sign-in reads $0 after the
upgrade: Usage's Overview and Requests, the tray, the ledger and key
limits' estimated-cost caps (their in-memory sums are rebuilt at start).
Nothing is rewritten on disk.

Left alone: a Codex window's holds (apiPricer) still count these calls,
filed as #4181. docs/subsystems/providers-accounts.md has the rule.

Run at this tree (rebased on 033b17baf):
- mote-run: TestAutoReviewFreeOnChatGPTSignIn (provider) and
  TestAutoReviewFreeOnChatGPT (usage: ledger, Summarize, ledger sum,
  NewCoster), the KimiCode, CodexSignInPlan and gateway Review tests: ok.
- Red on the old code: both new tests fail with the code changes taken
  out (codex priced at luna, $0.234; summary 0.992 vs 0.758; key limit
  0.134).
- Broken by hand: dropping the plan check or the provider check turns
  the Free-plan and relay/openai assertions red in both tests.
- go vet on mote, and GOOS=linux and GOOS=windows; gofmt -l clean.
- At the rebased head, mote-run go test ./internal/provider
  ./internal/usage ./internal/usageapi ./internal/gateway: all ok (gateway 1883s, provider 846s,
  usage 158s, usageapi 4s); gofmt -l clean.
- Full suite: a mote run at the pre-rebase head reached two packages (ok)
  and then died (exit 144) when the touched-package run re-synced the
  same mote copy, at load ~340 with five other full suites; per the owner's
  ship-at-once rule it is run again after the push.
Not tried: a real auto-review row (none in ~/.codex/sessions or the
real usage log); a multi-account Codex with mixed plans (the live
sign-in's plan decides); the summary cache's plan key was not broken by
hand.
2026-10-29 16:11:26 +08:00
yetoneandggbdpq 3142a55594 usage: the fine-clock hash test times each read from the append's stamp, not the wall clock (#3511)
TestUsageReadAfterAppendHashesNothingOnAFineClock/whole-second_stamp was
red on CI on macOS and ubuntu at f02390544 (run 40802792343), and 2 to 3
of 20 with -count=20 on the Mac mini. It truncated the log's change time
to whole seconds and read at time.Now()+150ms, expecting every read to
fall inside the stamp's 1s settle. An append at x.86s or later has stamp
x.0 and its read at x+1.01s is past it, so the snapshot counted as
settled and nothing was hashed. Under load (#3551, WSL) the read's
time.Now() drifts later the same way.

The reader is right, not a bug: settledLogStamp takes the read's time
before the stat and calls a whole-second stamp c settled only when the
read is past c+1s. Any write at or after that read has a stamp of c+1s
or later, so an equal stamp can't hide a later write on a filesystem
with 1s mtimes. The test's assumption was wrong.

Each read is now stamp + tc.after, the stamp taken from the history log
and then from each append's stat (the one the fine case already took for
its skip). No wall clock is read on the path. A third case pins the
other side: a whole-second stamp read 1.15s later (the next second)
hashes nothing. ggbdpq's patch on #3511 proposed the same stamp-relative
read.

Run (mote = Mac mini, via mote-run; base f02390544):
- Old test, wall clock injected at x.95 of its second (logIndexNow =
  time.Now().Truncate(1s)+950ms+150ms), -count=10: 10 of 10 red with
  CI's "0 bytes hashed over 5 appends".
- New test, -count=50 -v: 150 of 150 subtests pass.
- Broken by hand: logStampSettle = 100ms turns whole-second_stamp red
  (3/3); logStampSettle = 2s turns the next-second case red (3/3, 54MB
  hashed). The next-second case first used logStampSettle+150ms and
  stayed green under the 2s break, so it is pinned to time.Second.
- mote: go vet ./internal/usage; -count=50 of the test; go test
  -count=1 -timeout 45m ./internal/usage/...: ok.
- Linux (wsl-run, magpie-desktop): go test ./internal/usage/...: ok.
- Windows (win-run, xiaomi-gpu): the three subtests pass (-count=3);
  the package is red only on TestDesktopSessionAccountMetadata ("Code
  tab account mapping"), which fails the same at untouched f02390544
  and is #1356.
- gofmt -l internal/usage: clean.

Not tried: a real filesystem with whole-second mtimes (HFS+/FAT); the
test fakes the truncation through logChangeTime as before.

Issues: #3511, #3551 (its duplicate)

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-29 10:13:06 +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 c93d9e0c0b usage: an unchanged Codex effort ask is told the kept answer, not a copy (#2278)
CodexModelEffort copied every thread's consumption for each ask
(cloneEffort), though the kept answer is only replaced by a later build,
never written, and its callers (the Sessions list, overview and a
session's details) only index it and copy their thread's slice
(addCodexModelEffort, addCodexSummaryModelEffort). On the #2278 bench
(15G .codex) the copies were ~230 MB allocated every 80 s of an open
Sessions page. Asks are now told the kept map itself; the doc comment
says it is read-only.

TestCodexModelEffortReadsLedgerOnlyWhenCallsChange wrote into the answer
to check a caller's copy was its own. That guarantee is now the GUI's:
TestCodexModelEffortCopiedPerSession checks a session and a summary get
their own slice. TestCodexModelEffortAsksShareTheKeptAnswer checks two
unchanged asks get the same map.

Run at this tree on mote (macOS 27, Go 1.26.8):
- go test -count=1 ./internal/usage ./internal/sessions ./internal/gui:
  usage ok, sessions ok; gui red only in TestMainWindowCorners/
  macOS_26_SDK, which is #3949 (filed, red on macOS 27 on main).
- GOOS=linux,windows,darwin go vet -tags nogui ./internal/usage
  ./internal/gui: ok.
Broken by hand: maps.Clone back in the kept-answer return makes
TestCodexModelEffortAsksShareTheKeptAnswer red ("told a copy"); dropping
the GUI's slices.Clone makes TestCodexModelEffortCopiedPerSession red
("written through a session's copy: 999").
Not run: the full ./... suite, and the bench A/B (the 230 MB is from the
v0.1.1967 heap profile, not yet re-measured).
2026-10-29 06:30:58 +08:00
yetone 2b6ff0fbf9 usage: the gateway's sessions count only the log's blocks since the last
The gateway's projection of all time (gatewayProjection) was built
again from every call in the log whenever the log grew, every poll with
calls coming in: buildGatewaySessions was ~8% of CPU on the #2278 bench.
It is now counted on from the sessions its full blocks counted, which
never change: a session the new blocks touch is copied from the prefix
and counted on, the rest are reused as they are, and the list is sorted
again. The prefix is kept per price meta (usagePriceCacheKey, which
holds aliases and clients) and zone, and dropped when the log is read
afresh. Ranges and native exclusions still read out of the projection,
and buildGatewaySessions stays for a since.

finishGatewayModels now sorts a session's models before it sums their
cost, so the sum has one order however the models were gathered (it
was map order before).

TestGatewaySessionsCountedOnAreCountedAfresh DeepEquals every session
counted on with buildGatewaySessions afresh, after appends over a
block's edge, a new session and a call older than the rest, a zone
change and the log written over, and checks it was counted on. Broken
by hand (a prefix session's days dropped): red at "first".

Run at this tree on mote: go test -count=1 ./internal/usage/...
./internal/usageapi/... ./internal/tui/... ok; ./internal/gui/ red only
on TestMainWindowCorners/macOS_26_SDK (#3949, open); GOOS=linux,windows,
darwin go vet -tags nogui ./internal/usage/... ./internal/gui/ ok.

The #2278 bench on mote (15G .codex, 10 endpoints polled every 5s, 4
calls/s appended, 240s), v0.1.1966 then this tree, back to back:
- CPU profile 60s: 24.17s -> 20.83s samples; buildGatewaySessions
  (1.07s) and buildVias (0.79s) gone
- poll mean 0.57s -> 0.51s; /api/sessions 1.47 -> 1.04s, overview 0.93
  -> 0.63s, stats 0.49-0.52 -> 0.26-0.32s, heatmap 1.48 -> 1.19s
- cpu after feed 43.6% -> 41.7%; RSS peak 982 -> 1125 MiB, footprint
  peak 742.5 -> 744.1M (the cold-start peak swings run to run; not this)
Not tried: a real account's log (the bench log is generated).

Refs #2278
2026-10-29 06:21:46 +08:00
yetone 2be04305fd usage: a session's model lists count only the log's blocks since the last
The whole log's model lists (cachedVias) were counted again from every
call in the log whenever it grew, which with calls coming in is every
poll: buildVias was ~3% of CPU on the #2278 bench. They are now counted
on from what the log's full blocks counted, which never change, and only
the blocks after are counted again. A session's counts are copied from
the prefix before they are added to, so the prefix is never written.
Rows are counted in the log's order either way.

The prefix is kept for the same clients and renames key as the lists,
and is dropped when the log is read afresh (its blocks differ). Window
lists (a since) are built as before.

TestViasCountedOnAreCountedAfresh DeepEquals the lists counted on with
buildVias afresh, after appends over a block's edge, a new session and
model, and the log written over, and checks that lists were counted on.
Broken by hand (a prefix session's list cut in half): red at "first".

Run at the next commit's tree (this one plus the gateway projection's
fold, in other files): go test ./internal/usage/... ./internal/usageapi/...
./internal/tui/... ok; ./internal/gui/ red only on TestMainWindowCorners
(#3949); GOOS=linux,windows,darwin go vet -tags nogui ./internal/usage/...
./internal/gui/ ok. Bench numbers are in the next commit.

Refs #2278
2026-10-29 06:21:46 +08:00
yetone 28c89afcef usage: a period's summary counts only the log's blocks since the last
Each call the gateway logged changed the log's version, and every
/api/usage ask for Week or Month counted the whole period again: on
the #2278 bench (a busy gateway, 4 calls a second, the GUI's polls every
5 s) topSummary was 11% of CPU, beside GC at ~30%.

A period's summary now keeps what it counted over the log's full blocks
(512 rows each, never written again once full) and counts only the
blocks since, then the last block. It counts afresh when anything a
count depends on changed: a block it counted was replaced, a rewrite,
prices or names (meta), cleared calls, the period's bounds or series, or
the keying (hosts, accounts, keyed providers) changed. In the last case
an account that newly answers for a provider splits that provider's
earlier calls too. Rows are counted in the same order as before, so
every float comes out bit-identical. The group maps are copy-on-write
over the kept prefix, and only what was touched is copied.

Run at this tree, 213a31b4d before this message (the parent is origin/main 7795f5573, no rebase):
- New TestSummaryCountedOnIsCountedAfresh. Over 3*512+100 rows, for
  Today, Week, Month and All, it DeepEquals the folded summary against
  summarizeFrom: after appends across a block edge, a new host, an
  account newly answering for openai, another block, and a log written
  over. It also checks that at least one summary per period was counted
  on from a prefix.
- Broken by hand twice. With the keying check skipped, red at "an
  account". With one block left uncounted, red at "first". Restored
  after each.
- On mote: go test ./internal/usage ./internal/usageapi ./internal/tui
  all ok (usage 17.2s); GOOS=linux/windows/darwin go vet -tags nogui
  ok; gofmt clean. Before the last comment-only edit: go test
  ./internal/gui is red only on TestMainWindowCorners/macOS_26_SDK,
  the known #3949 on mote's macOS 27.
- A/B on mote, v0.1.1963 against this, 240 s each, under the same
  polls and feed, with another session's GUI suite also running (load
  ~35):
  - topSummary: 3.24 s to 0.93 s of a 60 s CPU profile.
  - Polls, mean seconds:
    - /api/usage?period=7d: 0.16 to 0.13
    - /api/usage?period=30d: 0.27 to 0.14
    - all polls: 0.65 to 0.63
  - Steady RSS after 130 s: 892 to 920 MiB.
  - The cold-start peak at 30 s, before any calls were fed: 1000 to
    1219 MiB (ps); footprint peak 755 to 781 MB. The cold-start peak
    swings between runs; the RSS peak is the next work.

Not tried: rolling windows ("last:") and picked ranges are still
counted afresh on every ask, as before.

Refs #2278
2026-10-29 06:04:22 +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 fb59595530 usage: TestClearedUsageLeavesThePages leaves no clear behind for the next test
The test ends by clearing everything up to now. readCleared keeps what it
read in clearedAs, and a test that builds a page straight from chunks
(buildRequestBlocksWithCodex) never reads the clears again, so it judged
its rows by that stale clear and hid them all: with
-run "Heatmap|Pair|Scratch|Request|Page", TestCodexRequestPageDoesNotMutateSharedCompactionChunks
(3 subtests), TestCodexRequestPageFoldsCopiesBeforeResponseMatching and
TestRequestDiskNamesItsSource failed on origin/main 49d4d0f7a ("page rows
= 0"). Bisected to this test as the only polluter. The full package's
order happened to put them before it. The test now drops clearedAs when
it ends.

Run on mote at this head (rebased on a0ba8e1f2):
- go test -count=1 -run "Heatmap|Pair|Scratch|Request|Page" ./internal/usage: ok
  (red without the cleanup, as above)
- go test -count=1 -timeout 45m ./internal/usage: ok
- go test -count=1 -timeout 45m ./internal/usage: ok
2026-10-29 04:44:43 +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 157d575c39 usage: pairing Codex calls by response id allocates no pick an id (#2278)
codexChunkResponsePairs kept a *pick for every response id the gateway
had. The alloc profile of v0.1.1928 on mote (34k session files, 240k
gateway rows, two minutes of polls while an agent worked) had it at
1.05 GB, &pick{} alone 308 MB. The picks are now one slice the map
holds places in, so a poll makes a few slice growths, not an allocation
an id. What is paired is unchanged: every pick is still read once.

TestPairsAllocateNoPickAnID: 4000 Codex calls named once on both sides
are all paired, and a second pairing makes at most n/4 allocations. Red
on the old code (4161 allocations), green on the new.

Run on mote at the pushed head (origin/main 655f8dbd1 plus this; rebased
onto b7da6cf93, a gateway test commit that touches neither package):
  go test -count=1 -timeout 45m ./internal/usage/ ./internal/sessions/
    ok (30.8s, 37.9s)
  GOOS=linux/windows/darwin go vet -tags nogui ./internal/usage/ ok
Not run: the GUI suite (no GUI file changed; at 655f8dbd1 it was red
only in TestMainWindowCorners, #3949), an A/B of the page (next).
2026-10-29 00:57:04 +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 cb167fcbd8 usage: CodexModelEffort's allocation bar is a packed row a call, not a visit (#2278)
TestCodexModelEffortLetsUnrelatedCallsGo held a build of
CodexModelEffort to a visit of the log and a half. Since dc6f6d902 a
visit decodes into a lent buffer, and allocated 74 KB or 289 KB as the
pool kept that buffer through the test's GC or not, so the bar moved
under a build of ~430 KB and the test was red now and then (1 of 2 runs
on mote at the change below, "a build allocated 430336 bytes, a visit
73848").

The bar is now what #2776 was about: a build over 3000 unrelated calls
allocates less than one packed row (216 B) for each of them, 648 KB.
Builds measured 215 to 430 KB.

Run at this head, on mote:
- go test ./internal/usage -run TestCodexModelEffortLetsUnrelatedCallsGo
  -count=30: ok.
- go test ./internal/usage -timeout 45m: ok (23.2s).
Not tried: reverting #2776's fix to see the bar go red.
2026-10-29 00:14:17 +08:00