Files
magpie/internal/usage/request_disk_map_unix_test.go
T
yetone cbbf3163cb usage: a cold build's chunks are of the file's pages once it is written (#3493)
A start that reads requests-v1.bin keeps each chunk's archive in the
file's mapped pages, not on the heap. A start that builds the chunks
(a cold one: no file, or one of another build) kept the archives it
encoded on the heap until the next start, after writing the very same
bytes to the file: 32-40MB for 15.7k sessions, and a resting heap
~50MB over a warm start's.

Once save has written the file, onDisk maps it and makes, for each
chunk whose archive is of the heap, a copy whose archive is the same
bytes of the mapping (checked equal). save swaps it in for the chunk
of the same serial: a read since has copied the chunk with a use of
its own, so the pointer it wrote is gone by then. A read that copied
the chunks before the swap and finishes after it keeps the mapped
archive (keep), or it would put the heap one back. Nothing changes
where no file is mapped (Windows).

diskUnmapped, the tests' hook, is an atomic.Pointer: a mapping's
cleanup reads it on its own goroutine while the next test sets it,
which -race -count=4 caught once the new test let go of mappings.

Run at this tree (67a137744 + this change):
- go test -count=1 -timeout 45m ./internal/usage/ ./internal/sessions/:
  ok. go test -run 'Warm|Session|Request|Usage' ./internal/gui/
  ./internal/gateway/: ok.
- go test -race -count=4 -run TestRequestDisk ./internal/usage/: ok,
  six times in a row.
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage/: ok;
  gofmt -l clean.
- TestRequestDiskBuiltChunksMapped holds the write while a second page
  copies the chunks and a third copies them before the write and keeps
  them after it. It went red (0 of 4 mapped) with the swap matched by
  pointer instead of serial, and with keep not carrying the mapping.
- The real warm-up (gui warmSteps in sessions.Warm) on a copy of the
  owner's ~/.claude and ~/.codex sessions, cold (requests-v1.bin
  removed), parent and change alternating, 3 runs each, measured 5s
  after the warm-up:
  - heap at rest: 200/200/198MB before, 154/148/152MB after;
  - phys_footprint at rest: 233/234/237MB before, 198/197/205MB after;
  - phys_footprint_peak: 361/396/347MB before, 335/367/378MB after,
    the same within noise (the build itself is unchanged).

Not tried: Windows (it maps no file, so it is unchanged there).
2026-10-25 16:19:18 +08:00

165 lines
5.4 KiB
Go

