usage: a cold start's builds find the pairing the build before them made (#2278)

On a cold start the page of the month, the page of All, Codex's effort
and the heatmap read the history side by side and pair it in turn
(holdBigBuild). Each one missed the pairing the one before had kept
(pairMemo), and paired the whole history again beside it. On the real
history (469 gateway blocks, 16619 session chunks) every big build
missed; the warm All page's miss had a memo whose session serials all
differed (16619 of 16619).

Three things kept them apart:

- A session file's chunk got a serial from a counter each time a read
  built it. The builds read the same files together and share one build
  of each (sharedBuild), but each named its copy apart. A chunk's
  serial is now made from what it is made of: the file's path, size
  and mtime under the index's root and meta (sourceSerial), the same
  in a build and in a chunk read back from requests-v1.bin. The top
  bit keeps it apart from a counted serial (gateway blocks, other
  computers' days). The caches keyed by serial (cells, fold ids, match
  hints, message keys) hold what a chunk's rows give, so a chunk of
  the same file and meta reads the same from them.
- A build took the last pairing when it began, before waiting its
  turn. It now takes it once it has the turn (lastPairs).
- A build kept its pairing after it let the turn go, so the build
  that waited took its turn first and found none. It now keeps it
  while still holding the turn (keepPairsFor). The memo is kept
  though the build's index isn't: it stands only for chunks of its
  serials.

TestBigBuildsBegunTogetherPairOnce starts the page of All and the
heatmap together over a gateway log and eight session files, both
having read their rows before either pairs: two pairings, every row
once and the heatmap's recent days.

Broken by hand, the test is red (3 pairings) with any one of the three
undone: the counted serial back, the memo taken before the turn, the
memo not kept.

