Files
magpie/internal/sessions/race_off_test.go
T
yetone 2bd1dc81d6 sessions: a scan's read buffer is reused from a pool, not allocated per scan
Why: a 48-minute heap profile of the user's magpie allocated 6.3 GB
in sessions.scanAt, while ~157 MB was live. bufio.NewReaderSize made
~3.5 GB of it: each scan made its own buffer, up to 1 MiB (scanBuffer)
for a big file, and threw it away at the end. The earlier commits cut
how often unchanged files are scanned. This one removes the buffer
cost for the scans that still happen: a first read, a grown file, the
calls ledger.

What changed:

- scanAt takes its bufio.Reader from lineReader. lineReader keeps a
  sync.Pool per power-of-two size from 16 KiB to 1 MiB and gives the
  reader back (Reset to nil) when the scan returns.
- A line from the reader was already valid only for the callback that
  got it: long lines are copied into `long`, and callers that keep a
  line copy it.
- Tests run with poisonReleased set in TestMain. A buffer given back
  is overwritten with 0xFF, so a caller that kept a line past its
  scan reads garbage and fails, rather than reading the next scan's
  bytes in a user's magpie.
- sync.Pool drops items at random under -race, so the allocation test
  is skipped there (race_on_test.go / race_off_test.go).

Tests:

- TestScansShareTheirBuffers scans a ~2.4 MB file 50 times and needs
  under 128 KiB allocated per scan.
- TestALineKeptPastItsScanIsGarbageInTests checks the poison.
- Broken by hand: with the pool off (a new reader every time), the
  first test goes red with "a scan of a 2.4 MB file allocated 1049911
  bytes". Green again once restored.
- The whole sessions package passes with the poison on.

Measured on a read-only APFS clone of the user's ~/.claude/projects
and ~/.codex/sessions/2026/10, in a sandbox HOME, at load ~500. Cold
StatsAndNative(0) reads every file once:

| Code | Allocated | Allocations | Time |
| --- | --- | --- | --- |
| origin/main dee5c9d75 | 11,999.5 MB | 24,817,390 | 2m4.7s |
| this series | 5,672.0 MB | 24,431,553 | 1m5.9s |

An earlier run with the pool and the stats change but not the lazy
subagent title: 5,773.3 MB, 24,497,066 allocations. The cold-pass
drop is this commit's.

Run at this tree:

- gofmt -l internal: nothing.
- GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean.
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/gui/:
  - sessions: ok, 366.7s.
  - gui: only TestMainWindowCorners failed, "measuring the windows:
    signal: killed". It also fails alone on an untouched origin/main
    export, at load ~500. Filed as #1936 and #2645. Every other gui
    test passed.
- go test -race -count=3 on the scan, subagent and stats tests: ok,
  207.8s.
2026-10-20 20:32:05 +08:00

6 lines
57 B
Go

//go:build !race
package sessions
const raceOn = false