diff --git a/internal/usage/heatmap.go b/internal/usage/heatmap.go index 6c2b0d80e..db8c2d753 100644 --- a/internal/usage/heatmap.go +++ b/internal/usage/heatmap.go @@ -149,12 +149,21 @@ func heatmapFrom(since, now time.Time, days []Day) *Heatmap { // read every row of the year again for it, and paired them: ~4 GB a // minute and seconds of CPU a refresh while an agent worked (#2278). func (ps *pairedRows) heatOf(since, now time.Time, f Filter, cache *partCache, identities map[string]sessions.CodexIdentity) *Heatmap { + return heatmapFrom(since, now, ps.heatDaysOf(since, now, f, cache, identities, nil)) +} + +// heatDaysOf is heatOf's days, oldest first, each with a call, of the +// chunks of ps that only keeps (nil: all). +func (ps *pairedRows) heatDaysOf(since, now time.Time, f Filter, cache *partCache, identities map[string]sessions.CodexIdentity, only func(*rowChunk) bool) []Day { sigs := ps.sigs(identities) var rows chunkRows defer rows.release() var r Row all := heatDays{} for _, c := range ps.all { + if only != nil && !only(c) { + continue + } sig := sigs[c] var part *chunkPart if cache != nil && c.serial != 0 { @@ -181,8 +190,151 @@ func (ps *pairedRows) heatOf(since, now time.Time, f Filter, cache *partCache, i all.addDay(d) } } + return all.list() +} + +// heatRecent is how many days before today the heatmap pairs again for a +// call (heatSplit), and heatReach how far before them a chunk's newest +// call can be and still be paired with one of theirs: the gateway's calls +// are read from a day before a period (gatewaySince), the other +// computers' days from two. +const ( + heatRecent = 2 + heatReach = 48 * time.Hour +) + +// heatOldFresh is how long heatSplit keeps the days before its last few +// while only the chunks of those days change. A session file a call is +// written to now can hold older calls too, and those are taken to stay as +// they were: an agent appends to its file. What changes them anyway, a +// file written again or a thread's identity learnt, shows within this. +var heatOldFresh = 10 * time.Minute + +// heatOld is the heatmap's days before cut, from a pairing of every +// chunk, while settled, the serials of the chunks with no call since +// heatReach before cut, are the same. parts are the other chunks' sums +// from cut on, as the last pairing of them paired them. +type heatOld struct { + cut time.Time + settled []uint64 + at time.Time + days []Day + parts map[uint64]*chunkPart + // before is the recent chunks' rows before cut, which days counts + before heatSum +} + +// heatSum is a sum of rows as read, to tell a change in them. +type heatSum struct { + n int + at, tokens int64 +} + +// heatBefore is the sum of the recent chunks' rows before cut: a recent +// chunk can hold calls of the days before (a session file copied in, a +// rollout forked from an old one), and they change the days the last +// pairing of every chunk counted. +func heatBefore(cut time.Time, recent [3][]*rowChunk) heatSum { + rows := lentRows() + defer rows.release() + var s heatSum + for _, set := range recent { + for _, c := range set { + open := rows.of(c) + for i := range open.Rows { + if pr := &open.Rows[i]; pr.Time.Before(cut) { + s.n++ + s.at += pr.Time.UnixNano() + for _, t := range pr.Tokens { + s.tokens += t + } + } + } + } + } + return s +} + +// heatSplit is heatOf of the rows of every chunk, paired. A call through +// magpie changes the gateway's newest block and a session file, and the +// heatmap paired a year of calls again for it: ~1.8 s and most of the +// GC of each refresh of the Usage page while an agent worked (#2278). The +// days before the last heatRecent are taken from the last pairing of +// every chunk while the chunks that could change them are the same, and +// only the chunks of the days since are paired again, as a page of those +// days pairs them. +func heatSplit(since, now time.Time, gateways, chunks, others []*rowChunk, f Filter, identities map[string]sessions.CodexIdentity, cache *partCache) *Heatmap { + cut := time.Date(now.Year(), now.Month(), now.Day()-heatRecent, 0, 0, 0, 0, now.Location()) + edge := cut.Add(-heatReach) + isRecent := func(c *rowChunk) bool { return c.Latest.IsZero() || !c.Latest.Before(edge) } + if cache == nil || !cut.After(since) { + return heatmapFrom(since, now, pairRows(heatmapPeriod, now, gateways, chunks, others, identities).heatDaysOf(since, now, f, cache, identities, nil)) + } + var recent, settled [3][]*rowChunk + for k, set := range [3][]*rowChunk{gateways, chunks, others} { + for _, c := range set { + if isRecent(c) { + recent[k] = append(recent[k], c) + } else { + settled[k] = append(settled[k], c) + } + } + } + // recentDays adds up the recent chunks' rows from cut on, paired as + // the next call pairs them, into parts + recentDays := func(old, parts map[uint64]*chunkPart) []Day { + ps := pairRowsIn(cut, heatmapPeriod.Until(now), recent[0], recent[1], recent[2], identities) + return ps.heatDaysOf(cut, now, f, &partCache{old: old, next: parts}, identities, nil) + } + serials, ok := pairSerials(settled[0], settled[1], settled[2]) + old := cache.heatOld + var before heatSum + if ok { + before = heatBefore(cut, recent) + } + if !ok || old == nil || !old.cut.Equal(cut) || !slices.Equal(old.settled, serials) || old.before != before || time.Since(old.at) >= heatOldFresh { + if heatPairing != nil { + heatPairing(len(gateways) + len(chunks) + len(others)) + } + days := pairRows(heatmapPeriod, now, gateways, chunks, others, identities).heatDaysOf(since, now, f, cache, identities, nil) + if ok { + n, _ := slices.BinarySearchFunc(days, cut.Format(time.DateOnly), func(d Day, day string) int { return strings.Compare(d.Date, day) }) + parts := map[uint64]*chunkPart{} + var kept map[uint64]*chunkPart + if old != nil { + kept = old.parts + } + recentDays(kept, parts) + cache.heatOldNext = &heatOld{cut: cut, settled: serials, at: time.Now(), days: slices.Clip(days[:n]), parts: parts, before: before} + } + return heatmapFrom(since, now, days) + } + next := *old + next.parts = map[uint64]*chunkPart{} + cache.heatOldNext = &next + // the settled chunks' sums stay kept for the next pairing of them all + for _, set := range settled { + for _, c := range set { + if part := cache.old[c.serial]; part != nil { + cache.next[c.serial] = part + } + } + } + all := heatDays{} + for _, d := range old.days { + all.addDay(d) + } + if heatPairing != nil { + heatPairing(len(recent[0]) + len(recent[1]) + len(recent[2])) + } + for _, d := range recentDays(old.parts, next.parts) { + all.addDay(d) + } return heatmapFrom(since, now, all.list()) } +// heatPairing, in tests, is told how many chunks heatSplit pairs. +var heatPairing func(chunks int) + // heatReading, in tests, is told each chunk heatOf adds up again. var heatReading func(*rowChunk) diff --git a/internal/usage/heatmap_test.go b/internal/usage/heatmap_test.go index 89888083c..bc0068398 100644 --- a/internal/usage/heatmap_test.go +++ b/internal/usage/heatmap_test.go @@ -1,7 +1,10 @@ package usage import ( + "bytes" + "fmt" "math" + "os" "path/filepath" "reflect" "testing" @@ -157,6 +160,8 @@ func TestHeatmapAfterACallAddsUpOnlyWhatChanged(t *testing.T) { writeCodexCall(t, path, id, "s"+id, `"vscode"`, "resp-"+id, "m", "low", at, 100+i, 10) } Append(Record{Time: now.AddDate(0, 0, -40), Agent: "claude-code", Provider: "anthropic", Model: "x", Input: 3, Status: 200}) + // the gateway is in use: its log has a call of the last days already + Append(Record{Time: now.AddDate(0, 0, -1), Agent: "claude-code", Provider: "anthropic", Model: "x", Input: 4, Status: 200}) read := 0 heatReading = func(*rowChunk) { read++ } t.Cleanup(func() { heatReading = nil }) @@ -167,22 +172,150 @@ func TestHeatmapAfterACallAddsUpOnlyWhatChanged(t *testing.T) { } return n } - if h := HeatmapOf(Filter{}); calls(h) != files+1 || read < files { + if h := HeatmapOf(Filter{}); calls(h) != files+2 || read < files { t.Fatalf("cold: %d calls, %d chunks added up", calls(h), read) } read = 0 Append(Record{Time: now.Add(-time.Minute), Agent: "claude-code", Provider: "anthropic", Model: "x", Input: 5, Status: 200}) warm := HeatmapOf(Filter{}) - if calls(warm) != files+2 { + if calls(warm) != files+3 { t.Fatalf("a call through magpie isn't counted at once: %d calls", calls(warm)) } if read > 1 { t.Fatalf("a call added up %d chunks again, want only the one it changed", read) } requestCache.Lock() - requestCache.heatParts, requestCache.heats, requestCache.pages = nil, nil, map[pageKey]RequestPage{} + requestCache.heatParts, requestCache.heatOld, requestCache.heats, requestCache.pages = nil, nil, nil, map[pageKey]RequestPage{} requestCache.Unlock() if cold := HeatmapOf(Filter{}); !reflect.DeepEqual(cold, warm) { t.Fatalf("kept sums %+v, cold %+v", warm, cold) } } + +// A call through magpie pairs again only the chunks of the last days: the +// days before are the last pairing's of every chunk (#2278). What it shows +// is what a cold build shows, with calls paired across the days' edge, a +// 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) { + 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) + write := func(id string, at time.Time, input int) string { + 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, input, 10) + return path + } + // the gateway's calls of the session files' own: each counted once + gateway := func(id string, at time.Time, input int) { + Append(Record{Time: at, Agent: "codex", Provider: "openai", Model: "m", Input: input, Output: 10, Status: 200, ResponseID: "resp-" + id, Session: "s" + id}) + } + // a full block of the gateway's log whose newest call is before cut, + // the call of a session file's row after it + for range logBlockRows - 1 { + Append(Record{Time: now.AddDate(0, 0, -30), Agent: "claude-code", Provider: "anthropic", Model: "x", Input: 1, Status: 200}) + } + gateway("x", cut.Add(-time.Minute), 120) + write("x", cut.Add(time.Minute), 120) + for i, at := range []time.Time{now.AddDate(0, 0, -40), now.AddDate(0, 0, -10), now.AddDate(0, 0, -5), cut.Add(-time.Minute), cut.Add(time.Minute), now.Add(-time.Hour)} { + id := string(rune('a' + i)) + write(id, at, 100+i) + if i%2 == 1 { + // two minutes on: the call at cut-1m is the gateway's after cut + gateway(id, at.Add(2*time.Minute), 100+i) + } + } + settledFile := write("old", now.AddDate(0, 0, -20), 7) + for i := range 6 { + write(fmt.Sprintf("o%d", i), now.AddDate(0, 0, -12-3*i), 5) + } + Append(Record{Time: now.AddDate(0, 0, -60), Agent: "claude-code", Provider: "anthropic", Model: "x", Input: 3, Status: 200}) + paired := []int{} + heatPairing = func(n int) { paired = append(paired, n) } + t.Cleanup(func() { heatPairing = nil }) + cold := func() Heatmap { + requestCache.Lock() + requestCache.heatParts, requestCache.heatOld, requestCache.heats, requestCache.pages = nil, nil, nil, map[pageKey]RequestPage{} + requestCache.Unlock() + return HeatmapOf(Filter{}) + } + first := HeatmapOf(Filter{}) + if len(paired) != 1 { + t.Fatalf("paired %v", paired) + } + all := paired[0] + call := 0 + next := func() Heatmap { + call++ + gateway(fmt.Sprintf("new%d", call), now.Add(-time.Duration(call)*time.Second), 50) + return HeatmapOf(Filter{}) + } + for range 3 { + warm := next() + if n := paired[len(paired)-1]; n >= all/2 { + t.Fatalf("a call paired %d of %d chunks again", n, all) + } + if c := cold(); !reflect.DeepEqual(warm, c) { + t.Fatalf("after the last days' pairing %+v, cold %+v", warm, c) + } + } + if reflect.DeepEqual(first, cold()) { + t.Fatal("the calls weren't counted") + } + // a session file of the last days that holds a call of the days before + write("e", cut.Add(time.Minute), 104) + path := filepath.Join(sessions.CodexDir(), "sessions", cut.Add(-30*time.Hour).Format("2006/01/02"), "rollout-"+cut.Add(-30*time.Hour).Format("2006-01-02T15-04-05")+"-mixed.jsonl") + writeCodexCall(t, path, "mixed", "smixed", `"vscode"`, "resp-mixed-old", "m", "low", cut.Add(-30*time.Hour), 9, 1) + cold() + writeCodexCall(t, path, "mixed", "smixed", `"vscode"`, "resp-mixed-new", "m", "low", now.Add(-time.Minute), 9, 1) + if warm := next(); !reflect.DeepEqual(warm, cold()) { + t.Fatalf("a file of old and new calls: %+v, cold %+v", warm, cold()) + } + // a new session file that holds a call of last week too (a rollout + // forked from an old one): its call of then is counted + next() // kept: the pairing the call below starts from + scratch := t.TempDir() + writeCodexCall(t, filepath.Join(scratch, "then"), "fork", "sfork", `"vscode"`, "resp-fork-then", "m", "low", now.AddDate(0, 0, -7), 30, 3) + writeCodexCall(t, filepath.Join(scratch, "now"), "fork", "sfork", `"vscode"`, "resp-fork-now", "m", "low", now.Add(-2*time.Minute), 31, 3) + then, err := os.ReadFile(filepath.Join(scratch, "then")) + if err != nil { + t.Fatal(err) + } + later, err := os.ReadFile(filepath.Join(scratch, "now")) + if err != nil { + t.Fatal(err) + } + _, later, _ = bytes.Cut(later, []byte("\n")) // its session_meta is then's + // the session began then + then = bytes.Replace(then, []byte(`"2026-09-30T10:00:00Z"`), []byte(`"`+now.AddDate(0, 0, -7).Add(-time.Minute).UTC().Format(time.RFC3339)+`"`), 1) + forked := filepath.Join(sessions.CodexDir(), "sessions", now.Format("2006/01/02"), "rollout-"+now.Add(-2*time.Minute).Format("2006-01-02T15-04-05")+"-fork.jsonl") + if os.WriteFile(forked, append(then, later...), 0600) != nil { + t.Fatal("fork") + } + if warm := next(); !reflect.DeepEqual(warm, cold()) { + t.Fatalf("a new file with a call of last week: %+v, cold %+v", warm, cold()) + } + // a settled file written again: every chunk is paired again + next() + writeCodexCall(t, settledFile, "old", "sold", `"vscode"`, "resp-old", "m", "low", now.AddDate(0, 0, -20), 70, 10) + if os.Chtimes(settledFile, now.AddDate(0, 0, -20), now.AddDate(0, 0, -20)) != nil { + t.Fatal("chtimes") + } + before := len(paired) + warm := next() + if paired[before] < all { + t.Fatalf("a settled file changed, paired %d of %d", paired[before], all) + } + if !reflect.DeepEqual(warm, cold()) { + t.Fatalf("a settled file changed: %+v, cold %+v", warm, cold()) + } + // past heatOldFresh every chunk is paired again + old := heatOldFresh + heatOldFresh = 0 + t.Cleanup(func() { heatOldFresh = old }) + before = len(paired) + next() + if paired[before] < all { + t.Fatalf("past heatOldFresh, paired %d of %d", paired[before], all) + } +} diff --git a/internal/usage/request_cells.go b/internal/usage/request_cells.go index 1dc9a6d3f..fdfa82ea6 100644 --- a/internal/usage/request_cells.go +++ b/internal/usage/request_cells.go @@ -105,6 +105,9 @@ type partCache struct { old, next map[uint64]*chunkPart // pairs is the last pairing of the period, and pairsNext this page's pairs, pairsNext *pairMemo + // heatOld is the heatmap's days before its last few the page before + // kept, and heatOldNext this page's (heatSplit) + heatOld, heatOldNext *heatOld } // partSets bounds the partKeys kept: a page is open on one period and diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index 0aadaf5a9..fc4781a15 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -539,6 +539,8 @@ type requestIndex struct { // heatParts are the heatmap's sums of each chunk (heatOf), kept as // parts are but apart, so that the heatmap's never push a page's out heatParts map[partKey]map[uint64]*chunkPart + // heatOld are the heatmap's days before its last few (heatSplit) + heatOld map[partKey]*heatOld // pairs are the last pairing of each of a few periods (pairMemo), // kept as parts are pairs map[Period]*pairMemo @@ -775,7 +777,7 @@ func queryPageOf(p Period, f Filter, offset, limit int, readSource func(sessions var cache *partCache pk := partKey{p: p, f: f, since: p.Since(now), until: p.Until(now), loc: now.Location()} if p == heatmapPeriod { - cache = &partCache{old: idx.heatParts[pk], next: map[uint64]*chunkPart{}} + cache = &partCache{old: idx.heatParts[pk], next: map[uint64]*chunkPart{}, heatOld: idx.heatOld[pk]} } else if p.Last() == 0 { cache = &partCache{old: idx.parts[pk], next: map[uint64]*chunkPart{}, pairs: idx.pairs[p]} } @@ -805,6 +807,10 @@ func queryPageOf(p Period, f Filter, offset, limit int, readSource func(sessions shared.heatParts = map[partKey]map[uint64]*chunkPart{} } shared.heatParts[pk] = cache.next + if shared.heatOld == nil || len(shared.heatOld) >= partSets && shared.heatOld[pk] == nil { + shared.heatOld = map[partKey]*heatOld{} + } + shared.heatOld[pk] = cache.heatOldNext } else if cache != nil { if shared.parts == nil || len(shared.parts) >= partSets && shared.parts[pk] == nil { shared.parts = map[partKey]map[uint64]*chunkPart{} @@ -1073,6 +1079,7 @@ func (idx *requestIndex) adopt(st requestState) { idx.heats = nil idx.parts = nil idx.heatParts = nil + idx.heatOld = nil idx.pairs = nil idx.key = "" } @@ -1804,6 +1811,11 @@ type pairedRows struct { var pairing func() func pairRows(p Period, now time.Time, gateways, chunks, others []*rowChunk, identities map[string]sessions.CodexIdentity) *pairedRows { + return pairRowsIn(p.Since(now), p.Until(now), gateways, chunks, others, identities) +} + +// pairRowsIn is pairRows over the rows from since to until. +func pairRowsIn(since, until time.Time, gateways, chunks, others []*rowChunk, identities map[string]sessions.CodexIdentity) *pairedRows { if pairing != nil { pairing() } @@ -1819,7 +1831,6 @@ func pairRows(p Period, now time.Time, gateways, chunks, others []*rowChunk, ide for ref := range duplicateSkip { skip[ref] = true } - since, until := p.Since(now), p.Until(now) matched := matchedBlocks(gateways, chunks, skip, pairs, since, true) for gateway, local := range pairs { setCodexActor(gateway.Chunk, gateway.Index, local.Chunk.codexActors.at(local.Index)) @@ -1873,21 +1884,21 @@ func buildRequestBlocksOf(p Period, f Filter, offset, limit int, now time.Time, // cache's for the chunks it has them for (nil: every chunk's read). func buildRequestBlocksIn(p Period, f Filter, offset, limit int, now time.Time, gateways, chunks, others []*rowChunk, names map[string]string, identities map[string]sessions.CodexIdentity, cache *partCache) RequestPage { since := p.Since(now) - var ps *pairedRows - if cache != nil && p != heatmapPeriod { - ps, cache.pairsNext = pairRowsMemo(p, now, gateways, chunks, others, identities, cache.pairs) - } else { - ps = pairRows(p, now, gateways, chunks, others, identities) - } - out := RequestPage{Rows: []Row{}, Agents: []string{}, Providers: []string{}, Purposes: []string{}, By: map[string][]Share{}} chartFilter := f chartFilter.Day = "" // The heatmap's page is only its days, all HeatmapOf reads: over its // year the groups, shares and series below took seconds a call (#3493). if p == heatmapPeriod { - out.Heat = ps.heatOf(since, now, chartFilter, cache, identities) - return out + return RequestPage{Rows: []Row{}, Agents: []string{}, Providers: []string{}, Purposes: []string{}, By: map[string][]Share{}, + Heat: heatSplit(since, now, gateways, chunks, others, chartFilter, identities, cache)} } + var ps *pairedRows + if cache != nil { + ps, cache.pairsNext = pairRowsMemo(p, now, gateways, chunks, others, identities, cache.pairs) + } else { + ps = pairRows(p, now, gateways, chunks, others, identities) + } + out := RequestPage{Rows: []Row{}, Agents: []string{}, Providers: []string{}, Purposes: []string{}, By: map[string][]Share{}} agents, providers := map[string]bool{}, map[string]bool{} kinds := map[string]bool{} callers := map[string]*Group{}