Commit Graph
119 Commits
Author SHA1 Message Date
yetone e3f1efdaac usage: a message id's pairing key is 16 bytes, not 24
msgKeysOf keeps each chunk's message ids as hashes, with the row, for
every chunk a pairing reads. The key was two 64-bit hashes and an
int32, padded to 24 bytes. It is now a 64-bit and a 32-bit hash with
the row, 16 bytes: two of a long history's ~300k ids alike in all 96
bits is ~1e-18 likely.

Run on mote at this head:
- go test ./internal/usage: ok (28.8s)
- GOOS=darwin/linux/windows go vet ./internal/usage: ok
- gofmt -l: clean
- Broken by hand: with the second hash back at 64 bits,
  TestMsgKeySize is red (24 bytes).
- Real-account copy (~/r2278/acct), idle heap at 180s, v0.1.3404's
  tree vs this: appendMsgKeys 6.49 MB -> 3.69 MB, inuse 103.0 MB ->
  97.8 MB, Footprint 154 MB.
2026-11-09 19:58:17 +08:00
yetone 640825b09a usage: the Requests card's traffic line reads whole, and a row says how many images went by file
matrix0487 on Discord:
- The Requests card's line "↑ 13 GB · ↓ 13 MB · 图片文件省下 44…" was cut
  with an ellipsis. It was one nowrap span.
- A row's details say "图片文件省下 10 MB" and should say "10 MB(3 张)".

