Commit Graph
7 Commits
Author SHA1 Message Date
yetone 1d0fc2bb08 sessions: a fork's copies of its parent's calls are counted once (Codex, ZCode)
Sky (skyhuang1994) on Discord: on ZCode, 10-31 showed ~0.70B GLM-5.3
tokens where ZCode's own model_usage had ~0.28B. A selection side chat
opened on 11-02 from a 10-31 session holds a copy of its 860 assistant
messages, with the 10-31 times and the same 421,041,276 tokens, and made
no calls. On Codex, a week of 2026-03 read 5,136,041,178 gpt-5.4 tokens,
where the machine had spent ~0.27B.

ZCode: ZCode 3.17's CLI copies a session's messages (gce, for a side
chat, a fork and a checkpoint restored) with a new id and session, the
original's time, model and tokens, and metadata.forkOrigin
{sessionId, messageId}. zcDB.copied says a message is a copy of one still
in the database, and readZCodeCalls and parseOpenCode (for ZCode) leave
it out. A copy of a copy names the copy it came from, so of each chain
one is counted. A copy whose original is gone is counted. ZCode's own
fork notices carry a forkOrigin with no messageId, and are not copies.

Codex: a fork (/fork, spawn_agent with the parent's context) writes every
line of the parent's rollout into its own first, token_count events too,
stamped at the fork's time (codex-rs 0.117 record_initial_history,
InitialHistory::Forked). Each copied checkpoint was booked as a call on
the fork's day. The fork's session_meta has forked_from_id. The parent's
rollout is found in the same Codex home: the UUIDv7 day of its id ±1
day, then every day, then archived_sessions. Its checkpoints, {total,
last}, are read once (8 parents kept), and a fork's checkpoint found among
them only advances the running total, on Usage (calls) and Sessions
(stats) both. A parent not found leaves the fork read as before.

callParseVersions and parseVersions raise codex and zcode to 1, so their
kept parses are read again once. The version tests (call_versions,
parse_versions, cache_decode) now hold the versions at none raised: they
test the mechanism, not the current numbers.

docs/subsystems/gateway-sessions.md says all of this. Filed #5072:
OpenCode's fork copies the same way and names no original, so it is
still counted twice.

Run at this head on mote (mote-run):
- gofmt -l internal: empty
- GOOS=linux go vet -tags nogui ./... ; GOOS=windows go vet ./... : ok
- go test -count=1 -timeout 45m ./internal/sessions ./internal/usage
  ./internal/tune ./internal/otlp ./internal/davsync ./internal/tui : ok
- go test -run 'Session|Usage|Calls|Ledger|Stats|ZCode|Codex'
  ./internal/gui ./internal/cli : ok

Broken by hand:
- zcDB.copied returning false: TestZCodeCopiesCountedOnce red. msg_c1 and
  msg_d1 were counted as calls, and the Sessions page's 10-31 read
  {1200 300 1800} for {400 100 600}.
- the copied() check in count() off: TestCodexForkCountsOnlyItsOwnCalls
  red. 4 calls on the fork, {87984 5950 268416} for {45744 3550 179584}.

Not tried:
- a real ZCode database or side chat. There is none on this machine.
  The copy shape was read from ZCode 3.17.2's zcode.cjs (gce).
- a real forked Codex rollout or one from 2026-03. ~/.codex/sessions here
  spans 2026-07 to 11 and has no forks. The fixtures follow codex-rs
  0.117's writer. Whether Sky's 5.1B week is all fork copies is not
  known; a cumulative count read as per-turn in an older format was not
  found in that source.
- newer rollouts' token_usage_record copies in a fork, and a parent in
  another Codex home (WSL, CODEX_HOME).
- the whole gui and gateway suites. Another session's suite was running
  on mote; gui and cli ran only the tests above.
2026-11-03 19:13:00 +08:00
yetone c07ca663cd sessions: a change to one agent's parser reads that agent's files again, not every file (#2278)
cacheVersion was raised 7 times since 10-28, three on 10-30 alone, each
for one agent's parser (Claude Desktop's entrypoint, Droid's skills,
OpenCode/Cline/dsh tool calls...). Each raise threw the whole kept index
away, so every user's first start after the update read their whole
history again: on the 52GB Codex + 13GB Claude Code history on mote,
~4 minutes of CPU and the fans on, the slowness users report after an
update.

Now each kept parse names its agent, the index keeps parseVersions as
they were (Parsers), and decodeCache drops only the parses of an agent
whose version moved. A change to one agent's parser raises
parseVersions[agent]; cacheVersion stays for changes to the index
itself. An index kept by an older magpie names no agents: its parses
stand while no version has moved, and refresh names them on the next
read (a copy, as readers hold the old one) and saves, so a later raise
keeps them too.

