diff --git a/internal/dirent/stats.go b/internal/dirent/stats.go index 719c1bf1d..1082defdd 100644 --- a/internal/dirent/stats.go +++ b/internal/dirent/stats.go @@ -5,6 +5,7 @@ import ( "io/fs" "slices" "sync" + "sync/atomic" "time" ) @@ -51,6 +52,16 @@ 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) { old, room := taken(dir) + if old != nil && current(dir, old) { + if room != nil { + listings.Lock() + keepSpare(dir, room) + listings.Unlock() + } + return old, true + } + seq := begin(dir) + reads.Add(1) l, ok := stats(dir, room, old) if old != nil { listings.Lock() @@ -61,6 +72,7 @@ func Stats(dir string) (Listing, bool) { return nil, false } slices.SortFunc(l, func(a, b Entry) int { return cmp.Compare(a.Name, b.Name) }) + mark(l, seq) return l, true } @@ -96,6 +108,9 @@ var listings struct { const keptEntries = 1 << 17 +// reads counts the folders Stats has read, for the tests. +var reads atomic.Int64 + // 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) { @@ -191,4 +206,5 @@ func Forget() { listings.Lock() listings.last, listings.spare, listings.room, listings.entries = nil, nil, nil, 0 listings.Unlock() + forgetListed() } diff --git a/internal/dirent/watch.go b/internal/dirent/watch.go new file mode 100644 index 000000000..5473ea682 --- /dev/null +++ b/internal/dirent/watch.go @@ -0,0 +1,317 @@ +package dirent + +import ( + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "sync" + "time" + "unsafe" +) + +// Every 15 s Sessions poll lists every Codex day folder and Claude Code +// project again, ~18k files in a few hundred folders, and those listings +// were ~70% of the poll's CPU (~115 ms a poll on a real history) while +// nothing in them had changed. A folder under a root someone Watches is +// listed again only when the system said something in it changed since +// its last listing (FSEvents on macOS), and otherwise is its last listing, +// as it was. Where there is no such watch, every Stats lists the folder. +// +// The system's word comes a moment late, so Watch waits until every +// change made before it is heard: it writes a file of its own in a new +// folder the watch covers, and the system tells changes in the order they were +// made, so once that write is heard so is every one before it. Anything +// the watch can't vouch for (it dropped events, a root moved, a volume +// came or went, a wait ran out, it hasn't started) lists again, and so +// does a listing older than listedFor, should an event never come. +var watched struct { + sync.Mutex + roots []watchRoot + seq uint64 // counts listings begun and changes heard + all uint64 // seq when everything last changed + dirty map[string]uint64 // a folder's seq when it last changed + at map[uintptr]listed // a listing's seq and time, by its array + since uint64 // seq when the watch last started + active bool + tried map[string]bool // roots asked for + synced time.Time // when every change before was last heard + probe probe +} + +type watchRoot struct { + given, real string + dev uint64 +} + +// probe is the folder Watch writes in to know every change before is +// heard, and the wait for that write's word. +type probe struct { + dir, real string + dev uint64 + n int + want string // the folder whose word the wait is for + heard chan struct{} +} + +type listed struct { + seq uint64 + when time.Time + newest int64 // the newest Mod of its files +} + +const ( + // listedFor is how long a folder's listing is trusted without listing + // it again, in case a change was never heard: a write to a file held + // open is heard only when the file is closed, and Codex holds its + // rollout open for the whole session. + listedFor = 2 * time.Minute + // hotFor is how long after one of its files was written a folder is + // listed on every read: a session being written may hold its file + // open, and nothing is heard of it until it closes. + hotFor = 15 * time.Minute + // trustFor is how long after a Watch a listing is taken as current: a + // change made since may not have been heard yet. + trustFor = 2 * time.Second + // probeWait is how long Watch waits for its own write to be heard. + probeWait = time.Second +) + +// Watch has dir and everything under it watched for changes, where the +// system can, and waits until every change made before the call is +// heard: a reader calls it before each read of dir's folders, and Stats +// of a folder in it then skips listing one that hasn't changed. A Stats +// with no Watch of its root in the last trustFor reads its folder. +func Watch(dir string) { + dir = filepath.Clean(dir) + starting.Lock() + defer starting.Unlock() + watched.Lock() + tried := watched.tried[dir] + watched.Unlock() + if !tried && !add(dir) { + return + } + sync1() +} + +// starting is held while a watch is made or waited on, outside watched: +// stopping a stream waits for its word, which takes watched. +var starting sync.Mutex + +// add has the watch cover dir too, and is whether dir can be watched now. +// starting is held. +func add(dir string) bool { + real, err := filepath.EvalSymlinks(dir) + if err != nil { + return false // not there yet: tried again next time + } + fi, err := os.Stat(real) + if err != nil { + return false + } + watched.Lock() + if watched.tried == nil { + watched.tried = map[string]bool{} + } + watched.tried[dir] = true + for _, r := range watched.roots { + if within(dir, r.given) || within(real, r.real) { + watched.Unlock() + return true + } + } + roots := append(slices.Clip(watched.roots), watchRoot{dir, real, devOf(fi)}) + p := watched.probe + watched.active = false + watched.Unlock() + if p.dir == "" { + d, err := os.MkdirTemp("", "magpie-watch-") + if err != nil { + return false + } + r, err := filepath.EvalSymlinks(d) + pfi, err2 := os.Stat(d) + if err != nil || err2 != nil { + os.Remove(d) + return false + } + p = probe{dir: d, real: r, dev: devOf(pfi)} + } + paths := []string{p.real} + for _, r := range roots { + paths = append(paths, r.real) + } + on := startWatch(paths) + watched.Lock() + defer watched.Unlock() + watched.seq++ + watched.since, watched.all = watched.seq, watched.seq + watched.roots, watched.active, watched.probe = roots, on, p + return true +} + +// sync1 writes in the probe's folder and waits for the write to be heard, +// so every change before it is too. starting is held. +func sync1() { + at := time.Now() + watched.Lock() + if !watched.active { + watched.Unlock() + return + } + // each wait writes in a folder of its own: the word of an earlier + // write, come after its wait gave up, must not end this one + watched.probe.n++ + n := strconv.Itoa(watched.probe.n) + ch := make(chan struct{}) + watched.probe.heard = ch + watched.probe.want = filepath.Join(watched.probe.real, n) + p := watched.probe + watched.Unlock() + sub := filepath.Join(p.dir, n) + ok := os.Mkdir(sub, 0o700) == nil && os.WriteFile(filepath.Join(sub, "probe"), nil, 0o600) == nil + if ok { + select { + case <-ch: + case <-time.After(probeWait): + ok = false + } + } + os.RemoveAll(sub) + watched.Lock() + defer watched.Unlock() + watched.probe.heard, watched.probe.want = nil, "" + if ok { + watched.synced = at + return + } + watched.seq++ + watched.all = watched.seq +} + +func within(dir, root string) bool { + return dir == root || strings.HasPrefix(dir, root) && (strings.HasSuffix(root, string(filepath.Separator)) || dir[len(root)] == filepath.Separator) +} + +// heard is the system's word that something in each folder of paths +// changed, or, with all, that anything may have. +func heard(paths []string, all bool) { + watched.Lock() + defer watched.Unlock() + watched.seq++ + if ch := watched.probe.heard; ch != nil && slices.Contains(paths, watched.probe.want) { + close(ch) + watched.probe.heard = nil + } + if all || len(watched.dirty) > 1<<14 { + watched.all = watched.seq + watched.dirty = nil + if all { + return + } + } + if watched.dirty == nil { + watched.dirty = map[string]uint64{} + } + for _, p := range paths { + p = filepath.Clean(p) + watched.dirty[p] = watched.seq + for _, r := range watched.roots { + if r.given != r.real && within(p, r.real) { + watched.dirty[r.given+p[len(r.real):]] = watched.seq + } + } + } +} + +// begin is the seq of a listing of dir begun now, or 0 when dir isn't +// watched. +func begin(dir string) uint64 { + watched.Lock() + defer watched.Unlock() + if !watched.active || !watchedDir(dir) { + return 0 + } + watched.seq++ + return watched.seq +} + +func watchedDir(dir string) bool { + for _, r := range watched.roots { + if within(dir, r.given) || within(dir, r.real) { + // the probe's word vouches for a change made on its own volume + return r.dev == watched.probe.dev + } + } + return false +} + +// mark records l, a listing begun at seq, as current as of then, or, with +// seq 0, as nothing the watch vouches for. Every listing Stats makes is +// marked, so an array used again for another folder's listing, or freed +// and its address given to another, never keeps an earlier one's word: +// the address is kept, not the array. +func mark(l Listing, seq uint64) { + if cap(l) == 0 { + return + } + key := uintptr(unsafe.Pointer(unsafe.SliceData(l[:cap(l)]))) + watched.Lock() + defer watched.Unlock() + if seq == 0 { + delete(watched.at, key) + return + } + if watched.at == nil || len(watched.at) > 1<<14 { + watched.at = map[uintptr]listed{} + } + var newest int64 + for _, e := range l { + if e.Mode == 0 { + newest = max(newest, e.Mod) + } + } + watched.at[key] = listed{seq, time.Now(), newest} +} + +// current is whether l, dir's last listing, is still what dir holds: the +// watch has heard of no change in dir since l was listed. +func current(dir string, l Listing) bool { + if cap(l) == 0 { + return false + } + watched.Lock() + defer watched.Unlock() + if !watched.active || !watchedDir(dir) { + return false + } + at, ok := watched.at[uintptr(unsafe.Pointer(unsafe.SliceData(l[:cap(l)])))] + if !ok || at.seq <= watched.since || at.seq <= watched.all || time.Since(at.when) > listedFor || time.Since(watched.synced) > trustFor { + return false + } + if time.Since(time.Unix(0, at.newest)) < hotFor { + return false + } + dir = filepath.Clean(dir) + if watched.dirty[dir] >= at.seq { + return false + } + // a change in a root's own folder is word of a change anywhere under + // it: Codex appends history.jsonl, closed each time, at each prompt, + // while the rollout it writes stays open and unheard + for _, r := range watched.roots { + if (within(dir, r.given) || within(dir, r.real)) && (watched.dirty[r.given] >= at.seq || watched.dirty[r.real] >= at.seq) { + return false + } + } + return true +} + +// forget drops what the watch knows of listings let go. +func forgetListed() { + watched.Lock() + watched.at = nil + watched.Unlock() +} diff --git a/internal/dirent/watch_darwin.go b/internal/dirent/watch_darwin.go new file mode 100644 index 000000000..96a56d1aa --- /dev/null +++ b/internal/dirent/watch_darwin.go @@ -0,0 +1,115 @@ +//go:build darwin && cgo + +package dirent + +/* +#cgo LDFLAGS: -framework CoreServices +#include +#include +#include + +extern void direntHeard(size_t n, char **paths, FSEventStreamEventFlags *flags); + +static void direntCallback(ConstFSEventStreamRef s, void *info, size_t n, void *paths, + const FSEventStreamEventFlags flags[], const FSEventStreamEventId ids[]) { + direntHeard(n, (char **)paths, (FSEventStreamEventFlags *)flags); +} + +static dispatch_queue_t direntQueue; +static FSEventStreamRef direntStream; + +static int direntStart(char **paths, int n) { + if (direntStream != NULL) { + FSEventStreamStop(direntStream); + FSEventStreamInvalidate(direntStream); + FSEventStreamRelease(direntStream); + direntStream = NULL; + } + if (direntQueue == NULL) { + direntQueue = dispatch_queue_create("magpie.dirent", DISPATCH_QUEUE_SERIAL); + } + CFMutableArrayRef list = CFArrayCreateMutable(NULL, n, &kCFTypeArrayCallBacks); + for (int i = 0; i < n; i++) { + CFStringRef p = CFStringCreateWithCString(NULL, paths[i], kCFStringEncodingUTF8); + if (p == NULL) { + CFRelease(list); + return 0; + } + CFArrayAppendValue(list, p); + CFRelease(p); + } + FSEventStreamRef s = FSEventStreamCreate(NULL, direntCallback, NULL, list, + kFSEventStreamEventIdSinceNow, 0.01, + kFSEventStreamCreateFlagNoDefer | kFSEventStreamCreateFlagWatchRoot); + CFRelease(list); + if (s == NULL) { + return 0; + } + FSEventStreamSetDispatchQueue(s, direntQueue); + if (!FSEventStreamStart(s)) { + FSEventStreamInvalidate(s); + FSEventStreamRelease(s); + return 0; + } + direntStream = s; + return 1; +} +*/ +import "C" + +import ( + "os" + "strings" + "syscall" + "unsafe" +) + +// FSEvents' flags that say a folder's word can't be taken alone: events +// were dropped or merged, a root moved, a volume came or went. +const heardAll = C.kFSEventStreamEventFlagMustScanSubDirs | + C.kFSEventStreamEventFlagUserDropped | + C.kFSEventStreamEventFlagKernelDropped | + C.kFSEventStreamEventFlagEventIdsWrapped | + C.kFSEventStreamEventFlagRootChanged | + C.kFSEventStreamEventFlagMount | + C.kFSEventStreamEventFlagUnmount + +// startWatch has FSEvents tell heard of every folder under paths in which +// something changed: an entry made, renamed or removed, or a file written. +// It replaces the watch before it. watched is not held: stopping a +// stream waits for its callback, which takes it. +func startWatch(paths []string) bool { + cs := make([]*C.char, len(paths)) + for i, p := range paths { + cs[i] = C.CString(p) + } + defer func() { + for _, c := range cs { + C.free(unsafe.Pointer(c)) + } + }() + return C.direntStart((**C.char)(unsafe.Pointer(&cs[0])), C.int(len(cs))) == 1 +} + +// devOf is the volume fi is on. +func devOf(fi os.FileInfo) uint64 { + if st, ok := fi.Sys().(*syscall.Stat_t); ok { + return uint64(st.Dev) + } + return 0 +} + +//export direntHeard +func direntHeard(n C.size_t, paths **C.char, flags *C.FSEventStreamEventFlags) { + ps := unsafe.Slice(paths, int(n)) + fs := unsafe.Slice(flags, int(n)) + dirs := make([]string, 0, len(ps)) + all := false + for i, p := range ps { + if fs[i]&heardAll != 0 { + all = true + } + dirs = append(dirs, strings.TrimSuffix(C.GoString(p), "/")) + } + heard(dirs, all) +} diff --git a/internal/dirent/watch_other.go b/internal/dirent/watch_other.go new file mode 100644 index 000000000..b4c6f40f4 --- /dev/null +++ b/internal/dirent/watch_other.go @@ -0,0 +1,11 @@ +//go:build !darwin || !cgo + +package dirent + +import "os" + +// startWatch is false where the system has no watch magpie uses: every +// Stats lists its folder. +func startWatch([]string) bool { return false } + +func devOf(os.FileInfo) uint64 { return 0 } diff --git a/internal/dirent/watch_test.go b/internal/dirent/watch_test.go new file mode 100644 index 000000000..aaf89c45e --- /dev/null +++ b/internal/dirent/watch_test.go @@ -0,0 +1,163 @@ +//go:build darwin && cgo + +package dirent + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +// statsOf is dir's listing, given back at once, and whether Stats read the +// folder for it. +func statsOf(t *testing.T, dir string) (Listing, bool) { + t.Helper() + before := reads.Load() + l, ok := Stats(dir) + if !ok { + t.Fatalf("Stats(%s) failed", dir) + } + got := append(Listing(nil), l...) + l.Done(dir) + return got, reads.Load() != before +} + +// aged has path last written a day ago, as a session long finished is. +func aged(t *testing.T, path string) { + t.Helper() + old := time.Now().Add(-24 * time.Hour) + if err := os.Chtimes(path, old, old); err != nil { + t.Fatal(err) + } +} + +// sizeOf is name's size in dir's listing as the next read after a Watch +// of root has it, and whether it is there. +func sizeOf(t *testing.T, root, dir, name string) (int64, bool) { + t.Helper() + Watch(root) + l, _ := statsOf(t, dir) + s, ok := l.Get(name) + return s.Size, ok +} + +// quiet is whether dir is no longer read, after a few reads to settle. +func quiet(t *testing.T, root, dir string) bool { + t.Helper() + for range 3 { + Watch(root) + statsOf(t, dir) + } + Watch(root) + _, read := statsOf(t, dir) + return !read +} + +func dayFolder(t *testing.T) (root, day, rollout string) { + t.Helper() + root = t.TempDir() + day = filepath.Join(root, "sessions", "2026", "11", "12") + if err := os.MkdirAll(day, 0o755); err != nil { + t.Fatal(err) + } + rollout = filepath.Join(day, "rollout-a.jsonl") + if err := os.WriteFile(rollout, []byte("{}\n"), 0o644); err != nil { + t.Fatal(err) + } + aged(t, rollout) + Watch(root) + t.Cleanup(Forget) + return root, day, rollout +} + +// A watched folder nothing changed in is not read again (every Sessions +// poll read ~18k session files' folders, ~115 ms a poll), and the next +// read after a write to a file in it, a new file or a removed one sees +// it, with no wait. +func TestWatchedFolderReadOnlyWhenChanged(t *testing.T) { + root, day, rollout := dayFolder(t) + if !quiet(t, root, day) { + t.Fatal("an unchanged watched folder was read again") + } + for i := range 50 { + f, err := os.OpenFile(rollout, os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + f.WriteString(`{"type":"event"}` + "\n") + f.Close() + aged(t, rollout) // not hot: only the change heard has it read + fi, _ := os.Stat(rollout) + if n, _ := sizeOf(t, root, day, "rollout-a.jsonl"); n != fi.Size() { + t.Fatalf("append %d: read %d bytes, the file has %d", i, n, fi.Size()) + } + } + b := filepath.Join(day, "rollout-b.jsonl") + if err := os.WriteFile(b, nil, 0o644); err != nil { + t.Fatal(err) + } + aged(t, b) + if _, ok := sizeOf(t, root, day, "rollout-b.jsonl"); !ok { + t.Fatal("a new file wasn't seen") + } + if err := os.Remove(rollout); err != nil { + t.Fatal(err) + } + if _, ok := sizeOf(t, root, day, "rollout-a.jsonl"); ok { + t.Fatal("a removed file was still listed") + } + if !quiet(t, root, day) { + t.Fatal("a watched folder was read again after it settled") + } +} + +// A write to a file held open is heard only when it closes, and Codex +// holds its rollout open for the whole session: a folder with a file +// written lately is read every time, and a change in the root's own +// folder (Codex's history.jsonl, at each prompt) has every folder under +// it read. +func TestFileHeldOpenStillSeen(t *testing.T) { + root, day, rollout := dayFolder(t) + f, err := os.OpenFile(rollout, os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + defer f.Close() + if !quiet(t, root, day) { + t.Fatal("an unchanged watched folder was read again") + } + + // a session long quiet, taken up again: the root hears the prompt + f.WriteString(`{"type":"resumed"}` + "\n") + if err := os.WriteFile(filepath.Join(root, "history.jsonl"), []byte("{}\n"), 0o644); err != nil { + t.Fatal(err) + } + fi, _ := os.Stat(rollout) + if n, _ := sizeOf(t, root, day, "rollout-a.jsonl"); n != fi.Size() { + t.Fatalf("after a prompt: read %d bytes, the file has %d", n, fi.Size()) + } + // and from then on the folder is hot: each write is seen, unheard + for i := range 20 { + f.WriteString(`{"type":"event"}` + "\n") + fi, _ := os.Stat(rollout) + if n, _ := sizeOf(t, root, day, "rollout-a.jsonl"); n != fi.Size() { + t.Fatalf("write %d to the open file: read %d bytes, the file has %d", i, n, fi.Size()) + } + } +} + +// A folder outside every watched root is read on every Stats. +func TestUnwatchedFolderReadEachTime(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "a"), nil, 0o644); err != nil { + t.Fatal(err) + } + aged(t, filepath.Join(dir, "a")) + t.Cleanup(Forget) + for range 3 { + if _, read := statsOf(t, dir); !read { + t.Fatal("an unwatched folder's listing was reused") + } + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index c474e4144..64ecd142e 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -859,6 +859,7 @@ func joinedIs(s, a, b string, sep ...byte) bool { func listCCFiles(agent, dir string) []file { projects := filepath.Join(dir, "projects") + 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) @@ -1157,6 +1158,9 @@ func codexFilesIn(dir string) []file { if !Reads("codex") { return nil } + // 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"} { root := filepath.Join(dir, folder)