Commit Graph
28 Commits
Author SHA1 Message Date
yetone 8d68b5f219 usage: Codex's model and effort answers go with the chunks' caches when idle
CodexModelEffort kept each period's answer (every Codex thread's
consumption by model and effort) for the life of the process. On a real
history it was ~6.9 MB of the idle heap after one visit to the Sessions
page (t59 measured on mote, heap at 10 idle minutes:
usage.keptCodexModelEffort).

Each ask now notes itself with derivedUsed, as the pairing and heatmap
reads do, and dropDerived lets go of every period's answer but one being
built. The page polls every 15 s while open, so it keeps them; the first
ask after derivedIdle (3 minutes) builds the answer again, waiting for it
as a first ask does.

Run on mote (go1.26.8):
- go test -count=1 ./internal/usage ./internal/usageapi ./internal/gui: ok
- gofmt -l, go vet, GOOS=windows go vet, GOOS=linux go vet -tags nogui
  for internal/usage: clean.
- Broken by hand: with dropEffortPeriods left out of dropDerived,
  TestIdleCodexEffortLetGoAndBuiltAgain fails ("1 periods' answers kept
  while idle").
2026-11-11 06:10:18 +08:00
yetoneandNorethSea 4921bf5a97 usage, sessions: one model option for a found routing group's two ids (#5892, Norethcy on X)
A found routing group is called by its public id (auto/<model>) and is
kept as group/auto-<slug>; calls recorded under either were counted as two
models, so Usage › Sessions' model filter listed the same group twice and
the ledger, summaries and session lists split its calls.

Ported from NorethSea's 30d6261cd on their fork: UsageAlias names a found
group by its public id before the user's alias (both spellings, old
session files too), sessions' lists, the ledger keyer, the summary cache's
key and Codex's model/effort read through it, and a cache keyed on the
group names (UsageNamesKey) is read again when a group is renamed. A user's
own provider named "auto" keeps auto/<model> (autoRefsOn).

Changed in review: the patch's ledger filter compared every record with
provider.SameRef, which reads the providers (customIDs, a stat of
providers.json) for each record a filter passes over. FilterOf, the one
place a Filter is made from a query, now canonicalizes the model once, and
keepsRecord asks the providers only for an auto/ record under a group/
filter (sameGroupModel).

Run (mote's sshd reset every connection all afternoon, so on the Linux box
through wsl-run; the package run at base 720200092, and the -run tests,
quota-holds and i18n-keys again at this head on 208b89422; rebased since onto 44732325e,
a gateway test only):
- go test -count=1 -tags nogui ./internal/gui ./internal/provider
  ./internal/sessions ./internal/usage ./internal/usageapi: ok
- go vet -tags nogui (linux), GOOS=darwin CGO_ENABLED=0 go vet (provider,
  usage, usageapi, sessions), and go vet on Windows (win-run, those and
  internal/gui): clean. gofmt -l: clean.
- GUI: usage-ledger-model-pick, usage-ledger, quota-fit-batched,
  i18n-keys in chromium and webkit. usage-ledger's "newest live route
  needs no return-to-live button" (and zh "request routing links") is red
  the same on origin/main 987eac0aa on that box: #3104, #4078.

Broken by hand:
- keepsRecord back to r.Model != f.Model: TestUsageFoundGroupNames and
  TestLedgerFoundGroupNames red.
- usageGroupNames returning nothing: TestUsageFoundGroupNames (provider,
  usage), TestSessionsFoundGroupNames, TestCodexEffortFoundGroupNames,
  TestLedgerFoundGroupNames red.

Not tried: a macOS run (mote unreachable), the darwin gui package's vet,
and the reporter's own usage log.

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

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

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

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

Co-authored-by: yygutn <yygutn@gmail.com>
2026-11-06 10:07:06 +08:00
yetone 07dc0b4ec1 usage: an agy following the Antigravity app's gateway is counted once (Chamberlain_zyz on X)
An agy not connected on its own row follows the Antigravity app's
gateway, with the app's key (internal/agent/antigravity.go), so the
gateway records its calls as the app's ("antigravity"). Its transcript's
steps were matched only to records of agent "agy", so each one was
counted twice: Chamberlain_zyz's 17:00 hour showed Antigravity
39,104,506 and Antigravity CLI 38,562,861 tokens for the same calls.

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

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

