Files
magpie/internal/filememo/key_alloc_test.go
T
yetone f99b227c27 filememo: a parse is kept under a struct key, not a joined string
read joined kind + "\x00" + path into a new string for every read,
and Look scanned every key with HasSuffix of another joined string.
A read is asked for each model of each provider a poll lists, so the
keys alone were 33 MB of what twenty window polls allocated with
real accounts (m2463 profile). seen is now keyed by
memoKey{kind, path}; a held read and Look allocate nothing.

Test: TestHeldReadAndLookAllocateNothing. 50 files in a long folder,
under Hold: AllocsPerRun of a read found unchanged is 0, and of Look
0; a write then Look reads the new value.

Run on mote, at this tree on 88372a39d:
- gofmt, go vet (darwin, windows, linux): ok
- the new test alone: ok
- broken by hand (the old filememo.go back): red, "a held read of a
  file found unchanged allocated 1 times, want 0"
- go test ./internal/filememo ./internal/settings ./internal/catalog
  ./internal/provider ./internal/agent: all ok

Not run: an A/B with the real-account sandbox for this change alone.
2026-11-01 04:50:29 +08:00

50 lines
1.7 KiB
Go

package filememo
import (
"os"
"path/filepath"
"strconv"
"testing"
"time"
)
// A read was asked for each model of each provider a poll lists, and each
// joined its kind and path into a new string to look the file up, as Look
// did for every file kept: 33 MB of what twenty window polls allocated. A
// read of a file found unchanged while held, and a Look, allocate nothing.
func TestHeldReadAndLookAllocateNothing(t *testing.T) {
dir := filepath.Join(t.TempDir(), "a folder long enough to be past any short string")
os.MkdirAll(dir, 0o755)
var paths []string
parse := func(b []byte) (map[string]string, error) { return map[string]string{"k": string(b)}, nil }
old := time.Now().Add(-time.Minute)
for i := range 50 {
p := filepath.Join(dir, "settings-"+strconv.Itoa(i)+".json")
os.WriteFile(p, []byte("v"), 0o600)
os.Chtimes(p, old, old)
paths = append(paths, p)
}
release := Hold()
defer release()
for _, p := range paths {
if m, err := Read("settings model ids", p, parse); err != nil || m["k"] != "v" {
t.Fatal(m, err)
}
}
if n := testing.AllocsPerRun(100, func() {
Read("settings model ids", paths[7], parse)
}); n != 0 {
t.Fatalf("a held read of a file found unchanged allocated %v times, want 0", n)
}
if n := testing.AllocsPerRun(100, func() { Look(paths[7]) }); n != 0 {
t.Fatalf("Look over %d files allocated %v times, want 0", len(paths), n)
}
// and Look still has the file looked at again
os.WriteFile(paths[7], []byte("w"), 0o600)
os.Chtimes(paths[7], old.Add(time.Second), old.Add(time.Second))
Look(paths[7])
if m, _ := Read("settings model ids", paths[7], parse); m["k"] != "w" {
t.Fatalf("a file written by another and Looked: %q", m["k"])
}
}