From 10c3315312365888098b60e55dff802be4aa53e2 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 12 Nov 2026 04:50:48 +0800 Subject: [PATCH] sessions: an unchanged listing is the last one, not a new list (#2278) Every 15 s Sessions poll built every Claude Code file's and Codex rollout's list again, and merged and filtered them into more new lists, while nothing on disk had changed. On the owner's real history that was ~120 MB of garbage per 40 polls in listedRollouts, claudeFiles, listCCFiles and filesKept. Each lister now keeps its last list (listsKept). A listing walks the folders as before and compares each file with the kept list's file at the same place; while they match nothing is allocated, and the kept list itself is returned. On the first difference it copies the matched part and goes on, so a grown, new or gone file is listed as a fresh listing has it, and the kept list is never written. listCCFiles reuses its walk's scratch slice per lister. distinctPaths and distinctCodexFiles return their input when nothing is dropped and never filter in place; codexFilesIn's twin filter clones before deleting. rolloutsSeen's day entry is its part of the kept list (clipped), not a clone. The idle cache drop forgets all of it. Measured on mote with the owner's real account (75 GB history), 40 /api/sessions polls, `magpie heap` before and after, alloc_space diff: before (w6): 155.7 MB; listedRollouts 42.8, claudeFiles 32.2 (71.1 cum), listCCFiles 31.0, filesKept.distinct 18.0 after (w7): 34.8 MB; none of the listers in the top; distinct 4.5, provider.All 9.7 (next) CPU over 30 s of polling: 1.79 s -> 1.37 s. Tests: lists_kept_test.go, red on the old code (an unchanged listing made a list of its own; distinctPaths wrote its input), green now. TestClaudeFilesMadeAtTheirSize expects the clipped kept list. Run on mica at this tree (rebased on 0cff3429f, sessions vet + test again ok): go vet ./internal/sessions for darwin, linux and windows, ./internal/gui for darwin; go test ./internal/sessions ok (64 s); go test ./internal/gui ok but TestPanelHiddenByWailsMarksPageOutOfSight (#6203, flaky on mica, passes alone). -race of sessions: #4360 and #6213, both red on the old code too, no stack in the changed code. Not tried: Windows and Linux runs of the new test (the codex subtest is darwin-only). --- internal/sessions/cache_idle.go | 3 +- internal/sessions/claude_homes_test.go | 12 +- internal/sessions/codex_discovery.go | 7 +- internal/sessions/files_kept.go | 97 ++++++++++++ internal/sessions/lists_kept_test.go | 127 ++++++++++++++++ internal/sessions/sessions.go | 195 ++++++++++++++++++------- 6 files changed, 380 insertions(+), 61 deletions(-) create mode 100644 internal/sessions/lists_kept_test.go diff --git a/internal/sessions/cache_idle.go b/internal/sessions/cache_idle.go index 2b4007881..486382415 100644 --- a/internal/sessions/cache_idle.go +++ b/internal/sessions/cache_idle.go @@ -89,7 +89,8 @@ func dropIdleCache() bool { codexIdentityMemo.kept = nil codexIdentityMemo.Unlock() rolloutsSeen.Clear() - ccListed.Clear() // every Claude Code file's path and key (~2 MB) + forgetListsKept() // each lister's last list (~5 MB) + ccListed.Clear() // every Claude Code file's path and key (~2 MB) dirent.Forget() cacheDrops.Add(1) return true diff --git a/internal/sessions/claude_homes_test.go b/internal/sessions/claude_homes_test.go index f63bcb788..3fb2b91da 100644 --- a/internal/sessions/claude_homes_test.go +++ b/internal/sessions/claude_homes_test.go @@ -5,6 +5,7 @@ import ( "path/filepath" "testing" "time" + "unsafe" ) // Claude run with CLAUDE_CONFIG_DIR set to a folder of each account's @@ -57,8 +58,8 @@ func TestListReadsEveryClaudeFolderOnce(t *testing.T) { // Every Claude folder's files are listed into one slice made at their // size, not grown file by file on every pass (a pass every 10 s while -// the Sessions page is open), and a session kept in two folders is -// still listed once. +// the Sessions page is open), a pass like the last gives the last one's +// list, and a session kept in two folders is still listed once. func TestClaudeFilesMadeAtTheirSize(t *testing.T) { d := setupCalls(t) home, _ := os.UserHomeDir() @@ -80,7 +81,10 @@ func TestClaudeFilesMadeAtTheirSize(t *testing.T) { if len(fs) != 40 { t.Fatalf("%d files, want 40", len(fs)) } - if cap(fs) != 41 { - t.Fatalf("listed into room for %d, want the 41 listed", cap(fs)) + if cap(fs) != 40 { + t.Fatalf("listed into room for %d, want the 40 kept", cap(fs)) + } + if again := claudeFiles(); unsafe.SliceData(again) != unsafe.SliceData(fs) { + t.Fatal("an unchanged pass made its list again") } } diff --git a/internal/sessions/codex_discovery.go b/internal/sessions/codex_discovery.go index c5a8cdbfb..cfc706895 100644 --- a/internal/sessions/codex_discovery.go +++ b/internal/sessions/codex_discovery.go @@ -134,7 +134,12 @@ func distinctCodexFiles(files []file) []file { } more[name] = append(more[name], i) } - out := files[:0] + // files may be a list kept and read elsewhere: one left out is left + // out of a copy, and files is given back when none is + if !slices.Contains(keep, false) { + return files + } + out := make([]file, 0, len(files)-1) for i, f := range files { if keep[i] { out = append(out, f) diff --git a/internal/sessions/files_kept.go b/internal/sessions/files_kept.go index ce3734082..a72c70659 100644 --- a/internal/sessions/files_kept.go +++ b/internal/sessions/files_kept.go @@ -1,6 +1,7 @@ package sessions import ( + "slices" "sync" "unsafe" "weak" @@ -83,3 +84,99 @@ func (k *filesKept) distinct(lists ...[]file) []file { k.Unlock() return out } + +// sameFiles builds a lister's list a file at a time against the list it +// made last, and allocates nothing while each file is the last list's at +// its place. Every 15 s Sessions poll listed every rollout and Claude Code +// file again into lists made new, ~2.5 MB a poll on a real history while +// nothing in them had changed, and that garbage was a third of a poll's +// collections (#2278). Its lists are only read (heldFiles' contract), and +// clipped, so an append to one is made elsewhere. +type sameFiles struct { + last, out []file + i int + made bool + hint int // the least room out is made with +} + +func (s *sameFiles) add(f file) { + if !s.made { + if s.i < len(s.last) && s.last[s.i] == f { + s.i++ + return + } + s.made = true + s.out = append(make([]file, 0, max(len(s.last)+len(s.last)/16, s.hint)), s.last[:s.i]...) + } + s.out = append(s.out, f) +} + +// n is how many files were added. +func (s *sameFiles) n() int { + if s.made { + return len(s.out) + } + return s.i +} + +// list is the files added, the last list itself when they are all of it, +// and whether it is another list than the last. +func (s *sameFiles) list() ([]file, bool) { + switch { + case s.made: + return slices.Clip(s.out), true + case s.i == len(s.last): + return s.last, false + } + // files gone from its end + return append(make([]file, 0, s.i), s.last[:s.i]...), true +} + +// listsKept are the listers' last lists, by lister and folder. Unlike +// filesKept's they are held strongly: nothing else holds a lister's list +// from one poll to the next. forgetListsKept lets them go when the cache +// does. +var listsKept sync.Map // key → []file + +func keptFiles(key string) []file { + l, _ := listsKept.Load(key) + fs, _ := l.([]file) + return fs +} + +// sameAsKept is s's list, kept under key for the next pass when it is new. +func sameAsKept(key string, s *sameFiles) []file { + l, changed := s.list() + if changed { + listsKept.Store(key, l) + } + return l +} + +// concatKept is lists one after another: the one list itself when the +// others are empty, else the last such list when it is the same. +func concatKept(key string, lists ...[]file) []file { + var one []file + n := 0 + for _, l := range lists { + if len(l) > 0 { + n++ + one = l + } + } + if n <= 1 { + return one + } + s := sameFiles{last: keptFiles(key)} + for _, l := range lists { + for _, f := range l { + s.add(f) + } + } + return sameAsKept(key, &s) +} + +func forgetListsKept() { + listsKept.Clear() + ccScratch.Clear() +} diff --git a/internal/sessions/lists_kept_test.go b/internal/sessions/lists_kept_test.go new file mode 100644 index 000000000..47fadda8b --- /dev/null +++ b/internal/sessions/lists_kept_test.go @@ -0,0 +1,127 @@ +package sessions + +import ( + "fmt" + "os" + "path/filepath" + "runtime" + "slices" + "testing" + "unsafe" +) + +// A listing the same as the last one is the last one, and allocates no +// list of its own: every 15 s Sessions poll made every rollout's and +// Claude Code file's list again, ~2.5 MB a poll of garbage on a real +// history while nothing had changed (#2278). A file grown, new or gone is +// in the next listing as a fresh one has it. +func TestUnchangedListingsAreTheLast(t *testing.T) { + t.Cleanup(forgetListsKept) + t.Cleanup(func() { ccListed.Clear(); rolloutsSeen.Clear() }) + sameArray := func(a, b []file) bool { return len(a) > 0 && unsafe.SliceData(a) == unsafe.SliceData(b) } + + t.Run("claude code", func(t *testing.T) { + dir := t.TempDir() + path := func(i int) string { + return filepath.Join(dir, "projects", fmt.Sprintf("-Users-someone-p%d", i%3), fmt.Sprintf("%08d-1111-2222-3333-444444444444.jsonl", i)) + } + const n = 600 + for i := range n { + os.MkdirAll(filepath.Dir(path(i)), 0o755) + if err := os.WriteFile(path(i), []byte("{}\n"), 0o644); err != nil { + t.Fatal(err) + } + } + first := listCCFiles("claude", dir) + if len(first) != n { + t.Fatalf("listed %d, want %d", len(first), n) + } + again := listCCFiles("claude", dir) + if !sameArray(again, first) { + t.Fatal("an unchanged listing made a list of its own") + } + if err := os.WriteFile(path(7), []byte("{}\n{}\n"), 0o644); err != nil { + t.Fatal(err) + } + grown := listCCFiles("claude", dir) + if sameArray(grown, first) { + t.Fatal("a grown file's listing is the last one") + } + if i := slices.IndexFunc(grown, func(f file) bool { return f.path == path(7) }); i < 0 || grown[i].size != 6 { + t.Fatal("a grown file isn't listed at its size") + } + if first[slices.IndexFunc(first, func(f file) bool { return f.path == path(7) })].size != 3 { + t.Fatal("the last listing was written over") + } + os.Remove(path(8)) + if gone := listCCFiles("claude", dir); len(gone) != n-1 || slices.ContainsFunc(gone, func(f file) bool { return f.path == path(8) }) { + t.Fatalf("a gone file: %d listed", len(gone)) + } + }) + + t.Run("codex", func(t *testing.T) { + if runtime.GOOS != "darwin" { + t.Skip("listed in one call a folder on macOS only") + } + root := filepath.Join(t.TempDir(), "sessions") + day := filepath.Join(root, "2026", "11", "12") + os.MkdirAll(day, 0o700) + name := func(i int) string { + return filepath.Join(day, fmt.Sprintf("rollout-2026-11-12T10-00-%02d-0190aaaa-1111-7222-8333-4444555566%02d.jsonl", i, i)) + } + for i := range 40 { + if err := os.WriteFile(name(i), []byte("{}\n"), 0o600); err != nil { + t.Fatal(err) + } + } + first, ok := listedRollouts(root) + if !ok || len(first) != 40 { + t.Fatalf("listed %d, ok %t", len(first), ok) + } + again, _ := listedRollouts(root) + if !sameArray(again, first) { + t.Fatal("an unchanged listing made a list of its own") + } + // a day folder's rollouts are the list's own, not a copy + seen, _ := rolloutsSeen.Load(day) + if l, _ := seen.([]file); !sameArray(l, first) || cap(l) != len(l) { + t.Fatal("a day folder's rollouts are a copy, or open to an append") + } + os.WriteFile(name(3), []byte("{}\n{}\n"), 0o600) + os.WriteFile(name(50), []byte("{}\n"), 0o600) + changed, _ := listedRollouts(root) + if sameArray(changed, first) || len(changed) != 41 || changed[3].size != 6 || changed[40].path != name(50) { + t.Fatalf("a grown and a new rollout: %d listed", len(changed)) + } + if first[3].size != 3 { + t.Fatal("the last listing was written over") + } + }) +} + +// The lists a lister keeps are read by every pass after, so what is +// made from them never writes into them. +func TestListsKeptAreNotWritten(t *testing.T) { + t.Cleanup(forgetListsKept) + a := []file{{path: "/a"}, {path: "/b"}} + b := []file{{path: "/b"}, {path: "/c"}} + one := concatKept("test", a, nil) + if unsafe.SliceData(one) != unsafe.SliceData(a) { + t.Error("one list among empty ones was copied") + } + both := concatKept("test", a, b) + if again := concatKept("test", a, b); unsafe.SliceData(again) != unsafe.SliceData(both) || len(again) != 4 { + t.Error("the same lists one after another were made again") + } + was := slices.Clone(both) + d := distinctPaths(both) + if len(d) != 3 || !slices.Equal(both, was) { + t.Fatalf("distinctPaths gave %d files, and its list is %v, was %v", len(d), both, was) + } + if d := distinctPaths(a); unsafe.SliceData(d) != unsafe.SliceData(a) { + t.Error("a list with every path once was copied") + } + if l := concatKept("test", a, b[:1]); len(l) != 3 || l[2].path != "/b" { + t.Errorf("a list gone short: %v", l) + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 2b0bbd096..445c6e3c7 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -659,8 +659,10 @@ func claudeFiles() []file { lists[i] = ccFiles("claude", d) n += len(lists[i]) } - out := make([]file, 0, n) - owner := make(map[string]string, len(lists[0])) + // and the answer is the last one when it is the same + out := sameFiles{last: keptFiles("claude"), hint: n} + owner := takeClaudeOwners() + defer putClaudeOwners(owner) for i, d := range dirs { for _, f := range lists[i] { // a subagent's key is its session's: it goes where its session is @@ -668,10 +670,26 @@ func claudeFiles() []file { continue } owner[f.key] = d - out = append(out, f) + out.add(f) } } - return out + return sameAsKept("claude", &out) +} + +// claudeOwners is claudeFiles' map of each key's folder, kept from pass +// to pass: made new, ~15k keys were ~1 MB of each. +var claudeOwners shelf[map[string]string] + +func takeClaudeOwners() map[string]string { + if m, ok := claudeOwners.take(nil); ok { + return m + } + return map[string]string{} +} + +func putClaudeOwners(m map[string]string) { + clear(m) + claudeOwners.give(m, nil) } // CodexDir is Codex's folder: $CODEX_HOME, else ~/.codex. @@ -830,6 +848,7 @@ type ccNames struct { last []ccName at int // where the last listing is read up to now []ccName + made bool // now is made: until a name isn't the last's at its place, now is last[:at] } // of is filepath.Join(dir, name) and agent+":"+id, as last listed. @@ -837,16 +856,42 @@ func (c *ccNames) of(dir, name, agent, id string) (string, string) { // one file new or gone since is stepped over for i := c.at; i < min(c.at+2, len(c.last)); i++ { if l := c.last[i]; joinedIs(l.path, dir, name) && joinedIs(l.key, agent, id, ':') { - c.at = i + 1 - c.now = append(c.now, l) + c.keep(i, l) return l.path, l.key } } n := ccName{filepath.Join(dir, name), agent + ":" + id} - c.now = append(c.now, n) + c.keep(-1, n) return n.path, n.key } +// keep has n, the last listing's ith name or a new one (-1), next in now. +func (c *ccNames) keep(i int, n ccName) { + if !c.made && i == c.at { + c.at++ + return + } + if !c.made { + c.made = true + c.now = append(make([]ccName, 0, len(c.last)+len(c.last)/8), c.last[:c.at]...) + } + if i >= 0 { + c.at = i + 1 + } + c.now = append(c.now, n) +} + +// names are the names listed: the last listing's when they are all of it. +func (c *ccNames) names() []ccName { + switch { + case c.made: + return slices.Clip(c.now) + case c.at == len(c.last): + return c.last + } + return slices.Clone(c.last[:c.at]) +} + // joinedIs is whether s is a, sep, b: filepath.Join(a, b) for a clean a // and a b without a separator, as a folder's entries are. func joinedIs(s, a, b string, sep ...byte) bool { @@ -862,9 +907,21 @@ func listCCFiles(agent, dir string) []file { dirent.Watch(dir) // statFiles reads only the projects that changed last, _ := ccListed.Load(dir) names := ccNames{last: func() []ccName { l, _ := last.([]ccName); return l }()} - names.now = make([]ccName, 0, len(names.last)+len(names.last)/8) - out := make([]file, 0, cap(names.now)) - defer func() { ccListed.Store(dir, slices.Clip(names.now)) }() + // listed into a list of its own kept from the last pass, and given as + // the last pass's answer when it is the same once stat()ed + key := "cc\x00" + agent + "\x00" + dir + var out []file + if b, ok := ccScratch.LoadAndDelete(key); ok { + out = b.([]file)[:0] + } else { + out = make([]file, 0, len(names.last)+len(names.last)/8) + } + defer func() { + // the last listing's names are kept already + if names.made || names.at != len(names.last) { + ccListed.Store(dir, names.names()) + } + }() for _, project := range readDirectory(projects) { if !dirent.IsFolder(projects, project) { continue @@ -903,9 +960,18 @@ func listCCFiles(agent, dir string) []file { } } } - return statFiles(out, true) + same := sameFiles{last: keptFiles(key)} + for _, f := range statFiles(out, true) { + same.add(f) + } + ccScratch.Store(key, out[:0]) + return sameAsKept(key, &same) } +// ccScratch is each folder's list listCCFiles lists into, taken while it +// does: two listing one folder at once each have their own. +var ccScratch sync.Map // lister key → []file + // allFiles are every agent's session files. // filesHook, when a test sets it, runs on each pass over every agent's // files. @@ -986,16 +1052,27 @@ func putPathSet(m map[string]struct{}) { // listed. A path is one file to read and count: a session a database // 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. +// fs is given back as it is when every path in it is once: it may be a +// list kept and read elsewhere, so it is never written. func distinctPaths(fs []file) []file { seen := pathSet() defer putPathSet(seen) - out := fs[:0] - for _, f := range fs { - if _, ok := seen[f.path]; !ok { - seen[f.path] = struct{}{} + var out []file // made at the first path listed again + for i, f := range fs { + if _, ok := seen[f.path]; ok { + if out == nil { + out = append(make([]file, 0, len(fs)-1), fs[:i]...) + } + continue + } + seen[f.path] = struct{}{} + if out != nil { out = append(out, f) } } + if out == nil { + return fs + } return out } @@ -1110,17 +1187,14 @@ func forgetWarmListing() { // listCodexFiles is codexFiles listed now. func listCodexFiles() []file { - var out []file - for _, dir := range CodexDirs() { - // one folder's listing is the whole of it: copied, it was ~65 MB - // of what eight Sessions polls allocated - if out == nil { - out = codexFilesIn(dir) - } else { - out = append(out, codexFilesIn(dir)...) - } + dirs := CodexDirs() + lists := make([][]file, len(dirs)) + for i, dir := range dirs { + lists[i] = codexFilesIn(dir) } - return distinctPaths(out) + // one folder's listing is the whole of it: copied, it was ~65 MB of + // what eight Sessions polls allocated + return distinctPaths(concatKept("codex", lists...)) } // CodexDirs are every Codex folder of the user's, CodexDir first. @@ -1161,15 +1235,11 @@ func codexFilesIn(dir string) []file { // its unchanged day folders aren't read again; a change in dir itself // (history.jsonl, at each prompt) has them all read dirent.Watch(dir) - var out []file - for _, folder := range []string{"sessions", "archived_sessions"} { + var lists [2][]file + for i, folder := range []string{"sessions", "archived_sessions"} { root := filepath.Join(dir, folder) if listed, ok := listedRollouts(root); ok { - if out == nil { - out = listed - } else { - out = append(out, listed...) - } + lists[i] = listed continue } var found []file @@ -1184,8 +1254,9 @@ func codexFilesIn(dir string) []file { found = append(found, file{agent: "codex", key: "codex:" + m[1], path: p, main: true}) return nil }) - out = append(out, statFiles(found, false)...) + lists[i] = statFiles(found, false) } + out := concatKept("codex\x00"+dir, lists[:]...) // During compression, prefer the readable plain twin in the same // directory: the new compressed file may not have its trailer yet. // (a set kept from poll to poll: made new, it was ~0.4 MB of each, #2278) @@ -1196,14 +1267,17 @@ func codexFilesIn(dir string) []file { plain[f.path] = struct{}{} } } - kept := out[:0] - for _, f := range out { + twin := func(f file) bool { q, ok := strings.CutSuffix(f.path, zstSuffix) - if _, twin := plain[q]; !ok || !twin { - kept = append(kept, f) - } + _, plainToo := plain[q] + return ok && plainToo } - return distinctCodexFiles(kept) + // out may be a list kept and read elsewhere: a twin left out is left + // out of a copy + if slices.ContainsFunc(out, twin) { + out = slices.DeleteFunc(slices.Clone(out), twin) + } + return distinctCodexFiles(out) } // rolloutsListed is how many rollouts each root's last listing found. @@ -1221,17 +1295,14 @@ var rolloutsSeen sync.Map // shown folder → []file // folders were listed twice and every rollout lstat()ed on each 15 s // Sessions poll. ok is false when a folder couldn't be read so, and // walkLinked and statFiles read root instead. -func listedRollouts(root string) (out []file, ok bool) { - // sized as the last listing of root was: grown a rollout at a time, - // ~20k of them allocated five times their size on every poll +func listedRollouts(root string) ([]file, bool) { + // made against the last listing of root, and that listing itself when + // nothing in it changed + key := "rollouts\x00" + root + out := sameFiles{last: keptFiles(key)} if n, ok := rolloutsListed.Load(root); ok { - out = make([]file, 0, n.(int)+n.(int)/16) + out.hint = n.(int) + n.(int)/16 } - defer func() { - if ok { - rolloutsListed.Store(root, len(out)) - } - }() walk := root if fi, err := os.Lstat(root); err != nil { return nil, false @@ -1242,6 +1313,11 @@ func listedRollouts(root string) (out []file, ok bool) { } walk = real } + type span struct { + shown string + start, end int + } + var leaves []span var in func(real, shown string) bool in = func(real, shown string) bool { entries, ok := dirent.Stats(real) @@ -1251,7 +1327,7 @@ func listedRollouts(root string) (out []file, ok bool) { defer entries.Done(real) prev, _ := rolloutsSeen.Load(shown) seen, _ := prev.([]file) - start, made, leaf := len(out), false, true + start, leaf := out.n(), true for _, e := range entries { name := e.Name switch e.Mode { @@ -1269,26 +1345,35 @@ func listedRollouts(root string) (out []file, ok bool) { if len(seen) > 0 && filepath.Base(seen[0].path) == name { f := seen[0] f.size, f.mod = e.Size, modOf(e.ModTime()) - out = append(out, f) + out.add(f) continue } if m := rolloutName.FindStringSubmatch(name); m != nil { - out = append(out, file{agent: "codex", key: "codex:" + m[1], path: filepath.Join(shown, name), main: true, size: e.Size, mod: modOf(e.ModTime())}) - made = true + out.add(file{agent: "codex", key: "codex:" + m[1], path: filepath.Join(shown, name), main: true, size: e.Size, mod: modOf(e.ModTime())}) } } } // a day folder's only: in a folder with folders in it, out has // their rollouts among its own - if n, _ := prev.([]file); leaf && (made || len(out)-start != len(n)) { - rolloutsSeen.Store(shown, slices.Clone(out[start:])) + if leaf { + leaves = append(leaves, span{shown, start, out.n()}) } return true } if !in(walk, root) { return nil, false } - return out, true + l, changed := out.list() + rolloutsListed.Store(root, len(l)) + if changed { + listsKept.Store(key, l) + // each day folder's rollouts are its part of the list: a copy of + // each was the list again (#2278) + for _, sp := range leaves { + rolloutsSeen.Store(sp.shown, l[sp.start:sp.end:sp.end]) + } + } + return l, true } // rolloutTwin is a Codex rollout's file in its other form: the compressed