filememo: a file written just now is read again into one buffer

A file whose time is under two seconds old is read again on every read
and compared with the bytes parsed, since a second write inside a clock
tick can leave the same time and size. Each of those reads made a new
buffer. As magpie starts, Codex's sync writes ~/.codex/config.toml, and
every read of it for the next two seconds made one. With the owner's
real 1.45 MB config.toml, v0.1.2432's startup profile has
readCodexStoreSetting reading it ~155 times (226 MB) and the TOML table
spans ~89 times (129 MB). That is 381 MB of the 1.37 GB allocated before
the window's first poll, and the peak RSS with it.

Now a read that finds the same size and time reads into a buffer kept on
the entry while its bytes are, and gives the buffer back when they
match. A read beside it takes the buffer out first, so it reads into one
of its own. Bytes that differ are parsed from that read's buffer, which
no one else has. Nothing changes in what is looked at: the file is still
read and compared each time until it settles.

steady.ReadThereInto is ReadThere into a caller's buffer.

TestRecentFileReadAgainIntoOneBuffer (a 1.2 MB file stamped now): 20
reads allocate under a quarter of the file each, it is parsed once, 8
readers at once each get the right length, and a write of the same size
and time is seen and kept as its own bytes. Broken by hand on mote, with
the buffered path off, it is red (1191002 bytes a read).

