diff --git a/internal/usage/page_split.go b/internal/usage/page_split.go new file mode 100644 index 000000000..44004c16f --- /dev/null +++ b/internal/usage/page_split.go @@ -0,0 +1,291 @@ +package usage + +import ( + "cmp" + "crypto/sha256" + "encoding/json" + "fmt" + "os" + "path/filepath" + "slices" + "time" + "unique" + + "github.com/yetone/magpie/internal/sessions" +) + +// A page's cells of the rows before its last few days are kept as the +// heatmap's days are (heatSplit), in memory and in page-v1.json beside the +// sessions cache. A start's first page of All, the warm-up's, paired the +// whole history for them, every gateway call with its session row: after +// the heatmap's days and Codex's effort were kept, ~85 MB of a ~320 MB +// heap, and the Usage page's own first page paired it again beside it +// (#2278). Only the chunks of the days since cut are paired again, while +// what the cells before were counted of is the same and the page's rows +// are among theirs. + +// pageOld is a page's cells of the rows before cut, from a pairing of +// every chunk, named as heatOld is. parts are the recent chunks' cells +// from cut on, as the last pairing of them paired them. +type pageOld struct { + cut, since time.Time + settled []uint64 + before heatSum + at time.Time + key string + cells *chunkPart + parts map[uint64]*chunkPart +} + +// pageSplitting, in tests, is told how many chunks a split page pairs. +var pageSplitting func(chunks int) + +// pageSplit is the cells of a page of p at now read through pass, the +// pairing its newest rows are read from and that pairing's cells, in its +// all's order. False: the page can't be split so (p begins after cut or +// ends before it, its chunks can't be named, or fewer than take rows the +// filter keeps are since cut), and nothing was paired for the page. +func pageSplit(p Period, f Filter, now time.Time, take int, pass *cellPass, gateways, chunks, others []*rowChunk, identities map[string]sessions.CodexIdentity, cache *partCache) (cells []*chunkPart, ps *pairedRows, newest []*chunkPart, ok bool) { + since, until := p.Since(now), p.Until(now) + cut := time.Date(now.Year(), now.Month(), now.Day()-heatRecent, 0, 0, 0, 0, now.Location()) + if cache.disk.root == "" || !cut.After(since) || !until.IsZero() && !until.After(cut) { + return nil, nil, nil, false + } + edge := cut.Add(-heatReach) + var recent, settled [3][]*rowChunk + for k, set := range [3][]*rowChunk{gateways, chunks, others} { + for _, c := range set { + if c.Latest.IsZero() || !c.Latest.Before(edge) { + recent[k] = append(recent[k], c) + } else { + settled[k] = append(settled[k], c) + } + } + } + serials, named := pairSerials(settled[0], settled[1], settled[2]) + if !named { + return nil, nil, nil, false + } + before := heatBefore(cut, recent) + old := cache.pageOld + same := func(o *pageOld) bool { + return o != nil && o.cut.Equal(cut) && o.since.Equal(since) && o.before == before + } + kept := same(old) && slices.Equal(old.settled, serials) && time.Since(old.at) < heatOldFresh + key := "" + if !kept { + k, named := heatSettledKey(cache.disk, cut, since, f, identities, settled, before) + if !named { + return nil, nil, nil, false + } + key = fmt.Sprintf("%x", sha256.Sum256(fmt.Appendf(nil, "page-v1\x00%d\x00%t\x00%t\x00%s", until.UnixNano(), pass.names, pass.hours, k))) + switch { + case same(old) && old.key == key: + fresh := *old + fresh.settled, fresh.at = serials, time.Now() + old, kept = &fresh, true + default: + if c, found := pageDiskRead(key); found { + old, kept = &pageOld{cut: cut, since: since, settled: serials, before: before, at: time.Now(), key: key, cells: c}, true + } + } + } + if !kept { + if pageSplitting != nil { + pageSplitting(len(gateways) + len(chunks) + len(others)) + } + ps, cache.pairsNext = pairRowsMemo(p, now, gateways, chunks, others, identities, cache.pairs) + parts := ps.partsOf(pass, cache, identities) + next := &pageOld{cut: cut, since: since, settled: serials, before: before, at: time.Now(), key: key, cells: ps.cellsBefore(pass, cut)} + cache.pageOldNext = next + // not written, the cells are counted again on the next start + _ = pageDiskWrite(key, next.cells) + return parts, ps, parts, true + } + if pageSplitting != nil { + pageSplitting(len(recent[0]) + len(recent[1]) + len(recent[2])) + } + next := *old + next.parts = map[uint64]*chunkPart{} + ps = pairRowsIn(cut, until, recent[0], recent[1], recent[2], identities) + newest = ps.partsOf(pass, &partCache{old: old.parts, next: next.parts}, identities) + n := 0 + for _, part := range newest { + n += part.kept + } + if n < take { + // a page of rows older than cut: every chunk is paired for it + cache.pageOldNext = old + return nil, nil, nil, false + } + cache.pageOldNext = &next + // the pairing of every chunk is not this page's, and stays the next's + cache.pairsNext = cache.pairs + // the settled chunks' cells 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 + } + } + } + return append([]*chunkPart{old.cells}, newest...), ps, newest, true +} + +// cellsBefore is the cells of ps's rows before cut as one part: each +// chunk's, in all's order, a cell of the same names, bits and bucket +// added up, in the order of their last. +func (ps *pairedRows) cellsBefore(pass *cellPass, cut time.Time) *chunkPart { + before := *ps + before.until = cut + var rows chunkRows + defer rows.release() + var r Row + out := &chunkPart{} + at := map[pageCell]int{} + var last []int + seq := 0 + for _, c := range ps.all { + part := pass.part(&before, &rows, c, &r) + out.kept += part.kept + if !part.first.IsZero() && (out.first.IsZero() || part.first.Before(out.first)) { + out.first = part.first + } + for _, cell := range part.cells { + seq++ + k := cell + k.n, k.d = 0, Totals{} + i, ok := at[k] + if !ok { + i = len(out.cells) + at[k] = i + out.cells = append(out.cells, k) + last = append(last, 0) + } + out.cells[i].n += cell.n + out.cells[i].d.plus(&cell.d) + last[i] = seq + } + } + order := make([]int, len(out.cells)) + for i := range order { + order[i] = i + } + slices.SortFunc(order, func(a, b int) int { return cmp.Compare(last[a], last[b]) }) + cells := make([]pageCell, len(order)) + for i, j := range order { + cells[i] = out.cells[j] + } + out.cells = cells + return out +} + +func pageDiskPath() string { + return filepath.Join(filepath.Dir(sessions.CachePath()), "page-v1.json") +} + +// pageDiskCell is a pageCell as the file holds it. +type pageDiskCell struct { + Provider string `json:"p,omitempty"` + Agent string `json:"a,omitempty"` + Model string `json:"m,omitempty"` + Kind string `json:"k,omitempty"` + CallerID string `json:"ci,omitempty"` + CallerName string `json:"cn,omitempty"` + Account string `json:"ac,omitempty"` + Computer string `json:"co,omitempty"` + Source uint8 `json:"s,omitempty"` + Bits uint16 `json:"b,omitempty"` + Bucket int32 `json:"u,omitempty"` + N int `json:"n"` + D Totals `json:"d"` +} + +// pageDiskEntry is one page's cells, under the key they were counted +// under. +type pageDiskEntry struct { + Key string `json:"key"` + At time.Time `json:"at"` + Kept int `json:"kept"` + First time.Time `json:"first"` + Cells []pageDiskCell `json:"cells"` +} + +// pageDiskPages bounds the pages the file holds: a page is open on one +// period and filter, and the warm-up and the Sessions page ask for All's. +const pageDiskPages = partSets + +func pageDiskEntries() []pageDiskEntry { + b, err := os.ReadFile(pageDiskPath()) + if err != nil { + return nil + } + var all []pageDiskEntry + if json.Unmarshal(b, &all) != nil { + return nil + } + return all +} + +// pageDiskRead is the cells the file holds under key, or false. +func pageDiskRead(key string) (*chunkPart, bool) { + for _, e := range pageDiskEntries() { + if e.Key != key { + continue + } + part := &chunkPart{kept: e.Kept, cells: make([]pageCell, len(e.Cells))} + if !e.First.IsZero() { + part.first = e.First.In(time.Local) + } + for i, c := range e.Cells { + part.cells[i] = pageCell{ + provider: unique.Make(c.Provider), agent: unique.Make(c.Agent), model: unique.Make(c.Model), kind: unique.Make(c.Kind), + callerID: unique.Make(c.CallerID), callerName: unique.Make(c.CallerName), account: unique.Make(c.Account), computer: unique.Make(c.Computer), + source: c.Source, bits: c.Bits, bucket: c.Bucket, n: c.N, d: c.D, + } + } + return part, true + } + return nil, false +} + +// pageDiskWrite keeps part under key with the pages written last, through +// a file renamed over the last. +func pageDiskWrite(key string, part *chunkPart) error { + e := pageDiskEntry{Key: key, At: time.Now(), Kept: part.kept, First: part.first, Cells: make([]pageDiskCell, len(part.cells))} + for i := range part.cells { + c := &part.cells[i] + e.Cells[i] = pageDiskCell{ + Provider: c.provider.Value(), Agent: c.agent.Value(), Model: c.model.Value(), Kind: c.kind.Value(), + CallerID: c.callerID.Value(), CallerName: c.callerName.Value(), Account: c.account.Value(), Computer: c.computer.Value(), + Source: c.source, Bits: c.bits, Bucket: c.bucket, N: c.n, D: c.d, + } + } + all := []pageDiskEntry{e} + for _, o := range pageDiskEntries() { + if o.Key != key && len(all) < pageDiskPages { + all = append(all, o) + } + } + b, err := json.Marshal(all) + if err != nil { + return err + } + path := pageDiskPath() + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + out, err := os.CreateTemp(filepath.Dir(path), ".page-*.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) +} diff --git a/internal/usage/page_split_test.go b/internal/usage/page_split_test.go new file mode 100644 index 000000000..61085f347 --- /dev/null +++ b/internal/usage/page_split_test.go @@ -0,0 +1,89 @@ +package usage + +import ( + "os" + "path/filepath" + "reflect" + "testing" + "time" + + "github.com/yetone/magpie/internal/sessions" +) + +// A page's cells before the last days are kept in page-v1.json: a start +// pairs only the recent chunks for a page of the newest rows, and builds +// the page a pairing of every chunk does. A page of older rows, a +// settled file changed, or no file, pairs them all. +func TestPageSettledFromDisk(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{} + pageSplitting = func(n int) { paired = append(paired, n) } + t.Cleanup(func() { pageSplitting = nil }) + restart := func() { + requestCache.Lock() + requestCache.parts, requestCache.pageOld, requestCache.pairs, requestCache.pages = nil, nil, nil, map[pageKey]RequestPage{} + requestCache.Unlock() + } + restart() + t.Cleanup(restart) + first := QueryPage(All, Filter{}, 0, 1) + if len(paired) != 1 || len(first.Rows) != 1 || first.Total != 5 { + t.Fatalf("first page: pairings %v, %d rows of %d", paired, len(first.Rows), first.Total) + } + all := paired[0] + if _, err := os.Stat(pageDiskPath()); err != nil { + t.Fatal(err) + } + restart() + if again := QueryPage(All, Filter{}, 0, 1); 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) + } + // the fourth newest is older than cut: none of the recent chunks has it + restart() + n := len(paired) + deep := QueryPage(All, Filter{}, 3, 1) + if len(paired) != n+1 || len(deep.Rows) != 1 || deep.Rows[0].Input != 101 { + t.Fatalf("a page of older rows: pairings %v, rows %+v", paired[n:], deep.Rows) + } + restart() + os.Remove(pageDiskPath()) + pageSplitting = nil + if cold := QueryPage(All, Filter{}, 3, 1); !reflect.DeepEqual(cold, deep) { + t.Fatalf("a page of older rows %+v, cold %+v", deep, cold) + } + pageSplitting = func(n int) { paired = append(paired, n) } + restart() + os.Remove(pageDiskPath()) + QueryPage(All, Filter{}, 0, 1) + writeCodexCall(t, settled, "b", "sb", `"vscode"`, "resp-b", "m", "low", now.AddDate(0, 0, -20).Add(-time.Hour), 1001, 10) + restart() + changed := QueryPage(All, Filter{}, 0, 1) + if paired[len(paired)-1] < all { + t.Fatalf("a settled file changed, paired %d of %d", paired[len(paired)-1], all) + } + restart() + if again := QueryPage(All, Filter{}, 0, 1); paired[len(paired)-1] >= all || !reflect.DeepEqual(again, changed) { + t.Fatalf("started again after the change, paired %d of %d: %+v, was %+v", paired[len(paired)-1], all, again, changed) + } + restart() + os.Remove(pageDiskPath()) + if cold := QueryPage(All, Filter{}, 0, 1); !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 a2140b817..f842342dc 100644 --- a/internal/usage/request_cells.go +++ b/internal/usage/request_cells.go @@ -108,7 +108,11 @@ 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 + // pageOld is a page's cells before its last few days the page before + // kept, and pageOldNext this page's (pageSplit) + pageOld, pageOldNext *pageOld + // disk is where heatSplit and pageSplit keep what is settled between + // runs disk heatDiskRef } diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index 449335e3b..cc7556868 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -552,6 +552,8 @@ type requestIndex struct { heatParts map[partKey]map[uint64]*chunkPart // heatOld are the heatmap's days before its last few (heatSplit) heatOld map[partKey]*heatOld + // pageOld are a page's cells before its last few days (pageSplit) + pageOld map[partKey]*pageOld // pairs are the last pairing of each of a few periods (pairMemo), // kept as parts are pairs map[Period]*pairMemo @@ -790,7 +792,7 @@ func queryPageOf(p Period, f Filter, offset, limit int, readSource func(sessions if p == heatmapPeriod { 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]} + cache = &partCache{old: idx.parts[pk], next: map[uint64]*chunkPart{}, pairs: idx.pairs[p], pageOld: idx.pageOld[pk], disk: heatDiskRef{root: idx.root, meta: idx.meta}} } shared := idx idx = shared.private() @@ -831,6 +833,12 @@ func queryPageOf(p Period, f Filter, offset, limit int, readSource func(sessions } 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{} + } + if cache.pageOldNext != nil { + shared.pageOld[pk] = cache.pageOldNext + } } if len(shared.pages) >= 16 { shared.pages = map[pageKey]RequestPage{} @@ -1134,6 +1142,7 @@ func (idx *requestIndex) adopt(st requestState) { idx.parts = nil idx.heatParts = nil idx.heatOld = nil + idx.pageOld = nil idx.pairs = nil idx.key = "" } @@ -2035,12 +2044,6 @@ func buildRequestBlocksIn(p Period, f Filter, offset, limit int, now time.Time, 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{} @@ -2059,8 +2062,10 @@ func buildRequestBlocksIn(p Period, f Filter, offset, limit int, now time.Time, // Bound the requested prefix before adding limit: external offsets can // reach MaxInt, and a page beyond all sources needs no heap at all. maxRows := 0 - for _, c := range ps.all { - maxRows += rowsIn(c) + for _, set := range [][]*rowChunk{gateways, chunks, others} { + for _, c := range set { + maxRows += rowsIn(c) + } } take := 0 if offset < maxRows { @@ -2069,7 +2074,21 @@ func buildRequestBlocksIn(p Period, f Filter, offset, limit int, now time.Time, // a kept cell says which computer its rows are of whether this page // counts computers or not: the next one of its partKey may pass := newCellPass(p, f, now, names != nil || cache != nil) - parts := ps.partsOf(pass, cache, identities) + var ps *pairedRows + var parts, newestParts []*chunkPart + split := false + if cache != nil { + parts, ps, newestParts, split = pageSplit(p, f, now, take, pass, gateways, chunks, others, identities, cache) + } + if !split { + if cache != nil { + ps, cache.pairsNext = pairRowsMemo(p, now, gateways, chunks, others, identities, cache.pairs) + } else { + ps = pairRows(p, now, gateways, chunks, others, identities) + } + parts = ps.partsOf(pass, cache, identities) + newestParts = parts + } var first time.Time // Each dimension's groups are counted with its own pick cleared, and // the computers' with the computer's and day's (cellPass): a cell's @@ -2167,7 +2186,7 @@ func buildRequestBlocksIn(p Period, f Filter, offset, limit int, now time.Time, } } } - selected := ps.newest(f, parts, take) + selected := ps.newest(f, newestParts, take) slices.SortFunc(selected, func(a, b timedRef) int { if a.newer(b) { return -1