diff --git a/internal/usage/cut_advance_test.go b/internal/usage/cut_advance_test.go new file mode 100644 index 000000000..af3da5384 --- /dev/null +++ b/internal/usage/cut_advance_test.go @@ -0,0 +1,168 @@ +package usage + +import ( + "os" + "path/filepath" + "reflect" + "testing" + "time" + + "github.com/yetone/magpie/internal/sessions" +) + +// advanceHistory writes a Codex call, each with its gateway call, 368, +// 40, 20, 10, 5, 2 and 0 days before Sunday 2026-10-04 noon, and holds +// the clock there. The call two days back is after that day's cut and +// before the next day's; the one 368 days back is in that day's heatmap +// and not in the next day's, which begins a week later. +func advanceHistory(t *testing.T) (yesterday, today time.Time) { + pageHome(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)) + at := yesterday.AddDate(0, 0, -days).Add(-time.Hour) + 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) + 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}) + } + return yesterday, yesterday.AddDate(0, 0, 1) +} + +// pairedBelow fails unless every pairing since from paired fewer than all. +func pairedBelow(t *testing.T, what string, paired []int, from, all int) { + t.Helper() + if len(paired) == from { + t.Fatalf("%s: nothing paired", what) + } + for _, n := range paired[from:] { + if n >= all { + t.Fatalf("%s: paired %d of %d chunks, %v", what, n, all, paired[from:]) + } + } +} + +// The first start of a day pairs only the last days' chunks for the +// heatmap: the days kept at the day before's cut stand, and the day +// between the two cuts is added (#2278). The days are a cold pairing's. +func TestHeatmapDaysAdvanceACut(t *testing.T) { + _, today := advanceHistory(t) + 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.pairs, requestCache.pages = nil, nil, nil, nil, map[pageKey]RequestPage{} + requestCache.Unlock() + } + restart() + t.Cleanup(restart) + HeatmapOf(Filter{}) + all := paired[0] + holdClock(t, today) + restart() + from := len(paired) + warm := HeatmapOf(Filter{}) + pairedBelow(t, "the next day", paired, from, all) + if e, _ := heatDiskEntryRead(); !e.Cut.Equal(time.Date(2026, 10, 3, 0, 0, 0, 0, time.Local)) { + t.Fatalf("the next day's days were written at cut %v", e.Cut) + } + restart() + from = len(paired) + if again := HeatmapOf(Filter{}); !reflect.DeepEqual(again, warm) { + t.Fatalf("started again: %+v, was %+v", again, warm) + } + pairedBelow(t, "started again", paired, from, all) + restart() + os.Remove(heatDiskPath()) + cold := HeatmapOf(Filter{}) + if !reflect.DeepEqual(warm, cold) { + t.Fatalf("the next day %+v, cold %+v", warm, cold) + } + if len(cold.Days) != 6 { + t.Fatalf("cold days %+v", cold.Days) + } +} + +// The first start of a day pairs only the last days' chunks for a page +// (#2278), and builds the page a pairing of every chunk does. +func TestPageCellsAdvanceACut(t *testing.T) { + _, today := advanceHistory(t) + 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) + QueryPage(All, Filter{}, 0, 1) + all := paired[0] + holdClock(t, today) + restart() + from := len(paired) + warm := QueryPage(All, Filter{}, 0, 1) + pairedBelow(t, "the next day", paired, from, all) + restart() + from = len(paired) + if again := QueryPage(All, Filter{}, 0, 1); !reflect.DeepEqual(again, warm) { + t.Fatalf("started again: %+v, was %+v", again, warm) + } + pairedBelow(t, "started again", paired, from, all) + restart() + os.Remove(pageDiskPath()) + cold := QueryPage(All, Filter{}, 0, 1) + if !reflect.DeepEqual(warm, cold) { + t.Fatalf("the next day %+v, cold %+v", warm, cold) + } + if cold.Total != 7 { + t.Fatalf("cold page: %d rows", cold.Total) + } +} + +// The first start of a day pairs only the last days' chunks for Codex's +// effort (#2278), and tells the effort a pairing of every chunk does. +func TestCodexEffortAdvancesACut(t *testing.T) { + _, today := advanceHistory(t) + paired := []int{} + effortPairing = func(n int) { paired = append(paired, n) } + t.Cleanup(func() { effortPairing = nil }) + restart := func() { + codexEffort.Lock() + codexEffort.periods = map[Period]*effortEntry{} + codexEffort.Unlock() + codexEffortBuilding.Lock() + effortOlds = map[Period]*effortOld{} + codexEffortBuilding.Unlock() + requestCache.Lock() + requestCache.pairs = nil + requestCache.Unlock() + } + restart() + t.Cleanup(restart) + CodexModelEffort(All) + all := paired[0] + holdClock(t, today) + restart() + from := len(paired) + warm := CodexModelEffort(All) + pairedBelow(t, "the next day", paired, from, all) + restart() + os.Remove(effortDiskPath()) + cold := CodexModelEffort(All) + if len(cold) != 7 || len(warm) != len(cold) { + t.Fatalf("the next day %d threads, cold %d", len(warm), len(cold)) + } + for id, c := range cold { + w := warm[id] + if len(w) != len(c) { + t.Fatalf("thread %s: the next day %+v, cold %+v", id, w, c) + } + for i := range c { + if w[i].Tokens != c[i].Tokens || w[i].Priced != c[i].Priced { + t.Fatalf("thread %s: the next day %+v, cold %+v", id, w, c) + } + } + } +} diff --git a/internal/usage/effort_split.go b/internal/usage/effort_split.go index e09d94280..2d4d4a0fd 100644 --- a/internal/usage/effort_split.go +++ b/internal/usage/effort_split.go @@ -44,24 +44,34 @@ func effortDiskPath() string { } type effortDiskEntry struct { - Key string `json:"key"` - Sums map[string][]sessions.ModelEffort `json:"sums"` + Key string `json:"key"` + Cut time.Time `json:"cut,omitzero"` + Since time.Time `json:"since,omitzero"` + Sums map[string][]sessions.ModelEffort `json:"sums"` +} + +func effortDiskEntryRead() (effortDiskEntry, bool) { + b, err := os.ReadFile(effortDiskPath()) + if err != nil { + return effortDiskEntry{}, false + } + var e effortDiskEntry + if json.Unmarshal(b, &e) != nil || e.Sums == nil { + return effortDiskEntry{}, false + } + return e, true } func effortDiskRead(key string) (map[string][]sessions.ModelEffort, bool) { - b, err := os.ReadFile(effortDiskPath()) - if err != nil { - return nil, false - } - var e effortDiskEntry - if json.Unmarshal(b, &e) != nil || e.Key != key || e.Sums == nil { + e, ok := effortDiskEntryRead() + if !ok || e.Key != key { return nil, false } return e.Sums, true } -func effortDiskWrite(key string, sums map[string][]sessions.ModelEffort) error { - b, err := json.Marshal(effortDiskEntry{Key: key, Sums: sums}) +func effortDiskWrite(key string, cut, since time.Time, sums map[string][]sessions.ModelEffort) error { + b, err := json.Marshal(effortDiskEntry{Key: key, Cut: cut, Since: since, Sums: sums}) if err != nil { return err } @@ -95,17 +105,8 @@ func effortSplit(sums effortSums, p Period, now time.Time, gateways, chunks, oth if !cut.After(since) || disk.root == "" { return 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) - } - } - } + sets := [3][]*rowChunk{gateways, chunks, others} + recent, settled := splitAt(cut, sets) serials, ok := pairSerials(settled[0], settled[1], settled[2]) if !ok { return false @@ -130,6 +131,8 @@ func effortSplit(sums effortSums, p Period, now time.Time, gateways, chunks, oth default: if s, found := effortDiskRead(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 := 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 } } if !kept { @@ -146,7 +149,7 @@ func effortSplit(sums effortSums, p Period, now time.Time, gateways, chunks, oth next := &effortOld{root: disk.root, cut: cut, since: since, settled: serials, before: before, at: time.Now(), key: key, sums: part.values()} effortOlds[p] = next // not written, the effort is counted again on the next start - _ = effortDiskWrite(key, next.sums) + _ = effortDiskWrite(key, cut, since, next.sums) return true } } @@ -157,8 +160,40 @@ func effortSplit(sums effortSums, p Period, now time.Time, gateways, chunks, oth } } if effortPairing != nil { - effortPairing(len(recent[0]) + len(recent[1]) + len(recent[2])) + effortPairing(chunksIn(recent)) } pairRowsIn(cut, until, recent[0], recent[1], recent[2], identities).visitActors(func(r *Row) { sums.add(r) }) return 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. +func effortAdvance(d heatDiskRef, cut, since, until time.Time, identities map[string]sessions.CodexIdentity, sets [3][]*rowChunk, key string) (map[string][]sessions.ModelEffort, bool) { + e, ok := effortDiskEntryRead() + if !ok || e.Cut.IsZero() || !e.Cut.Before(cut) || !e.Since.Equal(since) { + return nil, false + } + at := e.Cut.In(cut.Location()) + recent, k, ok := settledAt(d, at, since, Filter{}, identities, sets) + if !ok || fmt.Sprintf("%x", sha256.Sum256([]byte("effort-v1\x00"+k))) != e.Key { + return nil, false + } + if effortPairing != nil { + effortPairing(chunksIn(recent)) + } + part := effortSums{} + for actor, values := range e.Sums { + for _, v := range values { + part.addValue(actor, v) + } + } + pairRowsIn(at, until, recent[0], recent[1], recent[2], identities).visitActors(func(r *Row) { + if r.Time.Before(cut) { + part.add(r) + } + }) + sums := part.values() + _ = effortDiskWrite(key, cut, since, sums) + return sums, true +} diff --git a/internal/usage/heat_disk.go b/internal/usage/heat_disk.go index 7f8f22e93..f0d53ae1a 100644 --- a/internal/usage/heat_disk.go +++ b/internal/usage/heat_disk.go @@ -36,28 +36,40 @@ 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. +// heatDiskEntry is the file: the key it was counted under, the cut and +// since it names, and the days. type heatDiskEntry struct { - Key string `json:"key"` - Days []Day `json:"days"` + Key string `json:"key"` + Cut time.Time `json:"cut,omitzero"` + Since time.Time `json:"since,omitzero"` + Days []Day `json:"days"` +} + +func heatDiskEntryRead() (heatDiskEntry, bool) { + b, err := os.ReadFile(heatDiskPath()) + if err != nil { + return heatDiskEntry{}, false + } + var e heatDiskEntry + if json.Unmarshal(b, &e) != nil { + return heatDiskEntry{}, false + } + return e, true } // 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 { + e, ok := heatDiskEntryRead() + if !ok || 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}) +// heatDiskWrite keeps days before cut from since under key, through a +// file renamed over the last. +func heatDiskWrite(key string, cut, since time.Time, days []Day) error { + b, err := json.Marshal(heatDiskEntry{Key: key, Cut: cut, Since: since, Days: days}) if err != nil { return err } @@ -184,3 +196,42 @@ func hashRows(h hash.Hash, c *rowChunk) { type heatDiskRef struct { root, meta string } + +// The cut moves a day each midnight, and every key names it: the first +// start of each day found none of its sums on disk and paired the whole +// history again, three times over (the page, the heatmap and Codex's +// effort), ~180 MB of a ~480 MB footprint each morning (#2278). Sums +// kept at an earlier cut still stand while that cut's key is the same: +// the days between are added from a pairing of the chunks they reach. + +// splitAt is the chunks of sets with rows a pairing from cut on reaches, +// and the rest. +func splitAt(cut time.Time, sets [3][]*rowChunk) (recent, settled [3][]*rowChunk) { + edge := cut.Add(-heatReach) + for k, set := range sets { + 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) + } + } + } + return recent, settled +} + +// settledAt is sets split at an earlier cut, and the key of its settled +// chunks there, or false. +func settledAt(d heatDiskRef, cut, since time.Time, f Filter, identities map[string]sessions.CodexIdentity, sets [3][]*rowChunk) ([3][]*rowChunk, string, bool) { + recent, settled := splitAt(cut, sets) + if _, ok := pairSerials(settled[0], settled[1], settled[2]); !ok { + return recent, "", false + } + key, ok := heatSettledKey(d, cut, since, f, identities, settled, heatBefore(cut, recent)) + return recent, key, ok +} + +// chunksIn is how many chunks sets hold. +func chunksIn(sets [3][]*rowChunk) int { + return len(sets[0]) + len(sets[1]) + len(sets[2]) +} diff --git a/internal/usage/heatmap.go b/internal/usage/heatmap.go index d99bd08b3..858b5e0a7 100644 --- a/internal/usage/heatmap.go +++ b/internal/usage/heatmap.go @@ -335,21 +335,11 @@ var heatBeforeOpening func(*rowChunk) // 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) - } - } - } + sets := [3][]*rowChunk{gateways, chunks, others} + recent, settled := splitAt(cut, sets) // 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 { @@ -375,6 +365,8 @@ func heatSplit(since, now time.Time, gateways, chunks, others []*rowChunk, f Fil 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 + } 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 } } } @@ -395,7 +387,7 @@ func heatSplit(since, now time.Time, gateways, chunks, others []*rowChunk, f Fil if named { next.key = key // not written, the days are counted again on the next start - _ = heatDiskWrite(key, next.days) + _ = heatDiskWrite(key, cut, since, next.days) } cache.heatOldNext = next } @@ -417,7 +409,7 @@ func heatSplit(since, now time.Time, gateways, chunks, others []*rowChunk, f Fil all.addDay(d) } if heatPairing != nil { - heatPairing(len(recent[0]) + len(recent[1]) + len(recent[2])) + heatPairing(chunksIn(recent)) } for _, d := range recentDays(old.parts, next.parts) { all.addDay(d) @@ -425,6 +417,41 @@ func heatSplit(since, now time.Time, gateways, chunks, others []*rowChunk, f Fil return heatmapFrom(since, now, all.list()) } +// heatAdvance is the days from since to cut, from the file's days 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. +func heatAdvance(d heatDiskRef, cut, since, now time.Time, f Filter, identities map[string]sessions.CodexIdentity, sets [3][]*rowChunk, key string) ([]Day, bool) { + e, ok := heatDiskEntryRead() + if !ok || e.Cut.IsZero() || !e.Cut.Before(cut) || e.Since.IsZero() || e.Since.After(since) { + return nil, false + } + at := e.Cut.In(cut.Location()) + recent, k, ok := settledAt(d, at, e.Since.In(since.Location()), f, identities, sets) + if !ok || k != e.Key { + return nil, false + } + if heatPairing != nil { + heatPairing(chunksIn(recent)) + } + from, to := since.Format(time.DateOnly), cut.Format(time.DateOnly) + all := heatDays{} + for _, day := range e.Days { + if day.Date >= from { + all.addDay(day) + } + } + // the days before the earlier cut are paired from it on, a pairing + // from since drops none of them + for _, day := range pairRowsIn(at, heatmapPeriod.Until(now), recent[0], recent[1], recent[2], identities).heatDaysOf(at, now, f, nil, identities, nil) { + if day.Date < to { + all.addDay(day) + } + } + 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/page_split.go b/internal/usage/page_split.go index d6f71ee6b..46a8807cf 100644 --- a/internal/usage/page_split.go +++ b/internal/usage/page_split.go @@ -51,17 +51,8 @@ func pageSplit(p Period, f Filter, now time.Time, take int, pass *cellPass, gate 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) - } - } - } + sets := [3][]*rowChunk{gateways, chunks, others} + recent, settled := splitAt(cut, sets) serials, named := pairSerials(settled[0], settled[1], settled[2]) if !named { return nil, nil, nil, false @@ -78,7 +69,7 @@ func pageSplit(p Period, f Filter, now time.Time, take int, pass *cellPass, gate 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))) + key = pageKeyOf(until, pass, k) switch { case same(old) && old.key == key: fresh := *old @@ -88,9 +79,11 @@ func pageSplit(p Period, f Filter, now time.Time, take int, pass *cellPass, gate if c, at, found := pageDiskRead(key); found { if at >= pageDiskPages/2 { // read again near the end: kept from being the next dropped - _ = pageDiskWrite(key, c) + _ = pageDiskWrite(key, cut, since, c) } 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 } } } @@ -103,11 +96,11 @@ func pageSplit(p Period, f Filter, now time.Time, take int, pass *cellPass, gate 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) + _ = pageDiskWrite(key, cut, since, next.cells) return parts, ps, parts, true } if pageSplitting != nil { - pageSplitting(len(recent[0]) + len(recent[1]) + len(recent[2])) + pageSplitting(chunksIn(recent)) } next := *old next.parts = map[uint64]*chunkPart{} @@ -136,6 +129,78 @@ func pageSplit(p Period, f Filter, now time.Time, take int, pass *cellPass, gate return append([]*chunkPart{old.cells}, newest...), ps, newest, true } +// pageKeyOf is the key of a page's cells until, read through pass, of +// the settled chunks heatSettledKey names k. +func pageKeyOf(until time.Time, pass *cellPass, k string) string { + return 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))) +} + +// pageAdvance is a page's cells before cut, from a page of the file's +// cells before an earlier cut counted under the same key there and the +// cells of a pairing of the chunks of the days between, written under +// key; or false. +func pageAdvance(d heatDiskRef, cut, since, until time.Time, f Filter, pass *cellPass, identities map[string]sessions.CodexIdentity, sets [3][]*rowChunk, key string) (*chunkPart, bool) { + keys := map[int64]string{} + for _, e := range pageDiskEntries() { + if e.Cut.IsZero() || !e.Cut.Before(cut) || !e.Since.Equal(since) { + continue + } + at := e.Cut.In(cut.Location()) + k, seen := keys[at.UnixNano()] + var recent [3][]*rowChunk + if !seen { + var named bool + if recent, k, named = settledAt(d, at, since, f, identities, sets); named { + k = pageKeyOf(until, pass, k) + } + keys[at.UnixNano()] = k + } + if k == "" || k != e.Key { + continue + } + if seen { + recent, _ = splitAt(at, sets) + } + if pageSplitting != nil { + pageSplitting(chunksIn(recent)) + } + between := pairRowsIn(at, until, recent[0], recent[1], recent[2], identities).cellsBefore(pass, cut) + cells := addCells(pageDiskPart(e), between) + _ = pageDiskWrite(key, cut, since, cells) + return cells, true + } + return nil, false +} + +// 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 { + out := &chunkPart{kept: a.kept + b.kept, first: a.first} + if !b.first.IsZero() && (out.first.IsZero() || b.first.Before(out.first)) { + out.first = b.first + } + key := func(c pageCell) pageCell { + c.n, c.d = 0, Totals{} + return c + } + later := make(map[pageCell]int, len(b.cells)) + for i, c := range b.cells { + later[key(c)] = i + } + cells := slices.Clone(b.cells) + out.cells = make([]pageCell, 0, len(a.cells)+len(b.cells)) + for _, c := range a.cells { + if i, ok := later[key(c)]; ok { + cells[i].n += c.n + cells[i].d.plus(&c.d) + continue + } + out.cells = append(out.cells, c) + } + out.cells = append(out.cells, cells...) + return out +} + // 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. @@ -209,6 +274,8 @@ type pageDiskCell struct { // under. type pageDiskEntry struct { Key string `json:"key"` + Cut time.Time `json:"cut,omitzero"` + Since time.Time `json:"since,omitzero"` At time.Time `json:"at"` Kept int `json:"kept"` First time.Time `json:"first"` @@ -237,29 +304,33 @@ func pageDiskEntries() []pageDiskEntry { // they are, or false. func pageDiskRead(key string) (*chunkPart, int, bool) { for at, e := range pageDiskEntries() { - if e.Key != key { - continue + if e.Key == key { + return pageDiskPart(e), at, true } - 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, at, true } return nil, 0, 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))} +// pageDiskPart is e's cells as one part. +func pageDiskPart(e pageDiskEntry) *chunkPart { + 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 +} + +// pageDiskWrite keeps part, a page's cells before cut from since, under +// key with the pages written last, through a file renamed over the last. +func pageDiskWrite(key string, cut, since time.Time, part *chunkPart) error { + e := pageDiskEntry{Key: key, Cut: cut, Since: since, 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{ diff --git a/internal/usage/page_split_test.go b/internal/usage/page_split_test.go index c8bd9d522..6abf74877 100644 --- a/internal/usage/page_split_test.go +++ b/internal/usage/page_split_test.go @@ -113,7 +113,7 @@ func TestPageReadAgainStaysOnDisk(t *testing.T) { QueryPage(All, Filter{}, 0, 1) all := (*paired)[0] for i := range pageDiskPages - 1 { - if err := pageDiskWrite(fmt.Sprint("other", i), &chunkPart{}); err != nil { + if err := pageDiskWrite(fmt.Sprint("other", i), time.Time{}, time.Time{}, &chunkPart{}); err != nil { t.Fatal(err) } } @@ -121,7 +121,7 @@ func TestPageReadAgainStaysOnDisk(t *testing.T) { if QueryPage(All, Filter{}, 0, 1); (*paired)[len(*paired)-1] >= all { t.Fatalf("the last page in the file, paired %d of %d", (*paired)[len(*paired)-1], all) } - if err := pageDiskWrite("one more", &chunkPart{}); err != nil { + if err := pageDiskWrite("one more", time.Time{}, time.Time{}, &chunkPart{}); err != nil { t.Fatal(err) } restart() diff --git a/internal/usage/settled_version_test.go b/internal/usage/settled_version_test.go index 79e82a2af..c34451412 100644 --- a/internal/usage/settled_version_test.go +++ b/internal/usage/settled_version_test.go @@ -74,8 +74,9 @@ func TestSettledCountedAsVersioned(t *testing.T) { read(pageDiskPath(), &pages) read(heatDiskPath(), &heat) read(effortDiskPath(), &effort) + // when and under what they were counted, not how for i := range pages { - pages[i].Key, pages[i].At = "", time.Time{} + pages[i].Key, pages[i].At, pages[i].Cut, pages[i].Since = "", time.Time{}, time.Time{}, time.Time{} } 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))