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.)