Skip to content

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

sessions: scan buffers and zstd decoders are kept on a small shelf across garbage collections, let go after 10 s unused

yetone4c0afc26d7c1
diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go
index a010805bf..a2b3413da 100644
--- a/internal/sessions/sessions.go
+++ b/internal/sessions/sessions.go
@@ -1487,6 +1487,9 @@ var longLines sync.Pool
// takeLong is an empty buffer of at least l bytes, from the pool when it
// has one that large (the one a scan had, too small, is let go).
func takeLong(l int) (*[]byte, []byte) {
+ if p, ok := longShelf.take(func(p *[]byte) bool { return cap(*p) >= l }); ok {
+ return p, (*p)[:0]
+ }
if p, _ := longLines.Get().(*[]byte); p != nil {
if cap(*p) >= l {
return p, (*p)[:0]
@@ -1509,9 +1512,25 @@ func giveLong(p *[]byte, long []byte) {
}
}
*p = (*p)[:0]
+ if cap(*p) <= longShelved {
+ // kept in place of a smaller one when the shelf is full
+ out, kept, swapped := longShelf.give(p, func(h, p *[]byte) bool { return cap(*h) < cap(*p) })
+ if !kept {
+ longLines.Put(p)
+ } else if swapped {
+ longLines.Put(out)
+ }
+ return
+ }
longLines.Put(p)
}
+// longShelf keeps long-line buffers up to longShelved bytes across garbage
+// collections; a longer one, rare, is left to longLines.
+var longShelf shelf[*[]byte]
+
+const longShelved = 4 << 20
+
// blocks hold a long line read from a packed file until its end is found:
// copied into 1 MiB blocks kept between scans, so the line is allocated
// only once, at its own length.
@@ -1595,6 +1614,9 @@ func scanBuffer(f io.Reader, off int64) int {
// per reader running at once, and lets idle ones go at the next GCs.
var lineReaders [7]sync.Pool
+// lineShelves keep a few of each first, across garbage collections.
+var lineShelves [7]shelf[*bufio.Reader]
+
// 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
@@ -1607,7 +1629,10 @@ func lineReader(f io.Reader, size int) (*bufio.Reader, func()) {
for class < len(lineReaders)-1 && 16<<10<<class < size {
class++
}
- r, _ := lineReaders[class].Get().(*bufio.Reader)
+ r, _ := lineShelves[class].take(nil)
+ if r == nil {
+ r, _ = lineReaders[class].Get().(*bufio.Reader)
+ }
if r == nil {
r = bufio.NewReaderSize(nil, 16<<10<<class)
}
@@ -1618,7 +1643,9 @@ func lineReader(f io.Reader, size int) (*bufio.Reader, func()) {
r.Peek(r.Size())
}
r.Reset(nil)
- lineReaders[class].Put(r)
+ if _, kept, _ := lineShelves[class].give(r, nil); !kept {
+ lineReaders[class].Put(r)
+ }
}
}
@@ -1644,7 +1671,10 @@ func openLines(path string) (io.ReadCloser, error) {
if err != nil || !packed(path) {
return f, err
}
- d := streams.Get().(*zstd.Decoder)
+ d, ok := streamShelf.take(nil)
+ if !ok {
+ d = streams.Get().(*zstd.Decoder)
+ }
if err := d.Reset(f); err != nil {
f.Close()
return nil, err
@@ -1656,7 +1686,10 @@ func openLines(path string) (io.ReadCloser, error) {
// read allocated its window (a packed rollout's is 2 MiB, held in 3 MiB at
// low memory) and its block buffers every time: 75 GB of a live magpie's
// first read of 11,591 rollouts. One kept here keeps them, and is let go
-// with the pool's other idle ones by the garbage collector.
+// with the pool's other idle ones by the garbage collector. streamShelf
+// keeps a few first, across collections.
+var streamShelf shelf[*zstd.Decoder]
+
var streams = sync.Pool{New: func() any {
d, err := zstd.NewReader(nil, zstd.WithDecoderConcurrency(1), zstd.WithDecoderLowmem(true))
if err != nil {
@@ -1684,7 +1717,9 @@ func (z *zstdFile) Close() error {
return os.ErrClosed
}
z.d.Reset(nil)
- streams.Put(z.d)
+ if _, kept, _ := streamShelf.give(z.d, nil); !kept {
+ streams.Put(z.d)
+ }
z.d = nil
return z.f.Close()
}
diff --git a/internal/sessions/shelf.go b/internal/sessions/shelf.go
new file mode 100644
index 000000000..3b6c199d1
--- /dev/null
+++ b/internal/sessions/shelf.go
@@ -0,0 +1,96 @@
+package sessions
+
+import (
+ "sync"
+ "time"
+)
+
+// shelfIdle is how long a shelf keeps what it holds after its last use.
+const shelfIdle = 10 * time.Second
+
+// shelfHeld is the most a shelf holds, which bounds it: 4 MiB of 1 MiB line
+// readers, 16 MiB of long lines, 4 zstd decoders (~3 MiB each).
+const shelfHeld = 4
+
+// shelf keeps up to shelfHeld buffers (or decoders) given back, for the next
+// scan to take. A sync.Pool lets what it holds go at every second garbage
+// collection, and a cold start collects about once a second: in its first
+// 2 minutes (155 GCs) the pools were empty for 611 of the 1 MiB line
+// readers, 205 long-line buffers and 281 zstd decoders scans asked for,
+// ~1.9 GB allocated again. A shelf keeps them across collections while
+// scans run, and lets them all go once none was taken or given back for
+// shelfIdle, so an idle magpie holds none.
+type shelf[T any] struct {
+ idleFor time.Duration // shelfIdle when 0; set by tests
+
+ mu sync.Mutex
+ held []T
+ used time.Time
+ timer *time.Timer
+}
+
+// take is the first held thing ok accepts, if any.
+func (s *shelf[T]) take(ok func(T) bool) (T, bool) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.used = time.Now()
+ for i, v := range s.held {
+ if ok == nil || ok(v) {
+ s.held = append(s.held[:i], s.held[i+1:]...)
+ return v, true
+ }
+ }
+ var zero T
+ return zero, false
+}
+
+// give keeps v, in place of the first held thing worse says v beats when
+// the shelf is full. It says false when v isn't kept (the shelf is full
+// and v beats none), and gives back what v took the place of, if any.
+func (s *shelf[T]) give(v T, worse func(held, v T) bool) (out T, kept, swapped bool) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.used = time.Now()
+ if s.timer == nil {
+ s.timer = time.AfterFunc(s.wait(), s.idle)
+ }
+ if len(s.held) < shelfHeld {
+ s.held = append(s.held, v)
+ return out, true, false
+ }
+ for i, h := range s.held {
+ if worse != nil && worse(h, v) {
+ s.held[i] = v
+ return h, true, true
+ }
+ }
+ return out, false, false
+}
+
+// idle lets go of everything held once the shelf has gone unused for
+// shelfIdle, or checks again when it was used since.
+func (s *shelf[T]) idle() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if left := s.wait() - time.Since(s.used); left > 0 {
+ s.timer.Reset(left)
+ return
+ }
+ clear(s.held)
+ s.held = s.held[:0]
+ s.timer = nil
+}
+
+func (s *shelf[T]) wait() time.Duration {
+ if s.idleFor > 0 {
+ return s.idleFor
+ }
+ return shelfIdle
+}
+
+// size is how many things the shelf holds.
+func (s *shelf[T]) size() int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return len(s.held)
+}
diff --git a/internal/sessions/shelf_test.go b/internal/sessions/shelf_test.go
new file mode 100644
index 000000000..449ef4dd4
--- /dev/null
+++ b/internal/sessions/shelf_test.go
@@ -0,0 +1,80 @@
+package sessions
+
+import (
+ "bytes"
+ "runtime"
+ "testing"
+ "time"
+)
+
+// A cold start collects about once a second, and a sync.Pool is empty two
+// collections later: what the scans give back must still be there.
+func TestLineReaderKeptAcrossCollections(t *testing.T) {
+ emptyShelf(&lineShelves[len(lineShelves)-1])
+ r, release := lineReader(bytes.NewReader(nil), 1<<20)
+ release()
+ runtime.GC()
+ runtime.GC()
+ runtime.GC()
+ again, release := lineReader(bytes.NewReader(nil), 1<<20)
+ defer release()
+ if again != r {
+ t.Fatal("a 1 MiB line reader was made again after three collections")
+ }
+}
+
+func TestLongLineKeptAcrossCollections(t *testing.T) {
+ emptyShelf(&longShelf)
+ p, b := takeLong(2 << 20)
+ giveLong(p, b)
+ runtime.GC()
+ runtime.GC()
+ runtime.GC()
+ again, b := takeLong(1 << 20)
+ defer giveLong(again, b)
+ if again != p {
+ t.Fatal("a 2 MiB long-line buffer was made again after three collections")
+ }
+}
+
+func TestShelfFullKeepsTheLarger(t *testing.T) {
+ var s shelf[int]
+ for i := 1; i <= shelfHeld; i++ {
+ s.give(i, nil)
+ }
+ if _, kept, _ := s.give(99, nil); kept {
+ t.Fatal("a full shelf kept one more")
+ }
+ out, kept, swapped := s.give(10, func(h, v int) bool { return h < v })
+ if !kept || !swapped || out != 1 {
+ t.Fatalf("gave 10 to a full shelf of 1..%d: out %d kept %v swapped %v", shelfHeld, out, kept, swapped)
+ }
+ if v, ok := s.take(func(v int) bool { return v >= 10 }); !ok || v != 10 {
+ t.Fatalf("took %d, %v", v, ok)
+ }
+}
+
+// An idle magpie holds nothing on a shelf.
+func TestShelfLetsGoWhenIdle(t *testing.T) {
+ s := shelf[int]{idleFor: 20 * time.Millisecond}
+ s.give(1, nil)
+ deadline := time.Now().Add(10 * time.Second)
+ for s.size() > 0 {
+ if time.Now().After(deadline) {
+ t.Fatal("an idle shelf still holds what it was given")
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ // and keeps again afterwards
+ s.give(2, nil)
+ if v, ok := s.take(nil); !ok || v != 2 {
+ t.Fatalf("after letting go: took %d, %v", v, ok)
+ }
+}
+
+// emptyShelf takes what earlier tests' scans left on s.
+func emptyShelf[T any](s *shelf[T]) {
+ for s.size() > 0 {
+ s.take(nil)
+ }
+}