Not tried: a real agy through a real Antigravity app's gateway; the
reporter's case is taken from their screenshots and the app's wiring.
2026-11-02 19:08:59 +08:00
yetone 5bb252c8f3 usage: a poll's small pairing lets a whole history's scratch go (#2278)
The matcher, the response picks and visibleLocal's set of ids seen are
kept for the next pairing, and each pairing that puts one back holds it
scratchLinger more. A poll's pairing of its last few days put back the
scratch the cold start's pairing of the whole history made, sized for
every call, so ~140 MB of maps and slabs stayed while the window polled:
the heap profiles at 44, 50, 56, 62 and 68 s were alike to the MB, all
of it under codexEffortOfIndex, with no pairing of the history running.

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

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

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

The peak itself is the pairing of the whole history while it runs, beside
the Month page and the session stats; this change doesn't cut that.
Not tried: Windows and Linux runs.
2026-10-30 23:20:35 +08:00
yetone cd5df81ecd usage: Codex's effort before the last days is kept on disk, so a start pairs only the recent chunks (#2278)
After the heatmap's settled days were kept (heat-v1.json, fixed in the
commit before), the cold start's largest part was codexEffortOfIndex:
a pairing of the whole history, every gateway call with its session
row, for the effort column, ~90 MB of a ~310 MB heap at 18 s on the
real history bench.

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

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

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

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

