diff --git a/internal/usage/heat_disk.go b/internal/usage/heat_disk.go new file mode 100644 index 000000000..99921ac0e --- /dev/null +++ b/internal/usage/heat_disk.go @@ -0,0 +1,164 @@ +package usage + +import ( + "crypto/sha256" + "encoding/binary" + "encoding/json" + "fmt" + "hash" + "math" + "os" + "path/filepath" + "time" + + "github.com/yetone/magpie/internal/sessions" +) + +// The heatmap's settled days are kept on disk between runs (heat-v1.json). +// A started magpie paired the whole history for them, every gateway call +// with its session row, and so again every heatOldFresh: the cold start's +// peak, ~100 MB of a ~450 MB live heap, and seconds of CPU each time +// (#2278). They stand while what they were counted of is the same, which +// heatSettledKey names: the settled chunks, the recent chunks' rows before +// the cut, the threads' identities, the filter and the days, the code that +// counts them and what prices and names a call. + +func heatDiskPath() string { + return filepath.Join(filepath.Dir(sessions.CachePath()), "heat-v1.json") +} + +// heatDiskEntry is the file: the key it was counted under and the days. +type heatDiskEntry struct { + Key string `json:"key"` + Days []Day `json:"days"` +} + +// heatDiskRead is the days the file holds under key, or false. +func heatDiskRead(key string) ([]Day, bool) { + b, err := os.ReadFile(heatDiskPath()) + if err != nil { + return nil, false + } + var e heatDiskEntry + if json.Unmarshal(b, &e) != nil || e.Key != key { + return nil, false + } + return e.Days, true +} + +// heatDiskWrite keeps days under key, through a file renamed over the last. +func heatDiskWrite(key string, days []Day) error { + b, err := json.Marshal(heatDiskEntry{Key: key, Days: days}) + if err != nil { + return err + } + path := heatDiskPath() + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + out, err := os.CreateTemp(filepath.Dir(path), ".heat-*.json") + if err != nil { + return err + } + defer os.Remove(out.Name()) + _, err = out.Write(b) + if closeErr := out.Close(); err == nil { + err = closeErr + } + if err != nil { + return err + } + return os.Rename(out.Name(), path) +} + +// heatSettledKey names what the days before cut were counted of. A +// session file's chunk is named as requests-v1.bin names it, by its path, +// size and mtime under the same code, root and meta; any other chunk by +// its rows. False: the chunks can't be named so (a probe's chunk made +// again for each query). +func heatSettledKey(d heatDiskRef, cut, since time.Time, f Filter, identities map[string]sessions.CodexIdentity, settled [3][]*rowChunk, before heatSum) (string, bool) { + if d.root == "" { + return "", false + } + h := sha256.New() + fmt.Fprintf(h, "heat-v1\x00%s\x00%s\x00%s\x00%d\x00%d\x00%s\x00%#v\x00%d:%d:%d\x00", + requestDiskBinary(), d.root, d.meta, cut.UnixNano(), since.UnixNano(), cut.Location(), f, before.n, before.at, before.tokens) + hashCodexIdentities(h, identities) + var b []byte + rows := lentRows() + defer rows.release() + for k, set := range settled { + for _, c := range set { + if c.serial == 0 { + return "", false + } + b = fmt.Appendf(b[:0], "\x01%d\x00%s\x00%d\x00%d\x00%s\x00%d\x00", k, c.Computer, c.Count, c.Latest.UnixNano(), c.Source.Path, c.Source.Size) + if c.Source.Path != "" { + b = binary.AppendVarint(b, c.Source.Modified.UnixNano()) + h.Write(b) + continue + } + h.Write(b) + hashRows(h, rows.of(c)) + } + } + return fmt.Sprintf("%x", h.Sum(nil)), true +} + +// hashRows writes an unpacked chunk's rows into h, each field as a number +// and each string as written: a row's time holds a pointer, its padding +// isn't written by every copy, and a chunk packed and the same unpacked +// number their strings and shapes apart. A shape is written where a row +// first has it, and by that row after. +func hashRows(h hash.Hash, c *rowChunk) { + b := make([]byte, 0, 32<<10) + text := func(i uint32) { + s := "" + if int(i) < len(c.Strings) { + s = c.Strings[i] + } + b = binary.AppendUvarint(b, uint64(len(s))) + b = append(b, s...) + } + shapes := map[uint32]int{} + for i := range c.Rows { + p := &c.Rows[i] + b = binary.AppendVarint(b, p.Time.UnixNano()) + for _, v := range p.Varied { + text(v) + } + if first, ok := shapes[p.Shape]; ok { + b = binary.AppendUvarint(b, uint64(first)) + } else { + shapes[p.Shape] = i + b = binary.AppendUvarint(b, uint64(i)) + if int(p.Shape) < len(c.Shapes) { + for _, v := range c.Shapes[p.Shape] { + text(v) + } + } + } + for _, t := range p.Tokens { + b = binary.AppendVarint(b, t) + } + b = binary.AppendVarint(b, p.Order) + b = binary.AppendVarint(b, p.RouteID) + b = binary.AppendUvarint(b, math.Float64bits(p.Cost)) + b = binary.AppendUvarint(b, math.Float64bits(p.Credits)) + for _, v := range [...]int32{p.Millis, p.TTFT, p.FirstText, p.Sent, p.Flow, p.FirstReasoning, p.Own, p.Retried, p.Queued, p.Masking, p.Status, p.Tries} { + b = binary.AppendVarint(b, int64(v)) + } + b = binary.AppendUvarint(b, uint64(p.Flags)) + if len(b) > 30<<10 { + h.Write(b) + b = b[:0] + } + } + h.Write(b) +} + +// heatDiskRef is where a heatmap's settled days are kept and what prices +// and names its calls: the index's root and meta. Empty, they aren't kept. +type heatDiskRef struct { + root, meta string +} diff --git a/internal/usage/heatmap.go b/internal/usage/heatmap.go index db8c2d753..4f78b4fc7 100644 --- a/internal/usage/heatmap.go +++ b/internal/usage/heatmap.go @@ -207,7 +207,9 @@ const ( // 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. +// file written again or a thread's identity learnt, shows within this: +// the days are named again (heatSettledKey), and counted again only when +// the name changed. var heatOldFresh = 10 * time.Minute // heatOld is the heatmap's days before cut, from a pairing of every @@ -222,6 +224,8 @@ type heatOld struct { parts map[uint64]*chunkPart // before is the recent chunks' rows before cut, which days counts before heatSum + // key names what days were counted of (heatSettledKey); "" unnamed + key string } // heatSum is a sum of rows as read, to tell a change in them. @@ -292,7 +296,23 @@ func heatSplit(since, now time.Time, gateways, chunks, others []*rowChunk, f Fil 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 { + var key string + named := false + kept := ok && old != nil && old.cut.Equal(cut) && slices.Equal(old.settled, serials) && old.before == before && time.Since(old.at) < heatOldFresh + if ok && !kept { + // the days are counted again only when what they were counted of + // changed: kept, or on disk from the last run + if key, named = heatSettledKey(cache.disk, cut, since, f, identities, settled, before); named { + if old != nil && old.key == key && old.cut.Equal(cut) && old.before == before { + fresh := *old + fresh.settled, fresh.at = serials, time.Now() + old, kept = &fresh, true + } else if days, found := heatDiskRead(key); found { + old, kept = &heatOld{cut: cut, settled: serials, at: time.Now(), days: days, before: before, key: key}, true + } + } + } + if !kept { if heatPairing != nil { heatPairing(len(gateways) + len(chunks) + len(others)) } @@ -305,7 +325,13 @@ func heatSplit(since, now time.Time, gateways, chunks, others []*rowChunk, f Fil 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} + next := &heatOld{cut: cut, settled: serials, at: time.Now(), days: slices.Clip(days[:n]), parts: parts, before: before} + if named { + next.key = key + // not written, the days are counted again on the next start + _ = heatDiskWrite(key, next.days) + } + cache.heatOldNext = next } return heatmapFrom(since, now, days) } diff --git a/internal/usage/heatmap_test.go b/internal/usage/heatmap_test.go index bc0068398..bb90c75bd 100644 --- a/internal/usage/heatmap_test.go +++ b/internal/usage/heatmap_test.go @@ -237,6 +237,7 @@ func TestHeatmapAfterACallPairsOnlyTheLastDays(t *testing.T) { requestCache.Lock() requestCache.heatParts, requestCache.heatOld, requestCache.heats, requestCache.pages = nil, nil, nil, map[pageKey]RequestPage{} requestCache.Unlock() + os.Remove(heatDiskPath()) return HeatmapOf(Filter{}) } first := HeatmapOf(Filter{}) @@ -309,13 +310,75 @@ func TestHeatmapAfterACallPairsOnlyTheLastDays(t *testing.T) { if !reflect.DeepEqual(warm, cold()) { t.Fatalf("a settled file changed: %+v, cold %+v", warm, cold()) } - // past heatOldFresh every chunk is paired again + // past heatOldFresh the days are named again, and paired again only + // when what they were counted of changed: a thread's identity learnt 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) + if paired[before] >= all { + t.Fatalf("past heatOldFresh with nothing changed, paired %d of %d", paired[before], all) + } + write("forked-id", now.AddDate(0, 0, -15), 8) + before = len(paired) + if warm := next(); paired[before] < all || !reflect.DeepEqual(warm, cold()) { + t.Fatalf("past heatOldFresh with a settled file new, paired %d of %d", paired[before], all) + } +} + +// A started magpie takes the heatmap's settled days from the last run's +// pairing of every chunk, and pairs only the last days' chunks (#2278): +// 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) { + 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 { + 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 + } + var settled string + for i, days := range []int{40, 20, 10, 5, 0} { + id := string(rune('a' + i)) + at := now.AddDate(0, 0, -days).Add(-time.Hour) + path := write(id, at, 100+i) + if days == 20 { + settled = path + } + Append(Record{Time: at.Add(time.Minute), Agent: "codex", Provider: "openai", Model: "m", Input: 100 + i, Output: 10, Status: 200, ResponseID: "resp-" + id, Session: "s" + id}) + } + paired := []int{} + heatPairing = func(n int) { paired = append(paired, n) } + t.Cleanup(func() { heatPairing = nil }) + restart := func() { + requestCache.Lock() + requestCache.heatParts, requestCache.heatOld, requestCache.heats, requestCache.pages = nil, nil, nil, map[pageKey]RequestPage{} + requestCache.Unlock() + } + first := HeatmapOf(Filter{}) + all := paired[0] + if _, err := os.Stat(heatDiskPath()); err != nil { + t.Fatal(err) + } + restart() + if again := HeatmapOf(Filter{}); paired[len(paired)-1] >= all || !reflect.DeepEqual(again, first) { + t.Fatalf("started again, paired %d of %d: %+v, was %+v", paired[len(paired)-1], all, again, first) + } + restart() + if HeatmapOf(Filter{Model: "m"}); paired[len(paired)-1] < all { + t.Fatalf("another filter paired %d of %d", paired[len(paired)-1], all) + } + writeCodexCall(t, settled, "b", "sb", `"vscode"`, "resp-b", "m", "low", now.AddDate(0, 0, -20).Add(-time.Hour), 1001, 10) + restart() + changed := HeatmapOf(Filter{}) + if paired[len(paired)-1] < all { + t.Fatalf("a settled file changed, paired %d of %d", paired[len(paired)-1], all) + } + restart() + os.Remove(heatDiskPath()) + if cold := HeatmapOf(Filter{}); !reflect.DeepEqual(cold, changed) { + t.Fatalf("after a settled file changed %+v, cold %+v", changed, cold) } } diff --git a/internal/usage/request_cells.go b/internal/usage/request_cells.go index 7c3891e3c..a2140b817 100644 --- a/internal/usage/request_cells.go +++ b/internal/usage/request_cells.go @@ -108,6 +108,8 @@ type partCache struct { // heatOld is the heatmap's days before its last few the page before // kept, and heatOldNext this page's (heatSplit) heatOld, heatOldNext *heatOld + // disk is where heatSplit keeps its settled days between runs + disk heatDiskRef } // 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 a760ff2c3..1993c1243 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -788,7 +788,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{}, heatOld: idx.heatOld[pk]} + cache = &partCache{old: idx.heatParts[pk], next: map[uint64]*chunkPart{}, heatOld: idx.heatOld[pk], disk: heatDiskRef{root: idx.root, meta: idx.meta}} } else if p.Last() == 0 { cache = &partCache{old: idx.parts[pk], next: map[uint64]*chunkPart{}, pairs: idx.pairs[p]} }