Run at this head, rebased on e31ccf230, on mote: go test -timeout 45m
./internal/usage/ (ok 16.3s; 52.9s at 2f65a33aa) and ./internal/usageapi/ (ok); gofmt -l
clean; GOOS=linux, windows and darwin go vet ./internal/usage/
./internal/usageapi/ ok. ./internal/gui/ was run at 2f65a33aa: the AppKit
real-window tests (TestMainWindowCorners, TestPanelCloseHidesIt, the
Dock and tray ones) hit their 20-80s deadlines on mote, which has no
window session for them (#4125, #2645); nothing in the GUI changed.
GOOS=linux go vet ./internal/gui/ stops in Wails' cgo files, as a cross
build without cgo does.

On mote, the real history, a true cold start (caches deleted), 240 s
polled as the Usage page polls: phys_footprint_peak 551, 553, 548 MB
against v0.1.2213's 607 (592-628 in earlier runs), CPU 3:50-4:08 against
3:40, under load ~27 from other sessions. An instrumented build logs
one pairing of All, then hits for the rest (30d, then All miss, All
hit, All hit). A restart with the caches kept: 317 MB against 341, CPU
10.5 s against 10.5 s. The peak left is Codex's effort pairing All
(~150 MB) while the page of the month, under bigBuildRows, pairs its
own beside it (~80 MB); not changed here.
This commit is contained in:
yetone
2026-10-30 22:49:35 +08:00
parent a6e7d40421
commit 18b63fe5f8
3 changed files with 110 additions and 12 deletions
+49
View File
@@ -1,8 +1,12 @@
package usage
import (
"path/filepath"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/sessions"
)
// The heatmap's year and the whole history's page pair the same chunks
@@ -54,3 +58,48 @@ func TestHeatmapPairsAsAllDoes(t *testing.T) {
})
}
}
// Big builds that began together take the pairing the one before them
// made while they waited their turn (holdBigBuild): each took the memo
// when it began, found none, and a cold start paired the whole history
// once for each of them (#2278). Each also read the session files with
// chunks of its own serials, so none was the pairing's the one before
// had paired.
func TestBigBuildsBegunTogetherPairOnce(t *testing.T) {
pageHome(t)
settleLogClock(t)
now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local))
historyLog(t, 400)
for i := range 8 {
at := now.AddDate(0, 0, -20*i).Add(-time.Hour)
id := string(rune('a' + i))
path := filepath.Join(sessions.CodexDir(), "sessions", at.Format("2006/01/02"), "rollout-"+at.Format("2006-01-02T15-04-05")+"-"+id+".jsonl")
writeCodexCall(t, path, id, "s"+id, `"vscode"`, "resp-"+id, "m", "low", at, 100+i, 10)
}
rows := bigBuildRows
bigBuildRows = 1
t.Cleanup(func() { bigBuildRows = rows })
var mu sync.Mutex
n := 0
pairing = func() {
mu.Lock()
n++
mu.Unlock()
}
t.Cleanup(func() { pairing = nil })
// both have read their rows before either pairs them
var began sync.WaitGroup
began.Add(2)
building = func() {
began.Done()
began.Wait()
}
t.Cleanup(func() { building = nil })
var wg sync.WaitGroup
wg.Go(func() { QueryPage(All, Filter{}, 0, 50) })
wg.Go(func() { HeatmapOf(Filter{}) })
wg.Wait()
if n != 2 {
t.Fatalf("paired %d times, want 2: every row once, and the heatmap's recent days", n)
}
}
+1 -1
View File
@@ -370,7 +370,7 @@ func (idx *requestIndex) fromDisk(want map[string]sessions.CallSource) {
return true
}
c.Source = s
c.serial = nextChunkSerial()
c.serial = sourceSerial(idx.root, idx.meta, s)
c.used = useAt(idx.tick)
idx.chunks[s.Path] = c
return true
+60 -11
View File
@@ -880,7 +880,17 @@ func queryPageOf(p Period, f Filter, offset, limit int, readSource func(sessions
}
func() {
defer holdBigBuild(b.gateways, b.chunks, b.others)() // on a panic too
memo := p
if p == heatmapPeriod {
memo = All
}
if cache != nil {
cache.pairs = shared.lastPairs(idx, memo)
}
page = buildRequestBlocksIn(p, f, offset, limit, now, b.gateways, b.chunks, b.others, names, codexIdentities, cache)
if cache != nil && (p != heatmapPeriod || cache.pairsNext != nil) {
shared.keepPairsFor(idx, memo, cache.pairsNext)
}
}()
ownStrings(reflect.ValueOf(&page).Elem())
b.priced.release()
@@ -899,15 +909,11 @@ func queryPageOf(p Period, f Filter, offset, limit int, readSource func(sessions
shared.heatOld = map[partKey]*heatOld{}
}
shared.heatOld[pk] = cache.heatOldNext
if cache.pairsNext != nil {
shared.keepPairs(All, cache.pairsNext)
}
} else if cache != nil {
if shared.parts == nil || len(shared.parts) >= partSets && shared.parts[pk] == nil {
shared.parts = map[partKey]map[uint64]*chunkPart{}
}
shared.parts[pk] = cache.next
shared.keepPairs(p, cache.pairsNext)
if shared.pageOld == nil || len(shared.pageOld) >= partSets && shared.pageOld[pk] == nil {
shared.pageOld = map[partKey]*pageOld{}
}
@@ -938,9 +944,6 @@ func codexEffortOfIndex(st requestState, p Period, now time.Time) map[string][]s
shared.Lock()
shared.keepWhileAsked()
shared.adopt(st)
// the page of p just before, the warm-up's of All, paired these rows:
// a build after it paired every session file's calls again (#3493)
memo := shared.pairs[p]
idx := shared.private()
shared.Unlock()
b := readRequestBlocks(idx, st, p, now, settledBefore(now), sessions.ReadCallSource, true)
@@ -950,6 +953,10 @@ func codexEffortOfIndex(st requestState, p Period, now time.Time) map[string][]s
paired := false
func() {
defer holdBigBuild(b.gateways, b.chunks, b.others)()
// the page of p just before, the warm-up's of All, paired these
// rows: a build after it paired every session file's calls again
// (#3493)
memo := shared.lastPairs(idx, p)
full := func() *pairedRows {
var ps *pairedRows
ps, next = pairRowsMemo(p, now, b.gateways, b.chunks, b.others, st.codexIdentities, memo)
@@ -959,14 +966,14 @@ func codexEffortOfIndex(st requestState, p Period, now time.Time) map[string][]s
if !effortSplit(sums, p, now, b.gateways, b.chunks, b.others, st.codexIdentities, heatDiskRef{root: st.root, meta: st.meta}, full) {
full().visitActors(func(r *Row) { sums.add(r) })
}
if paired {
shared.keepPairsFor(idx, p, next)
}
}()
b.priced.release()
shared.Lock()
if shared.keep(idx, b.on) {
shared.noteBuilt(b)
if paired {
shared.keepPairs(p, next)
}
shared.trim(requestCacheBytes)
}
shared.Unlock()
@@ -1144,7 +1151,7 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now, settle
put := false
if reused := c != nil && c.Source.Size == s.Size && c.Source.Modified.Equal(s.Modified); !reused {
c = read(i)
c.serial = nextChunkSerial()
c.serial = sourceSerial(st.root, st.meta, s)
built++
builtRows += c.Count
c.used = useAt(idx.tick)
@@ -1203,6 +1210,48 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now, settle
// adopt drops what idx keeps of a state other than st: every chunk when
// what prices or names a call changed (meta), the pages when anything
// did (key). idx is locked.
// sourceSerial names a session file's chunk by what it is made of: the
// file's path, size and mtime under the index's root and meta, as a read reuses
// a chunk it keeps and joins another query's build of it (sharedBuild).
// A serial of each read's own made a cold start's builds, which read the
// files side by side, name every chunk apart: none found the pairing the
// one before it made (pairMemo), and the whole history was paired once
// for each, the footprint's peak (#2278). Its top bit keeps it apart from
// a counted one.
func sourceSerial(root, meta string, s sessions.CallSource) uint64 {
h := sha256.New()
fmt.Fprintf(h, "%s\x00%s\x00%s\x00%d\x00%d", root, meta, s.Path, s.Size, s.Modified.UnixNano())
return binary.BigEndian.Uint64(h.Sum(nil)) | 1<<63
}
// lastPairs is p's last pairing for read, idx's private copy, taken once
// the build of read has its turn (holdBigBuild). Taken when it began, a
// cold start's page of the month, heatmap, page of All and Codex's effort
// each found none, as they began together and paired in turn: the whole
// history was paired three times, each beside what the last kept, the
// footprint's peak (#2278). idx is not locked.
func (idx *requestIndex) lastPairs(read *requestIndex, p Period) *pairMemo {
idx.Lock()
defer idx.Unlock()
if idx.root != read.root || idx.meta != read.meta {
return nil
}
return idx.pairs[p]
}
// keepPairsFor keeps memo as p's last pairing for read, idx's private
// copy, while the build of read still has its turn (holdBigBuild): kept
// once it let go, as the page was, the build that had waited for it took
// its turn first and found none (#2278). The memo is kept though read
// isn't, as it stands only for chunks of its serials. idx is not locked.
func (idx *requestIndex) keepPairsFor(read *requestIndex, p Period, memo *pairMemo) {
idx.Lock()
defer idx.Unlock()
if idx.root == read.root && idx.meta == read.meta {
idx.keepPairs(p, memo)
}
}
// keepPairs keeps memo as p's last pairing (nil: there is none to keep).
func (idx *requestIndex) keepPairs(p Period, memo *pairMemo) {
if idx.pairs == nil || len(idx.pairs) >= partSets && idx.pairs[p] == nil {