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 {