Not changed: calls-vN (call_cache.go) still names one version for every
agent's call shards; it was raised once since 10-01.

Run on mote (Go 1.26.8):
- gofmt clean; go vet ./internal/sessions ./internal/usage ./internal/gui
  for darwin and windows, ./internal/sessions ./internal/usage for linux:
  ok
- go test -count=1 ./internal/sessions ./internal/usage: ok
- go test -race -count=3 -run TestParseVersion ./internal/sessions: ok
- Broken by hand: decodeCache keeping every parse makes both
  TestParseVersionsReadOneAgentAgain and
  TestParseVersionRaiseReadsThatAgentAlone red; refresh not naming an
  old index's parses makes the latter red (read claude:3 codex:2).

Real history (the 52GB Codex + 13GB Claude Code copy, 16,619 kept
parses, index left by v0.1.2314), warm starts, 75s each:
- v0.1.2314: 10.7s CPU, 275MB peak
- this change, first start on the old index: 13.7s, 259MB; nothing
  read again, all 16,619 parses named and saved
- the same with parseVersions{"claude": 1}: 47.0s, 269MB, Claude Code's
  files alone read again (a cacheVersion raise: ~4:00)
- the next start: 13.2s, 261MB
- heatmap, requests, overview 0/7/30 and stats 0/30 answers
  byte-identical to v0.1.2314's in every run.
2026-10-31 11:53:10 +08:00
yetone bbb4fd478a sessions: a parse's models, days and tools are sorted slices, not maps
A kept parse holds a model or two, a day or two and a few tools, and Go's
map of one entry is a whole group of eight: ~500 bytes for one model's
Tokens, where a sorted slice entry is 56. Over a long history (15.9k kept
parses) state.Models, Days, day.Models, Tools and Skills held 18.4MB as
maps and 4.2MB as named[V], a slice kept in name order. It is written as
the same JSON object a map writes, byte for byte, so the parse cache
saved before reads unchanged; names are interned with unique.Make, and
plain integers in ints and Tokens are read without reflection.

Measured with the real ~/.codex and ~/.claude histories (sandbox HOME,
warm cache, 40s after start), base 3393e61d0 vs this change, two
alternating runs each:
  live heap   102 / 105MB  ->  92 / 91MB
  footprint   164 / 167MB  -> 156 / 150MB
Cache decode at start: ~58ms -> ~61ms (best of 7).
Side by side on the same data, /api/sessions/overview?agent=codex and
/api/stats?days=30 are identical; the other overview queries differed
only in the two Claude sessions being written during the run.

TestNamedIsAMapInJSON: marshal is byte-equal to a map's (HTML-escaped
key included), round trip, a repeated name keeps its last value, an
unknown Tokens field is ignored, omitempty leaves none out, and 1.5,
"1", [1], 1e3 and a too-big int fail as they fail into a map. Broken by
hand (the int fast path accepting 1.5) it went red.

Run at this head (rebased on 2beed3b04): gofmt clean; go build ./...;
GOOS=linux go vet -tags nogui sessions, gui, usage; GOOS=windows vet
sessions; go test -timeout 45m ./internal/sessions ./internal/usage
./internal/gui ./internal/gateway all ok.
Not run: the full ./... suite and the GUI node tests (no GUI change).
2026-10-27 04:39:56 +08:00
yetone 13f9070135 sessions: a kept file of one day holds that day's models once (#3493)
A long history's kept parses held 28MB live after a start's decode of
sessions.json (15,624 files). 15,345 of them have exactly one day, and
that day's model map is the file's own, so every such file held two
equal maps of ~700B each. decodeCache's share now points the day at the
file's map when they are equal.

A kept state is never written: use, unuse and dropUse are the only
writers of Models, and every parser (sessions.go, calls.go, calls_dsh,
dsh, droid, grok, kimi, cline) writes a clone, which copies the two
maps apart.

Run, at this head on 42ab93551:
- the real sessions.json (sbpairs, 22.8MB): live heap after decode
  28MB -> 21MB, 3 of 3.
- StatsAt(3650) over the real sessions in a sandbox HOME, digest of
  the 96 days before 10-24: a21dc1d1... with this change (twice, the
  second from the cache it wrote) and with the sharing turned off
  (twice): the same.
- TestDecodeCacheSharesOneDaysModels: red with the sharing removed
  ("holds its models twice") and red with clone keeping the shared map
  ("the kept state was written").
