Commit Graph
4 Commits
Author SHA1 Message Date
yetone 10939ebdf1 sessions: a dsh frame is read into one buffer of its own size
scanFrames reads a dsh session (zstd frames, a batch of whole lines
each) frame by frame, and readFrame took each frame's bytes by growing
its buffer a block at a time (blocks are at most 128 KiB). A frame with
a pasted image is megabytes long, and growing to it by append allocated
several times what it read (3.7 times on the first case below).

- frameSize finds a frame's length from its headers alone (frame
  header, then each block's 3-byte header, then the checksum), read
  ahead with ReadAt without moving the file, and readFrame makes its
  buffer that large at once. The buffer is still reused across frames.
- frameHeaderLen and blockLen are readFrame's own header arithmetic,
  moved out so both read the format the same way.
- A skippable frame, or one the file doesn't hold whole yet, has size
  0, and readFrame reads it as before: a frame still being written
  waits for the next read, and a size that turned wrong (the file
  rewritten in between) only makes the buffer grow again.

scanFrames runs on dsh session reads (dsh.go's session list and
calls_dsh.go's calls), cold once per file and then on from the last
frame read.

Measured (TotalAlloc of scanFrames over a whole dsh file, 3 runs
each, all within 2%):

  session                                    before      after
  3 frames, images of 1/3/5 MiB (9.4 MB)     34.85 MB    18.93 MB
                                             (3.69x)     (2.01x)
  one frame, a 6 MiB image (the test below)  38.4-39.5 MB 12.6-13.7 MB

pprof (memprofilerate 1) put readFrame's take at 24.8 MB of the first
case's 34.9 MB. What is left is the frames once and DecodeAll's output.

Tests (internal/sessions/frames_size_test.go):
- TestFrameSizeIsWhatReadFrameReads: frameSize equals what readFrame
  reads for frames with and without a checksum, a 3 MiB and a 2 MiB
  line, and is 0 for a skippable frame and a frame cut short.
- TestScanFramesLongLinesUnchanged: the lines scanFrames hands over
  equal a whole-stream decode's, for a 5 MiB line with an empty line
  after it, a 3 MiB line split across two frames, and a 1 MiB line;
  and with the last frame half written, the read stops at the frame
  before it and reads on, once it is whole, to the same lines.
- TestScanFramesReadsALongFrameOnce: a scan of one frame with a 6 MiB
  line allocates at most the frame plus the line plus 2 MiB. With
  frameSize's hint replaced by 0 (the old growth) it is red 3 of 3:
  "a scan of a 6291688-byte frame allocated 38445616/39495688/39495704
  bytes, want at most 14680367". Passed -count=10.

Run at this commit's tree on origin/main c84864ffc, macOS arm64, go1.26.8,
sandbox HOME: gofmt -l internal clean; go vet ./internal/... ok, and
GOOS=linux/windows go vet -tags nogui of sessions and usage ok;
go test -race -count=3 ./internal/sessions/ ok (512s); go test
-timeout 45m ./... exit 0, 65 packages ok, none failed. (On the older
base a9304efe0 the race run was red in TestManageReadsOnlyTheAgentsItShows,
TestOpenCodeSubagents and TestLongReadKeepsWhatItRead: test-only races
that 9afdeb89c and c84864ffc fixed on main.)
2026-10-21 02:44:23 +08:00
yetone 21c2ab6fa5 sessions: packed session files are decompressed by decoders kept between reads
Why: a live heap profile of v0.1.1296 (pid 554, up 67 min) allocated
173 GB, 75 GB of it in zstd decoding, through sessions.scanAt from both
usage.prefetchSources (ReadCallSource → readCalls) and sessions.refresh
(parse). openLines made a new zstd decoder for every packed file it
opened, and a decoder's first frame allocates its window: the Codex app
packs rollouts with a 2 MiB window, which a low-memory decoder holds in
3 MiB, plus ~350 KB of block buffers. scanFrames (dsh .zstd) did the same
on every read on.

What was found, on 180 real packed rollouts (360 MB, copied with their
times) and the profile:
- An unchanged packed file (same size and time) is not opened again by
  either path, while magpie runs or after it starts from what it saved
  (Saved, Reset): 180 scans each path cold, 0 on every later round. A
  changed one is read again alone.
- The 75 GB was each path's one full pass over all 11,591 packed rollouts
  at the app's start, both caches invalid for them then: about 3.4 MB a
  file for each path's decoder, and its 1 MiB copy buffer to pass over
  what came before off.
- dsh files are already read on from their last whole frame
  (TestDshPackedReadsOnlyWhatWasAppended, TestDshCallsReadOnlyWhatWasAppended).

What changed:
- openLines takes a decoder from a pool (streams) and Resets it onto the
  file; zstdFile's Close Resets it to nil and puts it back. Read or Close
  after Close is os.ErrClosed. IOReadCloser isn't used, since its Close
  closes the decoder for good.
- scanFrames decodes frames with a pooled decoder of its own pool
  (frameDecoders): a decoder that has read a stream holds its block
  decoder, which DecodeAll would wait for. Its reader comes from
  lineReader's pooled buffers, not a new bufio.Reader.
- scanAt passes over what comes before off in a packed file through its
  pooled line reader (Discard), not io.CopyN's buffer of its own.
- Decoder options and window limits are unchanged, so what is read is
  the same; an idle pooled decoder is let go by the garbage collector
  with the pool, and as many are held at once as files are read at once,
  as before.

Numbers:
- go test -bench 'PackedScan|DshFrames' -benchtime 40x, before → after:
  - an 8 MB Codex rollout, 2 MiB window, scanAt from 0: 3,364,175 →
    110,902 B/op, 25 → 6 allocs/op;
  - a 6 MB dsh session of 8-line frames, scanFrames whole: 1,959,606 →
    491,117 B/op, 63 → 22 allocs/op;
  - the same, read on from its last frame: 182,087 → 74,361 B/op, 34 → 9
    allocs/op.
- TestPackedScanKeepsItsDecoder (a warmed scan): 3,330,508 → 452 bytes.
- The 180 real rollouts, read cold by List, CallSources and
  ReadCallSource: 1,294 and 1,299 MB → 375 and 386 MB allocated (two
  runs each). The sessions and calls read (177 sessions, 306 calls) are
  byte for byte the same JSON before and after.

Tests (packed_decoder_test.go):
- TestPackedScanKeepsItsDecoder and TestDshFramesKeepTheirDecoder fail on
  the old code (3,330,508 and 181,995 bytes) and with either Put taken
  out by hand (3,330,344 and 165,539 bytes). Skipped under -race, where
  sync.Pool drops what it is given.
- TestPackedScanSameThroughAKeptDecoder: lines and places through kept
  decoders are what a decoder of its own reads, for a large file after a
  small one cut short, read on from a line, past the end, and by 8
  readers at once.
- TestUnchangedPackedNotReadAgain passes on the old code too (it held
  already). It fails when refresh's or readCalls's size-and-time check is
  broken by hand for packed files.

Run, at this commit's tree:
- go test -timeout 45m -count=1 ./internal/sessions/ ./internal/usage/:
  ok (79s, 39s).
- go test -race -count=3 -run 'TestUnchangedPacked|TestPackedScan|
  TestDshFrames|TestCodexPacked|TestDsh.*Packed|TestDsh.*Append|Frame'
  ./internal/sessions/: ok.
- gofmt -l internal/sessions: nothing. GOOS=linux go vet -tags nogui
  ./... and GOOS=windows go vet -tags nogui ./...: exit 0.
- go test -tags nogui -timeout 45m -count=1 ./... under a scratch HOME,
  GOPATH, GOMODCACHE and GOCACHE pinned: exit 0, every package ok (65,
  no FAIL); gateway 802s, agent 733s, provider 355s, sessions 273s,
  usage 92s.
Not tried: in the running app; on real dsh files (none on this machine,
so the profile's zstd was all Codex .zst). Why both caches were invalid
for the packed rollouts at that start is not found here.
2026-10-20 23:11:32 +08:00
yetone baef679f29 sessions: every other reader of a session file sizes its buffer by what is left of it, as scanAt does (#2776)
d7e02ae08 sized scanAt's buffer by the rest of the file. The other line
readers of a session file still took 1 MiB per file read:
- readMiniMaxCalls, readAgyCalls and readWorkBuddyCalls (WorkBuddy and
  CodeBuddy Code), which read a changed file whole;
- scanFrames, dsh's packed (.zstd) sessions, read on from a frame;
- mayHold, a search's first look at each file.
(calls_pi, calls_kimi, calls_dsh and dsh.go no longer hold one since
the incremental readers before a77f6ae16.) Each now takes
scanBuffer(f, off): the rest of a plain file plus one byte, 16 KiB to
1 MiB. ReadBytes and readFrame read a line or frame longer than the
buffer whole, as before; a packed WorkBuddy file (a zstd stream, not
an *os.File) keeps 1 MiB.

TestReadersOfASmallFileTakeASmallBuffer reads a two-line file 50 times
through each of the five and allows 256 KiB per read. With the five
readers put back (the test kept): red in all five, 1,049,161 (minimax),
1,049,271 (agy), 1,049,256 (workbuddy), 1,068,296 (frames) and
1,056,984 (search) bytes per read.

Not measured on the 600k sandbox: it holds no MiniMax, agy, WorkBuddy or
dsh sessions, so the saving there is the test's: ~1 MiB per file each
time one of these is read again.

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 b3642e7277 sessions: a dsh session read before is read on from where it was left, not whole
dsh only appends to a session file, a line at a time or, packed
(.zstd), a frame of lines at a time. Every reply still made the
Sessions and Usage pages read, and for a packed file decompress, the
whole file again: a packed file "can't be read on from the middle of a
frame".

It can be read on from the start of one. frames.go walks a file of zstd
frames without decoding them (RFC 8878: the frame header, then blocks
that each give their length, then the checksum), decodes one frame at a
time, and says where to go on from: the frame the first line not yet
whole starts in, and how far into what it holds. A frame not yet
written whole waits for the next read, and so does a line a frame ends
inside of.

parseDsh keeps a tail (tail.go) and the header it read, and counts each
event as it comes (dshCount) instead of collecting them all first. A
fork's inherited end-seed met in a later read starts the counts over
from the session's start, keeping its title and name, as the whole read
did by cutting at the last one. A file that shrank or was replaced is
read whole again. One change from before: a last line not ended by a
newline now waits for it, like every other appended file's.

Measured (CPU, getrusage; 50 MB of events, a reply appended between
reads; packed: 17 MB of frames; machine loaded):
  plain   before: ~110-120 ms per read after an append
          after:  0.4-2.6 ms per read after an append; first read ~120 ms
  packed  before: ~190-250 ms per read after an append
          after:  0.4-0.5 ms per read after an append; first read ~260 ms

Tests: TestDshReadsOnlyWhatWasAppended runs the shared append, half
line, cut-short and rewritten-in-place cases.
TestDshPackedReadsOnlyWhatWasAppended appends a frame (read alone), half a frame (waits), a
frame ending inside a line and the frame that ends it (read on from the
first of the two, the line counted once), then cuts the file short and
replaces it with a longer one (read whole). TestDshEndSeedAcrossReads
writes a fork's seeded lines, its end-seed and its own, a read apart
each. Every read on is checked equal to a whole read.
Broken by hand: resume off -> red in both ReadsOnly tests ("after a
line appended to 1308 bytes, read from 0", "after a frame appended to
654 bytes, read from 0"); a line split over two frames resumed at the
second frame -> red (read on differs from whole); the end-seed reset
removed -> red in TestDshEndSeedAcrossReads and TestDsh.

Run: go test ./internal/sessions -count=1 -timeout 45m ok; gofmt -l
and go vet ./internal/sessions clean. The full-suite record is in the
last commit of this series.
2026-10-19 11:30:47 +08:00