sessions: a scan's read buffer is the size of what is left of the file, 1 MiB at most (#2776)

scanAt gave every scan a 1 MiB bufio buffer. A start reads ~4,600
mostly small session files (and reads each again from where it was
left), so those buffers were the largest single allocation of a start:
9.4 GB of the 22.4 GB a warm start allocated on the sandbox below. The
buffer is now the rest of a plain file plus one byte, at least 16 KiB
and at most 1 MiB; a packed (zstd) file keeps 1 MiB. A line longer than
the buffer (a file grown since its size was read) is still read whole
through scanAt's long-line path.

Tests (internal/sessions/scan_buffer_test.go):
- TestScanOfASmallFileTakesASmallBuffer: 200 scans of a two-line file
  allocate under 64 KiB each. With the 1 MiB buffer back: red, "a scan
  of a two-line file allocated 1048871 bytes".
- TestScanReadsALineLongerThanItsBuffer: a line three buffers long, then
  a short one, are both handed over whole.

Measured on a sandbox instance (600k gateway calls, ~4,600 sessions),
base 1a3b92688 against this branch with every #2776 commit, back to back
at a load average of 340-450 (nine agents running suites), heap profile
after the four first API calls and 60s idle:

                       allocated   of it scan buffers   live heap
  warm  base            22.40 GB         9.40 GB          483 MB
  warm  new             15.86 GB         1.98 GB          498 MB
  cold  base            22.48 GB         9.31 GB          450 MB
  cold  new             15.76 GB         1.98 GB          498 MB

What is left in bufio.NewReaderSize is the other call readers' own
1 MiB buffers (calls_pi, calls_kimi, ...). Peak RSS did not drop at this
load (base 4.38/4.41 GB, new 4.59/4.54 GB): the peak comes from the four
first calls each materialising the 600k-call ledger at once
(gatewayRecords appends every Record, 2.56 GB allocated; ledgerOfAt
6.2 GB for CodexModelEffort), which this commit does not change.

Run on origin/main 2ceff7370 with all four #2776 commits' changes
(this one and the three beside it), load average 291-568 (nine agents
running suites), macOS:
- go test -p 4 ./... -timeout 45m, 09:35-10:49: 62 packages ok,
  among them agent (2310s), gateway (1707s), provider (764s), usage
  (83s). Red:
  - internal/sessions: TestWSLOmpProfiles, TestWSLStoppedDistroKept,
    TestWSLStoppedSinceNotOpened, TestWSLNoneWithoutHomes, each
    "TempDir: mkdir ...: no space left on device" (the disk filled
    mid-run). After space was freed, ./internal/sessions alone: ok
    (139s).
  - internal/gui: TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
    TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow,
    TestDockReopenKeepsTheWindowsSpace (each killed at 30s) and
    TestMainWindowCorners (86s): the real-window AppKit tests under
    load, already filed as #2645 and #1936. Rerun alone at load ~335:
    all pass, with TestSetAnswersWhileDevinAndProvidersHang (17s).
- gofmt -l: none. go vet: darwin, GOOS=linux -tags nogui and
  GOOS=windows all exit 0.
- No internal/gui/assets file changed, so the GUI Playwright suite was
  not run.
This commit is contained in:
yetone
2026-10-19 11:32:59 +08:00
parent c381e4cd1e
commit d7e02ae088
2 changed files with 80 additions and 1 deletions
+63
View File
@@ -0,0 +1,63 @@
package sessions
import (
"os"
"path/filepath"
"runtime"
"strings"
"testing"
)
// A scan of a small session file takes a buffer the size of the file, not
// 1 MiB: a start reads thousands of them, and their buffers were most of
// what it allocated (#2776).
func TestScanOfASmallFileTakesASmallBuffer(t *testing.T) {
p := filepath.Join(t.TempDir(), "s.jsonl")
if err := os.WriteFile(p, []byte(`{"type":"user","n":1}`+"\n"+`{"type":"assistant","n":2}`+"\n"), 0o600); err != nil {
t.Fatal(err)
}
const scans = 200
lines := 0
var before, after runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&before)
for range scans {
if _, err := scanAt(p, 0, nil, func(b []byte, _, _ int64) bool { lines++; return true }); err != nil {
t.Fatal(err)
}
}
runtime.ReadMemStats(&after)
if lines != 2*scans {
t.Fatalf("read %d lines, want %d", lines, 2*scans)
}
// 16 KiB each, with room for the file handles and anything else
if per := (after.TotalAlloc - before.TotalAlloc) / scans; per > 64<<10 {
t.Fatalf("a scan of a two-line file allocated %d bytes", per)
}
}
// A line longer than the buffer (the file grew after its size was read) is
// still handed over whole.
func TestScanReadsALineLongerThanItsBuffer(t *testing.T) {
p := filepath.Join(t.TempDir(), "s.jsonl")
if err := os.WriteFile(p, []byte("{}\n"), 0o600); err != nil {
t.Fatal(err)
}
f, err := os.Open(p)
if err != nil {
t.Fatal(err)
}
size := scanBuffer(f, 0)
f.Close()
long := `{"text":"` + strings.Repeat("x", 3*size) + `"}`
if err := os.WriteFile(p, []byte(long+"\n{}\n"), 0o600); err != nil {
t.Fatal(err)
}
var got []int
if _, err := scanAt(p, 0, nil, func(b []byte, _, _ int64) bool { got = append(got, len(b)); return true }); err != nil {
t.Fatal(err)
}
if len(got) != 2 || got[0] != len(long) || got[1] != 2 {
t.Fatalf("lines %v, want [%d 2]", got, len(long))
}
}
+17 -1
View File
@@ -1371,7 +1371,7 @@ func scanAt(path string, off int64, head func([]byte) bool, fn func(b []byte, st
}
return off, err
}
r := bufio.NewReaderSize(f, 1<<20)
r := bufio.NewReaderSize(f, scanBuffer(f, off))
var long []byte
var n int64 // bytes of the line so far
skip, seen := false, false
@@ -1413,6 +1413,22 @@ func scanAt(path string, off int64, head func([]byte) bool, fn func(b []byte, st
}
}
// scanBuffer is the read buffer scanAt needs for what is left of f from off:
// 1 MiB at most, and no more than that rest of a plain file. Every scan
// took 1 MiB, and a start's read of ~4,600 mostly small session files
// (each read again from where it was left) allocated ~9 GB of them, which
// the GC's heap target followed up (#2776). A line longer than the buffer
// (a file grown since) is still read whole, through scanAt's long line.
func scanBuffer(f io.Reader, off int64) int {
const most, least = 1 << 20, 16 << 10
if pf, ok := f.(*os.File); ok {
if info, err := pf.Stat(); err == nil {
return int(min(most, max(least, info.Size()-off+1)))
}
}
return most
}
// packed says whether a session file is compressed: a Codex rollout the
// Codex app has packed (.zst), a dsh session (.zstd). A packed rollout is
// written whole, so it is read whole again whenever it changes.