sessions: listing the session files stats them on a few goroutines and sweeps the shard folder once a minute
Every Requests page lists every session file again
(CallSourcesAndCodexIdentities), and on a busy machine that listing was
most of a warm page after the pairing memo (#3493): ~130ms for 15.6k
Codex rollouts and the Claude Code transcripts, of which the lstat of
each rollout was half, stat()ing each Claude file a sixth, and
pruneCalls a sixth: it read the ~16k-shard cache folder and sha256'd
every path on each call.
- statFiles stats the files a walk found on up to 8 goroutines (from 512
files), keeping the walk's order and leaving out what is gone or no
regular file, as before. Codex's still take their info from the walk's
entry (free on Windows), Claude Code's from os.Stat.
- pruneCalls still drops the in-memory entries of gone files each call,
but looks over the shard folder (and hashes the paths for it) at most
once a minute, and at once when the cache folder moved. Temps already
waited an hour; an orphan shard waits up to a minute more.
Run at 4982ded8a (origin/main, fetched):
go test -timeout 45m of agent (363s), cli (77.7s), davsync (78.4s),
gateway (533s), gui (150s), otlp (20.4s), tui (33.6s), tune (2.9s), usage
(51.4s), usageapi (14.8s): ok. sessions was red at first:
TestRequestShardsAreBoundedAndIndependent found a removed session's shard
still there, since the sweep waited its minute. pruneCalls now sweeps at
once when a file it had read is gone; sessions ok (19.2s) after, and
usage (18.6s) and usageapi (4.6s) again. gofmt clean; GOOS=linux and
GOOS=windows go vet -tags nogui ./internal/sessions/ clean.
Real data (sandbox HOME with the live ~/.codex/sessions and
~/.claude/projects symlinked, read only): the old and new listings,
dumped as path, key, agent, size and mtime, are the same 15,601 sources
in the same order with the same 12,077 Codex identities. Mean of 20
listings after a first one, load ~160: old 142 / 132 ms, new 56 / 66 ms.
Tests: TestCodexFilesStatInOrder (new; 1500 rollouts with folders,
links and files of every size in one day, -race -count=3) is red when
statFiles keeps what failed to stat and when a worker skips half its
batch. TestCallShardsSweptOnceAMinute (new) is red with the gate taken
out. TestAbandonedCallTempsAndLRU now clears the gate before the call
that must sweep.
This commit is contained in:
@@ -79,6 +79,10 @@ func TestAbandonedCallTempsAndLRU(t *testing.T) {
|
||||
os.WriteFile(live, []byte("partial"), 0600)
|
||||
then := time.Now().Add(-2 * time.Hour)
|
||||
os.Chtimes(old, then, then)
|
||||
// the folder is looked over once a minute
|
||||
callsMu.Lock()
|
||||
callSwept = time.Time{}
|
||||
callsMu.Unlock()
|
||||
Calls(time.Time{})
|
||||
if _, err := os.Stat(old); !os.IsNotExist(err) {
|
||||
t.Fatal("abandoned temp remains")
|
||||
@@ -98,6 +102,32 @@ func TestAbandonedCallTempsAndLRU(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Listing the sources reads the shard folder at most once a minute, not
|
||||
// on every Requests page, and a shard no file names goes when it does.
|
||||
func TestCallShardsSweptOnceAMinute(t *testing.T) {
|
||||
d := setupCalls(t)
|
||||
writeLines(t, filepath.Join(d.claude, "projects", "p", "s.jsonl"), claudeMsg("m", "m", 1, 1, 0, 0, 1))
|
||||
Calls(time.Time{})
|
||||
orphan := filepath.Join(callCacheDir(), hashHead("gone.jsonl")+".gob")
|
||||
if err := os.WriteFile(orphan, []byte("x"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
CallSources()
|
||||
if _, err := os.Stat(orphan); err != nil {
|
||||
t.Fatalf("the folder was read again within the minute: %v", err)
|
||||
}
|
||||
callsMu.Lock()
|
||||
callSwept = time.Now().Add(-callSweepEvery)
|
||||
callsMu.Unlock()
|
||||
CallSources()
|
||||
if _, err := os.Stat(orphan); !os.IsNotExist(err) {
|
||||
t.Fatal("an orphan shard outlived the next sweep")
|
||||
}
|
||||
if len(Calls(time.Time{})) != 1 {
|
||||
t.Fatal("the sweep lost a live shard")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoveryDetectsNewCoworkSessions(t *testing.T) {
|
||||
d := setupCalls(t)
|
||||
Calls(time.Time{})
|
||||
|
||||
@@ -55,6 +55,15 @@ var callCounts = map[string]int{} // small allocation hints, never call records
|
||||
var callOrder []string
|
||||
var callRoot string
|
||||
|
||||
// callSwept is when pruneCalls last looked for shards no session file
|
||||
// names any more. Every Requests page lists the sources, and reading a
|
||||
// folder of ~16k shards and hashing every path each time was a tenth of
|
||||
// a warm page (#3493). The shard of a file read here goes as soon as the
|
||||
// file does; any other is left for a minute at most.
|
||||
var callSwept time.Time
|
||||
|
||||
const callSweepEvery = time.Minute
|
||||
|
||||
func callCacheDir() string { return filepath.Join(filepath.Dir(CachePath()), callCacheVersion) }
|
||||
func callCachePath(path string) string { return filepath.Join(callCacheDir(), hashHead(path)+".gob") }
|
||||
|
||||
@@ -65,6 +74,7 @@ func resetCalls() {
|
||||
callContinuations, callContinuationOrder = map[string]callContinuation{}, nil
|
||||
callCounts = map[string]int{}
|
||||
callRoot = ""
|
||||
callSwept = time.Time{}
|
||||
callGeneration++
|
||||
resetOCCalls()
|
||||
// ZCode's listing and WorkBuddy's gateway ids name another HOME's files
|
||||
@@ -89,10 +99,8 @@ func pruneCalls(files []file) {
|
||||
callCounts = map[string]int{}
|
||||
}
|
||||
on := make(map[string]bool, len(files))
|
||||
shards := make(map[string]bool, len(files))
|
||||
for _, f := range files {
|
||||
on[f.path] = true
|
||||
shards[hashHead(f.path)+".gob"] = true
|
||||
}
|
||||
order := callOrder[:0]
|
||||
for _, path := range callOrder {
|
||||
@@ -103,9 +111,11 @@ func pruneCalls(files []file) {
|
||||
}
|
||||
}
|
||||
callOrder = order
|
||||
gone := false
|
||||
for path := range callCounts {
|
||||
if !on[path] {
|
||||
delete(callCounts, path)
|
||||
gone = true
|
||||
}
|
||||
}
|
||||
order = callContinuationOrder[:0]
|
||||
@@ -119,6 +129,11 @@ func pruneCalls(files []file) {
|
||||
callContinuationOrder = order
|
||||
|
||||
trimCallRevisions(time.Now())
|
||||
// a session file read here and gone since takes its shard with it now
|
||||
sweep := moved || gone || time.Since(callSwept) >= callSweepEvery
|
||||
if sweep {
|
||||
callSwept = time.Now()
|
||||
}
|
||||
callsMu.Unlock()
|
||||
if moved {
|
||||
// an older version's shards are never read again
|
||||
@@ -129,7 +144,14 @@ func pruneCalls(files []file) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if !sweep {
|
||||
return
|
||||
}
|
||||
// IO never holds the metadata lock. A grace period protects live writers.
|
||||
shards := make(map[string]bool, len(files))
|
||||
for _, f := range files {
|
||||
shards[hashHead(f.path)+".gob"] = true
|
||||
}
|
||||
entries, _ := os.ReadDir(root)
|
||||
for _, e := range entries {
|
||||
if e.IsDir() {
|
||||
|
||||
@@ -437,6 +437,49 @@ func stat(f *file) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// statFiles fills in each file's size and modification time from info(i),
|
||||
// or leaves the file out when it is gone or no regular file. Every
|
||||
// Requests page walks every session folder again, and stat()ing ~16k files
|
||||
// one after another was most of that walk (#3493), so they are stat()ed on
|
||||
// a few goroutines.
|
||||
func statFiles(files []file, info func(i int) (os.FileInfo, error)) []file {
|
||||
ok := make([]bool, len(files))
|
||||
one := func(i int) {
|
||||
if fi, err := info(i); err == nil && fi.Mode().IsRegular() {
|
||||
files[i].size, files[i].mod, ok[i] = fi.Size(), fi.ModTime(), true
|
||||
}
|
||||
}
|
||||
if workers := min(runtime.GOMAXPROCS(0), 8, len(files)/256); workers < 2 {
|
||||
for i := range files {
|
||||
one(i)
|
||||
}
|
||||
} else {
|
||||
var next atomic.Int64
|
||||
var wg sync.WaitGroup
|
||||
for range workers {
|
||||
wg.Go(func() {
|
||||
for {
|
||||
i := int(next.Add(64)) - 64
|
||||
if i >= len(files) {
|
||||
return
|
||||
}
|
||||
for j := i; j < min(i+64, len(files)); j++ {
|
||||
one(j)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
kept := files[:0]
|
||||
for i, f := range files {
|
||||
if ok[i] {
|
||||
kept = append(kept, f)
|
||||
}
|
||||
}
|
||||
return kept
|
||||
}
|
||||
|
||||
// ccFiles are the session files of an agent that keeps them as Claude Code
|
||||
// does, under its folder's projects/: a session's own <id>.jsonl in its
|
||||
// project's folder, its subagents' in <id>/subagents/, and the agents of
|
||||
@@ -454,9 +497,7 @@ func ccFiles(agent, dir string) []file {
|
||||
path := filepath.Join(root, e.Name())
|
||||
if !e.IsDir() && strings.HasSuffix(e.Name(), ".jsonl") {
|
||||
f := file{agent: agent, key: agent + ":" + strings.TrimSuffix(e.Name(), ".jsonl"), path: path, main: true}
|
||||
if stat(&f) {
|
||||
out = append(out, f)
|
||||
}
|
||||
out = append(out, f)
|
||||
} else if dirent.IsFolder(root, e) {
|
||||
subs := filepath.Join(path, "subagents")
|
||||
for _, sub := range readDirectory(subs) {
|
||||
@@ -464,9 +505,7 @@ func ccFiles(agent, dir string) []file {
|
||||
continue
|
||||
}
|
||||
f := file{agent: agent, key: agent + ":" + e.Name(), path: filepath.Join(subs, sub.Name())}
|
||||
if stat(&f) {
|
||||
out = append(out, f)
|
||||
}
|
||||
out = append(out, f)
|
||||
}
|
||||
for _, run := range readDirectory(filepath.Join(subs, "workflows")) {
|
||||
if !dirent.IsFolder(filepath.Join(subs, "workflows"), run) {
|
||||
@@ -478,15 +517,13 @@ func ccFiles(agent, dir string) []file {
|
||||
continue
|
||||
}
|
||||
f := file{agent: agent, key: agent + ":" + e.Name(), path: filepath.Join(dir, sub.Name())}
|
||||
if stat(&f) {
|
||||
out = append(out, f)
|
||||
}
|
||||
out = append(out, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
return statFiles(out, func(i int) (os.FileInfo, error) { return os.Stat(out[i].path) })
|
||||
}
|
||||
|
||||
// allFiles are every agent's session files.
|
||||
@@ -605,6 +642,7 @@ func walkLinked(root string, fn fs.WalkDirFunc) error {
|
||||
// codexFilesIn are the rollouts in a Codex folder.
|
||||
func codexFilesIn(dir string) []file {
|
||||
var out []file
|
||||
var entries []fs.DirEntry
|
||||
for _, folder := range []string{"sessions", "archived_sessions"} {
|
||||
walkLinked(filepath.Join(dir, folder), func(p string, d os.DirEntry, err error) error {
|
||||
if err != nil || d.IsDir() {
|
||||
@@ -614,14 +652,12 @@ func codexFilesIn(dir string) []file {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
fi, err := d.Info()
|
||||
if err != nil || !fi.Mode().IsRegular() {
|
||||
return nil
|
||||
}
|
||||
out = append(out, file{agent: "codex", key: "codex:" + m[1], path: p, main: true, size: fi.Size(), mod: fi.ModTime()})
|
||||
out = append(out, file{agent: "codex", key: "codex:" + m[1], path: p, main: true})
|
||||
entries = append(entries, d)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
out = statFiles(out, func(i int) (os.FileInfo, error) { return entries[i].Info() })
|
||||
// During compression, prefer the readable plain twin in the same
|
||||
// directory: the new compressed file may not have its trailer yet.
|
||||
plain := map[string]bool{}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The rollouts of a busy Codex folder are stat()ed on several goroutines,
|
||||
// and the list comes back as one walk gave it: in the walk's order, each
|
||||
// with its own size, and without what is gone, a folder or a link.
|
||||
func TestCodexFilesStatInOrder(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
day := filepath.Join(dir, "sessions", "2026", "09", "30")
|
||||
if err := os.MkdirAll(day, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var want []string
|
||||
for i := range 1500 {
|
||||
name := fmt.Sprintf("rollout-2026-09-30T10-00-00-t%04d.jsonl", i)
|
||||
p := filepath.Join(day, name)
|
||||
switch {
|
||||
case i%97 == 5:
|
||||
if err := os.Mkdir(p, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
continue
|
||||
case i%89 == 7 && runtime.GOOS != "windows":
|
||||
if err := os.Symlink(filepath.Join(day, "rollout-2026-09-30T10-00-00-t0000.jsonl"), p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := os.WriteFile(p, make([]byte, i), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want = append(want, p)
|
||||
}
|
||||
got := codexFilesIn(dir)
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("%d rollouts, want %d", len(got), len(want))
|
||||
}
|
||||
for i, f := range got {
|
||||
var n int
|
||||
fmt.Sscanf(filepath.Base(f.path), "rollout-2026-09-30T10-00-00-t%04d.jsonl", &n)
|
||||
if f.path != want[i] || f.size != int64(n) || f.mod.IsZero() || f.key != fmt.Sprintf("codex:t%04d", n) {
|
||||
t.Fatalf("rollout %d: %s size %d key %s, want %s size %d", i, f.path, f.size, f.key, want[i], n)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user