usage: a large build's archives are held in a spill file as they are made (#3493)

A cold build (first start, or after an update that changes internal/usage)
kept every chunk's archive on the heap until save had written
requests-v1.bin and swapped them for the file's pages: 31MB for 15.7k
sessions, the largest thing a cold peak held over a warm start's.

Now a build that wants requestDiskLeast or more files written writes each
archive to requests-*.spill as the chunk is made, lets go of the heap copy,
and maps the file once the build is done (unlinked at once). save then
swaps the spill's pages for requests-v1.bin's as before: pagesRank orders
heap < spill < file, and keep and save take the later. A spill that can't
be written or mapped has each of its chunks made again from its source, so
none is left without an archive. Windows maps no file, so nothing changes
there.

Run, real data (15.7k Claude Code + Codex sessions, sandbox HOME, copies of
the call shards, requests-v1.bin removed before each run), the gui warm-up
harness alternating old (cbbf3163c) and new, 4 rounds each:
  phys_footprint_peak old 396 353 346 352 MB, new 319 322 329 329 MB
  peak live (gctrace) old 209-259 MB, new 188-205 MB
  at rest unchanged (184-205 MB), warm-up time in the same range.
  gctrace: cold max live after mark is now 187MB against warm's 173MB; what
  is left of the gap is allocation churn (1.2GB allocated in the cold
  build against 280MB warm), not held data.