Run at 8ce36a0ef (on d714c4216), on mote: gofmt clean; filememo, steady,
provider (146s) and agent (300s) ok. gateway: TestBurstTellsNoSpeed red
(#2719, under load, no file read on its path). gui:
TestSettingsSaveKeepsWhatItDoesNotSend (#4514, red on main) and
TestMainWindowCorners (#3949, macOS 27). vet ok on darwin, linux and
windows. Windows: filememo and steady ok. WSL: filememo, steady,
provider and gateway ok; agent's 6 reds are the same on origin/main
80bcef18f (#4033, #3548).
This commit is contained in:
yetone
2026-11-01 03:47:03 +08:00
parent bb50f4ad94
commit 68c413ea05
3 changed files with 180 additions and 7 deletions
+54 -7
View File
@@ -24,6 +24,9 @@ type entry struct {
// milliseconds) coarse, so two writes of one size inside a tick (two
// accounts swapped) leave the same time and size
raw []byte
// again is the buffer the file is read into again while raw is kept,
// to be compared with it
again []byte
// when the file was last found unchanged, while a request held them
// (Hold), and in which of Forget's generations
checked time.Time
@@ -207,25 +210,69 @@ func read[T any](kind, path string, parse func([]byte) (T, error), held bool) (T
mu.Unlock()
return e.v.(T), nil
}
if ok && e.raw != nil && e.mod.Equal(fi.ModTime()) && e.size == fi.Size() {
// written just now and the same size and time: most often the
// same bytes, read into the buffer kept for it rather than a new
// one each time. A read beside this one takes a buffer of its own.
mu.Lock()
buf := seen[key].again
if cur, ok := seen[key]; ok {
cur.again = nil
seen[key] = cur
}
mu.Unlock()
if int64(cap(buf)) <= fi.Size() {
buf = make([]byte, 0, fi.Size()+512)
}
b, err := steady.ReadThereInto(path, buf)
if err != nil {
return zero, err
}
if bytes.Equal(b, e.raw) {
mu.Lock()
if cur, ok := seen[key]; ok && cur.again == nil && cur.mod.Equal(e.mod) {
cur.again = b[:0]
seen[key] = cur
}
mu.Unlock()
settle(key, e)
return e.v.(T), nil
}
// the buffer was this read's alone: it is what was parsed now
return parsed(key, fi, b, parse, g)
}
b, err := steady.ReadThere(path)
if err != nil {
return zero, err
}
if ok && e.mod.Equal(fi.ModTime()) && bytes.Equal(b, e.raw) {
if time.Since(e.mod) > settled {
mu.Lock()
e.raw = nil
seen[key] = e
mu.Unlock()
}
settle(key, e)
return e.v.(T), nil
}
return parsed(key, fi, b, parse, g)
}
// settle drops e's bytes once its file's time is old enough to tell a
// later write by: from then on its time and size are looked at alone.
func settle(key string, e entry) {
if time.Since(e.mod) > settled {
mu.Lock()
e.raw, e.again = nil, nil
seen[key] = e
mu.Unlock()
}
}
// parsed is parse of b, the file at key's bytes as fi found it, kept for
// the next read; g is Forget's generation when it was looked at.
func parsed[T any](key string, fi os.FileInfo, b []byte, parse func([]byte) (T, error), g uint64) (T, error) {
v, err := parse(b)
if err != nil {
var zero T
return zero, err
}
mu.Lock()
e = entry{mod: fi.ModTime(), size: fi.Size(), v: v}
e := entry{mod: fi.ModTime(), size: fi.Size(), v: v}
if time.Since(e.mod) <= settled {
e.raw = b
} else if holds > 0 && g == gen {
+90
View File
@@ -0,0 +1,90 @@
package filememo
import (
"bytes"
"os"
"path/filepath"
"runtime"
"sync"
"testing"
"time"
)
// A file written just now is read again on each read and compared with
// the bytes parsed, into a buffer kept for it: a new one each time was
// most of what magpie allocated as it started, the 1.5 MB config.toml
// Codex's sync had just written read 150 times over (226 MB). A write of
// the same size and time is still seen.
func TestRecentFileReadAgainIntoOneBuffer(t *testing.T) {
p := filepath.Join(t.TempDir(), "config.toml")
big := bytes.Repeat([]byte("model = \"gpt-5.5\"\n"), 1<<16)
if err := os.WriteFile(p, big, 0o600); err != nil {
t.Fatal(err)
}
now := time.Now()
if err := os.Chtimes(p, now, now); err != nil {
t.Fatal(err)
}
parses := 0
parse := func(b []byte) (int, error) { parses++; return len(b), nil }
if n, err := Read("reread", p, parse); err != nil || n != len(big) {
t.Fatal(n, err)
}
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
const reads = 20
for range reads {
if n, err := Read("reread", p, parse); err != nil || n != len(big) {
t.Fatal(n, err)
}
}
runtime.ReadMemStats(&after)
if per := (after.TotalAlloc - before.TotalAlloc) / reads; per*4 > uint64(len(big)) {
t.Fatalf("a read of a %d-byte file written just now took %d bytes", len(big), per)
}
if parses != 1 {
t.Fatalf("the same bytes parsed %d times", parses)
}
if e := seen["reread\x00"+p]; e.raw == nil {
t.Fatal("the file written just now is not compared byte by byte")
}
// reads at once each read into a buffer of their own
var wg sync.WaitGroup
for range 8 {
wg.Go(func() {
for range 10 {
if n, err := Read("reread", p, parse); err != nil || n != len(big) {
t.Error(n, err)
}
}
})
}
wg.Wait()
// another write of the same size, stamped the same time
other := bytes.ToUpper(big)
if err := os.WriteFile(p, other, 0o600); err != nil {
t.Fatal(err)
}
if err := os.Chtimes(p, now, now); err != nil {
t.Fatal(err)
}
parse2 := func(b []byte) (int, error) { parses++; return int(b[0]), nil }
if v, err := Read("reread", p, parse2); err != nil || v != 'M' {
t.Fatalf("a write of the same size and time read as %v %v", v, err)
}
// what was parsed is its own, not the buffer read into again
if e := seen["reread\x00"+p]; !bytes.Equal(e.raw, other) {
t.Fatal("the bytes kept are not the file's")
}
if err := os.WriteFile(p, big, 0o600); err != nil {
t.Fatal(err)
}
if err := os.Chtimes(p, now, now); err != nil {
t.Fatal(err)
}
Read("reread", p, parse2)
if e := seen["reread\x00"+p]; !bytes.Equal(e.raw, big) {
t.Fatal("the bytes kept were written over by the next read")
}
}
+36
View File
@@ -11,6 +11,7 @@ package steady
import (
"errors"
"io"
"io/fs"
"os"
"path/filepath"
@@ -93,6 +94,41 @@ func ReadThere(p string) ([]byte, error) {
return b, err
}
// ReadThereInto is ReadThere into buf's room, grown when the file needs
// more: for a caller that reads one file again and again only to compare
// it, which a new buffer each time made the bulk of what magpie allocated
// as it started (a 1.5 MB config.toml read 150 times over).
func ReadThereInto(p string, buf []byte) ([]byte, error) {
var b []byte
err := retryGone(func() (err error) {
b, err = readInto(p, buf[:0])
return err
})
return b, err
}
// readInto is os.ReadFile into buf; a test stands in for it.
var readInto = func(p string, buf []byte) ([]byte, error) {
f, err := os.Open(p)
if err != nil {
return nil, err
}
defer f.Close()
for {
if len(buf) == cap(buf) {
buf = append(buf, 0)[:len(buf)]
}
n, err := f.Read(buf[len(buf):cap(buf)])
buf = buf[:len(buf)+n]
if err == io.EOF {
return buf, nil
}
if err != nil {
return nil, err
}
}
}
// ReadFile is os.ReadFile, waiting out a file being replaced.
func ReadFile(p string) ([]byte, error) {
var b []byte