The card line is now made of whole parts (usageParts, the pattern the
token line has since #2378). A card too narrow for all three puts the
saving on a line of its own. A part that is wider than the card by
itself (German at 420 wide) wraps inside itself; it is never cut.

The count:
- withDeepSeekFiles counts the image blocks it puts a file id in place
  of, on each try, and upBytes keeps the most of any one try (a retry
  sends the same images again, as the saved bytes are counted).
- It goes into usage.Record as `image_files` (omitempty) beside
  image_files_saved.
- packedRow keeps Tries and ImageFiles in int16 each (clamped to
  MaxInt16), so the row stays 152 bytes. request_snapshot carries the
  new field, and heat_disk hashes Tries as before.
- The detail row says "{size} ({n} image|images)": zh "10 MB(3 张)",
  zh-TW 張, ja 枚, de "Bild/Bilder", en "image/images".
- A row from before the count was kept has no image_files and shows
  the size alone, with no parentheses. The card's period total gets no
  count.

Run on mote, at this tree:
- gofmt -l (clean), go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build ./...: ok.
- go test -run 'TestRowImageFilesKept|TestRowBytesKept|TestRowsOfOneSession|
  TestDeepSeek|Snapshot|Heat' ./internal/usage ./internal/gateway: ok.
  - TestRowImageFilesKept: the count survives pack/unpack beside Tries,
    100000 clamps to 32767, an old row reads 0, the JSON has
    "image_files":3 and leaves out 0, and packedRow is 152 bytes.
  - TestDeepSeekImageFilesCountedInRow: two images in one message and
    one again in a later message make 3 in the stored row, twice, and a
    request with no image makes 0.
- GUI, BROWSER=chromium and webkit: usage-ledger-bytes runs every
  language at 1180 and 420. The 3-image and 1-image rows read in each
  language's unit, singular in en and de, and the old row stays bare.
  The reporter's period (13 GB, 13 MB, 44 MB) at 1180, 760 and 420 has
  every part whole and inside its card.
- The 79 usage-*/led* GUI files (concurrency 2): 641 of 659 pass in
  chromium and 637 of 654 in webkit. Every red is filed and red on
  origin/main d2c29abe7 too (run alone there in chromium, the same 17
  subtests): usage-agents-hide (#2276, #3414), usage-fold (#3415, #2163;
  in webkit also a timeout in "several accounts"), usage-ledger's
  return-to-live (#4078, #5048) and usage-overview-fold (#3947).
- Broken by hand, each red:
  - The count left out of packedRow: TestRowImageFilesKept.
  - The count not kept in withDeepSeekFiles:
    TestDeepSeekImageFilesCountedInRow ("0 images by file, want 3").
  - The detail's count dropped: usage-ledger-bytes in every language
    ("expected '10 MB(3 张)', actual '10 MB'").
  - The in-part wrap dropped: "de big 420" ("cut: 0,0,0,11").

Not tried: a real DeepSeek account (the count rides the same path as the
saved bytes, which were tried for #5407), and Linux WebKitGTK.

Reported-by: matrix0487
2026-11-06 11:46:25 +08:00
yetoneandyygutn 783537e810 sessions: the Antigravity app's own conversations count on Usage and Sessions (#2190)
xxooioo (Discord) asked for the Antigravity desktop app's calls made
without magpie's gateway on Usage and Sessions. The app keeps each
conversation as a SQLite database, ~/.gemini/antigravity/conversations/
<id>.db (WAL). Messages are encrypted, but steps.metadata is plain
protobuf: 1 the step's start, 9 the call's usage (2 input, 3 output,
4 cache write, 5 cache read, 11 response id), 20.3 the gen_metadata idx
of its generator, whose message names the model (field 19, else 21/22).

The reader opens the database read only, in one read transaction; a
response id seen twice is one call at its last step. Each conversation is
a read-only session under agent "antigravity", gated by Reads like every
other agent and added to Found. A call the app sent through magpie is
matched to the gateway's record by tokens and time the way agy's steps
are (agyLocal now covers "antigravity"), so it is counted once.
"gemini-3.8-flash-n", the model the rows name, is counted as
gemini-3.8-flash (b2432754e).

Fixture: the four steps.metadata rows yygutn posted on #2190, byte for
byte (testdata/antigravity/steps.tsv), under the schema he posted; the
decoded tokens and times match his figures. The gen_metadata rows wrap
the posted field-19 bytes in a field-1 message, since the rest of that
row was not posted.

Run on mote: go test -count=1 ./internal/sessions/ ./internal/usage/
./internal/agent/ ok; ./internal/gui/ ok but TestMainWindowCorners
(#3949, macOS 27, untouched); gofmt -l clean; GOOS=linux and
GOOS=windows go vet of sessions and usage clean (./... for linux stops in
Wails' cgo files, as without this change). skillsCounted says why the
app's skills aren't counted (step payloads are encrypted).
Broken by hand: agyLocal back to "agy" only fails
TestAntigravityAppCallThroughMagpieCountedOnce; the wholeCallReaders key
renamed fails TestAntigravityAppCalls (0 calls).
Not tried: a real app database (the app isn't installed on any test
machine); whether a call through the gateway records the same tokens;
conversation titles (not read; agyhub_summaries_proto.pb unknown).

Co-authored-by: yygutn <yygutn@gmail.com>
2026-11-06 10:07:06 +08:00
yetone 8b70b7d976 usage: a request's bytes up and down, and what DeepSeek's image files saved, in Requests
Suggested by @faithleysath (matrix0487 on Discord): the usage ledger now
keeps what each request received back (down_bytes) beside what it sent up
(up_bytes, #4456), and what DeepSeek's image files (#5407) kept out of the
upload (image_files_saved).

Shown in Usage → Requests:
- a row's details: "Sent upstream", "Received" and "Saved by image files",
  each only when it is above 0. A row from before has none of them, not 0;
- under the Requests card, the period's "↑ up · ↓ down", with
  "{n} saved by image files" when there is a saving. Its title gives the
  exact bytes. A period with no counted bytes shows no line.

What is counted:
- Down bytes are counted as the reply body is read, after Go's transport
  has undone gzip, so a gzipped reply counts its plain size, not wire
  bytes. A plugin's row counts the local hop to the plugin host. A 101
  body is not wrapped. Every try counts, so a refused try plus the
  answering one add up (TestLedgerKeepsDownBytes).
- Image files saved, per try: the body before the swap minus the body
  sent, minus the upload bytes this request itself paid (len(b64)/4*3).
  It can be negative on the turn that uploads; the GUI shows only a
  saving above 0. Gaps: an upload that finishes after the wait timeout or
  ctx-done is not subtracted (as with up_bytes); a joined upload flight is
  paid by the request that started it; multipart overhead is approximate.
- packedRow grows by three int32 (152 bytes, still within the test's
  bound), clamped to the int32 range. Totals sum all three.
- settledCountVersion goes 1 → 2, because Totals now count bytes. The
  settled page, heat and effort caches recount once, on the first start
  after the update. The heat key hash includes the new fields.

Run on mote at 84ad780b6 (origin/main, fetched):
- go test ./internal/usage: ok.
- go test ./internal/gateway -run 'TestLedgerKeepsDownBytes|TestDeepSeek|
  TestCodexOwnTurnKeepsUpBytes|TestLedgerKeepsUpBytes|
  TestLedgerCountsATrysSecondAsk': ok.
- go test ./internal/gui: only TestMainWindowCorners/macOS_26_SDK fails,
  as on main (#3949).
- gofmt -l clean; go vet of usage and gateway for darwin, linux (nogui)
  and windows; go build ./...
- New GUI test usage-ledger-bytes.test.cjs: 30 of 30 in Chromium and
  WebKit, en/zh/zh-TW/ja/de, at 1180 and 420 wide. It is red on the old
  page.js.
- usage-*, ledger-*, i18n-* and nav-timeout GUI files: 1231 of 1267.
  Every red is red on a clean 84ad780b6 too: usage-agents-hide (#3414),
  usage-fold (#3415), usage-ledger's "newest live route" (#5048),
  usage-overview-fold, which flakes in other languages on each run
  (#3947), i18n-keys (#5332, and #5426 filed now for "No session ID"),
  and nav-timeout (#5425, filed now).

Broken by hand:
- gotDown not wrapping the body: red, "down 0; the vendors answered
  141/265 bytes" and "the backend answered 105 bytes".
- the saved += removed: red, "saved 0".
- the settled guard red with the bytes fixture until the version raise.

Not tried: a real DeepSeek or other vendor account through a built app,
and a screenshot of the real app. The CSV export does not have the new
columns yet.
2026-11-06 09:17:10 +08:00
yetone e156fdd032 usage: a model's region deployment answered under its own name is not a swap (plugins#628)
WorkBuddy AI lists DeepSeek V4.1 Flash as deepseek-v4.1-flash-sg, its
paid id for the Singapore deployment. The plugin's product config names
it paidId to the free deepseek-v4.1-flash, with one window for both.
WorkBuddy answers under the model's own name, so the Routing page tagged
each request "请求 deepseek-v4.1-flash-sg · 实际 deepseek-v4.1-flash".
Old routes and kept usage rows kept the mark, so removing the model and
setting the provider up again didn't clear it (chansee97, plugins#628).

- RegionTail (internal/usage/served.go) covers a name that is the other
  with -sg, -us, -eu, -cn, -intl or -global after it. Such a pair is the
  same model, and Swapped excludes it.
- A region in both names, or a name that differs besides the region, is
  still a swap.
- Kept rows (request_page.go) and kept routes (gateway history.go's
  routedAgain) are judged again with it, so old marks go too.

Run on mote, at 5f0a84a00 plus this change:
- gofmt -l internal plugins: clean.
- go test -count=1 -timeout 45m on ./internal/usage, ./internal/usageapi,
  ./internal/budget, ./internal/davsync, ./internal/middleware,
  ./internal/otlp, ./internal/gui/..., ./internal/cli, ./internal/tui,
  ./internal/gateway/..., ./plugins/middleware/..., ./plugins/otel/... and
  ./internal/agent (every importer of internal/usage): all ok except four
  reds that are filed and don't touch swap marking:
  - internal/gui TestMainWindowCorners (#3949)
  - internal/cli TestEveryRouteHasACommandOrIsNamed (#4826)
  - internal/gateway TestCodexPoolSaysTheClientsVersion (#4807)
  - internal/gateway TestUnroutedRequestShownThenAnswered (#4200)
- GOOS=linux and GOOS=windows go vet ./internal/usage
  ./internal/gateway/...: ok.

After the rebase onto a32588528, which changed internal/usage's
request_page.go and match_chunks.go:
- ./internal/usage and ./internal/usageapi: ok.
- go test -run "RouteKept|Swap|Served|History" ./internal/gateway: ok.
- vet: ok.

Broken by hand, each red:
- RegionTail taken out of Swapped: TestSwappedRegionTail.
- The kept-row re-judge taken out: TestKeptRowRegionTailNotSwapped.
- The routedAgain re-judge taken out: TestRouteKeptRegionTailNotSwapped.

Not tried:
- A live WorkBuddy AI request to -sg, which would spend credits. That
  WorkBuddy answers -sg under the plain name rests on the report.
- The reporter's screen. This assumes the "实际" tag they saw is the
  Routing page's swap tag (or Usage's Served column, which is fixed by
  the same rule).
2026-11-02 19:26:26 +08:00
yetone 07dc0b4ec1 usage: an agy following the Antigravity app's gateway is counted once (Chamberlain_zyz on X)
An agy not connected on its own row follows the Antigravity app's
gateway, with the app's key (internal/agent/antigravity.go), so the
gateway records its calls as the app's ("antigravity"). Its transcript's
steps were matched only to records of agent "agy", so each one was
counted twice: Chamberlain_zyz's 17:00 hour showed Antigravity
39,104,506 and Antigravity CLI 38,562,861 tokens for the same calls.

agyGateway takes the app's session-less records too, at all three places
that matched agy's alone: the gateway side of the match key, the chunk
hints that pick which transcripts to open, and matchingRecords. The
match is still by exact tokens and time, so an app call of its own is
paired with an agy step only if both counted the same tokens within the
step's window. It is worked out when usage is read, so hours already
recorded are counted once too, for every user, with nothing to redo.

Run (mote, this tree):
- go test -count=1 -run Agy ./internal/usage: ok.
- Broken by hand (agyGateway back to "agy" alone):
  TestAgyStepThroughTheAppsGatewayCountedOnce and
  TestMatchOpensAgyChunksForTheApp fail; restored, ok.
- go test -count=1 ./internal/usage ./internal/sessions: both ok.
- go vet ./internal/usage, and with GOOS=linux and GOOS=windows: ok.
- The whole suite was not run: only these two packages are touched.

Not tried: a real agy through a real Antigravity app's gateway; the
reporter's case is taken from their screenshots and the app's wiring.
2026-11-02 19:08:59 +08:00
yetone d7b42fcf23 usage: a chunk's one-byte numbers are read without Uvarint's loop, and a copying pass keeps its decode buffer (#4372)
A pass over packed chunks decodes every row's ~40 varints, and most are
under 128. binary.Uvarint was 42% of a lent pass's CPU on mote; take
now reads a one-byte number itself. A pass that copies its strings
(visitBlocks, rowsOf, within, the Codex pairs) decoded into a sync.Pool
buffer, which each collection empties, so after one it made the buffer
again and grew it to the largest block. It now decodes into its
rowBuffer's, as a lent pass does; unpackReusing takes the buffer and
whether its strings are lent apart.

Run on mote (M5 Pro), BenchmarkChunkRowsPass, 40 chunks of 3000 rows,
4 runs each, base 43d442700 and this change alternating twice (mote at
high load, so the lowest of each):
- lent: 16.3 ms at base, 13.0 ms here.
- copied: 55.7 and 55.1 ms; rowChunk.row's Record is most of it.
- copied after a collection: 3.34 MB and 45 allocs a pass at base,
  2.95 MB and 40 here.
- TestCopiedPassKeepsItsDecodeBuffer: red at base ("made 8
  allocations, want 4"), ok here.
- go test ./internal/usage: ok. go vet; GOOS=windows and GOOS=linux
  go vet ./internal/usage: ok. gofmt -l: clean.

Not done: a pass still decodes every chunk again; keeping them decoded
holds the history unpacked, which packing is there to avoid.
2026-11-01 18:19:53 +08:00
yetone 43d442700c usage: a row keeps its zone as an id, so the collector never scans rows (#4737)
A packedRow held its *time.Location, and that one pointer made every
[]packedRow a slice the GC scans word by word: the pages' rows of a
period, the kept decode buffers and every unpacked chunk, hundreds of
thousands of rows on each cycle. #4737's profile has gcDrain at 12% of
the CPU, scanObject 7.65% of it.

A row now keeps its zone as a uint16 into rowZones, a copy-on-write
list read with one atomic load. A zone is known by its String() and
offset, not its pointer: a time parsed with an offset, and a chunk read
from disk, has a new FixedZone each, and 30 parses of +05:30 are one
zone. time.Local is a zone as any other (a test sets it to UTC), so a
row keeps the zone it was written in, as before. Past 65535 zones a new
one's times are kept in UTC: the same instants. unpack looks a chunk's
Locations up once, not once a row. packedRow is 8 bytes smaller, so
TestPackedGatewayRetainsOversizedSnapshot's fixture has 180000 rows to
stay over its 32 MB.

Run on mote (M5 Pro):
- BenchmarkCollectWithRowsHeld, a runtime.GC() with 1M rows held:
  4.1-7.9 ms at origin/main 1fac66c06, 1.1-1.5 ms here (3 runs of 20).
- TestPackedRowsAreNotScanned: red with a *time.Location field put
  back ("packedRow.broke is a ptr"). TestRowZoneKeptThroughPack: times
  and zones (name, offset, String) the same through pack and unpack;
  red with the name-and-offset lookup taken out ("30 parses of +05:30
  added 31 zones").
- go test ./internal/usage: ok. go vet; GOOS=windows and GOOS=linux
  go vet ./internal/usage: ok. gofmt -l: clean.

Not tried: the GC share in a running magpie with a real history; the
benchmark is the scan this takes away, not the reporter's 12%.
2026-11-01 18:10:04 +08:00
ggbdpq 96a37ee5e3 usage: the vendor's own alias for a model isn't a swap (#4593)
A request via Top-API for deepseek-v4.1-flash answered under
deepseek-flash was marked a swap. It isn't one: DeepSeek renamed its
V4.1 Flash deepseek-flash (api-docs.deepseek.com/updates, 2026-09-10:
"Change the model name to deepseek-flash to call the latest V4.1 Flash
model"), and every exemption Swapped knows is structural - a dated or
pinned tail, a Bedrock geography, a relay's word in front, a serving
name - none of which an official rename reads as.

VendorAlias reads a small table of rename pairs the vendor's own docs
state (deepseek-flash is V4.1 Flash), both ways, over squashed bare
names so case and separators don't matter; a bareModel'd name feeds it,
so the dated spellings either side writes hit it too. Only pairs the
docs state go in: a retired name routed elsewhere (deepseek-v4-flash)
is another model, and catalog's SameModel keeps deepseek-flash an id of
its own. The kept-row readers take the alias in beside the other
exemptions, so rows recorded before it are read back as not swapped.

Run (sandbox HOME, GOTOOLCHAIN=auto, -tags nogui):

  go test ./internal/usage -run 'TestSwappedVendorAlias|
  TestKeptRowVendorAliasNotSwapped'  ->  ok (base f811bf291: both FAIL,
  the seven alias pairs read as swaps)

  go test ./internal/usage -run 'TestSwapped|TestKeptRow|TestListed|
  TestRelay'  ->  ok

Reviewed and landed as one batch of 12 commits (gua's #4593, #3269,
#3881, #2887, #3289, #2718, #2855, Edward4226's #2718 key-path
sibling, and four review follow-ups). Run for the batch, whose last
commit's tree is 5d58a75f3:
- Full suite before the rebase (base d307aa648, wsl-run magpie-desktop,
  go test -tags nogui -count=1 -timeout 45m ./...): 81 packages ok. Reds,
  all with issues and none in code this batch touches: internal/agent
  TestInstalledVersion, TestGrokInstalled, TestOmpDetectedWithPiDir
  (#4033, #3548, #3141); gateway TestUnroutedHeldReportSaved (#4300);
  gui TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  TestColdTurnsTaken (#4510); provider
  TestClaudeAccountServesModelsListedSinceItsFetch (#3174). Run alone at
  origin/main 573b21f4b, TestGrokInstalled, TestOmpDetectedWithPiDir
  and TestSettingsSaveKeepsWhatItDoesNotSend are red there too. The
  other four pass there alone.
- After the rebase onto origin/main 573b21f4b, at this tree:
  internal/usage, update, gateway and provider ok. In internal/agent,
  the #4033/#3141 install-detection reds plus TestCopilotFolderFrom-
  AnIDEPluginIsNotTheCLI and TestZedAppPath. Those two are flaky the
  same way at origin/main (-count=10 alone: 4 and 5 of 10 red) and are
  already listed in #4033. The #3269 tests (TestCopilotLauncher*) pass
  5 of 5.
- Rebased onto origin/main ef63ef4a2. The #2855 commit met 0b9727ec9
  (#2974) in responses.go: the streamed item's done now takes both, the
  upstream's own id (thinkUp) and the made-over item; and in
  gateway-routing.md main's paragraph is kept with #2855's clause. That
  matches gua's latest head (range-diff: context only). At tree d7c76c6fa:
  internal/gateway, provider, usage, redact and update ok; vet
  GOOS=linux -tags nogui ./internal/..., darwin and GOOS=windows for
  gateway and provider.
- Rebased last onto origin/main d8f7d089f (5 commits: internal/agent
  and GUI files only). At tree 0d4bfd8c8, the pushed one: internal/agent's
  TestCopilotLauncher*, TestClaude*, TestOwn* and TestVSCode* ok, -count=3;
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI red once there, as it is at
  main (#4033). Vet of internal/agent: darwin, linux and windows.
- gofmt -l clean. On mote: go vet darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- Broken by hand, each turning its guard red: the lift gate
  (TestReadingKeepsARefusalsRest, TestAutoVisionKeepsOffARefusedAccount);
  the named-time condition (TestNamedQuotaTimeReplacesAGuess); the
  filter-chain hop (WholeReply/glm-5.3-flash); Edward's aAt
  (TestKeyAllowanceElapsedResetStartsAgain); and the old
  magpieMadeReasoning, which panics in TestMadeReasoningSaysItsTextOnce/
  no_summary. Every new test of gua's is red at base d307aa648.
Not tried: real OpenAI, DeepSeek, GLM or ChatGPT accounts; a real VS Code
1.144 install on Windows; a GUI run (no GUI files are touched).

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 07:06:19 +08:00
yetone 7b09d2c951 provider: a model can be listed by an id of the user's at its provider, asked for by its own
zeewell on X (tweet 2116404121930432888): relays serve one model under
ids of their own (deepseek-v4.1-flash-1017, grok-4.6@500k). They want to
give each one their own id at the provider layer. magpie then lists,
routes, groups and finds groups by that id, and the upstream request
still carries the vendor's id.

Choice: a new per-model map, settings' ModelIDs
("<pid>/<local>": "<own id>"), served through the wire names that
already exist. ModelSameAs was not widened. It means "same as another
vendor's model": it lends specs and joins found groups. Making it rename
models everywhere would change every existing user's ids and refs.
ModelWires was not reinterpreted either, for the same reason. ModelIDs is
ModelWires turned round: a wire keeps magpie's id and changes the one
sent, and this keeps the one sent and changes magpie's. Settings.Wires()
merges each entry in as a wire name (wrapped by a "<pid>/*" wire). Every
place that sent a ModelWires name (gateway, usage ledger, request page,
UpstreamName, UpstreamNameAs) reads Wires(), so the upstream id needs no
new path. An explicit ModelWires entry for the same id wins.

- Listed by the local id: Available, liveIDs/liveByID, Serving and
  ListPrice translate through OwnModelID. /v1/models, agents' lists,
  Resolve, routing groups and found groups (auto/<local>, merged with
  every other provider serving that id) all see the local id.
- Only a provider of the user's own (Account == nil) takes one. An
  account's or a plugin's request is built from its list's id, which no
  wire reaches.
- Two variants of one provider given one id: the latest given it wins,
  and the earlier one is listed by its own id again. The CLI names it.
  The editor refuses two rows given one id in one save. A model of the
  provider's own id that a variant is listed by (plain grok-4.6 beside
  grok-4.6@500k) is not listed while the variant has it.
- The user's values are never overridden. SetModelID moves picks,
  contexts, fallbacks, groups' members/rules/fast/placed/off/weights/
  classifier/pick, the pickers' lists, every per-model setting
  (Settings.MoveModel) and gateway keys' models (provider.ModelMoved,
  set by access) to the new id, but only where nothing is under the new
  id yet. Agents' own files are not rewritten: an old provider/<own id>
  still resolves and is sent as it is. Group match patterns and key
  patterns stay as written.
- Key limits: a key held to either id passes for both (modelAllowed:
  the ref, OwnModelID, ListedModelID). Group members use the same check.
- Usage: model = the listed id, served = the vendor's id from its reply.
  The price is the own id's first.

CLI: magpie model id <provider/model> [<id>|--reset], magpie model ids.
GUI: Providers > a provider's editor > Names & levels > "Listed as",
beside Same as. It is staged with the editor's Save and taken back by
Restore default, in zh, zh-TW, ja and de. Accounts have no box.
Docs: providers-accounts.md, gateway-routing.md, and site start.html in
en, zh and ja.

Run (mote-run, at this tree rebased on 841326709):
- go test -tags nogui of internal/gateway, provider, settings, access,
  usage and cli: ok. internal/gui: ok but for
  TestSettingsSaveKeepsWhatItDoesNotSend's SearchAll, red on main since
  b09349d17 (#4514, yiqiui's patch); its ModelIDs case passes.
- TestAutoVisionDoesNotBuildListsAgain: 457 allocations with 4 models,
  458 with 400 (main 459), searcherModel within its 50. Reading
  Shared() per list cost 3041; SharedModelIDs parses only modelIDs once
  per file change, the settings path is built again only when what it is
  built from changes, and Serving looks up the own id only when a key is
  listed to some model.
- TestCoreScriptBudget: raised by 1,178 bytes for the Listed as box,
  with a note.
- gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet ok.
- GUI: provider-listed-as (en, zh, zh-TW, ja, de), provider-same-as,
  provider-detect in Chromium on mote and WebKit on the Linux box (mote's
  WebKit launch hangs, #4125): 9 of 9.
Broken by hand, each red: the wire name (wires), the list (list), a key
held to the own id (keyown), the key move hook (hook), liveIDs, liveByID,
moving refs (moverefs) and moving per-model settings (movemodel).
Not tried: a red for ListPrice's or Serving's own-id lookup; a real relay
with variant ids; Match patterns are not rewritten to the new id. The
full Go suite and the whole GUI suite are still running and their reds
get their own issues.
2026-10-31 15:04:44 +08:00
yetone 2eac916170 gateway: short-lived gateway keys, issued by POST /v1/magpie/keys or magpie gateway-key issue
xazaj on X is moving an enterprise LLM gateway onto magpie. Their
orchestrator gives each sandboxed agent a key of its own, and that key
has to stop working by itself.

A gateway key can now expire (Key.Expires) and can be issued under
another key (Key.Issuer). It lives from 1m to 30d. It can be held to a
set of models, a set of accounts, tokens or cost over its whole life
(one "hours" limit as long as its life), and read-only.

- POST /v1/magpie/keys {"ttl":"1h"|3600, name, models, accounts, tokens,
  cost, readOnly} answers 201 with the secret once, no-store. GET lists
  the caller's keys, masked. DELETE /v1/magpie/keys/{id} revokes one.
- magpie gateway-key issue --ttl 1h [--name] [--models] [--accounts]
  [--tokens] [--cost] [--read-only] [--from <id>] [--json] prints the key
  alone. gateway-key issuer <id> on|off lets a key issue keys. list shows
  until/expired/issued by.

Who may issue:
- a key the user let issue (Issues), from wherever that key is let in,
  so a container or CI can;
- with no key, a request that profileRefused passes: loopback, no
  forwarding header, no Origin/Sec-Fetch/Mozilla marks, a loopback Host.
  Such a request can already use every model with no key and run the CLI,
  so it gains nothing.
Never: a page, another computer without such a key, a key not let issue,
an issued or expiring key, or a read-only key (readOnlyGuard).

An issued key never outlives or exceeds its issuer. IssueKey clamps its
expiry and refuses models and accounts the issuer can't use. On every
authentication (access.Check, under Authenticate and On), identityOf
folds the key into its issuer as the issuer is now: models, accounts,
read-only, quotas and expiry. An issuer that is off, removed or expired
refuses its keys. Spend counts against the issuer too: the new usage
field callerIssuerId, budget.read/Append counting both keys, and Reserve
reserving on both. /v1/magpie/limit answers expires and issuerLimits.

An expired or refused key gets 401 with why ("… expired at …: ask for a
new one") on every route, from loopback too. Otherwise a held sandbox
whose key ran out would be let in as no key. Expired keys are pruned
after an hour (every 10 minutes while serving, and on each issue).
rowText packs CallerIssuerID: without it, usage.Visit returned the field
empty and the issuer's limit counted none of its keys' calls.

Docs: gateway-routing.md has "Short-lived gateway keys" and the
/v1/magpie stats API table. site/public/docs remote has "Short-lived
keys" and "Stats API" in en, zh and ja. GitHub OIDC is filed as #4531.

Run at base 07a3312c5 (origin/main, fetched just before):
- mote: go test -count=1 -timeout 45m on access, budget, gwbudget,
  usage, cli, gateway, davsync, agent: ok.
- mote: internal/gui fails TestCoreScriptBudget (#4526),
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and ten AppKit window
  tests killed at their deadline (#4125, #2645). The first three fail the
  same at origin/main 07a3312c5 on mote. This change touches no GUI file.
- mote: gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build; node --test site/*.test.mjs (49
  pass).
- win-run: access and budget ok. usage fails TestDesktopSessionAccountMetadata
  the same at origin/main (#1356). cli's TestLibraryMCPHub failed once on
  TempDir cleanup (#4140) and passed alone.
- Real binary on mote, sandbox HOME, port 47811: issued a 1m key with
  curl, read its limit, listed it, saw `gateway-key list` show "until",
  had a page's Origin refused 403, and after 62s /v1/models answered 401
  "the gateway key "sandbox-1" expired at …".

Broken by hand, each restored:
- no expiry check in Check: TestIssuedKeyExpires and
  TestIssuedKeyExpiresOnEveryRoute go red.
- no 401 for a refused key on loopback: TestIssuedKeyExpiresOnEveryRoute
  goes red (the expired key let in as no key).
- budget not counting CallerIssuerID: TestIssuedKeysSpendTheirIssuersLimit
  goes red (5 calls reached the upstream).

Not tried: a Responses WebSocket open across the expiry. The GUI shows
no expiry or issuer yet (issued keys look like plain keys until pruned).
A held issuer's /v1/magpie/usage shows its own rows, not its keys'. The
refused-key 401 doesn't count toward tooManyAuthFails. Issued keys sync
through davsync like other keys, with their expiry.
2026-10-31 13:44:29 +08:00
yetone 64aaf421ac usage: a packed row holds its time as unix ns and a zone, its tokens in 32 bits (#2278)
A packedRow was 184 bytes; it is 152 now. Its time.Time (24 bytes) is
kept as unix nanoseconds and the *time.Location it was in, read back
with Time(); its six token counts are int32s, not int64s. No call
reads or writes 2^31 tokens; one past it is kept as the most an int32
holds (tokensOf), not wrapped. The archive's encoding is varints and
is unchanged.

Run (mote, through mote-run): go build, go vet, GOOS=linux and
GOOS=windows go vet ./internal/usage, go test ./internal/usage
./internal/usageapi: ok. TestRowTokensAndZoneKept (new) packs a row in
a +05:30 zone at 123ns with 3e9 and -3e9 tokens, and checks time,
zone and the saturated counts after a pack/unpack round trip.
Broken by hand: tokensOf as a plain int32(n) makes it red ("read back
Input -1294967296 ... want 2147483647").

Real history copy on mote (cold start, magpie-ext = v0.1.2296 change):
  cold peak  this 346/342/354 MB (avg 347)  before 373/349/359 (avg 360)
  warm peak  this 273/262 MB               before 297/276
heatmap, overview 0/7/30, stats 0/30 and the request page JSON are
byte-identical to before.
2026-10-31 10:24:23 +08:00
yetone 86e19b9b74 gui: a cold start's turn lets the matcher's scratch go when it ends (#2278)
Each turn of the warm-up and of a page's first ask (coldTurns) now ends
with usage.ReleaseMatchScratch: the request matcher's kept maps, picks
and row buffers, which sat for scratchLinger (30 s) under the next
turn's read of the history. The priced blocks stay, so the next turn's
queries don't price the history again.

On mote, a sandbox HOME with the real history (13k sessions, ~720k
gateway calls), 75 s with ten answers asked every 5 s, phys_footprint
peak:
- start with its caches: 260 and 263 MB, against 274 and 285 MB at
  v0.1.2284.
- first start, run alternately with v0.1.2284: 359, 359 and 361 MB
  against 360, 360 and 364. CPU 3:41-3:47 against 3:35-3:41. The
  slowest first answer was 31.5-32.4 s against 30.9-31.8 s.
- the heatmap and the requests answers are byte for byte the same.
Dropped: releasing the priced blocks too (ReleaseScratch). That gave
253-255 MB with caches, but 362-369 MB on a first start, which priced
the history again in each turn.

Run on mote at 03d21ab8e + this:
- go vet ./...: ok.
- go test ./internal/usage: ok.
- go test ./internal/gui: red only in ten real-window AppKit tests,
  killed at their deadlines under load. They are the same ten that fail
  on a clean a6951cc63 (#4125, #2645).
- TestMatchScratchGoesPricedBlocksStay goes red with
  ReleaseMatchScratch made a no-op, and red when it releases the priced
  blocks too.
- gofmt -l: clean.
Not run: Linux vet of internal/gui (no gtk4 on wsl-run). After this was
run, the rebase onto origin/main brought in 11fc687c0 (a GUI test's
wait), 06c2c35d1 (Claude's interactive start) and 6ba593de0 (the main
window's passing note). They touch none of these files.
2026-10-31 08:31:15 +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 0606e03702 usage: a settled chunk's message keys are read for a pairing, not kept (#2278)
msgKeysOf kept every chunk's message keys by serial, for the next
pairing of the same chunks. A cold start pairs the whole history (the
warm-up's page of All, then the heatmap's year and Codex's effort when
page-v1, heat-v1 and effort-v1 miss), so it kept every session file's:
67 MB of the 460 MB live heap 30s after the footprint passed 400 MB
(heap profile of a cold start of the real history on mote), while
polls pair only the days since the split's cut.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

What a call pairs with is unchanged.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Run at this tree: go test ./internal/usage/ ./internal/sessions/ ok;
./internal/cli ./internal/davsync ./internal/gui ./internal/middleware
./internal/otlp ./internal/tui ./internal/tune ./internal/usageapi ok;
gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui of usage
and sessions ok. Not run: internal/agent and internal/gateway, which
don't call CodexModelEffort.
2026-10-27 07:46:32 +08:00