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).
265 lines
7.1 KiB
Go
265 lines
7.1 KiB
Go
package sessions
|
|
|
|
import (
|
|
"bytes"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
codexCopiesDiffer = iota
|
|
codexCopiesEqual
|
|
codexFirstPrefix
|
|
codexSecondPrefix
|
|
maxCodexCopyPairs = 4096
|
|
)
|
|
|
|
type codexCopyPair struct{ First, Second string }
|
|
type codexCopyResult struct {
|
|
First, Second os.FileInfo
|
|
Relation int
|
|
}
|
|
|
|
var codexCopyCache = struct {
|
|
sync.Mutex
|
|
Pairs map[codexCopyPair]codexCopyResult
|
|
}{Pairs: map[codexCopyPair]codexCopyResult{}}
|
|
|
|
// Windows replaces this with a same-handle stat carrying ChangeTime.
|
|
var codexDiscoveryStat = os.Stat
|
|
var compareCodexCopies = readCodexCopies
|
|
var codexDiscoveryNow = time.Now
|
|
|
|
// A file system stamps change times from the clock tick, not the precise
|
|
// clock: NTFS from Windows' system time (0.5 ms to 15.6 ms), Linux from the
|
|
// coarse kernel clock. Two writes within one tick get the same change time,
|
|
// so a comparison is cached only for files whose change time is older than
|
|
// this when it starts. A later rewrite is then in a later tick and changes
|
|
// the stamp; a file changed more recently is compared again.
|
|
const codexStampSettle = time.Second
|
|
|
|
type codexDiscoveryInfo struct {
|
|
os.FileInfo
|
|
ChangeTime time.Time
|
|
}
|
|
|
|
// codexChangeTime is the file's change time, zero when the file system
|
|
// doesn't expose one.
|
|
func codexChangeTime(info os.FileInfo) time.Time {
|
|
if wrapped, ok := info.(codexDiscoveryInfo); ok {
|
|
return wrapped.ChangeTime
|
|
}
|
|
// Darwin and Linux expose nanosecond ctime under different field names.
|
|
// An unsupported filesystem gets no cached content comparison: mtime
|
|
// alone cannot detect a same-size rewrite with a restored timestamp.
|
|
v := reflect.ValueOf(info.Sys())
|
|
if v.Kind() == reflect.Pointer && !v.IsNil() {
|
|
v = v.Elem()
|
|
}
|
|
if v.Kind() != reflect.Struct {
|
|
return time.Time{}
|
|
}
|
|
for _, name := range []string{"Ctimespec", "Ctim"} {
|
|
c := v.FieldByName(name)
|
|
if c.IsValid() && c.Kind() == reflect.Struct {
|
|
sec, nsec := c.FieldByName("Sec"), c.FieldByName("Nsec")
|
|
if sec.IsValid() && nsec.IsValid() && sec.CanInt() && nsec.CanInt() {
|
|
return time.Unix(sec.Int(), nsec.Int())
|
|
}
|
|
}
|
|
}
|
|
return time.Time{}
|
|
}
|
|
|
|
// settledCodexStamp reports whether a comparison of this file, started at
|
|
// start, can be cached: it has a change time from before the current tick.
|
|
func settledCodexStamp(info os.FileInfo, start time.Time) bool {
|
|
c := codexChangeTime(info)
|
|
return !c.IsZero() && c.Before(start.Add(-codexStampSettle))
|
|
}
|
|
|
|
func sameCodexSnapshot(a, b os.FileInfo) bool {
|
|
if a == nil || b == nil || a.Size() != b.Size() || !a.ModTime().Equal(b.ModTime()) || !codexChangeTime(a).Equal(codexChangeTime(b)) {
|
|
return false
|
|
}
|
|
if wrapped, ok := a.(codexDiscoveryInfo); ok {
|
|
a = wrapped.FileInfo
|
|
}
|
|
if wrapped, ok := b.(codexDiscoveryInfo); ok {
|
|
b = wrapped.FileInfo
|
|
}
|
|
return os.SameFile(a, b)
|
|
}
|
|
|
|
// Only a proven decoded prefix is a redundant copy. A shared thread/name
|
|
// alone cannot establish ownership of divergent logs or distinct segments.
|
|
func distinctCodexFiles(files []file) []file {
|
|
// a name's first file, and the rest of its files, which few names
|
|
// have: a slice made for every name was ~45 MB of a minute of the
|
|
// page's polls (#2278)
|
|
first := nameFirsts()
|
|
defer putNameFirsts(first)
|
|
var more map[string][]int
|
|
keep := make([]bool, len(files))
|
|
for i, f := range files {
|
|
keep[i] = true
|
|
name := strings.TrimSuffix(filepath.Base(f.path), zstSuffix)
|
|
j0, seen := first[name]
|
|
if !seen {
|
|
first[name] = i
|
|
continue
|
|
}
|
|
for _, j := range slices.Concat([]int{j0}, more[name]) {
|
|
if !keep[j] {
|
|
continue
|
|
}
|
|
switch codexCopyRelation(files[j].path, f.path) {
|
|
case codexCopiesEqual, codexSecondPrefix:
|
|
keep[i] = false
|
|
case codexFirstPrefix:
|
|
keep[j] = false
|
|
}
|
|
if !keep[i] {
|
|
break
|
|
}
|
|
}
|
|
if more == nil {
|
|
more = map[string][]int{}
|
|
}
|
|
more[name] = append(more[name], i)
|
|
}
|
|
// 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)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// nameFirstSets are distinctCodexFiles' sets of names, kept on a shelf from
|
|
// poll to poll as pathSets are: made new for ~13k rollouts, each was ~0.4
|
|
// MB of every Sessions poll (#2278).
|
|
var nameFirstSets shelf[map[string]int]
|
|
|
|
func nameFirsts() map[string]int {
|
|
if m, ok := nameFirstSets.take(nil); ok {
|
|
return m
|
|
}
|
|
return map[string]int{}
|
|
}
|
|
|
|
func putNameFirsts(m map[string]int) {
|
|
clear(m)
|
|
nameFirstSets.give(m, nil)
|
|
}
|
|
|
|
func codexCopyRelation(first, second string) int {
|
|
start := codexDiscoveryNow()
|
|
a, errA := codexDiscoveryStat(first)
|
|
b, errB := codexDiscoveryStat(second)
|
|
if errA != nil || errB != nil {
|
|
return codexCopiesDiffer
|
|
}
|
|
key := codexCopyPair{first, second}
|
|
cacheable := settledCodexStamp(a, start) && settledCodexStamp(b, start)
|
|
codexCopyCache.Lock()
|
|
saved, found := codexCopyCache.Pairs[key]
|
|
codexCopyCache.Unlock()
|
|
if cacheable && found && sameCodexSnapshot(a, saved.First) && sameCodexSnapshot(b, saved.Second) {
|
|
return saved.Relation
|
|
}
|
|
relation, err := compareCodexCopies(first, second)
|
|
if err != nil {
|
|
return codexCopiesDiffer
|
|
}
|
|
// A comparison spanning an append/replacement is not a stable proof.
|
|
afterA, errA := codexDiscoveryStat(first)
|
|
afterB, errB := codexDiscoveryStat(second)
|
|
if errA != nil || errB != nil || !sameCodexSnapshot(a, afterA) || !sameCodexSnapshot(b, afterB) {
|
|
return codexCopiesDiffer
|
|
}
|
|
if cacheable {
|
|
codexCopyCache.Lock()
|
|
if len(codexCopyCache.Pairs) >= maxCodexCopyPairs {
|
|
for old := range codexCopyCache.Pairs {
|
|
delete(codexCopyCache.Pairs, old)
|
|
break
|
|
}
|
|
}
|
|
codexCopyCache.Pairs[key] = codexCopyResult{a, b, relation}
|
|
codexCopyCache.Unlock()
|
|
}
|
|
return relation
|
|
}
|
|
|
|
// Stream comparisons use constant memory. When one stream ends, consume the
|
|
// other to validate its compression trailer before selecting the longer copy.
|
|
func readCodexCopies(first, second string) (int, error) {
|
|
a, err := openLines(first)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer a.Close()
|
|
b, err := openLines(second)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer b.Close()
|
|
x, y := make([]byte, 32<<10), make([]byte, 32<<10)
|
|
for {
|
|
nx, endA, ex := readCodexChunk(a, x)
|
|
ny, endB, ey := readCodexChunk(b, y)
|
|
if ex != nil {
|
|
return 0, ex
|
|
}
|
|
if ey != nil {
|
|
return 0, ey
|
|
}
|
|
if !bytes.Equal(x[:min(nx, ny)], y[:min(nx, ny)]) {
|
|
return codexCopiesDiffer, nil
|
|
}
|
|
if nx < ny {
|
|
_, err = io.Copy(io.Discard, b)
|
|
return codexFirstPrefix, err
|
|
}
|
|
if ny < nx {
|
|
_, err = io.Copy(io.Discard, a)
|
|
return codexSecondPrefix, err
|
|
}
|
|
if endA && endB {
|
|
return codexCopiesEqual, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
// io.ReadFull turns a clean short EOF into ErrUnexpectedEOF, making it
|
|
// indistinguishable from a truncated zstd frame. Preserve that distinction.
|
|
func readCodexChunk(r io.Reader, b []byte) (n int, end bool, err error) {
|
|
for n < len(b) {
|
|
read, err := r.Read(b[n:])
|
|
n += read
|
|
if err == io.EOF {
|
|
return n, true, nil
|
|
}
|
|
if err != nil {
|
|
return n, false, err
|
|
}
|
|
if read == 0 {
|
|
return n, false, io.ErrNoProgress
|
|
}
|
|
}
|
|
return n, false, nil
|
|
}
|