Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

sessions: a scan's read buffer is reused from a pool, not allocated per scan

yetone2bd1dc81d61d
diff --git a/internal/sessions/main_test.go b/internal/sessions/main_test.go
index 189461b62..20cc448aa 100644
--- a/internal/sessions/main_test.go
+++ b/internal/sessions/main_test.go
@@ -6,5 +6,10 @@ import (
"github.com/yetone/magpie/internal/testenv"
)
-// The tests run in a home of their own, never the user's real files.
-func TestMain(m *testing.M) { testenv.Main(m) }
+// The tests run in a home of their own, never the user's real files, and
+// a scan's buffer given back is filled with garbage, so a reader that kept
+// a line past its scan fails here rather than for a user.
+func TestMain(m *testing.M) {
+ poisonReleased = true
+ testenv.Main(m)
+}
diff --git a/internal/sessions/race_off_test.go b/internal/sessions/race_off_test.go
new file mode 100644
index 000000000..df92b8824
--- /dev/null
+++ b/internal/sessions/race_off_test.go
@@ -0,0 +1,5 @@
+//go:build !race
+
+package sessions
+
+const raceOn = false
diff --git a/internal/sessions/race_on_test.go b/internal/sessions/race_on_test.go
new file mode 100644
index 000000000..e07d52f72
--- /dev/null
+++ b/internal/sessions/race_on_test.go
@@ -0,0 +1,7 @@
+//go:build race
+
+package sessions
+
+// raceOn says the tests run under -race, where sync.Pool lets a quarter of
+// what is put in it go, so a test of what a pool saves is skipped.
+const raceOn = true
diff --git a/internal/sessions/scan_buffer_test.go b/internal/sessions/scan_buffer_test.go
index ebaacfaed..87fb90e5e 100644
--- a/internal/sessions/scan_buffer_test.go
+++ b/internal/sessions/scan_buffer_test.go
@@ -1,6 +1,7 @@
package sessions
import (
+ "bytes"
"context"
"os"
"path/filepath"
@@ -166,3 +167,50 @@ func TestScanStepsOverATooLongLineUngathered(t *testing.T) {
t.Fatalf("a scan stepping over a %d-byte line allocated %d bytes", len(long), alloc)
}
}
+
+// Scans of big files share their read buffers: each took a new one of up
+// to 1 MiB, and a live magpie's scans allocated 3.8 GB of them in 48
+// minutes while ~157 MB was live.
+func TestScansShareTheirBuffers(t *testing.T) {
+ if raceOn {
+ t.Skip("-race drops pooled buffers at random")
+ }
+ p := filepath.Join(t.TempDir(), "big.jsonl")
+ line := `{"type":"assistant","text":"` + strings.Repeat("x", 4000) + `"}` + "\n"
+ writeFile(t, p, strings.Repeat(line, 600)) // ~2.4 MB
+ const scans = 50
+ lines := 0
+ scan := func() {
+ if _, err := scanAt(p, 0, nil, func([]byte, int64, int64) bool { lines++; return true }); err != nil {
+ t.Fatal(err)
+ }
+ }
+ scan()
+ var before, after runtime.MemStats
+ runtime.ReadMemStats(&before)
+ for range scans {
+ scan()
+ }
+ runtime.ReadMemStats(&after)
+ if lines != 600*(scans+1) {
+ t.Fatalf("read %d lines", lines)
+ }
+ // a GC between scans may let a pooled buffer go: room for a few
+ if per := (after.TotalAlloc - before.TotalAlloc) / scans; per > 128<<10 {
+ t.Fatalf("a scan of a 2.4 MB file allocated %d bytes", per)
+ }
+}
+
+// The tests run with a buffer given back filled with garbage: what makes
+// a line kept past its scan fail in them.
+func TestALineKeptPastItsScanIsGarbageInTests(t *testing.T) {
+ r, release := lineReader(bytes.NewReader([]byte("{\"a\":1}\n")), 16<<10)
+ b, err := r.ReadSlice('\n')
+ if err != nil {
+ t.Fatal(err)
+ }
+ release()
+ if !bytes.Equal(b, bytes.Repeat([]byte{0xFF}, len(b))) {
+ t.Fatalf("a line kept past its scan reads %q", b)
+ }
+}
diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go
index 01bafc4f2..d95e12cd0 100644
--- a/internal/sessions/sessions.go
+++ b/internal/sessions/sessions.go
@@ -1384,7 +1384,8 @@ func scanAt(path string, off int64, head func([]byte) bool, fn func(b []byte, st
}
return off, err
}
- r := bufio.NewReaderSize(f, scanBuffer(f, off))
+ r, release := lineReader(f, scanBuffer(f, off))
+ defer release()
var long []byte
var n int64 // bytes of the line so far
skip, seen := false, false
@@ -1471,6 +1472,51 @@ func scanBuffer(f io.Reader, off int64) int {
return most
}
+// lineReaders keep scanAt's read buffers between scans, one pool per
+// power-of-two size from scanBuffer's 16 KiB to its 1 MiB. Every scan
+// allocated its own: a live magpie's start read ~3,200 Claude Code subagent
+// files for their first lines (ccTask), most over 1 MiB, and with the
+// session and call reads scanAt allocated 6.3 GB in 48 minutes, 3.8 GB of
+// it these buffers, while ~157 MB was live. A pool keeps about one buffer
+// per reader running at once, and lets idle ones go at the next GCs.
+var lineReaders [7]sync.Pool
+
+// poisonReleased, set by the tests, fills a buffer given back with 0xFF, so
+// a reader that kept a line past its scan reads garbage and fails.
+var poisonReleased = false
+
+// lineReader is a reader of f with a buffer of at least size bytes (at
+// most 1 MiB); release gives the buffer back. A line handed out from it is
+// only good until release: one kept longer is copied.
+func lineReader(f io.Reader, size int) (*bufio.Reader, func()) {
+ class := 0
+ for class < len(lineReaders)-1 && 16<<10<<class < size {
+ class++
+ }
+ r, _ := lineReaders[class].Get().(*bufio.Reader)
+ if r == nil {
+ r = bufio.NewReaderSize(nil, 16<<10<<class)
+ }
+ r.Reset(f)
+ return r, func() {
+ if poisonReleased {
+ r.Reset(poison{})
+ r.Peek(r.Size())
+ }
+ r.Reset(nil)
+ lineReaders[class].Put(r)
+ }
+}
+
+type poison struct{}
+
+func (poison) Read(b []byte) (int, error) {
+ for i := range b {
+ b[i] = 0xFF
+ }
+ return len(b), nil
+}
+
// 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.