dirent: Each lists a folder with nothing made an entry; Codex's idle check uses it

b5adaa8bd read Codex's sessions folders with dirent.Stats, and measured
on a real-account HOME it allocated about as much as the walk it
replaced (dirent.entry and nameOf 4.1 MB of 12.7 MB in 4 idle minutes):
Stats copies every name and builds a listing, for a check that keeps
none of it.

dirent.Each gives a callback each entry's name, in getattrlistbulk's
buffer, and its Stat, and stops when told; stats is now built on the
same reader. codexSessionsQuietListed makes a path for each folder and
nothing for a file.

Run:
- mote: go test -count=1 ./internal/dirent ./internal/sessions ok;
  ./internal/provider ok (141s); GOOS=windows and GOOS=linux -tags nogui
  go vet ./internal/dirent ./internal/provider ok; gofmt clean
- xiaomi-gpu (Windows): -run 'TestEach|TestCodexSessionsQuiet' ok
Broken by hand: Each copying each name (string(name)), and
TestEachIsLstatWithNothingMade is red with 302 allocations for 301
entries.
This commit is contained in:
yetone
2026-11-11 08:33:52 +08:00
parent 68d1fda92b
commit 328dc97e28
5 changed files with 137 additions and 40 deletions
+59
View File
@@ -0,0 +1,59 @@
package dirent
import (
"os"
"path/filepath"
"runtime"
"testing"
)
// Each gives every entry of a folder as os.Lstat has it, stops when told,
// and makes nothing for an entry: Codex's idle check reads every session
// folder with it on each look.
func TestEachIsLstatWithNothingMade(t *testing.T) {
dir := t.TempDir()
for i := range 300 {
p := filepath.Join(dir, "rollout-"+string(rune('a'+i%26))+string(rune('a'+i/26))+".jsonl")
if err := os.WriteFile(p, make([]byte, i), 0o644); err != nil {
t.Fatal(err)
}
}
if err := os.Mkdir(filepath.Join(dir, "sub"), 0o755); err != nil {
t.Fatal(err)
}
seen := 0
ok := Each(dir, func(name string, s Stat) bool {
seen++
fi, err := os.Lstat(filepath.Join(dir, name))
if err != nil {
t.Fatalf("%s: %v", name, err)
}
if s.Size != fi.Size() && !fi.IsDir() || s.Mod != fi.ModTime().UnixNano() || fi.IsDir() != (s.Mode == os.ModeDir) {
t.Fatalf("%s: %+v, lstat %d %v %v", name, s, fi.Size(), fi.ModTime(), fi.Mode())
}
return true
})
if runtime.GOOS != "darwin" {
if ok {
t.Fatal("a listing where the system has none")
}
return
}
if !ok || seen != 301 {
t.Fatalf("ok %v, %d entries, want 301", ok, seen)
}
n := 0
if !Each(dir, func(string, Stat) bool { n++; return n < 3 }) || n != 3 {
t.Fatalf("told to stop at the third, gave %d", n)
}
var mods int64
allocs := testing.AllocsPerRun(20, func() {
Each(dir, func(name string, s Stat) bool { mods += s.Mod + int64(len(name)); return true })
})
if allocs > 4 {
t.Fatalf("%v allocations a listing of 301 entries; want none a entry", allocs)
}
if Each(filepath.Join(dir, "gone"), func(string, Stat) bool { return true }) {
t.Fatal("a folder that isn't there listed")
}
}
+10
View File
@@ -64,6 +64,16 @@ func Stats(dir string) (Listing, bool) {
return l, true
}
// Each gives f each entry of dir as Stats has it, in the order the
// system lists them, with nothing made for an entry: name is valid only
// during the call, and f copies what it keeps of it. f returning false
// stops the listing. ok is false where Stats' is: the system has no such
// listing, or the folder or an entry couldn't be read (some entries may
// have been given f by then).
func Each(dir string, f func(name string, s Stat) bool) (ok bool) {
return eachIn(dir, f)
}
// listings are Stats' answers given back: a listing made new for each
// 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
+46 -24
View File
@@ -44,84 +44,107 @@ var bufs = sync.Pool{New: func() any { b := make([]byte, 64<<10); return &b }}
// and this is one call for every few hundred.
// old is dir's last listing, whose names are taken where they are the same.
func stats(dir string, out, old Listing) (Listing, bool) {
out = out[:0]
ok := each(dir, func(name []byte, s Stat) bool {
out = append(out, Entry{nameOf(name, old), s})
return true
})
if !ok {
return nil, false
}
return out, true
}
// eachIn is Each where the system has getattrlistbulk.
func eachIn(dir string, f func(name string, s Stat) bool) bool {
return each(dir, func(name []byte, s Stat) bool {
return f(unsafe.String(&name[0], len(name)), s)
})
}
// each reads dir's entries with getattrlistbulk and gives f each one's
// name, in the call's buffer, and Stat, until f says stop. It is false
// when the folder or an entry couldn't be read.
func each(dir string, f func(name []byte, s Stat) bool) bool {
fd, err := unix.Open(dir, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
if err != nil {
return nil, false
return false
}
defer unix.Close(fd)
al := attrList{bitmapCount: attrBitMapCount, common: attrCmnReturned | attrCmnName | attrCmnObjType | attrCmnModTime, file: attrFileDataLen}
bp := bufs.Get().(*[]byte)
defer bufs.Put(bp)
buf := *bp
out = out[:0]
for {
n, _, errno := syscall.Syscall6(unix.SYS_GETATTRLISTBULK, uintptr(fd), uintptr(unsafe.Pointer(&al)), uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)), 0, 0)
if errno == syscall.EINTR {
continue
}
if errno != 0 {
return nil, false
return false
}
if n == 0 {
return out, true
return true
}
b := buf
for range int(n) {
if !entry(b, &out, old) {
return nil, false
name, s, ok := entry(b)
if !ok {
return false
}
if !f(name, s) {
return true
}
b = b[binary.NativeEndian.Uint32(b):]
}
}
}
// 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. A name old has is its string.
func entry(b []byte, out *Listing, old Listing) bool {
// entry reads one entry of getattrlistbulk's answer: its length, the
// attributes it returned, then each in the order of their bits, a file's
// data length after the common ones. name is in b.
func entry(b []byte) (name []byte, s Stat, ok bool) {
if len(b) < 4 {
return false
return nil, s, false
}
size := int(binary.NativeEndian.Uint32(b))
if size < 4+20 || size > len(b) {
return false
return nil, s, false
}
e := b[:size]
common := binary.NativeEndian.Uint32(e[4:])
file := binary.NativeEndian.Uint32(e[16:])
p := e[24:]
var s Stat
var name string
if common&attrCmnName != 0 {
if len(p) < 8 {
return false
return nil, s, false
}
off, n := int(int32(binary.NativeEndian.Uint32(p))), int(binary.NativeEndian.Uint32(p[4:]))
at := len(e) - len(p) + off
if off < 0 || n < 1 || at+n > len(e) {
return false
return nil, s, false
}
name = nameOf(e[at:at+n-1], old)
name = e[at : at+n-1]
p = p[8:]
}
typ := uint32(0)
if common&attrCmnObjType != 0 {
if len(p) < 4 {
return false
return nil, s, false
}
typ = binary.NativeEndian.Uint32(p)
p = p[4:]
}
if common&attrCmnModTime != 0 {
if len(p) < 16 {
return false
return nil, s, false
}
s.Mod = int64(binary.NativeEndian.Uint64(p))*1e9 + int64(binary.NativeEndian.Uint64(p[8:]))
p = p[16:]
}
if file&attrFileDataLen != 0 {
if len(p) < 8 {
return false
return nil, s, false
}
s.Size = int64(binary.NativeEndian.Uint64(p))
}
@@ -134,11 +157,10 @@ func entry(b []byte, out *Listing, old Listing) bool {
default:
s.Mode = fs.ModeIrregular
}
if name == "" || common&attrCmnName == 0 || common&attrCmnObjType == 0 || common&attrCmnModTime == 0 || typ == vReg && file&attrFileDataLen == 0 {
return false
if len(name) == 0 || common&attrCmnName == 0 || common&attrCmnObjType == 0 || common&attrCmnModTime == 0 || typ == vReg && file&attrFileDataLen == 0 {
return nil, s, false
}
*out = append(*out, Entry{name, s})
return true
return name, s, true
}
// nameOf is b as a string, old's where old has it.
+2
View File
@@ -3,3 +3,5 @@
package dirent
func stats(string, Listing, Listing) (Listing, bool) { return nil, false }
func eachIn(string, func(string, Stat) bool) bool { return false }
+20 -16
View File
@@ -743,35 +743,39 @@ func codexSessionsQuietFor(home string, now time.Time, d time.Duration) bool {
}
// codexSessionsQuietListed is codexSessionsQuietFor read with one listing
// a folder (dirent.Stats) where the system has one, not a listing and an
// a folder (dirent.Each) where the system has one, not a listing and an
// lstat() a file: Codex idle runs it on every look while Codex is idle,
// over every session file of the history, and each walk allocated a
// listing, a path and an lstat's answer a file. ok is false where a folder
// can't be read so (no bulk listing, Windows, an error), and the caller
// walks the folder itself. The listings are not kept for the next read:
// held between looks minutes apart they cost more than they save.
// listing, a path and an lstat's answer a file. Nothing is made for a
// file now, only a path for each folder. ok is false where a folder can't
// be read so (no bulk listing, Windows, an error), and the caller walks
// the folder itself.
func codexSessionsQuietListed(dir string, now time.Time, d time.Duration) (quiet, ok bool) {
if _, err := os.Lstat(dir); errors.Is(err, fs.ErrNotExist) {
return true, true
}
quiet = true
since := now.Add(-d).UnixNano()
var in func(dir string) bool
in = func(dir string) bool {
entries, ok := dirent.Stats(dir)
if !ok {
return false
}
for _, e := range entries {
var sub []string // folders, read after this one's listing is done
if !dirent.Each(dir, func(name string, s dirent.Stat) bool {
switch {
case e.Mode == fs.ModeDir:
if !in(filepath.Join(dir, e.Name)) {
return false
}
case strings.HasSuffix(e.Name, ".jsonl") && now.Sub(e.ModTime()) < d:
case s.Mode == fs.ModeDir:
sub = append(sub, filepath.Join(dir, name))
case s.Mod > since && strings.HasSuffix(name, ".jsonl"):
quiet = false
}
return quiet
}) {
return false
}
for _, f := range sub {
if !quiet {
return true
break
}
if !in(f) {
return false
}
}
return true