- go test -count=1 ./internal/sessions ./internal/usage ./internal/gui
  ok; go test -race ./internal/sessions ok; GOOS=linux and
  GOOS=windows go vet -tags nogui on the three ok; gofmt -l clean.

Not tried: a full go test ./... (one suite per machine).
2026-10-25 07:33:35 +08:00
yetone 89dc164765 sessions: sessions.json is written a file's parse at a time
A save marshalled the whole index into one buffer: 22.8MB for a long
history (15,624 files), grown by doubling to ~85MB of allocation a save,
and a save follows every refresh that read a changed session file, so a
start while agents run, and a Sessions or Usage poll after any call. It
is written through a json.Encoder into a 256KB buffer handed to a 1MB
bufio.Writer on the temp file, keys in json.Marshal's order and escaped
as it escapes them, so the file is the same bytes.

Measured on the real sessions.json (sbpairs, 22,836,803 bytes):
json.Marshal 54-73ms and 85MB alloc; encodeCache 51ms and 14MB alloc;
the output equal byte for byte.

Run at this tree (3767addd4 + the race skip + this change):
- go test -race -count=1 ./internal/sessions: ok
- go test -count=1 ./internal/sessions ./internal/usage ./internal/gui
  ./internal/agent/...: ok
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/sessions: ok;
  gofmt -l clean
- TestEncodeCacheIsMarshal compares with json.Marshal for 3002 files (a
  key and a title with <, &, quotes and U+2028, a file of no parse), an
  empty index and none. Broken by hand (keys in map order): red; restored:
  green.

Not tried: the save on Windows or Linux.
2026-10-25 07:17:17 +08:00
yetone 94503901c0 sessions: a string many kept files repeat is held once
decodeCache's Unmarshal made a string for every file's title, cwd and
model names, however many files gave the same one. On the real history
copy (sbpairs, 27,699 kept files) 23,689 sessions a script ran carry one
~420-byte prompt as their title. The kept parses held 54 MB after a
collection, 11 MB of it such copies. Each decode worker now takes those
fields (title, cwd, first, named, model, provider, msg_model, msg_day,
codex_nickname, and the Codex identity's role and parents) through
unique.Make, so the parses hold 44 MB. The decode took 104-114 ms, as it
did (121 ms when measured for e2dbb0340).

One QueryPage(All) from requests-v1.bin under GOGC=25, as the GUI's
warm-up runs it: max RSS 319-327 MB -> 296-305 MB. From cold (no file):
390 MB, against 448-462 MB before this and 31bff66be.

TestDecodeCacheSharesRepeats decodes 2000 files of two titles and one
cwd, model and role, and counts the copies held. It is red with share
taken out (2000 of each).

Run at this head: go test ./internal/sessions ./internal/usage (ok);
go vet ./internal/sessions, GOOS=linux and GOOS=windows -tags nogui;
gofmt -l. Not run: the full suite (one per machine).
2026-10-25 06:27:13 +08:00
yetone e2dbb03405 sessions: the kept parses are decoded on a few goroutines at start
One json.Unmarshal of sessions.json (40MB, 27,679 files on a long
history) took 310 to 440ms of every start before the first page (#3493).
decodeCache checks the file is valid JSON (gjson), reads its version and
zone, splits the files without copying them, and decodes each file's
parse with json.Unmarshal on up to 8 goroutines. The result is what one
Unmarshal gave: a key given twice is its last, and the file is refused
where it was refused (bad JSON, another version or zone, no files, a
parse that doesn't decode). Only the keys are copied out of the read.

Real data (sandbox copy of the live sessions.json, load ~60): Unmarshal
311ms, decodeCache 121ms, reflect.DeepEqual the same 27,679 parses.

Run at 5d2260d3e (origin/main, fetched): go test -timeout 45m of
sessions (14.6s), usage (18.4s), usageapi (7.9s), cli (35.9s) and tui
(15.4s) ok; TestDecodeCacheIsUnmarshal -race ok. gofmt clean; GOOS=linux
and GOOS=windows go vet -tags nogui ./internal/sessions/ clean.

TestDecodeCacheIsUnmarshal (new) compares decodeCache with Unmarshal on
3000 files, escaped keys, a null parse, a key given twice, no files, an
old version, another zone, a bad parse first and last, a cut file,
trailing bytes, a missing comma and garbage. Red with the validity check
taken out (trailing, missing comma), with a bad parse ignored, with the
first of two keys kept, and with the zone not compared.
2026-10-25 06:09:30 +08:00