From fc9ce34d86ce116b1ccec797e7e1007bc1822c34 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 9 Nov 2026 23:56:10 +0800 Subject: [PATCH] usage: hashRows reuses its scratch, within sizes its rows exactly Startup on a copy of the owner's real accounts (mote, GUI, network blocked, acgui.sh) allocated ~3.5GB, and two usage functions were near the top of it: - hashRows built a fresh 32KB byte buffer and shape map for every chunk it hashed: 510MB of the startup's allocations. It now takes them from a sync.Pool and clears the map before use. The digest is the same byte for byte (checked against the old code on the same chunks). - rowChunk.within appended into a nil slice, growing it step by step (292MB flat). It now counts the rows in range first, returns nil when there are none, and makes the slice at that size. Measured, same real-account copy, t9 (main) against t10 (this): startup CPU 13.81s -> 9.77s allocated (3m) 3483MB -> 2768MB (hashRows 510MB -> gone, within 427MB -> 244MB cumulative) footprint 179MB -> 175MB Tests: TestHashRowsReusesItsScratch hashes a chunk again after a bigger one and must get the same digest, and must allocate under 16KB a call (min of 5 batches, so other goroutines' allocations don't count). Old heat_disk.go: red at 32768 bytes a chunk; dropping clear(shapes): red. TestWithinSizesItsRows needs len = cap = 600 (old code: cap 646). Run on mote at this tree: go test ./internal/usage -count=1 ok, -race ok, gofmt clean, go vet darwin/linux/windows ok, gui tests ok earlier. An earlier usage run went red on a test whose name was lost (the log was cut by tail); four full runs since are green, and the likely cause, the first byte check counting other goroutines, is what the min-of-5 fixes. --- internal/usage/cold_split.go | 18 +++++- internal/usage/hash_rows_reuse_test.go | 82 ++++++++++++++++++++++++++ internal/usage/heat_disk.go | 19 +++++- 3 files changed, 116 insertions(+), 3 deletions(-) create mode 100644 internal/usage/hash_rows_reuse_test.go diff --git a/internal/usage/cold_split.go b/internal/usage/cold_split.go index 78b6e3dc6..d68aa83e2 100644 --- a/internal/usage/cold_split.go +++ b/internal/usage/cold_split.go @@ -115,10 +115,26 @@ func (c *rowChunk) within(lo, hi time.Time) *rowChunk { if len(ids) > 0 { ids[0], order = 1, append(order, 0) } + in := func(p *packedRow) bool { + t := p.Time() + return t.IsZero() || !t.Before(lo) && t.Before(hi) + } + // the rows counted first: grown by append, out's rows were 245 MB of + // what a real history's start allocated, twice what they needed + n := 0 + for i := range open.Rows { + if in(&open.Rows[i]) { + n++ + } + } + if n == 0 { + return nil + } + out.Rows = make([]packedRow, 0, n) size := 0 for i := range open.Rows { p := &open.Rows[i] - if t := p.Time(); !t.IsZero() && (t.Before(lo) || !t.Before(hi)) { + if !in(p) { continue } t := open.texts(p) diff --git a/internal/usage/hash_rows_reuse_test.go b/internal/usage/hash_rows_reuse_test.go new file mode 100644 index 000000000..066f7eebf --- /dev/null +++ b/internal/usage/hash_rows_reuse_test.go @@ -0,0 +1,82 @@ +package usage + +import ( + "crypto/sha256" + "fmt" + "math" + "runtime" + "testing" + "time" +) + +func hashedRows(c *rowChunk) [sha256.Size]byte { + h := sha256.New() + hashRows(h, c) + var sum [sha256.Size]byte + copy(sum[:], h.Sum(nil)) + return sum +} + +// hashRows gave each chunk a new 32 KB buffer and shape map: 522 MB of a +// real history's start, a digest per session file's chunk. It reuses +// them now, and what it writes for a chunk is the same whatever it hashed +// before: a shape another chunk saw first is not taken as seen. +func TestHashRowsReusesItsScratch(t *testing.T) { + now := time.Unix(1_800_000_000, 0) + chunk := func(agent string, n int) *rowChunk { + c := &rowChunk{} + for i := range n { + r := Row{Record: Record{Time: now.Add(time.Duration(i) * time.Second), Agent: agent, Model: fmt.Sprint("m", i%3), Input: i}} + c.add(r, fmt.Sprint("msg", i), int64(i), false) + } + return c + } + a, b := chunk("claude", 40), chunk("codex", 2000) + first := hashedRows(a) + t.Logf("digest %x", first) + hashedRows(b) + if again := hashedRows(a); again != first { + t.Fatal("a chunk's rows hashed differently after another chunk's") + } + // by bytes: a pool may drop what it keeps (-race drops some on + // purpose). The process's count takes in whatever else runs, so the + // least of five batches is the one judged. + h := sha256.New() + per := uint64(math.MaxUint64) + for range 5 { + var m0, m1 runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&m0) + const n = 20 + for range n { + h.Reset() + hashRows(h, b) + } + runtime.ReadMemStats(&m1) + per = min(per, (m1.TotalAlloc-m0.TotalAlloc)/n) + } + if per >= 16<<10 { + t.Fatalf("hashRows allocated %d bytes a chunk", per) + } +} + +// within made its rows by append, growing them up to twice what they +// needed: 245 MB of a real history's start. It counts them first now. +func TestWithinSizesItsRows(t *testing.T) { + now := time.Unix(1_800_000_000, 0) + c := &rowChunk{} + for i := range 1000 { + r := Row{Record: Record{Time: now.Add(time.Duration(i) * time.Minute), Agent: "claude", Model: "m", Input: i}} + c.add(r, fmt.Sprint("msg", i), int64(i), false) + } + out := c.within(now.Add(100*time.Minute), now.Add(700*time.Minute)) + if out == nil || len(out.Rows) != 600 || cap(out.Rows) != 600 { + t.Fatalf("within kept %d rows in room for %d", len(out.Rows), cap(out.Rows)) + } + if r := out.row(0); r.Input != 100 || out.row(599).Input != 699 { + t.Fatalf("within kept rows %d to %d", r.Input, out.row(599).Input) + } + if c.within(now.Add(-time.Hour), now) != nil { + t.Fatal("rows outside the span were kept") + } +} diff --git a/internal/usage/heat_disk.go b/internal/usage/heat_disk.go index bc1680975..aff86c0f5 100644 --- a/internal/usage/heat_disk.go +++ b/internal/usage/heat_disk.go @@ -194,7 +194,10 @@ func sourceDigest(c *rowChunk, rows *chunkRows) [sha256.Size]byte { // 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) + sc := hashScratchPool.Get().(*hashScratch) + defer hashScratchPool.Put(sc) + b, shapes := sc.b[:0], sc.shapes + clear(shapes) text := func(i uint32) { s := "" if int(i) < len(c.Strings) { @@ -203,7 +206,6 @@ func hashRows(h hash.Hash, c *rowChunk) { 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()) @@ -238,8 +240,21 @@ func hashRows(h hash.Hash, c *rowChunk) { } } h.Write(b) + sc.b = b } +// hashScratch is what hashRows writes through, kept between calls: a new +// 32 KB buffer and map for each chunk was 522 MB of a real history's start +// (a digest per session file's chunk), the most of any one function. +type hashScratch struct { + b []byte + shapes map[uint32]int +} + +var hashScratchPool = sync.Pool{New: func() any { + return &hashScratch{b: make([]byte, 0, 32<<10), shapes: map[uint32]int{}} +}} + // 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 {