From f2eb56c6bbde1300dddc402861b59cd4e45e0215 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 31 Oct 2026 03:12:19 +0800 Subject: [PATCH] usage: a first start pairs the history a few weeks at a time, not at once (#2278) With no sums on disk (a first install, or a version that counts rows otherwise), the page's cells, the heatmap's days and Codex's effort before the cut were built from one pairing of the whole history. Every gateway block was priced, every session row's message id went into one set, and every call into one match map. On the owner's history that was ~212 MB of the warm-up's 341 MB in use and the cold start's peak. coldSpans builds them as a day's start advances them (pageAdvance), 14 days at a time. A span pairs the chunks with a row from heatReach before it to heatReach after. Each chunk's oldest row is kept by its serial. A gateway block not priced yet is priced by a pricer of the span alone, and its rows go back to the pool after the span. The recent days are then paired as on any kept start. The page's cells come out in another order (by span, then chunk), so TestSettledCountedAsVersioned now sorts them before it hashes. The sorted hash is the same for a pairing at once and in spans, so settledCountVersion stays. Tests that count a pairing of every chunk use pairAtOnce (coldSpan 0). Run on mote at the pushed head (rebased on b62fa332f): gofmt -l clean; go vet ./internal/usage for darwin, linux and windows ok; go test -count=1 ./internal/usage ok (20.0s); go build . ok. Broken by hand: TestFirstBuildPairsSpans goes red when a span pairs only its own days (lo, hi := from, to): the effort differs. Bench, real history (a year), cold first start, against v0.1.2256, two rounds each, on mote at load ~22: no GUI polls: footprint peak 451, 407 MB (2256: 493, 484); live heap max 318, 289 MB (2256: 367, 362) GUI polls: footprint peak 483, 410 MB (2256: 534, 532); live heap max 316, 290 MB (2256: 395, 406) The heatmap's answers are byte-equal to 2256's. The request page's differ only in float digits from the summation order (232 floats, largest relative difference 6.5e-14); every other value is equal. Not tried: a start on Windows or Linux. --- internal/usage/cold_split.go | 164 +++++++++++++++++++++++++ internal/usage/cold_split_test.go | 102 +++++++++++++++ internal/usage/cut_advance_test.go | 1 + internal/usage/effort_split.go | 16 +++ internal/usage/effort_split_test.go | 1 + internal/usage/heat_pairs_test.go | 2 + internal/usage/heatmap.go | 21 ++++ internal/usage/heatmap_test.go | 2 + internal/usage/page_split.go | 15 +++ internal/usage/page_split_test.go | 1 + internal/usage/request_pairs_test.go | 1 + internal/usage/settled_version_test.go | 13 +- 12 files changed, 337 insertions(+), 2 deletions(-) create mode 100644 internal/usage/cold_split.go create mode 100644 internal/usage/cold_split_test.go diff --git a/internal/usage/cold_split.go b/internal/usage/cold_split.go new file mode 100644 index 000000000..df9f12e63 --- /dev/null +++ b/internal/usage/cold_split.go @@ -0,0 +1,164 @@ +package usage + +import ( + "sync" + "time" +) + +// A first start, with no sums kept on disk, built the page's cells, the +// heatmap's days and Codex's effort before the cut from one pairing of +// the whole history: every gateway call priced, every session row's +// message id in one set, every call matched in one map, ~210 MB of a +// ~355 MB live heap and a ~500 MB footprint on a year's history (#2278). +// They are built as a day's start advances them (pageAdvance), a few +// weeks of history at a time: a span's chunks are those with a row a +// pairing of it reaches, and each span's pairing is let go before the +// next. + +// coldSpan is the days of history a first build pairs at a time. Zero +// pairs them all at once (tests compare the two). +var coldSpan = 14 + +// coldSpanning, in tests, is told how many chunks each span pairs. +var coldSpanning func(chunks int) + +// coldSpans calls fn for each span of days from since, or the day of the +// oldest row of sets, to cut, with the chunks of sets a pairing of that +// span reaches: those with a row from heatReach before it to heatReach +// after. A gateway block not priced yet is priced for its span alone, and +// let go after it. False: coldSpan is zero, and fn was not called. +func coldSpans(since, cut time.Time, sets [3][]*rowChunk, fn func(from, to time.Time, span [3][]*rowChunk)) bool { + if coldSpan <= 0 { + return false + } + first := chunkFirsts(sets) + oldest := time.Time{} + for _, set := range sets { + for _, c := range set { + if at := first(c); !at.IsZero() && (oldest.IsZero() || at.Before(oldest)) { + oldest = at + } + } + } + from := since + if oldest.IsZero() { + from = cut + } else if day := time.Date(oldest.Year(), oldest.Month(), oldest.Day(), 0, 0, 0, 0, cut.Location()); from.Before(day) { + from = day + } + for from.Before(cut) { + to := time.Date(from.Year(), from.Month(), from.Day()+coldSpan, 0, 0, 0, 0, cut.Location()) + if to.After(cut) { + to = cut + } + lo, hi := from.Add(-heatReach), to.Add(heatReach) + var span [3][]*rowChunk + alone := map[*blockPricer]*blockPricer{} + for k, set := range sets { + for _, c := range set { + at := first(c) + if at.IsZero() || c.Latest.Before(lo) || !at.Before(hi) { + continue + } + if b := c.lazy; b != nil { + // priced into a copy: the query's stub stays one, and + // the span's priced rows go back to the pool after it + if alone[b] == nil { + alone[b] = b.alone() + } + copy := *c + copy.lazy = alone[b] + c = © + } + span[k] = append(span[k], c) + } + } + if coldSpanning != nil { + coldSpanning(chunksIn(span)) + } + fn(from, to, span) + for _, b := range alone { + b.release() + } + from = to + } + return true +} + +// alone is a pricer of b's prices that keeps the blocks it prices to +// itself, until release. +func (b *blockPricer) alone() *blockPricer { + o := *b + o.shared, o.held, o.pooled = false, nil, nil + return &o +} + +// chunkFirsts is the time of each chunk's oldest row, zero for one with +// none. A named chunk's is kept by its serial: the page, the heatmap and +// Codex's effort each ask it of every chunk. +func chunkFirsts(sets [3][]*rowChunk) func(*rowChunk) time.Time { + firsts.Lock() + firsts.turn++ + turn := firsts.turn + if firsts.by == nil { + firsts.by = map[uint64]chunkFirst{} + } + for k, kept := range firsts.by { + if kept.turn+hintsKept < turn { + delete(firsts.by, k) + } + } + firsts.Unlock() + rows := lentRows() + known := map[*rowChunk]time.Time{} + for _, set := range sets { + for _, c := range set { + if c.Latest.IsZero() { + continue + } + if c.serial != 0 { + firsts.Lock() + kept, ok := firsts.by[c.serial] + if ok { + kept.turn = turn + firsts.by[c.serial] = kept + } + firsts.Unlock() + if ok { + known[c] = kept.at + continue + } + } + read := c + if c.lazy != nil { + read = c.raw // the block's times are its priced copy's + } + var at time.Time + open := rows.of(read) + for i := range open.Rows { + if t := open.Rows[i].Time; at.IsZero() || t.Before(at) { + at = t + } + } + known[c] = at + if c.serial != 0 { + firsts.Lock() + firsts.by[c.serial] = chunkFirst{at: at, turn: turn} + firsts.Unlock() + } + } + } + rows.release() + return func(c *rowChunk) time.Time { return known[c] } +} + +type chunkFirst struct { + at time.Time + turn uint64 +} + +var firsts struct { + sync.Mutex + by map[uint64]chunkFirst + turn uint64 +} diff --git a/internal/usage/cold_split_test.go b/internal/usage/cold_split_test.go new file mode 100644 index 000000000..9a52b2b9e --- /dev/null +++ b/internal/usage/cold_split_test.go @@ -0,0 +1,102 @@ +package usage + +import ( + "os" + "path/filepath" + "reflect" + "testing" + "time" + + "github.com/yetone/magpie/internal/sessions" +) + +// pairAtOnce has a first build pair every chunk at once, for the tests +// of what a pairing of all of them is told apart from. +func pairAtOnce(t *testing.T) { + span := coldSpan + coldSpan = 0 + t.Cleanup(func() { coldSpan = span }) +} + +// A first start pairs the history a few weeks at a time, not at once +// (#2278), and builds the page, the heatmap and Codex's effort a pairing +// of every chunk does: a call whose gateway row is after a span's end is +// paired, and a span pairs only the chunks it reaches. +func TestFirstBuildPairsSpans(t *testing.T) { + yesterday, _ := advanceHistory(t) + // a call just before midnight, its gateway row just after + at := time.Date(2026, 9, 23, 23, 59, 30, 0, time.Local) + path := filepath.Join(sessions.CodexDir(), "sessions", at.Format("2006/01/02"), "rollout-"+at.Format("2006-01-02T15-04-05")+"-z.jsonl") + writeCodexCall(t, path, "z", "sz", `"vscode"`, "resp-z", "m", "high", at, 300, 30) + Append(Record{Time: at.Add(time.Minute), Agent: "codex", Provider: "openai", Model: "m", Input: 300, Output: 30, Status: 200, ResponseID: "resp-z", Session: "sz"}) + // a call through magpie alone, 30 days back + Append(Record{Time: yesterday.AddDate(0, 0, -30), Agent: "claude-code", Provider: "anthropic", Model: "c", Input: 50, Output: 5, Status: 200}) + restart := func() { + requestCache.Lock() + requestCache.parts, requestCache.pageOld, requestCache.heatParts, requestCache.heatOld, requestCache.heats, requestCache.pairs, requestCache.pages = nil, nil, nil, nil, nil, nil, map[pageKey]RequestPage{} + requestCache.Unlock() + codexEffort.Lock() + codexEffort.periods = map[Period]*effortEntry{} + codexEffort.Unlock() + codexEffortBuilding.Lock() + effortOlds = map[Period]*effortOld{} + codexEffortBuilding.Unlock() + for _, path := range []string{pageDiskPath(), heatDiskPath(), effortDiskPath()} { + os.Remove(path) + } + } + restart() + t.Cleanup(restart) + type built struct { + page RequestPage + heat Heatmap + effort map[string][]sessions.ModelEffort + written bool + } + build := func() built { + var b built + b.page = QueryPage(All, Filter{}, 0, 50) + b.heat = HeatmapOf(Filter{}) + b.effort = CodexModelEffort(All) + _, page := os.Stat(pageDiskPath()) + _, heat := os.Stat(heatDiskPath()) + _, effort := os.Stat(effortDiskPath()) + b.written = page == nil && heat == nil && effort == nil + return b + } + paired := []int{} + pageSplitting = func(n int) { paired = append(paired, n) } + whole := build() + pageSplitting = nil + if !whole.written || len(paired) == 0 { + t.Fatal("a pairing of every chunk wrote no sums") + } + all := paired[0] + for _, days := range []int{1, 14} { + coldSpan = days + restart() + spans := []int{} + coldSpanning = func(n int) { spans = append(spans, n) } + got := build() + coldSpanning = nil + if !got.written { + t.Fatalf("%d days a span: no sums written", days) + } + if len(spans) < 2 { + t.Fatalf("%d days a span: %d spans", days, len(spans)) + } + pairedBelow(t, "a span", spans, 0, all) + if !reflect.DeepEqual(got.page, whole.page) { + t.Fatalf("%d days a span: page %+v, paired at once %+v", days, got.page, whole.page) + } + if !reflect.DeepEqual(got.heat, whole.heat) { + t.Fatalf("%d days a span: heatmap %+v, paired at once %+v", days, got.heat, whole.heat) + } + if !reflect.DeepEqual(got.effort, whole.effort) { + t.Fatalf("%d days a span: effort %+v, paired at once %+v", days, got.effort, whole.effort) + } + } + if whole.page.Total != 9 { + t.Fatalf("page: %d rows", whole.page.Total) + } +} diff --git a/internal/usage/cut_advance_test.go b/internal/usage/cut_advance_test.go index af3da5384..c71504516 100644 --- a/internal/usage/cut_advance_test.go +++ b/internal/usage/cut_advance_test.go @@ -17,6 +17,7 @@ import ( // and not in the next day's, which begins a week later. func advanceHistory(t *testing.T) (yesterday, today time.Time) { pageHome(t) + pairAtOnce(t) yesterday = holdClock(t, time.Date(2026, 10, 4, 12, 0, 0, 0, time.Local)) for i, days := range []int{368, 40, 20, 10, 5, 2, 0} { id := string(rune('a' + i)) diff --git a/internal/usage/effort_split.go b/internal/usage/effort_split.go index 2d4d4a0fd..ae7a29d3e 100644 --- a/internal/usage/effort_split.go +++ b/internal/usage/effort_split.go @@ -133,6 +133,8 @@ func effortSplit(sums effortSums, p Period, now time.Time, gateways, chunks, oth old, kept = &effortOld{root: disk.root, cut: cut, since: since, settled: serials, before: before, at: time.Now(), key: key, sums: s}, true } else if s, found := effortAdvance(disk, cut, since, until, identities, sets, key); found { old, kept = &effortOld{root: disk.root, cut: cut, since: since, settled: serials, before: before, at: time.Now(), key: key, sums: s}, true + } else if s, found := effortCold(cut, since, identities, sets, key); found { + old, kept = &effortOld{root: disk.root, cut: cut, since: since, settled: serials, before: before, at: time.Now(), key: key, sums: s}, true } } if !kept { @@ -166,6 +168,20 @@ func effortSplit(sums effortSums, p Period, now time.Time, gateways, chunks, oth return true } +// effortCold is the effort from since to cut, of a pairing a few weeks +// at a time (coldSpans), written under key; or false. +func effortCold(cut, since time.Time, identities map[string]sessions.CodexIdentity, sets [3][]*rowChunk, key string) (map[string][]sessions.ModelEffort, bool) { + part := effortSums{} + if !coldSpans(since, cut, sets, func(from, to time.Time, span [3][]*rowChunk) { + pairRowsIn(from, to, span[0], span[1], span[2], identities).visitActors(part.add) + }) { + return nil, false + } + sums := part.values() + _ = effortDiskWrite(key, cut, since, sums) + return sums, true +} + // effortAdvance is the effort before cut, from the file's effort before // an earlier cut counted under the same key there and a pairing of the // chunks of the days between, written under key; or false. diff --git a/internal/usage/effort_split_test.go b/internal/usage/effort_split_test.go index 4f7a252b4..c2cf25e5f 100644 --- a/internal/usage/effort_split_test.go +++ b/internal/usage/effort_split_test.go @@ -14,6 +14,7 @@ import ( // pairs only the recent chunks, and tells the same effort a pairing of // every chunk does. A settled file changed, or no file, pairs them all. func TestCodexEffortSettledFromDisk(t *testing.T) { + pairAtOnce(t) pageHome(t) now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local)) write := func(id string, at time.Time, input int) string { diff --git a/internal/usage/heat_pairs_test.go b/internal/usage/heat_pairs_test.go index ad0330cea..dfb039d86 100644 --- a/internal/usage/heat_pairs_test.go +++ b/internal/usage/heat_pairs_test.go @@ -15,6 +15,7 @@ import ( // footprint's peaks (#2278). Only the heatmap's recent days are paired // again for it. func TestHeatmapPairsAsAllDoes(t *testing.T) { + pairAtOnce(t) for _, heatFirst := range []bool{false, true} { name := "page first" if heatFirst { @@ -66,6 +67,7 @@ func TestHeatmapPairsAsAllDoes(t *testing.T) { // chunks of its own serials, so none was the pairing's the one before // had paired. func TestBigBuildsBegunTogetherPairOnce(t *testing.T) { + pairAtOnce(t) pageHome(t) settleLogClock(t) now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local)) diff --git a/internal/usage/heatmap.go b/internal/usage/heatmap.go index 858b5e0a7..533fe47ec 100644 --- a/internal/usage/heatmap.go +++ b/internal/usage/heatmap.go @@ -367,6 +367,8 @@ func heatSplit(since, now time.Time, gateways, chunks, others []*rowChunk, f Fil old, kept = &heatOld{cut: cut, settled: serials, at: time.Now(), days: days, before: before, key: key}, true } else if days, found := heatAdvance(cache.disk, cut, since, now, f, identities, sets, key); found { old, kept = &heatOld{cut: cut, settled: serials, at: time.Now(), days: days, before: before, key: key}, true + } else if days, found := heatCold(cut, since, now, f, identities, sets, key); found { + old, kept = &heatOld{cut: cut, settled: serials, at: time.Now(), days: days, before: before, key: key}, true } } } @@ -452,6 +454,25 @@ func heatAdvance(d heatDiskRef, cut, since, now time.Time, f Filter, identities return days, true } +// heatCold is the days from since to cut, of a pairing a few weeks at a +// time (coldSpans), written under key; or false. +func heatCold(cut, since, now time.Time, f Filter, identities map[string]sessions.CodexIdentity, sets [3][]*rowChunk, key string) ([]Day, bool) { + all := heatDays{} + if !coldSpans(since, cut, sets, func(from, to time.Time, span [3][]*rowChunk) { + end := to.Format(time.DateOnly) + for _, day := range pairRowsIn(from, to, span[0], span[1], span[2], identities).heatDaysOf(from, now, f, nil, identities, nil) { + if day.Date < end { + all.addDay(day) + } + } + }) { + return nil, false + } + days := all.list() + _ = heatDiskWrite(key, cut, since, days) + return days, true +} + // heatPairing, in tests, is told how many chunks heatSplit pairs. var heatPairing func(chunks int) diff --git a/internal/usage/heatmap_test.go b/internal/usage/heatmap_test.go index 9b96b7736..d858c43a4 100644 --- a/internal/usage/heatmap_test.go +++ b/internal/usage/heatmap_test.go @@ -198,6 +198,7 @@ func TestHeatmapAfterACallAddsUpOnlyWhatChanged(t *testing.T) { // session file of old and new calls, and the pairing kept no longer than // heatOldFresh, or once a settled file changes. func TestHeatmapAfterACallPairsOnlyTheLastDays(t *testing.T) { + pairAtOnce(t) pageHome(t) now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local)) cut := time.Date(2026, 9, 28, 0, 0, 0, 0, time.Local) @@ -332,6 +333,7 @@ func TestHeatmapAfterACallPairsOnlyTheLastDays(t *testing.T) { // the whole history's pairing was the cold start's peak. A settled file // changed since, or another filter, pairs every chunk again. func TestHeatmapSettledDaysFromDisk(t *testing.T) { + pairAtOnce(t) pageHome(t) now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local)) write := func(id string, at time.Time, input int) string { diff --git a/internal/usage/page_split.go b/internal/usage/page_split.go index 46a8807cf..9e0cd4ae4 100644 --- a/internal/usage/page_split.go +++ b/internal/usage/page_split.go @@ -84,6 +84,8 @@ func pageSplit(p Period, f Filter, now time.Time, take int, pass *cellPass, gate old, kept = &pageOld{cut: cut, since: since, settled: serials, before: before, at: time.Now(), key: key, cells: c}, true } else if c, found := pageAdvance(cache.disk, cut, since, until, f, pass, identities, sets, key); found { old, kept = &pageOld{cut: cut, since: since, settled: serials, before: before, at: time.Now(), key: key, cells: c}, true + } else if c, found := pageCold(cut, since, pass, identities, sets, key); found { + old, kept = &pageOld{cut: cut, since: since, settled: serials, before: before, at: time.Now(), key: key, cells: c}, true } } } @@ -172,6 +174,19 @@ func pageAdvance(d heatDiskRef, cut, since, until time.Time, f Filter, pass *cel return nil, false } +// pageCold is a page's cells before cut from since, of a pairing a few +// weeks at a time (coldSpans), written under key; or false. +func pageCold(cut, since time.Time, pass *cellPass, identities map[string]sessions.CodexIdentity, sets [3][]*rowChunk, key string) (*chunkPart, bool) { + cells := &chunkPart{} + if !coldSpans(since, cut, sets, func(from, to time.Time, span [3][]*rowChunk) { + cells = addCells(cells, pairRowsIn(from, to, span[0], span[1], span[2], identities).cellsBefore(pass, to)) + }) { + return nil, false + } + _ = pageDiskWrite(key, cut, since, cells) + return cells, true +} + // addCells is the cells of a and of b, the later, as one part: a cell of // the same names, bits and bucket added up, in the order of their last. func addCells(a, b *chunkPart) *chunkPart { diff --git a/internal/usage/page_split_test.go b/internal/usage/page_split_test.go index 6abf74877..1f79c10db 100644 --- a/internal/usage/page_split_test.go +++ b/internal/usage/page_split_test.go @@ -68,6 +68,7 @@ func TestPageSettledFromDisk(t *testing.T) { // settled is the 20-day call's file; restart drops what a start doesn't // have. func pageHistory(t *testing.T) (now time.Time, settled string, paired *[]int, restart func()) { + pairAtOnce(t) pageHome(t) now = holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local)) for i, days := range []int{40, 20, 10, 5, 0} { diff --git a/internal/usage/request_pairs_test.go b/internal/usage/request_pairs_test.go index 6984f0f70..b7d72aa4b 100644 --- a/internal/usage/request_pairs_test.go +++ b/internal/usage/request_pairs_test.go @@ -49,6 +49,7 @@ func TestRequestPairsReusedAcrossPages(t *testing.T) { // the effort read after it paired them all over (#3493). It is the effort // a pairing of its own gives. func TestCodexEffortReusesPagePairing(t *testing.T) { + pairAtOnce(t) pageHome(t) now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local)) dir := filepath.Join(sessions.CodexDir(), "sessions", "2026", "09", "30") diff --git a/internal/usage/settled_version_test.go b/internal/usage/settled_version_test.go index c34451412..a80d96e1f 100644 --- a/internal/usage/settled_version_test.go +++ b/internal/usage/settled_version_test.go @@ -1,11 +1,13 @@ package usage import ( + "bytes" "crypto/sha256" "encoding/json" "fmt" "os" "path/filepath" + "slices" "testing" "time" @@ -16,7 +18,7 @@ import ( // settled days, under settledCountVersion. A change that counts them // otherwise changes it: raise settledCountVersion and set this to the new // hash in the same commit. -const settledCounted = "f8a4cfb6f86c4145176efcbe1c879631849e1ee9d87987c182cd921b95acc2a8" +const settledCounted = "d7ac763fc3c86fa5e0061f7025974d9c18d5c0fca1305bbf1488139a1fbad51e" // The settled days, a page's cells and Codex's effort are kept on disk // under settledCountVersion, not under this package's source: an upgrade @@ -74,9 +76,16 @@ func TestSettledCountedAsVersioned(t *testing.T) { read(pageDiskPath(), &pages) read(heatDiskPath(), &heat) read(effortDiskPath(), &effort) - // when and under what they were counted, not how + // when and under what they were counted, not how; and the cells in + // one order, as a first build a few weeks at a time adds them up in + // another for i := range pages { pages[i].Key, pages[i].At, pages[i].Cut, pages[i].Since = "", time.Time{}, time.Time{}, time.Time{} + slices.SortFunc(pages[i].Cells, func(a, b pageDiskCell) int { + x, _ := json.Marshal(a) + y, _ := json.Marshal(b) + return bytes.Compare(x, y) + }) } if len(pages) == 0 || len(heat.Days) == 0 || len(effort.Sums) == 0 { t.Fatalf("kept %d pages, %d days, %d threads' effort", len(pages), len(heat.Days), len(effort.Sums))