sessions, dirent: a poll's listings are kept across collections (#2278)
A full history's page polls listed the same folders every few seconds into a fresh slice, map and set each time: the sync.Pools meant to keep them were emptied by the collector, which runs about twice a second at this size, before the next poll took them. - sessions: listingBufs and pathSets are shelves (shelf.go), which keep up to four across collections. listCCFiles makes its slice with the room of the folder's last listing. - dirent: Stats keeps each folder's last listing (Listing.Done(dir)) and the room of the one before, up to 1<<17 entries in all. A name already in the folder's last listing is taken from it, not copied again. 1<<16 kept too little of ~23k session files and their folders: the first bench of this change (budget 1<<16) took dirent.entry from 67-102 to 80-100 MB a minute, no gain. Bench, mote, the real full history (52G Codex in 12,495 files, 13G Claude Code in 10,186), fullallogh.sh, alloc_space between the 50s and 110s heap profiles, MB per minute, before (v0.1.2132 equivalent) -> after: distinctOf 59 -> 22 listCCFiles 42 -> 17 dirent.entry 67-102 -> 55 dirent.nameOf 24 -> 5 Totals swing 400-1200 MB with mote's load (other sessions), so these are per function. Run at this head (rebased on3bebc3839), on mote: - go build ./... ok - go test -race -count=1 ./internal/dirent ok, ./internal/sessions ok (109.7s; one earlier run had TestLongReadKeepsWhatItRead red with a data race in testenv.Zone, red on3bebc3839too, 1 of 80 at -count=40 -cpu 1,4: #4360) - ./internal/gui: TestMainWindowCorners red, #3949 (mote is macOS 27); gui is not touched here - GOOS=linux, windows, darwin go vet -tags nogui ./internal/dirent ./internal/sessions ok; gofmt -l clean Broken by hand: - TestListingKeptAcrossCollections (dirent) and TestListingPoolsKeptAcrossCollections (sessions) are red on the sync.Pool code: "a listing given back was let go by a garbage collection". - name reuse turned off: "a name listed before was copied again". Not tried: the Windows and Linux listers (stats_other.go returns no listing there, as before).
This commit is contained in:
+83
-14
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user