diff --git a/internal/dirent/stats.go b/internal/dirent/stats.go index a2167732b..a443cf0bb 100644 --- a/internal/dirent/stats.go +++ b/internal/dirent/stats.go @@ -45,11 +45,13 @@ func (l Listing) Get(name string) (Stat, bool) { // // A caller done reading the listing gives it back (Done) for the next. func Stats(dir string) (Listing, bool) { - var l Listing - if p, _ := listings.Get().(*Listing); p != nil { - l = *p + old, room := taken(dir) + l, ok := stats(dir, room, old) + if old != nil { + listings.Lock() + keepRoom(old) + listings.Unlock() } - l, ok := stats(dir, l) if !ok { return nil, false } @@ -58,17 +60,84 @@ func Stats(dir string) (Listing, bool) { } // listings are Stats' answers given back: a listing made new for each -// folder, grown an entry at a time, was ~95 MB of a minute of the page's -// polls (#2278). -var listings sync.Pool +// folder, grown an entry at a time, and each entry's name copied again, +// was ~95 MB of a minute of the page's polls (#2278). A folder's last +// listing is kept, so the next read of it takes its names where they are +// the same, and the one before it is room for the next folder's. They are +// kept here, not in a sync.Pool: a poll collects garbage about twice a +// second, and each collection emptied the pool before the next folder was +// read. A Sessions read holds a listing of each Claude Code project at +// once, a few hundred, so what is kept is bounded by its entries, +// keptEntries in all (~7 MB, and the names). Each folder's last listing +// and the room of the one before are kept: 1<<16 kept little of a history +// of ~23k session files, and the listings were made new again. +var listings struct { + sync.Mutex + last map[string]Listing // a folder's last listing + room []Listing // cleared + entries int // the room of those kept +} -// Done gives l back to be the next Stats' answer: whoever had it reads it -// no more. A Get of it before is only a copy of its entry. -func (l Listing) Done() { +const keptEntries = 1 << 17 + +// taken is dir's last listing and room for its next, each taken from +// what is kept, or none. +func taken(dir string) (old, room Listing) { + listings.Lock() + defer listings.Unlock() + if old = listings.last[dir]; old != nil { + delete(listings.last, dir) + listings.entries -= cap(old) + } + n := len(listings.room) + if n == 0 { + return old, nil + } + at := n - 1 // room enough for dir as last listed, or the last given back + for i, r := range listings.room { + if cap(r) >= len(old) { + at = i + break + } + } + room = listings.room[at] + listings.room[at] = listings.room[n-1] + listings.room[n-1] = nil + listings.room = listings.room[:n-1] + listings.entries -= cap(room) + return old, room +} + +// keepRoom keeps l, cleared, as room for a next listing, while the kept +// have room. listings is held. +func keepRoom(l Listing) { + clear(l[:cap(l)]) + if listings.entries+cap(l) <= keptEntries { + listings.room = append(listings.room, l[:0]) + listings.entries += cap(l) + } +} + +// Done gives l, dir's listing, back for the next Stats of dir: whoever had +// it reads it no more. A Get of it before is only a copy of its entry. +func (l Listing) Done(dir string) { if cap(l) == 0 || cap(l) > 1<<14 { - return // none, or a folder of more files than the pool keeps room for + return // none, or a folder of more files than are kept + } + listings.Lock() + defer listings.Unlock() + if prev := listings.last[dir]; prev != nil { // read twice at once + delete(listings.last, dir) + listings.entries -= cap(prev) + keepRoom(prev) } - clear(l[:cap(l)]) - l = l[:0] - listings.Put(&l) + if listings.entries+cap(l) > keptEntries { + keepRoom(l) + return + } + if listings.last == nil { + listings.last = map[string]Listing{} + } + listings.last[dir] = l + listings.entries += cap(l) } diff --git a/internal/dirent/stats_darwin.go b/internal/dirent/stats_darwin.go index fd0cb5b0c..1868fffea 100644 --- a/internal/dirent/stats_darwin.go +++ b/internal/dirent/stats_darwin.go @@ -3,6 +3,8 @@ package dirent import ( "encoding/binary" "io/fs" + "slices" + "strings" "sync" "syscall" "time" @@ -41,7 +43,8 @@ var bufs = sync.Pool{New: func() any { b := make([]byte, 64<<10); return &b }} // stats reads dir's entries with getattrlistbulk: a Sessions read stats // each of ~21k session files on every 15 s poll, ~10 µs a file on APFS, // and this is one call for every few hundred. -func stats(dir string, out Listing) (Listing, bool) { +// old is dir's last listing, whose names are taken where they are the same. +func stats(dir string, out, old Listing) (Listing, bool) { fd, err := unix.Open(dir, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) if err != nil { return nil, false @@ -65,7 +68,7 @@ func stats(dir string, out Listing) (Listing, bool) { } b := buf for range int(n) { - if !entry(b, &out) { + if !entry(b, &out, old) { return nil, false } b = b[binary.NativeEndian.Uint32(b):] @@ -75,8 +78,8 @@ func stats(dir string, out Listing) (Listing, bool) { // entry reads one entry of getattrlistbulk's answer into out: its length, // the attributes it returned, then each in the order of their bits, a -// file's data length after the common ones. -func entry(b []byte, out *Listing) bool { +// file's data length after the common ones. A name old has is its string. +func entry(b []byte, out *Listing, old Listing) bool { if len(b) < 4 { return false } @@ -99,7 +102,7 @@ func entry(b []byte, out *Listing) bool { if off < 0 || n < 1 || at+n > len(e) { return false } - name = string(e[at : at+n-1]) + name = nameOf(e[at:at+n-1], old) p = p[8:] } typ := uint32(0) @@ -138,3 +141,14 @@ func entry(b []byte, out *Listing) bool { *out = append(*out, Entry{name, s}) return true } + +// nameOf is b as a string, old's where old has it. +func nameOf(b []byte, old Listing) string { + if len(b) > 0 && len(old) > 0 { + v := unsafe.String(&b[0], len(b)) // compared only, never kept + if i, ok := slices.BinarySearchFunc(old, v, func(e Entry, v string) int { return strings.Compare(e.Name, v) }); ok { + return old[i].Name + } + } + return string(b) +} diff --git a/internal/dirent/stats_other.go b/internal/dirent/stats_other.go index f7775c4fd..79ba32261 100644 --- a/internal/dirent/stats_other.go +++ b/internal/dirent/stats_other.go @@ -2,4 +2,4 @@ package dirent -func stats(string, Listing) (Listing, bool) { return nil, false } +func stats(string, Listing, Listing) (Listing, bool) { return nil, false } diff --git a/internal/dirent/stats_test.go b/internal/dirent/stats_test.go index a7ee75d69..6fa2adbe7 100644 --- a/internal/dirent/stats_test.go +++ b/internal/dirent/stats_test.go @@ -9,6 +9,7 @@ import ( "strings" "testing" "time" + "unsafe" ) // Stats says of each entry what os.Lstat says: a file's size and time to @@ -116,7 +117,7 @@ func TestStatsAfterDone(t *testing.T) { if !ok || len(l) != 40 { t.Fatalf("big folder: %d entries, ok %t", len(l), ok) } - l.Done() + l.Done(big) s, ok := Stats(small) if !ok || len(s) != 1 || s[0].Name != "s" || s[0].Size != 3 { t.Fatalf("small folder after a big one given back: %+v, ok %t", s, ok) @@ -124,6 +125,60 @@ func TestStatsAfterDone(t *testing.T) { if rest := s[1:cap(s)]; slices.ContainsFunc(rest, func(e Entry) bool { return e.Name != "" }) { t.Fatalf("a listing given back kept its folder's entries: %+v", rest) } - s.Done() + s.Done(small) } } + +// A listing given back is kept across garbage collections: a poll +// collects about twice a second, and a sync.Pool emptied by each had none +// for the next folder (#2278). A folder's next read takes the names it had +// where they are the same, and the room of the read before. +func TestListingKeptAcrossCollections(t *testing.T) { + if runtime.GOOS != "darwin" { + t.Skip("listed in one call a folder on macOS only") + } + listings.Lock() + listings.last, listings.room, listings.entries = nil, nil, 0 // what tests before kept + listings.Unlock() + dir := t.TempDir() + for _, name := range []string{"rollout-a.jsonl", "rollout-b.jsonl", "rollout-c.jsonl"} { + if err := os.WriteFile(filepath.Join(dir, name), nil, 0o644); err != nil { + t.Fatal(err) + } + } + first, ok := Stats(dir) + if !ok { + t.Fatal("Stats failed") + } + room, b := unsafe.SliceData(first[:cap(first)]), unsafe.StringData(first[1].Name) + first.Done(dir) + runtime.GC() + runtime.GC() + if err := os.WriteFile(filepath.Join(dir, "rollout-b.jsonl"), []byte("grown"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Remove(filepath.Join(dir, "rollout-c.jsonl")); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "rollout-d.jsonl"), nil, 0o644); err != nil { + t.Fatal(err) + } + second, _ := Stats(dir) + var names []string + for _, e := range second { + names = append(names, e.Name) + } + if !slices.Equal(names, []string{"rollout-a.jsonl", "rollout-b.jsonl", "rollout-d.jsonl"}) || second[1].Size != 5 { + t.Fatalf("after a file grew, one went and one came: %+v", second) + } + if unsafe.StringData(second[1].Name) != b { + t.Error("a name listed before was copied again, or let go by a garbage collection") + } + second.Done(dir) + runtime.GC() + third, _ := Stats(dir) + if unsafe.SliceData(third[:cap(third)]) != room { + t.Error("a listing given back was let go by a garbage collection") + } + third.Done(dir) +} diff --git a/internal/sessions/calls.go b/internal/sessions/calls.go index 972137696..7ed36798f 100644 --- a/internal/sessions/calls.go +++ b/internal/sessions/calls.go @@ -1192,20 +1192,21 @@ func CallSourcesAndCodexIdentities() ([]CallSource, map[string]CodexIdentity) { return sources, codexIdentitiesOf(codex) } -// listingBufs are listings a read takes and lets go of before it ends. -var listingBufs sync.Pool +// listingBufs are listings a read takes and lets go of before it ends, +// kept on a shelf: a sync.Pool, emptied by the collections a poll makes +// about twice a second, had none for most reads (#2278). +var listingBufs shelf[[]file] func listingBuf() []file { - if b, ok := listingBufs.Get().(*[]file); ok { - return (*b)[:0] + if b, ok := listingBufs.take(nil); ok { + return b[:0] } return nil } func putListingBuf(fs []file) { clear(fs[:cap(fs)]) // its files' strings go with the listing - fs = fs[:0] - listingBufs.Put(&fs) + listingBufs.give(fs[:0], func(h, fs []file) bool { return cap(h) < cap(fs) }) } func callSourcesOf(fs []file) []CallSource { diff --git a/internal/sessions/one_listing_test.go b/internal/sessions/one_listing_test.go index 4dc4b757d..81c299ced 100644 --- a/internal/sessions/one_listing_test.go +++ b/internal/sessions/one_listing_test.go @@ -1,8 +1,10 @@ package sessions import ( + "runtime" "sync/atomic" "testing" + "unsafe" ) // holdsEnd ends, when the test does, every hold it left: one that fails @@ -151,3 +153,35 @@ func TestListingPoolsGiveBackEmpty(t *testing.T) { t.Fatalf("a listing given back kept its files: %v", b[:cap(b)]) } } + +// A listing or path set given back is kept across garbage collections: a +// poll collects about twice a second, and the sync.Pools they were in, +// emptied by each, had none for most reads (#2278). +func TestListingPoolsKeptAcrossCollections(t *testing.T) { + for ok := true; ok; _, ok = listingBufs.take(nil) { + } + for ok := true; ok; _, ok = pathSets.take(nil) { + } + fs := append(listingBuf(), make([]file, 64)...) + room := unsafe.SliceData(fs) + putListingBuf(fs) + m := pathSet() + m["a"] = struct{}{} + putPathSet(m) + runtime.GC() + runtime.GC() + if b := listingBuf(); cap(b) == 0 || unsafe.SliceData(b[:1]) != room { + t.Error("a listing given back was let go by a garbage collection") + } else { + putListingBuf(b) + } + got := pathSet() + defer putPathSet(got) + if len(got) != 0 { + t.Errorf("a path set given back kept its paths: %v", got) + } + got["b"] = struct{}{} + if _, ok := m["b"]; !ok { + t.Error("a path set given back was let go by a garbage collection") + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index e38a2a833..77974d202 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -523,8 +523,8 @@ func statFiles(files []file, follow bool) []file { f.size, f.mod, ok[i] = fi.Size(), fi.ModTime(), true } }) - for _, l := range listed { - l.Done() + for i, l := range listed { + l.Done(order[i]) } kept := files[:0] for i, f := range files { @@ -584,9 +584,17 @@ func ccFiles(agent, dir string) []file { return heldFiles("cc\x00"+agent+"\x00"+dir, func() []file { return listCCFiles(agent, dir) }) } +// ccListed is how many files each folder's last listCCFiles found: its +// listing grown from none, a file at a time, was ~35 MB of a minute of the +// page's polls over 13 GB of Claude Code history (#2278). +var ccListed sync.Map // dir → int + func listCCFiles(agent, dir string) []file { projects := filepath.Join(dir, "projects") - var out []file + n, _ := ccListed.Load(dir) + last, _ := n.(int) + out := make([]file, 0, last+last/8) + defer func() { ccListed.Store(dir, len(out)) }() for _, project := range readDirectory(projects) { if !dirent.IsFolder(projects, project) { continue @@ -674,14 +682,21 @@ func distinctInto(out []file, lists ...[]file) []file { // back after it: a set of every session file's path, made new on each of // a poll's several passes (distinctOf, refresh, pruneCalls), was ~100 MB // of what a minute of polls allocated over ~34k files (#2278). A set -// keeps its room when cleared. -var pathSets = sync.Pool{New: func() any { return map[string]struct{}{} }} +// keeps its room when cleared. They are kept on a shelf: a poll collects +// garbage about twice a second, which emptied a sync.Pool of them before +// the next pass. +var pathSets shelf[map[string]struct{}] -func pathSet() map[string]struct{} { return pathSets.Get().(map[string]struct{}) } +func pathSet() map[string]struct{} { + if m, ok := pathSets.take(nil); ok { + return m + } + return map[string]struct{}{} +} func putPathSet(m map[string]struct{}) { clear(m) - pathSets.Put(m) + pathSets.give(m, nil) } // distinctPaths is fs with each path kept once, the first time it is @@ -689,11 +704,12 @@ func putPathSet(m map[string]struct{}) { // holds twice under one id (a TEXT and a BLOB row, #2932), or a folder // two agents are told to share, would otherwise be counted twice. func distinctPaths(fs []file) []file { - seen := make(map[string]bool, len(fs)) + seen := pathSet() + defer putPathSet(seen) out := fs[:0] for _, f := range fs { - if !seen[f.path] { - seen[f.path] = true + if _, ok := seen[f.path]; !ok { + seen[f.path] = struct{}{} out = append(out, f) } } @@ -929,7 +945,7 @@ func listedRollouts(root string) (out []file, ok bool) { if !ok { return false } - defer entries.Done() + defer entries.Done(real) prev, _ := rolloutsSeen.Load(shown) seen, _ := prev.([]file) start, made, leaf := len(out), false, true