Not done here: queryPageOf, the warm-up's QueryPage(All) page 0, is now
the largest part (111 to 227 MB at 18 s), a full pairing for 50 rows.
2026-10-30 14:47:05 +08:00
yetone fddd7ff08f usage: pairing keeps its rows as bits and its groups by sums, and lets its pairs go (#2278)
A cold start pairs the whole history, and pairing held its row sets as
map[rowRef]bool, ~40 bytes a row, several sets of most rows at once.
They are now refSet: a bitset a chunk, a bit a row. matchScratch's
groupOf was keyed by the whole matchKey (a session string and its
tokens); it is keyed by a 128-bit maphash sum of them now, and the
sessions map is filled when a group is made. pairedRows' pairs and
compactions maps were filled and never read; they are gone.

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

Run at this tree (rebased onto dca3e2d71 from 807048470), on mote:
go vet ./internal/usage; GOOS=linux|windows|darwin go vet -tags nogui
./... all ok; go test -count=1 ./internal/usage ok (30.1s), with the
new TestRefSet and TestMatchKeySum (no allocation).
Not run: the full suite, the GUI suite.
2026-10-30 13:42:11 +08:00
yetone 99c2567cfa usage: the matcher's scratch goes 30s after the last pairing used it (#2278)
With nothing new to pair, every poll of the window is answered from the
pairings kept (pairMemo) and pairs nothing, so the scratch of one pairing
of the whole history (keptMatch's groupOf/calls/ends/byID maps, keptPicks'
picks and slab) sat unused while the window polled, until pageRest's
ReleaseScratch 30s after polling stopped. On the real 65 GB history
(52 GB Codex, 13 GB Claude) that was ~120 MB of the ~270 MB live heap
over 60s of polls. Now each release of either scratch (re)arms one timer,
and scratchLinger (30s) after the last pairing put it back both are let
go. While an agent works, every poll pairs again inside 30s and finds it
kept, as before.

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

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

Not tried: the startup peak (~4s, first poll burst during warm-up) is
the pricedRows pool and the chunks of a whole-history build; this commit
doesn't change it.
2026-10-30 09:37:19 +08:00
yetone c93d9e0c0b usage: an unchanged Codex effort ask is told the kept answer, not a copy (#2278)
CodexModelEffort copied every thread's consumption for each ask
(cloneEffort), though the kept answer is only replaced by a later build,
never written, and its callers (the Sessions list, overview and a
session's details) only index it and copy their thread's slice
(addCodexModelEffort, addCodexSummaryModelEffort). On the #2278 bench
(15G .codex) the copies were ~230 MB allocated every 80 s of an open
Sessions page. Asks are now told the kept map itself; the doc comment
says it is read-only.

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

Run at this tree on mote (macOS 27, Go 1.26.8):
- go test -count=1 ./internal/usage ./internal/sessions ./internal/gui:
  usage ok, sessions ok; gui red only in TestMainWindowCorners/
  macOS_26_SDK, which is #3949 (filed, red on macOS 27 on main).
- GOOS=linux,windows,darwin go vet -tags nogui ./internal/usage
  ./internal/gui: ok.
Broken by hand: maps.Clone back in the kept-answer return makes
TestCodexModelEffortAsksShareTheKeptAnswer red ("told a copy"); dropping
the GUI's slices.Clone makes TestCodexModelEffortCopiedPerSession red
("written through a session's copy: 999").
Not run: the full ./... suite, and the bench A/B (the 230 MB is from the
v0.1.1967 heap profile, not yet re-measured).
2026-10-29 06:30:58 +08:00
yetone 49d4d0f7ab usage: the request matcher keeps its maps for the next call, and gives them back once the window rests (#2278)
Every poll while an agent works matches a year's history again:
matchedBlocks and codexChunkResponsePairs grew their maps (byID,
reserved, used, groupOf, picks, picked, ...) and slices from nothing on
each call. They were ~3.0 GB of the ~40 GB a poll-heavy 80 s allocated
on the real-history harness (d1951 heap diff, 120 s to 200 s).

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

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

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

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

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

What a call pairs with is unchanged.

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

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

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

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

Not run: the full ./... suite.
2026-10-29 03:40:18 +08:00
yetone 157d575c39 usage: pairing Codex calls by response id allocates no pick an id (#2278)
codexChunkResponsePairs kept a *pick for every response id the gateway
had. The alloc profile of v0.1.1928 on mote (34k session files, 240k
gateway rows, two minutes of polls while an agent worked) had it at
1.05 GB, &pick{} alone 308 MB. The picks are now one slice the map
holds places in, so a poll makes a few slice growths, not an allocation
an id. What is paired is unchanged: every pick is still read once.

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

Run on mote at the pushed head (origin/main 655f8dbd1 plus this; rebased
onto b7da6cf93, a gateway test commit that touches neither package):
  go test -count=1 -timeout 45m ./internal/usage/ ./internal/sessions/
    ok (30.8s, 37.9s)
  GOOS=linux/windows/darwin go vet -tags nogui ./internal/usage/ ok
Not run: the GUI suite (no GUI file changed; at 655f8dbd1 it was red
only in TestMainWindowCorners, #3949), an A/B of the page (next).
2026-10-29 00:57:04 +08:00
yetone 0dc4cec85d usage: a row's Codex thread is kept as a 4-byte place, not a string (#2278)
Every row of a chunk had a 16-byte string header for its Codex
thread. A day's rows are a few hundred threads, one after another. At
the scale of #2278 (34k session files, 1M Codex rows), these headers
were the largest single holder in the heap, 24.5 MB of 184 MB live.
codexActors now keeps a []uint32 into the chunk's thread names. The
row before's thread is checked first, then the names. A clone shares
the names clipped, so adding a name to one never writes into the
other. The disk format is unchanged: each row's thread is still
written as a string.

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

Run at the pushed head (rebased onto 7e58591dc, rerun after):
- GOOS=linux, windows and darwin go vet -tags nogui ./internal/usage/...
  ./internal/sessions/... ./internal/gateway ./internal/cli: ok.
- go test ./internal/usage/... ./internal/sessions/...: ok.
TestCodexActorsTakeFourBytesARow: 100k rows of 200 threads hold at
most 5 bytes a row, read back, and a clone keeps its own rows. Broken
by hand (no lookup of a name already held) it goes red.
Not run before the push: the full suite. It runs next.
2026-10-28 20:43:10 +08:00
yetone 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 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 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 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 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 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 227b864a45 usage: CodexModelEffort keeps only the gateway calls a Codex session file's call can be matched to (#2776)
CodexModelEffort built the whole ledger of the period and kept the rows
that carry a Codex thread. Every gateway call became a Record (in
gatewayRecords' slice), a packed row (gatewayMatchesDetails' chunk) and
a priced Row (ledgerMatched), all held at once, though only a gateway
call paired with a Codex session file's call by its response id can
carry a thread. On the 720k-call sandbox this build was 7.6 GB of the
start's 18 GB allocated and most of its peak.

codexEffortRows visits the log once and keeps only the gateway calls
with a response id, request id or session (native, else magpie's) that
one of the session files' calls has, or an agy call when one is agy's.
No other gateway call can change gatewayMatchesDetails' answer: the
request-id match looks up only the locals' ids, the fallback groups are
looked up only by the locals' sessions, and a response id's uniqueness
is counted over every call that has it, all of which are kept. Only the
paired calls are priced into rows, and the rows are the whole ledger's
thread rows in the same order, so the sums (floats included) are the
same.

TestCodexEffortRowsAreTheWholeLedgers compares the rows with the whole
ledger's for All, Today and 7d, with Codex's reader and every agent's:
a pair by response id, an ambiguous response id, a session-and-tokens
match, a call two days old, and unrelated calls around them. With the
session test dropped from matchingRecords by hand it is red (all,
every agent: the session-matched call shows as a row of its own).

TestCodexModelEffortLetsUnrelatedCallsGo builds over 3000 unrelated
gateway calls and allows a visit of the log and a half. With the old
build put back (LedgerOf): red, 18,347,128 bytes against a visit's
1,198,680. With the fix: 1,321,824 against 1,321,744.

720k-call sandbox, cold start, the four first asks together, back to
back (load 48.7 then 14.7, so the times are not comparable; the memory
is what this measures):
  before (beb9c40d5): peak RSS 4411 MB, heapSys 5513 MB, live 574 MB
  after:              peak RSS 2427 MB, heapSys 2413 MB, live 542 MB
  manage?agent=codex answered in 41.5 s before, 23.1 s after.

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:18 +08:00
yetone 8a1b5916f3 sessions, usage, gui: one read of every call at a time, the Codex effort built once and kept, and the Sessions page asks for an overview once, so the app no longer grows to 85 GB (#2278)
On a long history (the reporter's: 68k call files in calls-v15, 415 MB;
42 MB usage.jsonl; 75k calls in 7 days), the app's main process grew to
85 GB in about 90 minutes and the gateway froze. `magpie serve` alone held
83-153 MB for 20 minutes (the reporter's follow-up), so the growth is in
the app's Sessions path:
/api/sessions/overview -> usage.CodexModelEffort -> LedgerOfAt ->
sessions.Calls(all history).

Why it grew:
- CodexModelEffort's cache key changes on every gateway write, and it
  never kept an answer when usage.jsonl was missing or grew during the
  build. So every /api/sessions, overview, /one and /manage ask with a Codex
  session rebuilt the all-history ledger, gob-decoding every shard (only
  64 stay in memory).
- Nothing joined concurrent asks.
- The page's 15s reload asked for an overview again while the last one
  was still under way, so slow asks piled up.

What changes:
- sessions.Calls and the new AgentCalls go through sharedCalls. An ask
  while the same read is under way waits for it and gets a copy, and
  reads run one at a time.
- AgentCalls(since, "codex") reads Codex's files only. pruneCalls still
  sees every file.
- CodexModelEffort is built from Codex's calls plus the gateway's records.
  Only those name a Codex actor, and TestCodexModelEffortIsTheWholeLedgers
  checks the answer equals the whole ledger's on a mixed Claude + Codex +
  gateway fixture.
  - One build per period at a time. An ask during a build gets the last
    answer for the same home (root), or waits if there is none.
  - The answer is kept when usage.jsonl is missing or grows during the
    build.
  - At most 8 periods are kept.
- page.js: sessOverview shares one promise per query, so the filter's ask
  and the 15s reload's ask for the same overview send one request.
- docs/subsystems/gateway-sessions.md says this.

Reproduced (temporary test, not committed): a sandbox HOME with 62k
Claude Code session files, 5.9k Codex rollouts and 100k gateway records.
Sessions routes in-process, 4 rounds x 6 concurrent asks
(overview?days=0 and /api/sessions), a usage record appended every 300ms:
  before (2b0037f41): 7m39s total, slowest ask 2m01s; 66264 MB allocated
    (2761 MB per ask); peak heap in use 4620 MB, peak Go sys 6274 MB,
    peak RSS 5325 MB
  after:              20.4s total, slowest ask 7.1s; 20728 MB allocated
    (863 MB per ask); peak heap in use 1168 MB, peak Go sys 1487 MB,
    peak RSS 1415 MB
Cold warm-up (index plus every shard) was 21m before and 18.5s after on the
same home. The after run reused the shards on disk, so it is not a
comparable number.

Tests, each red on the old code:
- TestConcurrentCallsShareOneRead: 8 reads, not 1. It also goes red when
  the join is broken by hand.
- TestCodexModelEffortConcurrentAsksBuildOnce: 8 builds.
- TestCodexModelEffortAnswersLastWhileBuilding: 3 builds.
- TestCodexModelEffortKeptWithoutLogAndAcrossAWrite: 2 builds.
- sessions-overview-once.test.cjs: 2 overview requests, not 1. That is
  chromium and webkit; en, zh, zh-TW and ja at 1100/900px, de at 420px.
  It was red with the old page.js served.
TestAgentCallsReadsOneAgent and TestCodexModelEffortIsTheWholeLedgers pass
on both versions.

Run:
- gofmt -l: clean.
- go vet -tags nogui for darwin, linux and windows: sessions, usage,
  gui. Before that, the whole tree for linux and windows.
- go test -race on ./internal/sessions/ and ./internal/usage/.
- go test of internal/sessions, internal/usage and internal/gui at the
  rebased head (on 95e7c6bcc): green. gui was red once, in a run whose
  output was cut, at load ~100; it was green on two reruns.
- Full suite: SUITE_LINE
- GUI: the 13 files that ask for sessions/overview, at the rebased head,
  in chromium and webkit: 198/198. Before the rebase, those plus every
  usage*.test.cjs,
  in chromium and webkit: 749 pass. The 24 failures are usage-fold
  (#2163) and usage-agents-hide (#2276). The same 24 fail with the old
  page.js on 2b0037f41, and both are filed.

Not tried: the real app on the reporter's data; an hour-long run.
2026-10-15 23:08:00 +08:00
yetone 84f14e555c usage: a Codex call with no response_id leaves compaction out of Usage requests instead of saying false (#1591)
Codex added token_usage_record and compaction_response_id together, in
openai/codex#41912 (2026-08-31). A call that magpie reads from a
token_count event alone, as in older rollouts, has no response_id. It
can't carry the compaction marker either way. The previous commit
reported such calls as `compaction: false`, which claims they were not
compactions. codexCompactionOf now returns no state for them, so the
ledger and the requests page leave the field out, as they do for any call
with no native evidence.

What was run:
- New test TestCodexCallWithoutResponseIDHasNoCompactionState. On the
  previous commit it fails with `ledger: a call with no response_id claimed
  a compaction state: {..."compaction":false...}`, and with the same message
  for the requests page. It passes now.
- go test -tags nogui ./internal/sessions ./internal/usage: ok.

For all three commits on origin/main 1ad60446f:
- gofmt -l on the changed files: clean.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: ok.
- go build for darwin, linux (nogui) and windows: ok.
- Full suite: go test -tags nogui -timeout 40m ./... (pipefail, sandbox
  HOME): 53 packages ok, exit 0.
- No GUI asset changed, so no Playwright run.
- Not tried: a real Codex subagent rollout (legacy or paginated). The
  formats are from Codex's source, and Hogeexxl checked two real paginated
  subagents.
- Rebased onto origin/main f255a3e3b (12 commits newer, including #2233 and
  #2234 in internal/sessions; no cache-version clash). Rerun there: go
  test -tags nogui -count=1 ./internal/sessions ./internal/usage
  ./internal/gui, gofmt and vet on both packages: ok.
2026-10-15 04:21:31 +08:00
Hogee 3c4b4dc973 sessions, usage: a Codex subagent with no title takes its parent's spawn_agent task_name, its nickname shows apart, and Usage requests say which calls were compactions (#1591, Hogeexxl)
Hogeexxl's change (his fork branch codex/codex-session-details, f7c176c9),
cherry-picked with his authorship:

- A Codex child thread whose title is still empty after the existing
  precedence takes the task_name of the parent's spawn_agent call, linked by
  the call id and the SubAgentActivity "started" item that names the child's
  agent_thread_id. Conflicting links leave the title empty.
- session_meta.agent_nickname is exposed as `nickname` on the list, one,
  manage and overview responses, beside the title, not in place of it.
- GET /api/usage/requests and /v1/magpie/usage/requests carry `compaction`
  (true/false) for Codex calls with native evidence, and leave it out
  otherwise. A gateway row matched by a unique response_id takes the marker
  and keeps its own model, usage, cost and kind.
- Flags bits 1024 (rowCompactionKnown) and 2048 (rowCompaction) are new.
  TestRowFlagsApart covers them, and they don't overlap 1..512. The sessions
  cache goes to version 21 and the calls cache to calls-v15.

Review:
- Rollout format checked against Codex's source (openai/codex 669449b):
  - v2 spawn_agent args carry task_name.
  - A paginated rollout persists item_completed with a SubAgentActivity
    item: kind "started", id = the call id, agent_thread_id.
  - SessionMeta has a top-level agent_nickname, which Codex's own list.rs
    and metadata.rs read too.
  - compaction_response_id lives in token_usage_record.
  Gaps in legacy rollouts and in calls without a response_id are fixed in
  the next two commits.
- Privacy: only a title string the user's own Codex wrote and a boolean
  are added to local API responses. Nothing new goes to a vendor or to
  telemetry. The ingest POST parses fields one by one, so it is unchanged.
- No .github, dependency or network changes.

What was run:
- His tests pass: go test -tags nogui ./internal/sessions ./internal/usage,
  and the two new internal/gui API tests.
- Broken by hand, each caught by his tests:
  - the nickname read removed;
  - the conflict checks removed;
  - mergeCodexCompactions broken;
  - the gateway pair's setCodexCompaction removed;
  - the flag read forced to true.
- Not caught:
  - the parent check on the title link (covered by a test in the next
    commit);
  - `copy.codexCompactions = nil` in cloneCodexChunks removed. That line is
    defensive only: the shared chunks never hold the map.
- The gofmt, vet and full-suite record for the three commits is in the
  last one.
2026-10-15 04:21:31 +08:00
yetone 019199e0f7 usage: Codex threads' model/effort consumption is read again only when a call, price or identity changed (#1591)
e3d3f75fd added model_effort to /api/sessions, /one, /manage and
/overview. Each answer read the whole ledger (LedgerOf(All) for the list),
and the Sessions page asks for the list and the overview every 15s while it
is open, so a long history was worked out again on every refresh.

CodexModelEffort now keeps its last answer per period under the key the
request index already keys its pages on (gateway log version, the agents'
call files, other computers' days, Codex identities, prices, the day).
That key is read by readRequestState, taken out of queryPage unchanged. An
answer from a log read part way is not kept, as cachedVias does. Callers
get their own copy.

Run at this commit on d692b2548 (Go 1.26.8 darwin/arm64, sandbox HOME):
- go test -tags nogui -run Codex ./internal/usage: pass
- TestCodexModelEffortReadsLedgerOnlyWhenCallsChange, broken by hand three
  ways, each red: the key not compared (a changed rollout still read 20,
  not 2000), the cache never hit (ledger read 2 times), the cached slice
  handed out (a caller's write showed in the next answer).
The full suite, vet and builds are in the commit that lands with it.
Not measured against a real 750k-call history.
2026-10-14 22:45:40 +08:00
Hogee 644f4316f9 sessions, usage, gui: separate Codex thread relationships and consumption (#1591)
Preserve native Codex thread IDs and explicit parent chains. Associate gateway
calls with their actual thread by unique response ID before legacy matching;
fold identical native history copies and keep ambiguous actors unknown.

Existing Sessions APIs expose optional Codex roles, parent/root relationships
and per-thread model/effort consumption. The overview uses its existing calendar
range. Usage request APIs expose query-time actor classification and reuse
session/subagent/parent_agent for Codex. Other agents, pricing, gateway routing,
UI assets, raw Usage logs and model-only aggregation retain their semantics.

Verified after rebasing onto main 331c27703a,
at commit 50baace0a52953263dddc49f4dc55f97a8457dd1, code tree
78743e334f8c841e2a188aafe26996c016a8fa4b. Only this message is amended afterward.
Go 1.26.8 darwin/arm64; tests used temporary HOME and pinned Go caches.

Passed (each exit 0):
- git diff --name-only origin/main...HEAD -- '*.go' | xargs gofmt -l (no output)
- go vet ./...
- GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go vet -tags nogui ./...
- GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go vet ./...
- go build -o /tmp/magpie-codex-session-identity-p4-darwin
- GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -tags nogui -o /tmp/magpie-codex-session-identity-p4-linux
- GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -o /tmp/magpie-codex-session-identity-p4-windows.exe
- go test -tags nogui ./...
- go test -race -tags nogui ./internal/sessions ./internal/usage ./internal/gui -run '^(TestCodexIdentityParentChainsAndSummaryCache|TestCodexIdentityParentMergeAcrossRolloutFiles|TestCodexCallThreadIDPriorityAndCache|TestCodexCompactionPromotesThreadID|TestCodexSourceNativeVariants|TestCodexIdentityFieldsOmitOtherAgents|TestCodexIdentityInvalidatesOldSummaryCache|TestCodexLedgerResponseIdentityAndOwnConsumption|TestCodexRequestPageFoldsCopiesBeforeResponseMatching|TestCodexExactResponsePairPreemptsLegacyMatchInLedgerAndDirect|TestCodexQueryPageExactResponsePairPreemptsLegacyMatch|TestCodexRejectedGatewayDoesNotPairWithNativeCall|TestCodexKnownSubagentWithUnknownRootKeepsOwnConsumption|TestCodexQueryPageRefreshesIdentityAndSharesJSONFields|TestCodexActorSurvivesPackedRequestChunk|TestPackedRequestPageCallerAndRouteIdentity|TestPackedGatewayRetainsOversizedSnapshot|TestCodexSessionAPIAddsOwnModelEffort)$' -count=1
- git diff --check

Behavior-break proof: removing identity/thread-ID promotion fails native identity,
upgrade/conflict and compaction assertions. Disabling exact-pair preemption loses
a neighboring main call. Removing API enrichment yields missing consumption;
using All for a 7-day overview yields 740/74 instead of 40/4. Restored code passed
its targeted tests and the final checks above.

Native checks had Clang enum/linker deployment-target warnings.
Linux/Windows runtime, real accounts/vendors and manual UI were not exercised.
No frontend suite was run because the change does not touch GUI assets.

Refs #1591 (Codex portion only).

Reviewed and applied by yetone (cherry-picked from Hogeexxl's fork, bf8c8c9e).
The one conflict was call_cache.go's version: main had taken calls-v13 for
compaction times (e1dcd1e1d), so this is calls-v14. Run with the follow-up
commit on top, at tree 122b933ba4c474e443f2b29c6d0a4163ae364f78 on origin/main e5cd125f0 (Go 1.26.8
darwin/arm64, sandbox HOME, private GOCACHE):
- gofmt -l on the changed files: none
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...
- the darwin, linux (nogui) and windows builds
- go test -tags nogui -timeout 40m ./...: all ok
- go test -race -tags nogui -run 'Codex|Packed|QueryPage|RequestPage'
  ./internal/sessions ./internal/usage ./internal/gui: ok
Broken by hand, each red: codexIdentityRow not setting Subagent (8 usage
tests), setting it for a main thread too (2), Session kept raw instead of
the root (7), thread_spawn's parent_thread_id not read (3 sessions tests),
response pairs not reserved before the old matching (6).
Not tried: a real Codex subagent rollout (none on this machine; every
recent rollout is a vscode main thread whose session_id equals its id),
and the GUI by hand. Claude Code's fields are unchanged.
2026-10-14 22:45:40 +08:00