//go:build unix
package usage
import (
"fmt"
"os"
"path/filepath"
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
"unsafe"
"github.com/yetone/magpie/internal/sessions"
)
// The chunks a start reads from the file are of the file's pages, not of
// the heap (#3493), and the pages are let go of once no chunk is of them.
func TestRequestDiskChunksMapped(t *testing.T) {
pageHome(t)
now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local))
least := requestDiskLeast
requestDiskLeast = 2
t.Cleanup(func() { requestDiskLeast = least })
var unmapped atomic.Int32
count := func() { unmapped.Add(1) }
diskUnmapped.Store(&count)
t.Cleanup(func() { diskUnmapped.Store(nil) })
dir := filepath.Join(sessions.CodexDir(), "sessions", "2026", "09", "30")
for i := range 4 {
writeCodexCall(t, filepath.Join(dir, fmt.Sprintf("rollout-2026-09-30T10-00-0%d-s%d.jsonl", i, i)), fmt.Sprintf("s%d", i), fmt.Sprintf("native-%d", i), `"cli"`, fmt.Sprintf("resp-%d", i), "m", "high", now.Add(-time.Duration(i+1)*time.Hour), 10*(i+1), i)
}
forget := func() {
requestDiskSaves.Wait()
requestCache.Lock()
requestCache.chunks = map[string]*rowChunk{}
requestCache.pages, requestCache.parts, requestCache.pairs, requestCache.heats = nil, nil, nil, nil
requestCache.key = ""
requestCache.Unlock()
sessions.Reset()
}
first := queryPage(All, Filter{}, 0, 100, sessions.ReadCallSource)
forget()
equalPage(t, queryPage(All, Filter{}, 0, 100, sessions.ReadCallSource), first)
requestCache.Lock()
mapped := 0
for _, c := range requestCache.chunks {
if len(c.Archive) == 0 {
continue
}
if c.mapped == nil {
t.Errorf("%s: read from the file into the heap", filepath.Base(c.Source.Path))
continue
}
at, start := uintptr(unsafe.Pointer(unsafe.SliceData(c.Archive))), uintptr(unsafe.Pointer(unsafe.SliceData(c.mapped.data)))
if at < start || at+uintptr(len(c.Archive)) > start+uintptr(len(c.mapped.data)) {
t.Errorf("%s: archive outside the mapping", filepath.Base(c.Source.Path))
}
mapped++
}
requestCache.Unlock()
if mapped != 4 {
t.Fatalf("%d chunks of the file's pages, want 4", mapped)
}
was := unmapped.Load()
forget()
for deadline := time.Now().Add(30 * time.Second); unmapped.Load() == was; {
if time.Now().After(deadline) {
t.Fatal("the mapping outlived every chunk of it")
}
runtime.GC()
runtime.Gosched()
}
}
// The chunks a cold build made are of the file's pages once it is written,
// as a warm start's are, not of the heap until the next start (#3493).
func TestRequestDiskBuiltChunksMapped(t *testing.T) {
pageHome(t)
now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local))
least := requestDiskLeast
requestDiskLeast = 2
t.Cleanup(func() { requestDiskLeast = least })
dir := filepath.Join(sessions.CodexDir(), "sessions", "2026", "09", "30")
for i := range 4 {
writeCodexCall(t, filepath.Join(dir, fmt.Sprintf("rollout-2026-09-30T10-00-0%d-s%d.jsonl", i, i)), fmt.Sprintf("s%d", i), fmt.Sprintf("native-%d", i), `"cli"`, fmt.Sprintf("resp-%d", i), "m", "high", now.Add(-time.Duration(i+1)*time.Hour), 10*(i+1), i)
}
// the write waits while another page copies the chunks with a use of
// its own, and a third has copied them before the write and keeps
// them after it
release, hold, held := make(chan struct{}), make(chan struct{}), make(chan struct{})
savingDisk = func() { <-release }
t.Cleanup(func() { savingDisk = nil })
first := queryPage(All, Filter{}, 0, 100, sessions.ReadCallSource)
queryPage(All, Filter{}, 1, 100, sessions.ReadCallSource)
var once sync.Once
building = func() { once.Do(func() { close(held); <-hold }) }
t.Cleanup(func() { building = nil })
done := make(chan struct{})
go func() {
defer close(done)
queryPage(All, Filter{}, 2, 100, sessions.ReadCallSource)
}()
<-held
close(release)
requestDiskSaves.Wait()
close(hold)
<-done
requestCache.Lock()
mapped, archived := 0, 0
for _, c := range requestCache.chunks {
if len(c.Archive) == 0 {
continue
}
archived++
if c.mapped == nil {
t.Errorf("%s: still of the heap after the file was written", filepath.Base(c.Source.Path))
continue
}
at, start := uintptr(unsafe.Pointer(unsafe.SliceData(c.Archive))), uintptr(unsafe.Pointer(unsafe.SliceData(c.mapped.data)))
if at < start || at+uintptr(len(c.Archive)) > start+uintptr(len(c.mapped.data)) {
t.Errorf("%s: archive outside the mapping", filepath.Base(c.Source.Path))
}
mapped++
}
requestCache.Unlock()
if archived != 4 || mapped != 4 {
t.Fatalf("%d of %d archived chunks of the file's pages, want 4 of 4", mapped, archived)
}
requestCache.Lock()
requestCache.pages, requestCache.parts, requestCache.pairs, requestCache.heats = nil, nil, nil, nil
requestCache.key = ""
requestCache.Unlock()
equalPage(t, queryPage(All, Filter{}, 0, 100, sessions.ReadCallSource), first)
}
// A file cut short under its mapping by another program is a read that
// failed, not a crash.
func TestRequestDiskMappingCutShort(t *testing.T) {
path := filepath.Join(t.TempDir(), "requests-v1.bin")
if err := os.WriteFile(path, make([]byte, 1<<20), 0o600); err != nil {
t.Fatal(err)
}
m, ok := mapDiskFile(path)
if !ok {
t.Fatal("not mapped")
}
var last byte
if !readMapped(m, func() { last = m.data[len(m.data)-1] }) || last != 0 {
t.Fatal("a whole file's read failed")
}
if err := os.Truncate(path, 0); err != nil {
t.Fatal(err)
}
if readMapped(m, func() { last = m.data[len(m.data)-1] }) {
t.Fatal("a read past the cut passed")
}
runtime.KeepAlive(m)
}