Files
magpie/internal/edit/toml_kept_test.go
T
yetone 46a615fb24 edit: a config's kept parse holds none of the file's text and no slack
tomlFileOf keeps a config's parse while the file is unchanged. Each key's
text, prefix and suffix were slices of the file's string, so the whole
file stayed alive beside the parse (1.5 MB of the owner's Codex
config.toml, ~11k project tables). The tables and names were also grown
by append and kept with their room. What is kept is now copied out:
text cloned, the prefixes and suffixes a config repeats on every line
(`trust_level = `, ` # …`) interned once through unique, and the tables,
each table's keys and the names held at their exact length.

Run on mote at this head:
- go test ./internal/edit: ok
- GOOS=darwin/linux/windows go vet ./internal/edit: ok
- gofmt -l: clean
- Broken by hand: without keptKeys on the tables,
  TestTOMLFileKeepsNoFileText is red ("2996 keys' text is still a slice
  of the file's"); with slices.Clone for the tables it was red on their
  room (3000/3072).
- Real-account copy (~/r2278/acct), idle heap at 180s: edit.tomlFileOf
  7.14 MB -> 2.97 MB; heap total 89.4 MB (102-103 MB the run before);
  Footprint 151 MB.
2026-11-09 20:35:17 +08:00

50 lines
1.7 KiB
Go

package edit
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"unsafe"
)
// What tomlFileOf keeps of a Codex config holds no piece of the file's
// text and no slack: a key's text sliced from it kept the whole file
// alive (1.5 MB of a real one with ~11k projects) beside the parse.
func TestTOMLFileKeepsNoFileText(t *testing.T) {
var b strings.Builder
b.WriteString("model = \"m\"\n\n")
for i := range 3000 {
fmt.Fprintf(&b, "[projects.\"/Users/someone/project-%d\"]\ntrust_level = \"trusted\" # ok\n\n", i)
}
path := filepath.Join(t.TempDir(), "config.toml")
if err := os.WriteFile(path, []byte(b.String()), 0o600); err != nil {
t.Fatal(err)
}
doc, err := tomlFileOf(path)
if err != nil {
t.Fatal(err)
}
if len(doc.tables) != 3000 || cap(doc.tables) != len(doc.tables) || cap(doc.names) != len(doc.names) {
t.Fatalf("tables %d/%d, names %d/%d: want 3000 kept with no room past them", len(doc.tables), cap(doc.tables), len(doc.names), cap(doc.names))
}
// in the file, one project's value is a block's length after the one
// before it; read out of it, each is a string of its own
at := func(s string) uintptr { return uintptr(unsafe.Pointer(unsafe.StringData(s))) }
sliced := 0
for i := 1; i < len(doc.tables); i++ {
a, z := doc.tables[i-1].keys, doc.tables[i].keys
if len(a) != 1 || len(z) != 1 || cap(z) != 1 || z[0].text != `"trusted"` {
t.Fatalf("table %d keys %+v", i, z)
}
block := len(fmt.Sprintf("[projects.\"/Users/someone/project-%d\"]\ntrust_level = \"trusted\" # ok\n\n", i-1))
if at(z[0].text)-at(a[0].text) == uintptr(block) {
sliced++
}
}
if sliced > 0 {
t.Fatalf("%d keys' text is still a slice of the file's", sliced)
}
}