go test ./internal/usage ./internal/gui ok; -race -count=3 of the disk and
spill tests ok; GOOS=linux and windows go vet -tags nogui ok; gofmt clean.
Broken by hand: no spill put -> TestRequestDiskBuildSpills red; done not
making a chunk again -> TestArchiveSpillFailedMadeAgain red; the spill
ranked as the file -> TestRequestDiskBuildSpills red after the save.
Not tried: Windows (no mapping, path unchanged), a disk that fills while
spilling (the made-again path is covered by the unit test only).
This commit is contained in:
yetone
2026-10-25 16:56:02 +08:00
parent e4809a150a
commit 9dc7d6eb84
6 changed files with 228 additions and 7 deletions
+5 -3
View File
@@ -231,6 +231,8 @@ func readDiskEntry(b []byte) (*rowChunk, error) {
// (#3493). It is unmapped once no chunk read from it is left.
type diskMapping struct {
data []byte
// spill: a build's own file (archiveSpill), not requests-v1.bin
spill bool
}
// diskUnmapped, in tests, is told each time a mapping is let go of.
@@ -407,8 +409,8 @@ func toDisk(root, meta string, chunks map[string]*rowChunk, on map[string]bool)
return os.Rename(out.Name(), path)
}
// onDisk is a copy of each chunk of chunks whose Archive is of the heap,
// with the same Archive of the pages of the file toDisk just wrote; save
// onDisk is a copy of each chunk of chunks whose Archive is of the heap
// or a build's spill, with the same Archive of the pages of the file toDisk just wrote; save
// swaps them in for the chunks of the same serial. Made
// in this run, they held a cold build's archives on the heap until the
// next start: 32MB of 15.7k sessions, and a resting heap 40MB over a warm
@@ -424,7 +426,7 @@ func onDisk(root, meta string, chunks map[string]*rowChunk) map[string]*rowChunk
return false
}
c := chunks[path]
if c == nil || c.serial == 0 || c.mapped != nil || len(c.Archive) == 0 {
if c == nil || c.serial == 0 || c.pagesRank() == 2 || len(c.Archive) == 0 {
return true
}
e, err := readDiskEntry(raw)
+2
View File
@@ -4,6 +4,8 @@ package usage
// mapDiskFile maps nothing: on Windows a file mapped can't be renamed over,
// and toDisk replaces the file so. The file is read into memory instead.
const mapsFiles = false
func mapDiskFile(string) (*diskMapping, bool) { return nil, false }
func (m *diskMapping) read() {}
+4
View File
@@ -12,6 +12,10 @@ import (
// mapDiskFile maps the file at path read-only. The file is only ever
// replaced by a rename (toDisk), never written in place, so what is
// mapped stays as it was read while the mapping lives.
// mapsFiles: the system maps a file, and archiveSpill holds a build's
// archives in one.
const mapsFiles = true
func mapDiskFile(path string) (*diskMapping, bool) {
f, err := os.Open(path)
if err != nil {
@@ -7,6 +7,7 @@ import (
"os"
"path/filepath"
"runtime"
"slices"
"sync"
"sync/atomic"
"testing"
@@ -162,3 +163,91 @@ func TestRequestDiskMappingCutShort(t *testing.T) {
}
runtime.KeepAlive(m)
}
// A large build's archives are of its spill's pages as soon as it is done,
// before requests-v1.bin is written, and of the file's once it is; the
// spill leaves no file behind (#3493).
func TestRequestDiskBuildSpills(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)
}
release := make(chan struct{})
savingDisk = func() { <-release }
t.Cleanup(func() { savingDisk = nil })
first := queryPage(All, Filter{}, 0, 100, sessions.ReadCallSource)
ranks := func() map[int]int {
requestCache.Lock()
defer requestCache.Unlock()
n := map[int]int{}
for _, c := range requestCache.chunks {
if len(c.Archive) == 0 {
continue
}
n[c.pagesRank()]++
if c.mapped == nil {
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))
}
}
return n
}
if n := ranks(); n[1] != 4 {
t.Fatalf("before the file is written: %v archived chunks by rank (heap 0, spill 1, file 2), want 4 of the spill", n)
}
left, _ := filepath.Glob(filepath.Join(filepath.Dir(requestDiskPath()), "*.spill"))
if len(left) > 0 {
t.Errorf("spill files left: %v", left)
}
close(release)
requestDiskSaves.Wait()
if n := ranks(); n[2] != 4 {
t.Fatalf("after the file is written: %v archived chunks by rank, want 4 of the file", n)
}
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 spill that can't be written has each of its chunks made again: none is
// left without its archive.
func TestArchiveSpillFailedMadeAgain(t *testing.T) {
pageHome(t)
sp := newArchiveSpill()
c := &rowChunk{Archive: []byte("archive")}
if !sp.put(c, 7) {
t.Fatal("not put")
}
if c.Archive != nil {
t.Fatal("archive kept on the heap")
}
kept, next := *c, *c
sp.hand(&kept, &next)
sp.f.Close() // the flush fails
var made []int
sp.done(func(i int) *rowChunk {
made = append(made, i)
return &rowChunk{Archive: []byte("again")}
})
if !slices.Equal(made, []int{7}) {
t.Fatalf("made again %v, want [7]", made)
}
for _, c := range []*rowChunk{&kept, &next} {
if string(c.Archive) != "again" || c.mapped != nil {
t.Errorf("archive %q mapped %v, want the one made again, of the heap", c.Archive, c.mapped)
}
}
if _, err := os.Stat(sp.f.Name()); !os.IsNotExist(err) {
t.Errorf("spill left: %v", err)
}
}
+13 -4
View File
@@ -894,13 +894,15 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now time.Ti
want[s.Path] = s
}
}
var spill *archiveSpill
if len(want) >= requestDiskLeast {
idx.fromDisk(want)
spill = newArchiveSpill()
}
built, builtRows := 0, 0
// A file's rows are made by the reader that read it: made one after
// another, they were most of a cold build's wait (#3493).
read := prefetchEach(sources, stale, func() func(sessions.CallSource) *rowChunk {
makeChunk := func() func(sessions.CallSource) *rowChunk {
priceRow := pricers()
return func(s sessions.CallSource) *rowChunk {
cs := readSource(s)
@@ -918,7 +920,8 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now time.Ti
c.dict, c.shapeIDs = nil, nil // local chunks are immutable until the source changes
return c.pack()
}
})
}
read := prefetchEach(sources, stale, makeChunk)
for i, s := range sources {
on[s.Path] = true
if !since.IsZero() && s.Modified.Before(since) {
@@ -927,17 +930,23 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now time.Ti
// kept packed: the page reads a chunk's rows when it reaches them
// (chunkRows), not every file's at once
c := idx.chunks[s.Path]
put := false
if reused := c != nil && c.Source.Size == s.Size && c.Source.Modified.Equal(s.Modified); !reused {
c = read(i)
c.serial = nextChunkSerial()
built++
builtRows += c.Count
put = spill.put(c, i)
}
kept, next := *c, *c
kept.Used, next.Used = idx.tick, idx.tick
idx.chunks[s.Path] = &kept
chunks = append(chunks, &next)
if put {
spill.hand(&kept, &next)
}
}
spill.done(func(i int) *rowChunk { return makeChunk()(sources[i]) })
// the other computers' days (#542), a chunk each, read again only when
// sync brought a new copy
var others []*rowChunk
@@ -1032,7 +1041,7 @@ func (idx *requestIndex) keep(read *requestIndex, on map[string]bool) bool {
if prev != nil && prev.Used > c.Used {
continue
}
if prev != nil && prev.serial == c.serial && prev.mapped != nil && c.mapped == nil {
if prev != nil && prev.serial == c.serial && prev.pagesRank() > c.pagesRank() {
// copied before the file of it was written (save): its archive
// stays of the file's pages
next := *c
@@ -1105,7 +1114,7 @@ func (idx *requestIndex) save() {
// a read since has copied the chunk with a use of its own: the same
// chunk while its serial is
for path, c := range kept {
if cur := idx.chunks[path]; cur != nil && cur.serial == c.serial && cur.mapped == nil {
if cur := idx.chunks[path]; cur != nil && cur.serial == c.serial && cur.pagesRank() < 2 {
next := *cur
next.Archive, next.mapped = c.Archive, c.mapped
idx.chunks[path] = &next
+115
View File
@@ -0,0 +1,115 @@
package usage
import (
"bufio"
"os"
"path/filepath"
)
// archiveSpill holds the archives a large build makes in a file of their
// own as each chunk is made, and maps the file once the build is done:
// kept on the heap until save wrote requests-v1.bin, a cold build's 31MB
// of archives (15.7k sessions) were most of what its peak held over a warm
// start's, and Go let the heap grow past them by as much again (#3493).
// Nil where the system maps no file: the archives would be read back into
// the heap.
type archiveSpill struct {
f *os.File
w *bufio.Writer
off int
err error
held []spilled
}
// spilled is a chunk whose archive is in the spill, at off, n bytes long,
// and the copies of it the build hands on.
type spilled struct {
copies []*rowChunk
src int
off, n int
}
func newArchiveSpill() *archiveSpill {
if !mapsFiles {
return nil
}
return &archiveSpill{}
}
// put writes c's archive to the spill and lets go of it: true when it did.
// i is c's source, for done to make it again.
func (sp *archiveSpill) put(c *rowChunk, i int) bool {
if sp == nil || sp.err != nil || len(c.Archive) == 0 || c.mapped != nil {
return false
}
if sp.f == nil {
dir := filepath.Dir(requestDiskPath())
if sp.err = os.MkdirAll(dir, 0o700); sp.err != nil {
return false
}
if sp.f, sp.err = os.CreateTemp(dir, "requests-*.spill"); sp.err != nil {
return false
}
sp.w = bufio.NewWriterSize(sp.f, 1<<20)
}
if _, sp.err = sp.w.Write(c.Archive); sp.err != nil {
return false
}
sp.held = append(sp.held, spilled{src: i, off: sp.off, n: len(c.Archive)})
sp.off += len(c.Archive)
c.Archive = nil
return true
}
// hand records the copies of the chunk put last, which done gives its
// archive.
func (sp *archiveSpill) hand(copies ...*rowChunk) {
sp.held[len(sp.held)-1].copies = copies
}
// done gives every chunk put its archive back, of the spill's pages. When
// the spill can't be written or mapped, each is made again with build from
// its source: none is left without one.
func (sp *archiveSpill) done(build func(int) *rowChunk) {
if sp == nil || sp.f == nil {
return
}
defer os.Remove(sp.f.Name())
err := sp.err
if err == nil {
err = sp.w.Flush()
}
if closeErr := sp.f.Close(); err == nil {
err = closeErr
}
var m *diskMapping
if err == nil {
if mm, ok := mapDiskFile(sp.f.Name()); ok && len(mm.data) == sp.off {
m = mm
m.spill = true
}
}
for _, s := range sp.held {
var archive []byte
if m != nil {
archive = m.data[s.off : s.off+s.n : s.off+s.n]
} else {
archive = build(s.src).Archive
}
for _, c := range s.copies {
c.Archive, c.mapped = archive, m
}
}
}
// pagesRank orders where a chunk's archive is: the heap, a build's spill,
// requests-v1.bin. A copy of the same chunk takes the later.
func (c *rowChunk) pagesRank() int {
switch {
case c.mapped == nil:
return 0
case c.mapped.spill:
return 1
}
return 2
}