Commit Graph
202 Commits
Author SHA1 Message Date
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 f39fc3ac8b usage: a model list that was answered is no row of Requests (ferock on Discord)
ferock (Discord #general): Usage > Requests is full of rows like
"magpie · magpie's own · Remote magpie · API · Model list · 0 0 · 757 ms
· 200, GET /v1/models", which no tool of theirs sent.

Cause: ffe493773 (v0.1.1446) wrote every request magpie sends a
provider on its own into the request log (source "probe"): the editor's
Test and Detect APIs, and every model-list fetch. 0152f6696 then gave a
Remote magpie a 10-minute list schedule (KeepListsFresh), so each Remote
magpie added ~144 such rows a day. The same rows came from every other
automatic fetch: start-up's FetchNew, the panel's FetchNewSoon, the
Providers page's FetchNewBehind and any provider with a RefreshEvery.
They were already counted in no token, cost, chart, budget or quota
total, but they were listed and counted in the page's row total.

Fix: a model_list probe with a 2xx/3xx status and no error
(usage.quietProbe) is not written by usage's probelog.Sink, and is
skipped when the log's index parses one (logSnapshot.probes). This rule
covers every list fetch, whoever started it, so every sibling is
covered by one check. A list that failed is still a row (the Failed
filter finds it, and the row says why models are missing), and every
Test and Detect APIs row stays as it was. Older rows: the answered
model lists already in usage.jsonl stop being listed at the next start
of the index, with no rewrite. The lines stay in the file and nothing
reads them. Quota and usage polls and health checks were never written
there (only Test, Detect and list are marked by probelog), so nothing
else needed changing. The TUI and CLI have no request list. The heatmap,
Summarize, Load and the exports skipped probes already.

Tests:
- usage TestAnsweredModelListIsNoRow (new): 200 and 304 lists aren't
  written; a 503 and a connection-refused list are listed and Failed
  finds both; a 200 Test is listed; an old answered list line in the log
  is not listed, and Total is 3.
- TestProbeRowsListedNotCounted and the rename tests now use a failed
  list (a 200 one would no longer be a row).

Broken by hand, each red: quietProbe returning false (the 200 list
written and listed); the index's skip removed, Sink's kept (the old line
listed, total 4).

Run, on mote:
- go test -tags nogui -timeout 45m ./... at the pre-rebase head
  (b4f2fa9d3 on 0a7633136): every package ok, 76 ok, exit 0 (gateway
  547s, agent 298s, provider 167s, usage 48s).
- After rebase on origin/main 9ba3f049e (which touched neither usage
  nor probelog): go build ./...; go vet for darwin, GOOS=linux and
  GOOS=windows on usage and probelog; go test usage, probelog,
  usageapi, and provider -run Probe|Detect|TestTestWrites: ok. gofmt
  -l clean.
- GUI (no asset changed): usage-ledger*.test.cjs, ledger-*.test.cjs and
  own-requests.test.cjs, chromium and webkit, each file's languages:
  381 tests, 375 pass. The 6 reds are usage-ledger's "newest live route
  needs no return-to-live button" (en, zh, both engines), which is
  already filed as #3104. usage-ledger-probe passed in every language.

Not tried: a real Remote magpie over a day. The row filter was not
checked on a real usage.jsonl.
2026-10-28 09:42:21 +08:00
yetone 3e22123c9c usage: a deleted provider's calls stay apart from a new one under its id
cybercaius (Discord): after deleting a provider and adding a new one
that took the same id, the old provider's usage showed under the new one.

Delete now records the provider in providers.json ("deleted": id, name,
icon, when, its Was and Gave). UsageRenames gives a deleted id to
<id>~<when> only once something reuses it (a live provider, a later
deleted record, or a later Was), so a deleted provider nobody replaced
keeps its raw id and the existing probe/usage tests stay as they were.
/api/usage's provider faces name a deleted id from its record and set
Named.deleted; the Usage provider picker notes "Deleted {date}" (zh, zh-TW,
ja, de translated). Old deletes, made before this, have no record and
stay merged: nothing tells their calls apart now.

Run (mote): go test -tags nogui -run 'Deleted|Rename|NotSetUp|Probe'
./internal/usage ./internal/usageapi ./internal/provider ok; gofmt -l
clean; go vet -tags nogui ok.
Broken by hand: dropping the f.Deleted append turns
TestDeletedProviderKeepsItsCallsFromOneAddedUnderItsID and
TestDeletedProviderListedApartAndMarked red; restored, green.
Not tried: a real delete-and-re-add in the GUI app.
2026-10-28 04:18:21 +08:00
yetone a42d90d7de usage: a test holds every Bedrock maker models.dev lists (#2199)
ggbdpq's change before this one adds xai, writer, moonshot and nvidia
to vendorDot, with six pairs read off the catalog. This test reads all
200 amazon-bedrock ids from models.dev's list of today (kept in
testdata) and checks that each one answered by its own name, or by
maker.name, is no swap. A maker the list gains later and vendorDot
lacks fails here once the testdata is refreshed. The four makers are
the only ones missing today: the list's makers are amazon, anthropic,
deepseek, google, meta, minimax, mistral, moonshot, moonshotai,
nvidia, openai, qwen, writer, xai and zai.

Reported by gua2100 (ggbdpq) on GitHub.

Run (on mote):
- go test -tags nogui -count=1 ./internal/usage ok.
- go test -tags nogui -count=1 -run 'Bedrock|Swapped|Served|RelayRenamed|Rename'
  ./internal/gateway ok.
- go vet -tags nogui of both packages on darwin, GOOS=linux and
  GOOS=windows clean; gofmt -l clean.

Broken by hand: with origin/main's served.go put back, this test fails
on 21 pairs (xai 10, writer 6, nvidia 4, moonshot 1), and
TestBedrockProfileAnsweredByItsModelIsNoSwap fails on ggbdpq's rows.

Not tried: a real Bedrock account; a full go test ./....
2026-10-28 03:17:14 +08:00
ggbdpq c2d6a64c7d usage: a Bedrock model of a newer maker answered by its own name is no swap
What changed:

vendorDot names Bedrock's makers so a reply saying the model's own id
reads as the model asked for (012be0fc, #1484). models.dev's bedrock
list has since grown makers the list did not have: xAI (xai.grok-4.7,
us.xai.grok-4.6), Writer (us.writer.palmyra-x5-v1:0), Moonshot
(moonshot.kimi-k2-thinking) and NVIDIA (nvidia.nemotron-nano-12b-v2).
A request sent as the geography.maker id and answered by the model's own
name was marked swapped — the route, its tries and the usage row — as if
the vendor had served another model. vendorDot takes the four makers
too, moonshotai kept before moonshot, so moonshotai.kimi-k3 strips
whole. Another model is still a swap (global.xai.grok-4.7 answered as
grok-4.6, us.writer.palmyra-x5-v1:0 as palmyra-x4).

Run:

- The new rows of TestBedrockProfileAnsweredByItsModelIsNoSwap fail on
  the old served.go, each with Swapped true where the model's own name
  answered (six pairs); with the change they pass, the two
  still-a-swap guards stay true, and the route and usage row of the
  anthropic run through the Bedrock preset stay unmarked.
- go test -tags nogui -count=1 ./internal/usage ok.
- go test -tags nogui -count=1 -run 'Bedrock|Swapped|Served|RelayRenamed|Rename'
  ./internal/gateway ok.
- gofmt -l clean; go vet -tags nogui of both packages on darwin,
  GOOS=linux -tags nogui and GOOS=windows clean.
- go build darwin, GOOS=linux -tags nogui, GOOS=windows ok.

Not tried: a real Bedrock account on xAI, Writer, Moonshot or NVIDIA
models; the pairs are read off models.dev's bedrock list of today.

Generated-by: GLM-5.3-Flash (ZCode)
2026-10-28 03:14:05 +08:00
ggbdpq 85b45b4d71 usage: a window's dollar whole prices the model the reply named (#2488)
The ledger prices a call whose own id has no price as the model the
reply named (Served, #1498). A window's whole priced through apiPricer,
which looked only at Record.Model, so one such call in a window had no
API price, the window counted as unpriced and its dollar whole was left
out while its tokens stayed. apiPricer now tries Served through the same
chain (maker, the provider's list, Same as) when the asked id has none.
The asked id keeps its own price when it has one; a price the user set
or a rate still never enters the whole. Past cycles use the same
apiPricer and take it too.

Patch by ggbdpq (Discord gua2100), as posted in #2488. Review: the
pricer is a closure built once per query with its own cache, keyed now
on (provider, model, served); no shared or stateful call added. The
only conflict on current main was the test file, where the Antigravity pools test
(TestWindowHoldsReckonsAntigravityPools) landed in the same spot; both
tests are kept.

Run (sandbox HOME, at this tree on origin/main 02cbdf5bd):
- go test -tags nogui -count=1 ./internal/usage/: ok
- Broken by hand: window_holds.go put back to origin/main, test kept:
  TestHoldsPriceTheModelTheReplyNamed FAIL "the model the reply named
  wasn't its API price: <nil>". Restored: ok.
- gofmt -l internal/usage: clean. go vet ./internal/usage/ on darwin,
  GOOS=windows, GOOS=linux: ok.
Not tried: the GUI's Usage page with a real relay account whose reply
names another model; go test ./... (one suite per machine).
2026-10-28 00:51:58 +08:00
yetone 22bc7a4477 usage: a probe at another host of a provider's site is listed under it (CyberCaius)
CyberCaius on Discord, on the latest release: the Usage page's provider
filter listed Leee and leee.baby, and leee.baby's rows were the model
lists ("模型列表", magpie 自身, 200) asked while Leee was being added.
In the first report the same shape was example on api.example.me with
example.me in the filter, which we had put down to another address typed.

The Add sheet's model list runs before the provider has an id, so
probelog records it under the host asked. 8e2ba36de (v0.1.1697) and
94c2aaecb (v0.1.1726) give such a row to the provider saved on that
exact host, or to the one the log's calls to it went to. The reporter
asks a relay's bare domain (leee.baby, example.me), which answers
/v1/models, and saves the provider on another host of it
(api.example.me). No provider is on leee.baby, no call went there, so
the row stayed the host.

Now a probe recorded under a host no provider is on, and no call went
to, goes by the host's site: its registrable domain (provider.SiteOf,
publicsuffix eTLD+1, port and case aside). The one provider saved on a
host of that site takes it (Renames.OnSite), and with none saved there,
the one the log's calls to that site went to (sitesOf over
logSnapshot.hosts), so it stays with a deleted provider too. A site two
providers are on stays the host; a tenant of a hosting suffix
(x.vercel.app), an address and a bare name (localhost) have no site and
stay as they were. It is done when the log is read: rows written before
this release, the reporter's 16:57 and 17:32 ones, are listed under the
provider too, with nothing to migrate and nothing to set.

Run (rebased on 97332140a):
- go test -tags nogui ./internal/usage ./internal/usageapi
  ./internal/probelog: ok.
- ./internal/provider -skip TestUnreadLoginsWriteErrorsKeepCredentials
  (#3632 crashes the binary): ok but TestFetchAsksASharedBaseOnce,
  TestFetchAsksOneListOnceForTwoBasesOfIt and
  TestFetchUnionsProtocolListsWithoutChat, open as #3854.
- New TestProbesOfAProviderOnAnotherHostOfItsSiteListIt: model lists at
  leee.baby, Leee.Baby and www.leee.baby:443 before Add on
  api.leee.baby; two providers on *.two.example, mine.vercel.app beside
  theirs.vercel.app, 127.0.0.1:7 beside 127.0.0.1:8. Providers are
  [127.0.0.1:7 leee mine.vercel.app two.example] with no call made,
  after a call, and after Delete; leee's filter has its 4 rows.
- New TestSiteOf.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows for
  internal/provider and internal/usage.
- Sandbox HOME, real binary, `magpie web`: POST /api/provider/list at
  http://leee.localhost:3488/v1 (a fake OpenAI-compatible server), then
  /api/provider/save on http://api.leee.localhost:3488/v1 as Leee2.
  Built at e54a7d50b, /api/usage/requests listed leee and
  leee.localhost:3488; the fixed build, over the same usage.jsonl, lists
  leee and leee2 with the row under leee2.

Broken by hand: probeProvider without the saved-site branch fails the
new test at "no calls" with [127.0.0.1:7 leee.baby mine.vercel.app
two.example www.leee.baby:443]; without the log-site branch it fails at
"deleted" with leee.baby and www.leee.baby:443 back. On e54a7d50b the
test fails with those two names, the reporter's extra entry.

Not tried: the reporter's own usage.jsonl and providers.json (Leee's
saved host is inferred from the example.me report, not seen); a
reporter whose two providers share one site (stays the host, by
design); the GUI suite (no GUI file changed); the full go test ./...
2026-10-28 00:14:13 +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 14e4d80402 usage: an Antigravity card's pools draw their curve, say when they run out and what the whole holds
max2020 (Discord #help, 10-27): "为什么反重力这里没有额度的预测和对价格的预估".
An Antigravity card's rows are its pools' windows (Gemini · 5 hours,
Claude & GPT · 7 days …). They are Aside, since routing reads the
models' own windows, and the models' windows are a Family's. So:
- quota history (pointOf) kept none of them. The card had no curve and
  no "Runs out … at this pace" line, though noteQuotaHistory and the
  GUI already name a pool's line "Pool · window" (9ccabdfbd said pools
  are kept; the Aside check left them out from the start).
- holdsBounds left every Family, Pool and Aside window out, so no
  "Whole ≈ N tokens · ≈ $X" and not even "not enough data".

Now a pool's own window (Pool set, no Family: QuotaWindow.PoolWindow)
is kept in the history under LineName ("Gemini · 5 hours") and has its
whole reckoned. It counts the calls to its own models (CountsIn): the
per-model windows given its pool, else, for a pool read with only its
week (a Starter plan, whose models get no pool), the families its name
says and no other pool took (PoolMembers). A model asked for by its
family's id (gemini-3.8-flash) counts toward its levels' windows.
withRecordedWindowStarts finds a pool's line by the same name. The
models' own windows, and a pool with no models known, are still not
told. Dry runs still skip pools: one pool spent says nothing about a
call to another pool's model.

Run (at a312bf3e3 + this change):
- TestQuotaHistoryKeepsAntigravityPools and
  TestWindowHoldsReckonsAntigravityPools (new).
- go test ./internal/provider ./internal/usage ./internal/gui
  ./internal/cli, skipping #3632's and #3854's tests: usage, cli and
  gui ok. provider's first run hit a full disk (ENOSPC in TempDir); its
  26 failed tests were all TempDir/mkdir "no space left", rerun by name
  with room: ok. Every other provider test passed in the first run.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok.
- Rebased on 28f3c4d7f (8 files of provider/usage changed upstream): both new
  tests, go test ./internal/usage ok, vet darwin/linux nogui/windows ok.
- app.js is unchanged (it already looks the pool lines up), so no GUI run.

Broken by hand:
- pointOf back to skipping every Aside window: the history test is red
  ("histories = []").
- holdsBounds without the pool case: the holds test is red ("no whole
  reckoned").
- Counts in place of CountsIn: the pool counts every call of the
  account (530000 tokens, want 10000).

Not tried:
- a real Antigravity account. The owner's kept card is a Starter plan
  with 0% used on Gemini and 100% on Claude & GPT, so its 7-day pools
  would read "not enough data" until 5% is used.
- A forecast needs 3 readings over an hour of the current cycle.
- Antigravity's level ids (gemini-3.1-pro-high, claude-opus-4-6-thinking,
  gemini-3.8-flash-tiered) have no API price in models.dev. A pool with
  such calls tells tokens with no $ ("some models have no API price").
- Past cycles (HistoricalWindowHolds) still leave pools out, since a kept
  card has no model ids to count by.
2026-10-27 18:41:27 +08:00
yetone 28f3c4d7fd codex: the Codex app's first 100 models hold the ones used, hidden ones last
@ZhenLuoTTAWDTT on X: with Codex on magpie the model list stops short,
and the models past it can't be chosen.

Cause, from the clients' own code: the Codex app (ChatGPT.app
26.1013.40934, app-initial-90eb42395b7d.js) and the VS Code extension
(openai.chatgpt 26.51021.22027, model-queries-667cf4bd657d.js) both ask
their app-server for model/list with includeHidden, cursor null and
limit 100 (e?.limit??100) and never ask for nextCursor. codex-rs's
list_models pages the list sorted by priority, hidden entries counted,
so anything past the 100th is in no picker there. The CLI's /model
(tui model_popups.rs) lists every preset in a scrolling popup and has no
cap. magpie truncated nothing; its models are numbered after the
account's own, so a user with many models lost everything past ~100 in
the app, while hidden entries (codex-auto-review and the like) took
slots at the top.

Fix: codexcat.Fit ranks the list last of all, on every route magpie
hands Codex a list (/backend-api/codex/models after the user's own
order, /v1/codex/models before its 1 MiB cut, and the
model_catalog_json file via CatalogUsed): hidden entries go after every
listed one, and with more than 100 listed, the models Codex used in the
last 30 days (usage.CodexUsed, most recent first, at most 100; on
/v1/codex/models only the asking key's, CodexUsedBy) are brought into
the first 100 in the order they stood. The rest keep their order. The
list's ETag and X-Models-Etag carry a tag of the used set
(codexcat.UsedTag), so Codex asks again when it uses a model it hadn't;
CodexUsed is read at most once a minute, or at once when Append writes a
Codex call to a model it doesn't hold. Documented in
docs/subsystems/gateway-routing.md.

Tests (each red on the old code, broken by hand: Fit a no-op, the gateway
calls and the used tag removed, Append's codexUsedNew removed):
TestFitKeepsUsedModelsWhereTheCodexAppReads, TestFitLeavesAShortListsOrder,
TestCatalogUsedFits, TestUsedTagIsTheSet (codexcat), TestCodexUsed
(usage), TestCodexModelListKeepsUsedModelsInTheAppsHundred and
TestCodexCatalogKeepsTheKeysUsedModelsFirst (gateway).

Real run: codex-cli 0.162.1's app-server in a sandbox CODEX_HOME (never
~/.codex) with a model_catalog_json of 3 hidden entries at priority 1-3
and 150 listed models, driven over stdio with the app's own request
(model/list includeHidden, limit 100). Before: page 1 held 100 of 153,
3 of them hidden, the last many/model-096, nextCursor "100". The same
catalog put through Fit with many/model-140 used: page 1 has no hidden
entry and ends with many/model-140. The TUI's /model scrolled to all
150 (tmux).

Run with this change on e4ca47b0f: gofmt -l clean; go vet
-tags nogui with GOOS=linux and GOOS=windows on codexcat, usage, gateway
and agent clean. go test -count=1 -timeout 45m: codexcat ok, usage ok;
-run 'Codex|Fit|Used|ModelList|Catalog' on gateway, usage and agent ok
(122s, 11s, 80s). The whole gateway and agent packages ran too, but the
machine's disk was full under other sessions' runs (209M to 2.5G free),
and 959 lines of that log are "no space left on device". Of the reds,
three are not that: TestFolderVarsAreListed is #3884 (CARGO_HOME, red on
main since e4552cca9); TestHistoryKeepsDaysAndDropsOld (gateway) and
TestSuffixModesReachAgentFiles (agent) failed beside half-written
settings files and pass alone 3 of 3 at this commit. Not run: the full
./... suite (no room on the disk); the Codex app and VS Code extension
themselves against a magpie with this change (their request was read
from their bundles and replayed against a real app-server).

Rebased on ca8a6f346 (agent rename and Codex app route, claude_runs in
gateway) and run again: GOOS=windows go vet on agent
and gateway clean; -run 'Codex|Fit|Used|ModelList|Catalog' ok on
codexcat, usage and gateway (75s), and with |Rename ok on agent (68s).
Then rebased on 94c2aaecb (usage rename) and usage run whole again: ok
(88s).
2026-10-27 18:37:16 +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 8e2ba36de9 usage: a provider's requests made while it was being added are listed under it, not its host (yyddbds)
yyddbds on Discord added one custom provider, 大灰狼 on dahuilang.best,
and the Usage page's provider filter listed it twice: 大灰狼 and
dahuilang.best. The Add sheet's Detect and model-list requests run
before the provider has an id, so probelog records them under the host
asked (probelog.Note: "a provider being added has no id yet"). Those
rows are listed on the Requests page, and their provider went into the
page's provider list as a provider of its own.

Renames now also knows each provider by the hosts of its URLs, and
probeChunk reads a probe row through Renames.ProbeOf: a host exactly
one provider is on is that provider's id. It is done when the log is
read, so rows written before this release are merged too. A host no
provider is on (an Add given up) or two providers share stays as it
was recorded; a provider id is never taken for a host.

Run:
- go test -tags nogui ./internal/usage ./internal/usageapi
  ./internal/probelog ./internal/provider (-skip
  TestUnreadLoginsWriteErrorsKeepCredentials, #3632) ./internal/gui:
  ok.
- New TestProbesOfAProviderBeingAddedListItOnce: Detect rows written
  through probelog.Note under dahuilang.best and DaHuiLang.best before
  provider.Add("大灰狼"), plus a gateway call under its id; providers
  are [dahuilang other.example shared.example:8443], and the filter on
  dahuilang has its 3 rows.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.

Broken by hand: probeChunk back on Renames.Of fails it with providers
[DaHuiLang.best dahuilang dahuilang.best other.example
shared.example:8443], the reporter's two entries.

Not tried: the reporter's own usage.jsonl; the full go test ./...
(other sessions' suites were on this machine).
2026-10-27 15:21:11 +08:00
yetone 51af40f9cb usage: a poll pairs Codex calls by id without decoding the session files the gateway names none of
codexChunkResponsePairs decoded every local chunk of the period on each
Requests poll to look up the few response ids the gateway logged. The ids
kept per chunk serial for the fold (foldIDs) now hold every call's id hash,
not only Codex log calls', and a chunk none of whose hashes is a pick's is
skipped. The pick is still made by the id string, so a hash match only
reads a chunk, never pairs one.

Measured on real history (rss-home, 8 GUI polls 15s apart, after a 90s
warm start), magpie-ids vs v0.1.1677's code, two runs each:
- CPU profile: pairRows 0.74s/0.70s vs 0.85s/0.89s; chunk unpacking
  0.65s/0.59s vs 0.74s/0.81s; codexChunkResponsePairs 0.13-0.18s gone.
- Allocations: the 191MB the pairs decoded is gone from it, but most of
  it moves to visibleLocal, which now grows the pooled row buffer the
  pairs grew before. Total 2671MB vs 2528MB, within live-history noise.

Run at the pushed head (on 2afacd7d1):
- go test ./internal/usage/... ./internal/usageapi/...: ok
- go test ./internal/gui/: ok on the base before the rebase (50606d8c0);
  the two commits rebased over touch neither usage nor its callers
- GOOS=linux/windows/darwin go vet -tags nogui ./internal/usage/ ./internal/gui/: ok; gofmt clean
- TestPairsReadOnlyChunksTheGatewayNamed: red with the skip taken out
  (read 2 local chunks), green restored.

Not tried: the live app; the A/B ran on rss-home, which reads the real
history read-only.
2026-10-27 12:16:01 +08:00
yetone 9fed5dc8c1 usage: a Codex effort past its minute is told while the next is built behind it
The Sessions page asks for every Codex thread's consumption on each 15s
poll. Once the kept answer was a minute old and any session file had
changed (a working Codex or Claude Code changes one all the time), the
ask built the ledger of all history inside the request, so /api/sessions
held for 0.8 to 1.3 s about once a minute. Now that ask is told the kept
answer and the build runs behind it, one at a time as before; the next
poll has the change. A period's first answer, and one for another home,
are still waited for.

effortBehind is off in the usage tests' TestMain, as effortFresh is, so
the tests that write a change and ask again still see it at once.
TestCodexModelEffortHeldForAMinute now holds the build and checks that
the ask after the minute, and one during the build, get the last answer,
and that the ask after the build gets the change without a third build.

Run at 5e3dd1d52 plus this change (main since gained e7173958e and
aa766289b, agent and gui only; re-run below at the rebased head):
- go test ./internal/usage/ ./internal/usageapi/ ./internal/gui/ ok
- go test -race -count=5 -run TestCodexModelEffort ./internal/usage/ ok
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage/ ok
- broken by hand (the background branch made unreachable):
  TestCodexModelEffortHeldForAMinute red, "after the minute the ask
  waited for the build"
- real history (rss-home over the live ~/.codex and ~/.claude, 120s
  CPU profile over 8 GUI-like polls, rss-bin/cpu6.sh), /api/sessions
  per poll:
    before: 1238 207 138 210 194 980 295 288 ms; 815 140 197 158 413 484 151 231 ms
    after:   348 141 330 177 263 233 135 263 ms; 449 267 203 210 161 239 317 290 ms
  pairRows CPU unchanged (0.79s vs 0.81/0.91s): the build moved, it
  wasn't added. Requests page max 260 ms after vs 404 ms before on the
  second pair.

At the rebased head (on e7173958e): go build ok; go test ./internal/usageapi/
./internal/gui/ ok; ./internal/usage/ ok except
TestUsageReadAfterAppendHashesNothingOnAFineClock/whole-second_stamp, a
known wall-clock flake taken by ggbdpq (#3511): 1 of 20 red on a clean
origin/main e7173958e worktree, 0 of 20 with this change.

Not tried: the Windows box and the Linux app; nothing here is OS-specific.
2026-10-27 11:24:15 +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 c272f3799e usage: a session file's Codex ids are hashed once while it stands
A Usage page polled while one session was live paired every chunk of the
period again, and foldCodexRows decoded each session file to hash the
same response ids: ~40 MB a poll of today's page, more than any other
part of it. Each chunk's Codex log calls are now kept by its serial as
one uint64 each (the id's hash shifted over its index, 8 bytes a call),
for the four folds after the last that read them, so a poll decodes
only the chunks that changed. Calls whose hash is the same are still
told apart by their ids after, as before.

Run (worktree clip; tests and vet again at this head, rebased on b7d5a97fe):
- go test -count=1 ./internal/usage/ ./internal/usageapi/: ok
- TestFoldReadsAChunksIDsOnce: red with the cache turned off by hand
  (the second fold read both chunks again), green with it
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/usage/: clean
- A/B, ab5.sh (warm start in a sandbox HOME with a copy of the real
  history, then 8 GUI-like polls 15 s apart), v0.1.1659 vs this:
  allocated over the polls 2.99 GB -> 2.39 GB; queryPage 726 -> 442 MB;
  foldCodexRows 326 MB -> under the profile's floor;
  /api/usage/requests?period=today mean 154 -> 100 ms;
  /api/sessions 305 -> 213 ms; footprint 10 s into each rest
  164-193 -> 156-187 MB.

Not done here: codexChunkResponsePairs, visibleLocal and Codex effort's
visit still decode every chunk a poll (~117, 85 and 91 MB over the run).
2026-10-27 08:46:33 +08:00
yetone 8fba65d0bc gateway: what masking took a request is kept, and shown as Masking in its time
fremontdango on Discord asked, after the request that sat as "routing…"
while it was masked, how long masking took. Now each request keeps it.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Run at this head: gofmt clean; GOOS=linux and GOOS=windows go vet
-tags nogui ./internal/usage; go test -timeout 45m -count=1
./internal/usage ./internal/gui ok.
Not run: the full ./... suite (only internal/usage changed).
2026-10-27 04:58:22 +08:00
yetone 39526c0690 usage: Append keeps the log open between calls, not an open and a close for each request (#3725)
Every request the gateway serves appends a line to usage.jsonl, and
Append opened and closed the file each time. In a CPU profile of the
request path (BenchmarkZZIO, a local benchmark not committed) Append was
0.51s of the handler's 1.36s, 0.35s of it in os.OpenFile and 0.07s in
Close.

Now the handle is held, under the same mu. Before each write the held
file's identity is checked against what Path names now (fstat and stat,
os.SameFile), so a log another program moves, removes or replaces, or a
Path that changes with HOME, is opened again. A failed write drops the
handle. Windows still closes after each write, since a file held open
there can't be removed or renamed.

Measured (local microbenchmark, open+fstat+write+fstat+close against a
held file with stat+fstat+write+fstat, 600-byte lines, 20000 runs, load
~80): 55 to 116µs per call before, 11 to 24µs held. On the whole
request (BenchmarkZZIO) the difference is inside the noise at this load,
so no request-time figure is claimed.

TestAppendHeldLogFollowsThePath appends twice and checks the second call
used the same handle (and that Windows holds none), then replaces the log
by rename, removes it, and moves HOME, checking each time that the next
call is counted in the file Path names. Broken by hand (identity check
skipped) it is red: after a replacement the call went to the old file and
Summarize counted 0 calls.

Windows box (test binary run outside the source tree): internal/usage,
mine and origin/main 92cf0b68d, both fail the same three tests:
TestDesktopSessionAccountMetadata (#1356), and TestKimiCodeCost and
TestRequestDiskNamesItsSource, which read testdata and source files that
aren't beside the binary there. TestUsageReadAfterAppendHashesNothingOnAFineClock
was red once in my first full run (#3511, the whole-second case); it
passed 30 of 30 alone with this change and in the next full run.

Run at this tree (fcbf618eb plus this change): gofmt -l internal/usage
clean; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage
ok; go test -count=1 -timeout 45m ./internal/usage ./internal/usageapi
./internal/gateway ok (16.161s, 6.655s, 448.476s).
2026-10-27 02:25:45 +08:00
yetone e1709ab42e usage: Append makes the log's folder only when it is missing (#3725)
Every request appends one line to usage.jsonl, and Append ran
os.MkdirAll on the folder first each time: a stat, and on its error
path a walk up the tree. Now the file is opened first, and the folder is
made (then the open tried again) only when that open says it doesn't
exist.

Measured with a scratch benchmark (not committed) at 1360689ef, Append into an
existing folder, -count 5: 3070 B and 25 allocs per call before, 2445 B
and 20 allocs after. Wall time is the write itself, ~45-60µs, and at
machine load ~160 the run-to-run noise was bigger than the saved stat,
so no time saving is claimed. A scratch test with XDG_CONFIG_HOME under
two missing folders checked the first Append still creates them and the
file.

Run at 1360689ef plus this change: gofmt -l clean; GOOS=linux and GOOS=windows
go vet -tags nogui ./internal/usage ok; go test -count=1 -timeout 45m
./internal/usage ok.
2026-10-27 01:58:09 +08:00
yetone 9dc7d6eb84 usage: a large build's archives are held in a spill file as they are made (#3493)
A cold build (first start, or after an update that changes internal/usage)
kept every chunk's archive on the heap until save had written
requests-v1.bin and swapped them for the file's pages: 31MB for 15.7k
sessions, the largest thing a cold peak held over a warm start's.

Now a build that wants requestDiskLeast or more files written writes each
archive to requests-*.spill as the chunk is made, lets go of the heap copy,
and maps the file once the build is done (unlinked at once). save then
swaps the spill's pages for requests-v1.bin's as before: pagesRank orders
heap < spill < file, and keep and save take the later. A spill that can't
be written or mapped has each of its chunks made again from its source, so
none is left without an archive. Windows maps no file, so nothing changes
there.

Run, real data (15.7k Claude Code + Codex sessions, sandbox HOME, copies of
the call shards, requests-v1.bin removed before each run), the gui warm-up
harness alternating old (cbbf3163c) and new, 4 rounds each:
  phys_footprint_peak old 396 353 346 352 MB, new 319 322 329 329 MB
  peak live (gctrace) old 209-259 MB, new 188-205 MB
  at rest unchanged (184-205 MB), warm-up time in the same range.
  gctrace: cold max live after mark is now 187MB against warm's 173MB; what
  is left of the gap is allocation churn (1.2GB allocated in the cold
  build against 280MB warm), not held data.
go test ./internal/usage ./internal/gui ok; -race -count=3 of the disk and
spill tests ok; GOOS=linux and windows go vet -tags nogui ok; gofmt clean.
Broken by hand: no spill put -> TestRequestDiskBuildSpills red; done not
making a chunk again -> TestArchiveSpillFailedMadeAgain red; the spill
ranked as the file -> TestRequestDiskBuildSpills red after the save.
Not tried: Windows (no mapping, path unchanged), a disk that fills while
spilling (the made-again path is covered by the unit test only).
2026-10-25 16:56:02 +08:00
yetone cbbf3163cb usage: a cold build's chunks are of the file's pages once it is written (#3493)
A start that reads requests-v1.bin keeps each chunk's archive in the
file's mapped pages, not on the heap. A start that builds the chunks
(a cold one: no file, or one of another build) kept the archives it
encoded on the heap until the next start, after writing the very same
bytes to the file: 32-40MB for 15.7k sessions, and a resting heap
~50MB over a warm start's.

Once save has written the file, onDisk maps it and makes, for each
chunk whose archive is of the heap, a copy whose archive is the same
bytes of the mapping (checked equal). save swaps it in for the chunk
of the same serial: a read since has copied the chunk with a use of
its own, so the pointer it wrote is gone by then. A read that copied
the chunks before the swap and finishes after it keeps the mapped
archive (keep), or it would put the heap one back. Nothing changes
where no file is mapped (Windows).

diskUnmapped, the tests' hook, is an atomic.Pointer: a mapping's
cleanup reads it on its own goroutine while the next test sets it,
which -race -count=4 caught once the new test let go of mappings.

Run at this tree (67a137744 + this change):
- go test -count=1 -timeout 45m ./internal/usage/ ./internal/sessions/:
  ok. go test -run 'Warm|Session|Request|Usage' ./internal/gui/
  ./internal/gateway/: ok.
- go test -race -count=4 -run TestRequestDisk ./internal/usage/: ok,
  six times in a row.
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage/: ok;
  gofmt -l clean.
- TestRequestDiskBuiltChunksMapped holds the write while a second page
  copies the chunks and a third copies them before the write and keeps
  them after it. It went red (0 of 4 mapped) with the swap matched by
  pointer instead of serial, and with keep not carrying the mapping.
- The real warm-up (gui warmSteps in sessions.Warm) on a copy of the
  owner's ~/.claude and ~/.codex sessions, cold (requests-v1.bin
  removed), parent and change alternating, 3 runs each, measured 5s
  after the warm-up:
  - heap at rest: 200/200/198MB before, 154/148/152MB after;
  - phys_footprint at rest: 233/234/237MB before, 198/197/205MB after;
  - phys_footprint_peak: 361/396/347MB before, 335/367/378MB after,
    the same within noise (the build itself is unchanged).

Not tried: Windows (it maps no file, so it is unchanged there).
2026-10-25 16:19:18 +08:00
yetone ba301e98e2 usage: a page's passes over the chunks decode into buffers kept between them (#3493)
Each pass of a Requests page over every chunk (foldCodexRows, the
response pairs, visibleLocal, matchedBlocks, visit, partsOf, newest,
rowsOf) started a chunkRows with no buffers and grew its rows, strings,
shapes and decode buffer from nothing. A warm start's All page and
Codex's effort after it read the same rows pass after pass, ~30 MB a
pass. chunkRows now takes a rowBuffer from a pool, unpacks into it
(unpackReusing gets a dst chunk too, so the open chunk isn't allocated
each block), and gives it back on release, its strings cleared so no
row text is held.

Measured on the real data copy (sbpairs: 12k Codex rollouts and the
Claude projects), warm-up harness TestZZWarm, each binary run 3 times
in a row and the first run dropped (the chunk file is named by this
package's source, so alternating binaries rebuilds it):
  step 2 (QueryPage All) allocated   835 MB -> 666 MB
  allocated through step 3 (effort)  994 MB -> 820 MB
  unpackReusing in step 2            163 MB -> 34 MB
  peak footprint                     ~240 MB, unchanged

Run at this head (base defbb1a15): go test ./internal/usage
./internal/sessions ./internal/gui ok; -race -count=3 of the chunkRows,
Pack and Archive tests ok; GOOS=linux and windows go vet -tags nogui
./internal/usage ok; gofmt clean. TestChunkRowsReuseReadsEachBlock now
runs 4 passes, lent and not, in both orders, through one pool; broken
by hand (a reused rows slice cut to its cap, not the block's count) it
fails "pass 0 block 1: 0 rows, want 3".

Not tried: Linux and Windows real-data runs.
2026-10-25 15:10:47 +08:00
yetone 42976f9a08 usage: a renamed provider is shown once, by the id it has now
cybercaius on Discord (#help, 10-25): "已经更改供应商 id 的也没有变更过来反而
分开显示了". Reproduced in a sandbox HOME (magpie web on 3582, fake upstream
on 3583): after renaming myrelay to newrelay in the editor, the Requests
page's provider list had both myrelay and newrelay, each named "myrelay",
because the model-list probe row was still under myrelay. The summary was
already folded; the probe chunk, the Sessions tab's vias and the gateway's
loggedAnswers (lead-first routing) were not renamed at all.

What changed
- provider.Renames (UsageRenames): Of(id, time) is the id a call recorded
  under id at that time belongs to now. Every usage reader goes through it:
  summarizeFrom (and its historical-key set), ledgerMatched, NewPricer,
  NewCoster, the Requests page's gateway blocks, probe rows and other
  computers' days, window holds and their history, buildVias, and
  gateway loggedAnswers. Visit stays as recorded so Of is taken once.
  The summary, Requests and vias caches key on Renames.Key.
- An id reused by another provider no longer pulls the new one's calls
  into the old one. Rename onto, or Save of a new provider under, an id in
  another's Was moves it into that one's Gave with the time (giveID):
  calls before then stay the old provider's. freeID treats Was ids as
  taken, so adding the vendor again gets "-2". Renamed() (refs) skips ids
  a provider or subscription holds now.
- A providers.json that can't be read keeps the last renames read instead
  of none (a failed read is unknown), so usage doesn't split meanwhile.
- History: nothing in usage.jsonl is rewritten. Calls from before this
  release under a renamed id show under the new id at once. An id that was
  reused before this release has no hand-over time, so its calls show under
  whoever holds the id now, as before.

Siblings checked: budget keys by caller key; per-key limits, RPM and
concurrency count live requests by the current id; tray totals go through
QueryPage; codex_memory reads Requested refs. None needed a change.

Run at the tree before the rebase; rebased onto 894603bcd (GUI-only,
none of these files) and provider, usage, usageapi, the build and the
Rename/Answer/Lead tests of gateway and gui run again there: ok.
- TestRenamesByWhenTheIDWasTaken (provider), TestRenamedProviderShownOnce
  (usage), TestRenamedProviderAnsweredItsLead (gateway): each red with its
  piece broken by hand (Save's giveID, freeID's Was, the last-good renames,
  probe rename, vias rename, block pricer's timed path, summarize's time,
  loggedAnswers' rename), green with it.
- go test -timeout 45m provider usage usageapi budget middleware cli agent
  gui gateway sessions profile tui: all ok.
- gofmt -l, go vet ./internal/..., GOOS=linux/windows -tags nogui vet of
  provider/usage/gateway and build of the binary: clean.
- Sandbox: rebuilt binary on the same HOME; /api/usage/requests lists only
  newrelay, the probe row included.

Not tried: the GUI suite (no JS or asset changed; /api/providers gains an
omitempty "gave"), Windows tests run on the Windows box, a real account,
and the full ./... suite (other sessions' suites were running).
2026-10-25 10:53:45 +08:00
yetone 115ca34343 usage: the chunks' file is mapped, not read into the heap (#3493)
A start read requests-v1.bin's 44MB of chunk archives into the heap,
where they stayed: a fifth of the heap at rest, and with GOGC 25 a
larger heap goal through every warm-up step. They are pointer-free and
only ever decoded, so on unix the file is now mapped read-only
(MAP_SHARED, PROT_READ) and each chunk's Archive is a capped slice of
the mapping. A cleanup unmaps it once no chunk refers to it. The file is
only replaced by a rename (toDisk), never written in place; a read past
its end, if another program cut it short, is caught by readMapped
(SetPanicOnFault) as a failed read, not a crash: the chunk unpacks as
nil and reads as no rows, as a corrupt archive did before, until its
session file changes or magpie starts again. Windows can't
rename over a mapped file, so it reads the file as before
(request_disk_map_other.go).

decodeMapped keeps the decode's closure out of unpackReusing: with the
closure there, data escaped to the heap and every row's take() through
it was slower, which made step 2 0.12-0.2s slower than before (found by
profile: unpackReusing.func2 0.28s -> 0.64s over three runs).

Run at this tree, on the owner's real data (sandbox HOME with
.claude/projects and .codex/sessions linked read-only, ~421k rows), warm
runs interleaved with v0.1.1471 (b1f44d099), load 26-32:
- phys_footprint_peak: 285-298MB -> 232-259MB
- phys_footprint at rest: 221-227MB -> 176-179MB
- peak live heap 200MB -> 157MB, heap at rest 198MB -> 147MB
- step 2 (QueryPage All): 771-952ms -> 754-814ms; warm-up 1.68-1.96s
  -> 1.54-1.89s
- every one of the 15624 mapped chunks unpacks to the same rows
  (reflect.DeepEqual, 359553 rows) as its archive copied to the heap
- mmap of the file alone and a CRC pass: 6.5ms, read+CRC 8-10ms

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

Not tried: a Linux or Windows real-data run (Linux vet only; Windows
keeps the old path); a file truncated under a running magpie outside
the test.
2026-10-25 08:29:23 +08:00
yetone b1f44d099e usage: Codex's effort reuses the pairing the page of its period just made (#3493)
The warm-up builds the Requests page of All and then Codex's model and
effort over All. The page keeps its pairing of the calls (pairMemo, by
chunk serials), but the effort paired every session file's calls again
from nothing, the warm-up's step 3. It now reads requestIndex.pairs[p]
before taking its private copy and pairs through pairRowsMemo, so
unchanged chunks keep their pairing, and it keeps the new pairing for
the next page or effort. Storing a period's pairing is one helper,
keepPairs, that queryPage uses too.

Run at this head (on e1f5f9c16, which origin/main still was):
- TestCodexEffortReusesPagePairing (new): the page pairs once, the
  effort after it pairs 0 times, and equals an effort that pairs on its
  own. Broken by hand (memo -> nil): red, "the effort after the page
  paired again (2 pairings)".
- go test ./internal/usage ./internal/gui ./internal/sessions: ok.
  -race ./internal/usage: ok. go vet -tags nogui GOOS=linux and
  GOOS=windows for usage and gui, gofmt: clean.
- Real data (a copy of the owner's sessions, 421,292 calls), warm-up
  three runs each after one to write the cache file, e1f5f9c16 -> this:
  step 3 0.52-0.58s -> 0.24s; warm-up alloc 1.24-1.29GB -> 1.06GB;
  warm-up 1.80-1.85s -> 1.50s (one 1.77s). Max RSS unchanged (~310-333MB).
- CodexModelEffort(All)'s JSON hash on that data, four runs alternating
  base and this: identical every time (78f93906...).

Not tried: the effort of a period whose page was not built first (it
pairs as before, from nil).
2026-10-25 08:05:33 +08:00
yetone e1f5f9c164 usage: the passes that pair a page's calls read a chunk's strings in place (#3493)
A Requests page decodes each packed session chunk in five passes, one
chunk at a time (chunkRows). Every decode copied the chunk's whole string
section out of the pooled buffer, though four of the passes (folding
Codex's repeated calls, pairing Codex response ids, Claude's repeated
message ids, request-id matching) only look strings up and clone the few
they keep. That copy was the largest allocation of a warm start's page.

Those four passes now read through lentRows: the chunk is decoded into a
buffer the reader owns, and its strings are of that buffer until the next
chunk is decoded over it. The cell pass and every reader that keeps rows
still copy.

What was run, at this head:
- Real data (sbpairs: 421,206 calls, 15.6k session files), warm-up steps
  three runs each, before / after:
  step 2 (first Requests page): 0.88-1.03s / 0.76-0.79s,
  ~560 MB / 446 MB allocated; whole warm-up 1.41-1.45 GB / 1.21 GB
  allocated; maxrss 320-336 MB / 318-319 MB.
- Real pages, base and this change alternately: QueryPage of All, today,
  7d and 30d at offsets 0 and 500, and CodexModelEffort(All). Totals,
  rows and every string are the same; the only differences are float
  costs' last digits, from summation order, which differ between two
  base runs as well (and one new live call).
- Broken by hand: storing the lent message id and request id without
  their clones turns TestRequestPageSameFromPackedLocalChunks red.
- go test ./internal/usage ./internal/gui ./internal/sessions ok;
  -race -run 'TestRequest|Codex|Packed|Visible|Match' ./internal/usage
  ok; GOOS=linux and GOOS=windows go vet -tags nogui of usage and gui
  clean; gofmt clean.

Not tried: the full ./... suite (one suite per machine; only the
packages this reaches were run).
2026-10-25 07:57:24 +08:00
yetone ac149224f9 usage: many rows made since the last write have it written once a run (#3493)
The file of the session files' chunks (requests-v1.bin) was written
only once 64 files' chunks had been made since the last write. Long
sessions that ended since then are few files with many rows: on the
real history (sbpairs) two starts in a row each made 9 files' chunks
again, 84,625 calls (one Claude Code session alone is 52,191), and
neither wrote them, so every start did it again, and the sessions that
ended next joined them until they were 64 files.

noteBuilt also counts the rows made, and writes the file once a run
when they are 20,000 or more. Once, as a session still at work is made
again after each of its calls; the 64-file write is as it was.

Run on 13f907013, and the packages again rebased on 73d17f90c
(usage, gui, sessions ok; vet and gofmt clean):
- real history in a sandbox HOME (the sbpairs copy of the caches), a
  page in each of three processes: before, 9 files (84,625 calls) read
  at each of two starts; after, a start that made every chunk (the
  source changed) and then 0 files read, then 2 (live sessions).
- the rows rule alone on the real history (requestDiskLeast raised past
  15.6k): with no file, a start wrote it (44,275,132 bytes), and the
  next start read it and made 2 files' chunks.
- TestRequestDiskRowsWrittenOnce: red with the rows rule removed ("no
  file of them") and red with the once guard removed ("written again
  for 4 rows").
- go test -count=1 ./internal/usage ./internal/gui ok; go test -race
  -run 'TestRequest|TestQueryPage|TestChunk' ./internal/usage ok;
  GOOS=linux and GOOS=windows go vet -tags nogui on both ok; gofmt -l
  clean.

Not tried: a full go test ./... (one suite per machine).
2026-10-25 07:47:12 +08:00
yetone 42ab935516 usage: requests-v1.bin is of the code that makes rows, not of the binary
The file of the session files' chunks was named by the binary's own
stat key, so every upgrade, and magpie ships several a day, read every
session file again on its first Requests page: on a 15.6k-shard history
warm-up step 2 went from ~0.8-0.9s (read from the file) to 1.6-1.9s and
~1.3GB more allocation. It is named now by the call shards' version
(sessions.CallCacheVersion, which already decides whether a shard of the
calls is read) and a SHA-256 of this package's non-test source, which
the binary carries (go:embed *.go, ~750KB with the tests, which the name
leaves out). Of the last 99 releases, 17 changed that source; the other
82 keep the file. Prices, names and settings are in the file's meta as
before. When the embedded source can't be read the name is the binary's,
as it was.

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

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

Not tried: an upgrade of the real app from one release to the next.
2026-10-25 07:23:45 +08:00
yetone 3767addd4d usage: a block's strings and shapes are read into buffers the next block reuses
Each Requests pass (warm-up step 2's whole-history page, step 3's Codex
effort pairs) decodes every packed block through chunkRows, which already
reused the rows' buffer. Each block still made its strings slice, its
shapes slice and a []int of every string's offset and length, ~170MB of
the ~450MB a pass allocated on a 15.6k-file history. chunkRows now keeps
the strings' and shapes' slices too (unpackReusing), and the offsets are
found by walking the copied section's length prefixes a second time
instead of being stored. The strings themselves still point into one
copy per block, so a row taken from a block keeps its text after the
buffer moves on; only the slices are reused, and nothing holds a block's
slices past the next of().

Measured (real history, sbpairs: 15,656 call shards, gui warm-up steps,
zzbase = 2a3d9f5ae, alternated, two rounds each):
- total alloc through step 3, cold: base 3171/2994MB, new 2610/2626MB
- warm (requests-v1.bin read): base 1763/1751MB, new 1399/1408MB
- times within noise: cold step 2 base 1.86/1.61s, new 1.56/1.85s;
  step 3 0.55-0.79s both

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

Not tried: a Windows or Linux run of the warm-up.
2026-10-25 07:06:36 +08:00
yetone 2a3d9f5aeb usage: a session file's rows are made by the reader that read it (#3493)
A cold Requests build (every upgrade) read the call shards eight at a
time, but turned every call into a row on the one loop that takes them:
logRecord, the account resolver, pricing, interning and packing, ~1 s
of serial CPU over a real history, with the readers waiting on the
window behind it.

prefetchSources becomes prefetchEach: each reader has a make of its own
from newMake, and the loop has its own for a source not wanted. Request
rows are made there. Each make has its own Pricer and Swapped memo, so
neither needs a lock; the session resolver is made once (sync.OnceValue)
and only read after. The serial number is still given in the loop, in
source order. The window now holds packed chunks, smaller than the
calls it held.

Measured on a copy of real data (15,656 shards, 3,451 Claude Code
subagent meta files), GUI warm-up step 2 (QueryPage(All)), cold
(requests-v1.bin written for the other binary), alternating runs:
- before (432393217): 3.24 s / 448 MB maxrss, 2.18 s / 433 MB
- after: 1.85 s / 417 MB, 1.84 s / 410 MB
The readers are now mostly in syscalls (shard and meta.json reads).

Run at this head (432393217 + this):
- go test -count=1 -timeout 45m ./internal/usage: ok; with -race: ok
- go test -count=1 -timeout 45m ./internal/gui: one red,
  TestRestartHandsTheGatewayOver (18 of 19 requests answered, EOF), the
  open #3451; alone -count=5 it passes. Load was ~45.
- TestPrefetchEachMakeIsAReadersOwn: 9 makes (8 readers, the loop's
  own) and no race. Broken by hand: one make shared by every reader ->
  -race reports DATA RACE, red.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/usage ok.
2026-10-25 06:58:27 +08:00
yetone 31bff66be3 usage: a session file's few calls are kept packed too
pack left a chunk of fewer than 64 rows as rows. Most session files hold
a handful of calls, so a cold build (the first start after an update, or
with no requests-v1.bin) kept 13,972 of 15,624 local chunks unpacked:
98,320 rows. The same chunks read back from requests-v1.bin are all
archives, so the cold build alone held them as rows. Now every chunk with
a row is packed when its archive is smaller, as the file's entries
already were.

Measured on the real history copy (sbpairs: 15.6k session files, 420k
calls), one QueryPage(All) from cold under GOGC=25 as the GUI's warm-up
runs it, three runs each, old then new:
- heap in use after: 267/267/269 MB -> 229/227/232 MB
- peak heap in use: 357/367/341 MB -> 308/338/336 MB
- max RSS: 454/462/448 MB -> 420/424/449 MB
- page: 2.95/2.41/2.52 s -> 3.66/2.19/2.42 s (no change past noise)
A page after a new call, packed chunks read from the file: 120-143 ms,
as before.

TestFewRowsArePacked packs three rows and reads them back. It is red
with the old 64-row floor.

Run at this head: go test ./internal/usage (ok);
go test -run 'Usage|Request|Tray|Session' ./internal/gui ./internal/gateway
(ok); go vet ./internal/usage, GOOS=linux and GOOS=windows
-tags nogui; gofmt -l. Not run: the full suite (one per machine).
2026-10-25 06:20:17 +08:00
yetone 5d2260d3e6 usage: the Requests page's chunks are kept on disk, so a start doesn't open every call shard again
A started magpie opened every session file's call shard (~15.6k on a busy
machine) and turned each call into a row again before its first Requests
page could show (#3493). requests-v1.bin (beside sessions.json) now keeps
each session file's chunk as the page packs it: an entry stands while its
file's size and mtime are the same, as a call shard does, and the whole
file while the binary that wrote it and the index's root and meta (prices,
names, providers) are the same. Each entry has a length and CRC-32; a bad
one ends the read and the entries before it stand.

- The file is read when 64 or more session files want reading (a start, a
  change of prices), and written behind the lock once 64 or more chunks
  were made since the last write; fewer are a few shard reads next start,
  not worth writing the whole file again. The idle trim does not write.
- A chunk of another computer's day is not kept; times keep their zone
  (Local, UTC, a tz-database name or a fixed offset).

Real data (sandbox HOME with the live ~/.codex/sessions and
~/.claude/projects symlinked read only, 15,603 sources, 420k rows, load
~90 to 130): a cold All page 3.6s; written in 76 to 168ms behind the lock,
44MB. A start from the file: fromDisk 50ms for 15,602 chunks, then the
blocks 100ms, against the shard reads before; the whole page 1.5s, most of
it now readRequestState (0.65 to 1.1s), which is next. Same total, cost
and input as the cold page.

Run at 500aa7096 (origin/main, fetched): go test -timeout 45m of usage
(14.7s), usageapi (6.5s) and gui (143.5s, before the idle-save removal,
which touches no GUI path) ok; TestRequestChunksFromDisk -race -count=3
ok. gofmt clean; GOOS=linux and GOOS=windows go vet -tags nogui
./internal/usage/ clean.

TestRequestChunksFromDisk (new): a start reads no session file, a file
written over to the same size is read again for its mtime, new prices read
every file, a file cut short stands for the entries before the cut, and
garbage reads every file; every page equals the ledger's. Red with the
header compare taken out, with the size/mtime check taken out, and with
the write skipped.
2026-10-25 05:54:24 +08:00
yetone 4982ded8a6 usage: a turned page reuses the last pairing while its chunks are the same
A Requests page paired every Codex session file's calls with the
gateway's again on each query: clone, fold forks, match response ids.
That unpacked every session chunk three times and was about half of a
warm page (#3493). pairRowsMemo names the chunks of a pairing by their
serials (the probe chunk, which has none, by its rows' log offsets and
times) and keeps what the pairing found: the rows left out (skip,
matched), the actors it changed and each chunk's compactions. The next
query over the same chunks and window applies that to fresh clones
instead of pairing again. A changed file gets a new serial, a new
window or period misses, and adopt drops the memos with the parts.

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

Not tried: the GUI against a live gateway; the page reads the same
QueryPage the tests and the real-data run used.
2026-10-25 05:18:41 +08:00
yetone a6399dd494 usage: a Requests page sums each chunk once and reuses it while the chunk is the same
Turning a page, or the 15s refresh of the open page, built every sum,
chart and share from every row of history again. On the owner's real
history that was 1.15-1.36s a page (load 170) after the chunks were
already cached.

Each chunk's rows are now folded into cells: one per provider, agent,
model, kind, caller, account, computer, source, filter bits and chart
bucket, with its totals. A page merges the cells. The cells of a chunk
are kept per (period, filter, since, until, zone), up to 4 such sets,
keyed by the chunk's serial (a new one every time a chunk is read or
frozen) and a signature of what pairing gave it: rows skipped or
matched, Codex actors and their identities (with the parent's role), and
compactions. A changed file, a gateway tail block or an identity change
from another file sums that chunk again. The newest rows are taken from
chunks in Latest order, stopping once the heap holds rows newer than
the next chunk. Cell strings are unique handles, so the cache holds no
chunk's string block. Totals and Part sums are linear, so merged cells
equal the row-by-row sums; date-mode buckets store the day number and
are placed against the chart's first day at merge time.

What was run (macOS, arm64):
- Real history (sbmem sandbox HOME, read-only links to the owner's
  data), zzbench dump of 9 cases x 2 pages (offset 0/50 after a warm
  7/50 call, and 120/30) with the base 1313b047f and this change: 0
  differences over 18 pages (floats at rel 1e-9).
- zzbench timing at load 170: warm pages 1.15s / 1.36s mean -> 0.45s /
  0.41s; first page 3.1s / 2.8s -> 2.4s / 2.6s.
- New TestRequestCellsFollowIdentityAndFiles: a child chunk whose
  parent's file changes (its root moves to top-z) without the child
  being read again, a changed child file, a gateway append, compared
  to pageFromLedger for All and Week. Broken by hand: reusing a part
  whatever its signature turns it red ("a cached part kept the old
  root: 0 rows, 0 input"). Passes in TZ=UTC too.
- go test -count=1 -timeout 45m ./internal/usage/... ./internal/usageapi/...
  ./internal/sessions/...: usageapi and sessions ok; usage red only on
  TestUsageReadAfterAppendHashesNothingOnAFineClock/whole-second_stamp,
  #3511 (taken by another session). -count=10 of it: 2 FAIL on this
  change and 2 FAIL on the base 1313b047f, at load ~100-145. Every
  other usage test passes.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/usage/.

Not done here: the pairing setup (unpacking unchanged chunks for
visibleLocal, matchedBlocks and foldCodexRows) is now most of a warm
page, ~0.18s each; it is next.
2026-10-25 05:02:18 +08:00
yetone 1313b047f5 usage: a Codex thread's model and effort are read through the request index
CodexModelEffort, which the Sessions list asks for, read the ledger again
on every build: sessions.AgentCalls(since, "codex") opened all of Codex's
shards (12k rollouts, 15.6k shards on the reporter-sized sandbox) after
any new call, beside the Requests page reading the same files into its
own index (#3493). It now reads through the request index as a page
does: readRequestBlocks (moved out of queryPage), the page's pairing and
visit (pairedRows, moved out of buildRequestBlocksOf), and the sums added
row by row as they are visited (effortSums), so a build after a call
reads only the files that changed, and the first of the Sessions list
and the Requests page reads them for both. The LogCalls path still
builds from codexEffortRows.

The visit's row is one per visit now: as a returned closure's local it
was moved to the heap, one allocation a row, which
TestRequestPageAppendDoesNotRepriceHistory caught (10890 allocations over
8000 records against 2000).

Measured before the rebase onto dbbe97991 (its parent ffe493773 adds
rows for magpie's own probes, none in this sandbox), on a sandbox copy of real data (sbmem: 12,069 Codex
rollouts, ~416k rows), base 22a7f86c9 against this, /api/sessions then
the Requests page then /api/sessions, one CPU profile over each run:
  total CPU          16.75s -> 9.40s  (first run 20.10s -> 8.32s)
  CodexModelEffort    4.21s -> 1.65s
  sessions.loadCalls  5.61s -> 1.22s  (now only under the first build;
                                       the page that follows reads none)
  wall, first run: sessions 4.97s -> 2.84s, requests 7.72s -> 2.01s
  (load average 78-133 from other sessions' suites, so wall is noisy)
/api/sessions of both binaries: 4,930 Codex sessions, 4,604 model/effort
entries, every token count equal and every cost equal within 1e-9
(summation order).

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

Not tried: a live Codex session writing while the list polls (the build
after a call is the page's incremental read, measured in 22a7f86c9).
2026-10-25 04:28:31 +08:00
yetone ffe493773c usage: magpie's own Test, Detect APIs and model list requests are rows of the request log, counted nowhere
neiko and gys619 on Discord: a provider's Test or Detect APIs left no
trace in Usage > Requests, so a failing test couldn't be read back.

The provider package marks the context of the editor's Test, Detect APIs
(and per-model detection) and a model list's refresh with a kind
(internal/probelog). Each request sent under the mark is written once:
by the provider's Do, or by probelog.Transport under http.DefaultClient
(netproxy.Install), whichever sends it first; the Claude Code run and
the gateway's translated test write theirs from their result. A row
keeps time, provider, account, model, host, path (no query, no
user:password), method, status, ms and the first 500 bytes of the error.

The row is usage.SourceProbe, agent "magpie", Kind provider_test /
api_detect / model_list ("Test", "Detect APIs", "Model list" in Called
for; purposes.js regenerated). The log index keeps probes apart
(logSnapshot.probes), so Visit, Load, Summarize, budgets, Vias, heatmap,
shared days, LastSeen and observers never meet one. The request page
lists them (probeChunk) and counts none: Row.IsProbe, since a packed row
keeps the row's Source and not its record's. The page shows a muted
badge "magpie's own · not counted in any total" (en, zh, zh-TW, ja, de);
no new control, no layout change.

Tests, each red on the old code:
- usage TestProbeRowsListedNotCounted: listed, clipped, and absent from
  Sum, Through, every By group, Summarize, Load, LastSeen, OwnDays and
  the observer; a provider filter lists it and sums 0.
- provider TestTestWritesItsRequestsDown / TestDetectWritesItsRequestsDown:
  every request the fake server saw is exactly one row, with the right
  kind, model and 401 text; an unmarked Do writes nothing.
- probelog TestNoteKeepsNoSecret, TestTransportOnce.
- GUI usage-ledger-probe: badge per language, both engines, 1180/420,
  light and dark, no left border, no sideways scroll.
- gui TestProviderDetectDraft now expects the log line (source probe,
  kind api_detect, no key) and leaves usage.jsonl out of the unchanged
  config comparison.

Broken by hand, each went red: request_page's uncounted check,
log_index's probe skip, Append's observer skip, Do's Taken (6 rows for
4 requests), Test's and Detect's marks, probelog's query strip,
page.js's badge (11 GUI fails).

Run at this head (on origin/main 22a7f86c9): gofmt -l clean; go vet
./..., GOOS=linux -tags nogui and GOOS=windows clean; go test -count=1
usage, probelog, netproxy, usageapi, provider and gui packages ok (the
rebase over 22a7f86c9 applied cleanly; upstream's 8b460833e chunk
cache leaves probeChunk, built per query, alone).

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

Not tried: no real vendor account (fake servers only); a plugin's model
list, fetched in the JS plugin host, isn't written down; the real GUI
app wasn't launched (Playwright only).
2026-10-25 04:12:06 +08:00
yetone 22a7f86c9b sessions: the Requests page walks the Codex folders once a rebuild
readRequestState asked CallSources and then CodexIdentities, and each
walked ~/.codex/sessions and archived_sessions, lstat()ing every
rollout. Over the 12,069 rollouts of a real Codex folder that was two
walks of ~75ms on every rebuild, which runs on each 5s refresh while
an agent works. CallSourcesAndCodexIdentities walks once and hands the
list to both; CallSources and CodexIdentities stay as they were for
their other callers.

Run at this head:
- go test -timeout 45m ./internal/sessions ./internal/usage
  ./internal/usageapi: ok. TestCodexIdentityParentChainsAndSummaryCache
  now checks the one-walk pair equals CallSources and CodexIdentities.
- GOOS=linux and GOOS=windows go vet -tags nogui on both packages, gofmt.
- Real data (sandbox HOME over the owner's ~/.codex, 12,069 rollouts,
  ~416k rows): CPU profile of two rebuilds, codexFiles 0.31s before,
  0.12s after. Wall times on a loaded machine were 1.0-2.1s both ways,
  too noisy to compare.

Not tried: Windows or WSL folders (wslFiles is still walked as before).
2026-10-25 04:07:20 +08:00
yetone 8b460833e0 usage: the Requests page keeps its chunks while it is open
Every new call is a new page key, so the open Requests tab works its
page out again on each 5s refresh. The session files' packed chunks
were held to 24 MB. A history of 416,000 calls has 63 MB of them, so
each rebuild read 2,679 shards again (39 MB), gob-decoded them, priced
each call and packed it again, and dropped them again after.

Now the chunks are held to 128 MB while the page is asked for. After 2
minutes with no ask (requestIdle), a timer cuts them back to the 24 MB
they were held to before (requestIdleBytes), so an unopened page holds
what it held before.

Measured on the real sandbox data (sbmem, 416,665 rows):
- zzbench, one QueryPage of period=all and six rebuilds at new offsets,
  alternated with v0.1.1439's code at load ~150-200: user CPU
  17.26 / 16.09 s before, 10.79 / 10.21 s after; sys 3.41 / 3.01 ->
  1.98 / 2.14 s; peak RSS 604 / 664 MB -> 566 / 543 MB. A debug count
  showed 2,679 shards read per rebuild before and 1-2 after (the
  files that grew).
- A running magpie (`web --gateway` under sbmem), /api/usage/requests
  period=all at offsets 1-5, warm file cache, load ~175: rebuilds
  1.98 / 1.99 / 1.50 / 1.69 / 1.52 s on v0.1.1439, 1.30 / 1.18 / 1.09 /
  1.07 / 1.07 s now. Cold (the first run after building), one rebuild
  took 23 s; v0.1.1439's cold rebuilds took 5.5-8.0 s, and the warm
  reruns didn't show it again.
- Heap in use on that server, by /v1/magpie/heap: after the builds
  175.7 MB (v0.1.1439) and 199.1 MB (now); after 140 s unasked 161.7
  and 149.8 MB. Footprint 339 -> 286 MB and 302 -> 254 MB.

Tests: TestRequestChunksTrimmedWhenIdle checks that three chunks over
the idle bound are kept while the page is asked for, and dropped once
it goes unasked. It waits for that state, not for a time. Broken by hand
both ways: without the idle trim it fails ("3 chunks kept after the
page went unasked"), and with the build trimming to the idle bound it
fails ("0 chunks kept while the page is asked for"). It also passes
with -race -count=3.

Run at this head: go test -count=1 ./internal/usage ./internal/gui ok
(16.1s, 201.8s); go vet -tags nogui for GOOS=linux and windows on
internal/usage ok; gofmt -l clean. Not run: the full suite (other
sessions' suites hold the machine).
2026-10-25 03:58:02 +08:00
yetone 66b6d6ade9 usage: the Requests page sums each row once, not once per group
Every Requests page build (each 5s refresh of the newest page, each page
turn, each filter) walks the whole period. Over all of it each row went
into about 17 sums: the page's own, a source cell, five chart series
groups, five dimension groups, the caller key and account groups, the
computers' share, and the chart point with its five parts. Each one
copied the 896-byte Row and worked out Decode and Floor again, and
each dimension rebuilt f.Without(d) and ran keepsRow on another copy.

Now each row's sums are made once (Totals.addRow into d) and added to
each group (Totals.plus, Part.plus). The filters with a dimension, or
the computer and day, cleared are built once. A filter that clearing
leaves unchanged reuses the row's own keep, and with no pick that is
every dimension. keepsRow, keepsRecord, computer, Row.key and keyer.key
take pointers.

Measured on the real sandbox data (sbmem, 416,665 rows), with zzbench:
one QueryPage of period=all, then six rebuilds at new offsets. Process
CPU at load ~110-127, three runs each, alternated with the old binary:
  before (7d67910f7): user 20.84 / 20.39 / 20.61 s, sys 2.69-2.93 s
  after:              user 15.33 / 15.74 / 15.75 s, sys 2.80-2.97 s
In the profile, buildRequestBlocksOf's row closure went from 5.56 s to
1.59 s cumulative. Wall time per page is too noisy at this load to quote
(1.9-3.1 s both ways). What remains per rebuild is mostly evicted shards
being read again (prefetchSources -> loadCalls, ~1.7 s over the seven
builds) and the walk of the Codex folders.

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

Run at this head: go test -count=1 ./internal/usage ./internal/gui ok
(36.5s, 150.0s); go build -tags nogui ./... ok; go vet -tags nogui for
GOOS=linux and windows on internal/usage ok; gofmt -l clean. Not run:
the full suite (other sessions' suites hold the machine) and the gateway
package (it only calls usage's exported API, which is unchanged).
2026-10-25 03:31:55 +08:00
yetone 7d67910f74 usage: the Requests page reads packed chunks in place, and owns its strings
The first Requests page after a start unpacked every local and shared
chunk whole and held them all while it built the page, so a cold page
on the owner's real usage peaked at ~450-480 MB footprint (#3493
follow-up: "发版后把 RSS 峰值也修了").

queryPage now keeps chunks packed. visibleLocal, matchedBlocks, the
Codex identity fold, the chart and rowsOf read a packed chunk through
chunkRows, a one-entry cache that decodes into one reused buffer. The
Codex response pairs are read per chunk (codexChunkResponsePairs), and
pack records Count so a packed chunk's length is known without a
decode. An unpacked block's strings are substrings of one text, so a
row or name the page kept would hold that whole block (~9 MB, kept by
the request cache): buildRequestBlocksWithCodex now copies every string
of the finished page (ownStrings).

Measured (owner's real usage copied into a sandbox HOME, warm caches,
first /v1/magpie/requests page, base = 2009d33a6):
- peak footprint 452-481 MB -> 351-389 MB; peak RSS 577-616 -> ~495-505
- live heap at 6s ~306 MB -> 203-229 MB
- settled footprint 246 -> 226-239 MB; settled live heap 142-143 ->
  147-148.6 MB. ~4 MB of one block's text is still held from the chart
  loop; its holder wasn't found (keyer, Row fields, Locations,
  EffortFamily ruled out). Cloning every chart row reached 143.8 MB but
  costs CPU per row, so it was left out.
- process CPU over 15s: 8.25/8.35s -> 9.29/11.65s at load 77-95; the
  profile puts most of it in syscalls and CodexModelEffort's reads, and
  the page's own work at queryPage 1.61 -> 1.97s, unpackInto 0.17s.

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

Run: go test -tags nogui -timeout 45m -count=1 ./internal/usage
./internal/gui ./internal/gateway ok at this head (gateway run after
rebase onto 3133f6343); gofmt clean; GOOS=linux and GOOS=windows go vet
-tags nogui ./internal/usage ok. Not run: the full ./... suite (other
sessions' suites are on this machine).
2026-10-25 03:11:41 +08:00
yetone 3a47e377e0 usage: a call whose vendor counts no cache is left out of every hit rate (#3464)
#3464 (zeewell on X): Kiro caches on its side, but its replies give only
credits and a context share, never cache tokens. Every hit rate outside
the Routing page read those calls' CacheRead of 0 as a miss. A Kiro-heavy
day showed "hit rate 6%" when the counted calls hit 90%.

The plugin already says so (opencode-kiro-auth 0.1.16 sends
usage.magpie_cache_unknown), and the gateway already kept it as
RouteUsage.CacheUnknown for Routing. This carries it the rest of the way:

- gateway: Usage.cacheNotCounted() (the vendor said so and no try
  reported a cache token) goes into usage.Record.CacheUnknown on every
  path that records a call: the gateway's own record, the OTel attempt
  path in observe.go, and trace's routeUsage.
- usage: Record.CacheUnknown is kept as ledger row flag 8192
  (rowCacheUnknown; grepped, no other flag uses that bit). Totals sums
  such calls' prompt into cache_unknown and counts them in
  cache_unknown_calls. Totals.HitRate leaves that prompt out of its
  denominator, and gives no rate when nothing is left.
- Old records: calls kept before the plugin said so carry no flag. A
  Kiro call (provider kiro or kiro-plugin) with no cache counted is read
  as uncounted (usage.CountsNoCache): in the ledger's row read, in
  Totals, and for Routing's history in internal/gui/trace.go
  (cacheCounted). The rule is scoped to Kiro's two ids, so another
  vendor's 0 stays a miss (tested).
- GUI: cacheHitOf in app.js drives the tray panel's card, the Usage
  page's agent rows and cache tile, the requests' Cache hit rate card and
  each ranking row. When only uncounted calls are left it shows "—" or
  nothing instead of 0%. Otherwise it says "{n} requests left out: their
  vendor doesn't count the cache". A request row's cache cells show "—",
  and its details say the vendor doesn't count the cache. The Context
  page (context.go, context.js) shows no cache for such a call and doesn't
  score it as a miss.
- No budget raised. This adds 625 bytes to app.js (1,320,224 to
  1,320,849, under its 1,321,336); d08b6118b had already moved the
  masking page's maskWho, maskProv and stillMotion out to
  plugins/redact, which an earlier version of this change did too.
- Strings in zh, zh-TW, ja and de. docs/subsystems/provider-plugins.md
  now describes the ledger side and what is not covered.

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

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

Not tried: a real Kiro account through the GUI.
2026-10-25 01:23:42 +08:00
yetone 1f589e3f4f usage: read today's usage ahead at startup
CyberCaius (Discord, Windows): "今天 N 次调用" is slow on the first
panel open after a start. The first usage?period=today parses
usage.jsonl: 0.33s for 2MB, 0.43s for a 40MB sandbox log here, more
on a slower disk. startBackend now runs usage.ReadAhead() in the
background, which works out today's summary into the summary cache,
so the panel's first ask finds it.

Parallel parsing was not done: with the read ahead, a request 1s
after start answers in 1-2ms, so there is nothing left to win there.

Test: TestReadAheadLeavesTodayNothingToRead. After ReadAhead, a
SummarizeTopIn(Today) parses nothing and works nothing out. Red with
ReadAhead's body emptied ("parsed the log 1 more times and was
worked out 1 more").

Run at tree 53ae48f72 (on origin/main 3b5a2f612): go test -tags nogui
-timeout 45m ./internal/usage ./internal/gui ok (TestCoreScriptBudget
included, no budget raised; app.js 1,317,465 of 1,317,486). GUI files
panel*, tray*, i18n-keys, routing-sessions (27 files, chromium and
webkit): 336 pass, 0 fail. gofmt clean. Earlier, at 7571ebc93: full
GUI suite 1095 pass; the 4 reds are two tests red on main too (#3497,
removed by hand gives "changed height 630 !== 561".
2026-10-24 23:49:08 +08:00
yetone 3be1f14ebb usage: a re-read source asks Swapped once per model pair (#3493)
Swapped's regexps ran for every call of every file read again: a few
hundred sent/served pairs over ~289k calls on the owner's real history,
about a third of the re-read's pricing cost in a CPU profile. queryPage
now keeps each pair's answer for the read.

Measured at internal/usage with the owner's real ~/.codex and ~/.claude
in a sandbox HOME: a heatmap read whose key changed, 3.0s -> 1.4s
together with the heatmap's own page.

Run at this tree: go test -count=1 -timeout 45m ./internal/usage
./internal/usageapi ok; GOOS=linux and windows go vet -tags nogui
./internal/usage ok.
2026-10-24 22:58:26 +08:00
yetone cf8b1e9338 usage: the heatmap works out only its days, kept 30s while only session files change (#3493)
The Requests tab asks for the year's heatmap on every ledger refresh. A
live agent writes its session file all the time, so the page's key
changed for every ask and the whole year was worked out again: groups,
shares and series the heatmap never reads, over ~289k calls on the
owner's real history.

- buildRequestBlocks returns at once for the heatmap's period with only
  HeatmapOf's days, from the rows the chart filter keeps.
- queryPage keeps a heatmap page 30s (heatFresh) while the gateway
  log's snapshot version is the same; a meta change (prices, names,
  wires) drops it, and a call through magpie shows at once.

Measured at the handler (internal/gui, sandbox HOME with the owner's
real ~/.codex and ~/.claude, 15,553 sources, 59.9 GB): heatmap steady
refresh 2.99s -> 0.15s, cold 5.5s -> 4.5s.

Run at this tree: go test -count=1 -timeout 45m ./internal/usage
./internal/usageapi ok. TestHeatmapKeptWhileOnlySessionsChange is red
with the throttle taken out (builds counted twice).
2026-10-24 22:58:26 +08:00
yetone 57a70aaf10 usage: a new Codex thread keeps the chunks read before (#3493)
Codex's thread identities were in the request index's meta, so every new
Codex thread, each subagent's included, dropped every chunk, and the next
Usage page read the whole history again: 7s on the reporter-sized
history here (15,553 session files, 418k calls). A chunk's rows don't
hold the identities; the page gives them to its rows as it is built
(cloneCodexChunks, codexIdentities). They now go in the key alone, which
drops only the built pages.

TestCodexNewThreadKeepsReadChunks writes a child thread, reads the page,
then writes its parent: only the parent's file is read again, and the
child's row names the parent's session. Red with the identities put back
in meta (both files read again).

Run at this head (origin/main 63c0c354a plus this): gofmt clean,
go test ./internal/usage ok. GOOS=linux and windows go vet -tags nogui of
internal/usage and internal/gui ok, and internal/gui and usageapi ok,
with the heatmap change after this one on top.
2026-10-24 22:58:25 +08:00
yetone f6a96b2f0b usage: a change time with a fraction settles in 100ms, so a read after an append hashes no log (#3394)
readLogSnapshot checks its snapshot against a SHA-256 of the log's whole
prefix whenever the log's change time is under a second old. Under steady
traffic every read came within a second of the gateway's last append, so
each one hashed the whole usage.jsonl again: 1.8 times the log for each
append and read. A stamp with a nonzero fraction of a second comes from a
clock that ticks in milliseconds (APFS in ns, Linux's coarse clock 1-10 ms,
NTFS ~15.6 ms), so it settles in logFineSettle = 100ms. A stamp in whole
seconds (HFS+, FAT, a share) keeps the one-second settle.

Run:
- go test -count=1 -timeout 45m ./internal/usage/ ./internal/budget/: ok.
- TestUsageReadAfterAppendHashesNothingOnAFineClock (20000-row log, 5
  appends, each followed by two reads): fine stamp 0 bytes hashed;
  whole-second stamp 50.7 MB. Broken by hand (logFineSettle = time.Second):
  54 MB hashed, red.
- Real account, sandbox HOME, a deepseek-only providers.json and a 98 MB
  usage.jsonl (the owner's own log, repeated 50 times). magpie serve took
  30 real /v1/responses calls with a Codex user agent to
  deepseek/deepseek-flash, all answered, while /v1/magpie/usage?period=today
  (the Usage page's read) was polled every second. Process CPU time, two
  runs each: before 3.11 s and 3.05 s, after 1.95 s and 2.25 s. The same
  calls with /v1/magpie/quotas polled cost 0.2 s on both binaries, since
  that path never reads the log.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/usage/ clean.

Not tried: an HFS+ or FAT volume (the test skips when the file system
gives whole-second stamps, and covers that case by truncating the stamp);
the full suite at this head runs after the push.
2026-10-24 21:00:05 +08:00
yetone 24f24abde3 usage: a ClinePass contributor-fallbacks route still shows as a swap (plugins#351)
woyin's Routing rows show cline-pass/deepseek-v4.1-flash-1017 served as
vmc/deepseek-v4p1-flash-1017-contributor-fallbacks. Third-party Cline Pass
tools record that name as a private contributor deployment
(finalProvider "openai-compatible-private"), not DeepSeek's own API. So
the row has to keep saying it was served elsewhere. 6db5e9d59's
ClineServing already does this, because only the exact model maps. This
commit is tests only: they hold the rule, so a looser match (a prefix,
say) can't hide the route later.

- TestSwappedClineServingName: -contributor-fallbacks (with and without
  the -1017 date), -contributor and -fallbacks are swaps.
- TestRouteKeptClineServingNameNotSwapped: a kept row served as
  ...-contributor-fallbacks stays swapped when it is read again.

Run at 616c87256's tree:
- go test ./internal/usage: ok.
- go test ./internal/gateway -run 'Clin|Swap|Served|routedAgain|History': ok.
- go vet on darwin, linux and windows: ok. gofmt -l: clean.

Broken by hand: ClineServing changed to a prefix match. Three usage cases
and the history case went red. Restored afterwards.

Not run: the full suite (tests only, in two packages).
2026-10-24 17:07:35 +08:00