Files
magpie/internal/usage/request_disk_map_unix_test.go
T
yetone 115ca34343 usage: the chunks' file is mapped, not read into the heap (#3493)
A start read requests-v1.bin's 44MB of chunk archives into the heap,
where they stayed: a fifth of the heap at rest, and with GOGC 25 a
larger heap goal through every warm-up step. They are pointer-free and
only ever decoded, so on unix the file is now mapped read-only
(MAP_SHARED, PROT_READ) and each chunk's Archive is a capped slice of
the mapping. A cleanup unmaps it once no chunk refers to it. The file is
only replaced by a rename (toDisk), never written in place; a read past
its end, if another program cut it short, is caught by readMapped
(SetPanicOnFault) as a failed read, not a crash: the chunk unpacks as
nil and reads as no rows, as a corrupt archive did before, until its
session file changes or magpie starts again. Windows can't
rename over a mapped file, so it reads the file as before
(request_disk_map_other.go).

decodeMapped keeps the decode's closure out of unpackReusing: with the
closure there, data escaped to the heap and every row's take() through
it was slower, which made step 2 0.12-0.2s slower than before (found by
profile: unpackReusing.func2 0.28s -> 0.64s over three runs).

Run at this tree, on the owner's real data (sandbox HOME with
.claude/projects and .codex/sessions linked read-only, ~421k rows), warm
runs interleaved with v0.1.1471 (b1f44d099), load 26-32:
- phys_footprint_peak: 285-298MB -> 232-259MB
- phys_footprint at rest: 221-227MB -> 176-179MB
- peak live heap 200MB -> 157MB, heap at rest 198MB -> 147MB
- step 2 (QueryPage All): 771-952ms -> 754-814ms; warm-up 1.68-1.96s
  -> 1.54-1.89s
- every one of the 15624 mapped chunks unpacks to the same rows
  (reflect.DeepEqual, 359553 rows) as its archive copied to the heap
- mmap of the file alone and a CRC pass: 6.5ms, read+CRC 8-10ms

Tests: go test -timeout 45m ./internal/usage ./internal/sessions
./internal/gui ok; -race on the usage request/chunk/page/disk tests ok;
gofmt clean; go vet -tags nogui with GOOS=linux and GOOS=windows ok.
TestRequestDiskChunksMapped checks every chunk read from the file is of
the mapping and that it is unmapped once forgotten; it is red with the
mapping turned off. TestRequestDiskMappingCutShort is red ("fatal error:
fault SIGBUS") with SetPanicOnFault off.

Not tried: a Linux or Windows real-data run (Linux vet only; Windows
keeps the old path); a file truncated under a running magpie outside
the test.
2026-10-25 08:29:23 +08:00

101 lines
3.0 KiB
Go

//go:build unix
package usage
import (
"fmt"
"os"
"path/filepath"
"runtime"
"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
diskUnmapped = func() { unmapped.Add(1) }
t.Cleanup(func() { diskUnmapped = 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()
}
}
// 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)
}