From fddd7ff08f677729ef8e3565111b3b5fb3c23581 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 30 Oct 2026 13:37:05 +0800 Subject: [PATCH] usage: pairing keeps its rows as bits and its groups by sums, and lets its pairs go (#2278) A cold start pairs the whole history, and pairing held its row sets as map[rowRef]bool, ~40 bytes a row, several sets of most rows at once. They are now refSet: a bitset a chunk, a bit a row. matchScratch's groupOf was keyed by the whole matchKey (a session string and its tokens); it is keyed by a 128-bit maphash sum of them now, and the sessions map is filled when a group is made. pairedRows' pairs and compactions maps were filled and never read; they are gone. Measured on mote, a copy of the real full history (52G Codex, 13G Claude), GODEBUG=gctrace=1, 120s of /api polls, 3 rounds each, alternating, v0.1.2143 (807048470) against this change: peak live heap 459 -> 439 MB (512/426/440 vs 470/433/413) heap at GC 543 -> 517 MB footprint peak 677 -> 641 MB The inuse profile at the peak shows groupOf 28.7 -> 11.8 MB and the matched set gone from matchedBlocks. This is a small part of the peak; the rest is the full re-pair itself, which is next. Run at this tree (rebased onto dca3e2d71 from 807048470), on mote: go vet ./internal/usage; GOOS=linux|windows|darwin go vet -tags nogui ./... all ok; go test -count=1 ./internal/usage ok (30.1s), with the new TestRefSet and TestMatchKeySum (no allocation). Not run: the full suite, the GUI suite. --- internal/usage/codex_fold_ids_test.go | 6 +- internal/usage/codex_identity.go | 12 +-- internal/usage/direct.go | 4 +- internal/usage/ledger.go | 6 +- internal/usage/match_chunks_test.go | 6 +- internal/usage/pair_bench_test.go | 4 +- internal/usage/pair_scratch_test.go | 6 +- internal/usage/refset.go | 58 ++++++++++ internal/usage/refset_test.go | 69 ++++++++++++ internal/usage/request_cells.go | 4 +- internal/usage/request_index_review_test.go | 6 +- internal/usage/request_page.go | 112 +++++++++++++------- internal/usage/request_page_test.go | 2 +- internal/usage/request_pairs.go | 23 ++-- 14 files changed, 236 insertions(+), 82 deletions(-) create mode 100644 internal/usage/refset.go create mode 100644 internal/usage/refset_test.go diff --git a/internal/usage/codex_fold_ids_test.go b/internal/usage/codex_fold_ids_test.go index 8298017be..ed7e36f9f 100644 --- a/internal/usage/codex_fold_ids_test.go +++ b/internal/usage/codex_fold_ids_test.go @@ -33,12 +33,12 @@ func TestFoldReadsAChunksIDsOnce(t *testing.T) { foldHashing = func(c *rowChunk) { read = append(read, c) } t.Cleanup(func() { foldHashing = nil }) - first := foldCodexRows([]*rowChunk{a, b}) + first := refMap(foldCodexRows([]*rowChunk{a, b})) if len(read) != 2 || len(first) != 1 || !first[rowRef{b, 0}] { t.Fatalf("first fold read %d chunks, skipped %v; want both read and b's resp-1 skipped", len(read), first) } read = nil - again := foldCodexRows([]*rowChunk{a, b}) + again := refMap(foldCodexRows([]*rowChunk{a, b})) if len(read) != 0 { t.Fatalf("a fold of the same chunks read %d of them again", len(read)) } @@ -48,7 +48,7 @@ func TestFoldReadsAChunksIDsOnce(t *testing.T) { read = nil live := chunk("resp-1", "resp-4") - folded := foldCodexRows([]*rowChunk{a, live}) + folded := refMap(foldCodexRows([]*rowChunk{a, live})) if len(read) != 1 || read[0] != live { t.Fatalf("a chunk made again wasn't the one read: %d read", len(read)) } diff --git a/internal/usage/codex_identity.go b/internal/usage/codex_identity.go index 30880b3a8..a062b12ee 100644 --- a/internal/usage/codex_identity.go +++ b/internal/usage/codex_identity.go @@ -217,7 +217,7 @@ func (s *pickScratch) release() { // both name by one response id, gateway to local, and each local call's // compaction. Only the ids the gateway names are kept of the locals': a map // of every Codex call's id held each decoded chunk's strings. -func codexChunkResponsePairs(gateways, locals []*rowChunk, duplicateLocal map[rowRef]bool) (map[rowRef]rowRef, map[rowRef]*bool) { +func codexChunkResponsePairs(gateways, locals []*rowChunk, duplicateLocal refSet) (map[rowRef]rowRef, map[rowRef]*bool) { // the picks are one slice the map points into: a pick each was ~300 MB // of what two minutes of polls allocated while an agent worked (#2278). // The slab holds the gateway's ids, and a gateway call is @@ -285,7 +285,7 @@ func codexChunkResponsePairs(gateways, locals []*rowChunk, duplicateLocal map[ro open := lent.of(chunk) for i := range open.Rows { ref := rowRef{chunk, i} - if duplicateLocal[ref] { + if duplicateLocal.has(ref) { continue } k, ok := picks[open.Strings[open.text(&open.Rows[i], rowResponseID)]] @@ -435,7 +435,7 @@ func chunkIDs(locals []*rowChunk, rows *chunkRows, next bool) map[*rowChunk]*fol return known } -func foldCodexRows(locals []*rowChunk) map[rowRef]bool { +func foldCodexRows(locals []*rowChunk) refSet { // The calls are found by a hash of their response id, not the id: a map // keyed by every Codex call's id held each decoded chunk's strings. Calls // whose hash is the same are told apart by their ids after. @@ -465,7 +465,7 @@ func foldCodexRows(locals []*rowChunk) map[rowRef]bool { refs = append(refs, hashed...) } read := rowsOf(locals, refs) - skip := map[rowRef]bool{} + skip := refSet{} for _, hashed := range again { byID := map[string][]rowRef{} var ids []string @@ -485,7 +485,7 @@ func foldCodexRows(locals []*rowChunk) map[rowRef]bool { // foldCodexCall keeps the first of refs, the calls a session file names by // one response id, and skips the rest when they are the same call. -func foldCodexCall(refs []rowRef, read map[rowRef]Row, skip map[rowRef]bool) { +func foldCodexCall(refs []rowRef, read map[rowRef]Row, skip refSet) { if len(refs) < 2 { return } @@ -518,7 +518,7 @@ func foldCodexCall(refs []rowRef, read map[rowRef]Row, skip map[rowRef]bool) { setCodexActor(refs[0].Chunk, refs[0].Index, "") } for _, ref := range refs[1:] { - skip[ref] = true + skip.add(ref) } compactions := make([]*bool, len(refs)) for i := range refs { diff --git a/internal/usage/direct.go b/internal/usage/direct.go index dbb009ce9..55a11a073 100644 --- a/internal/usage/direct.go +++ b/internal/usage/direct.go @@ -66,10 +66,10 @@ func directRows(p Period, now time.Time) []Row { } duplicates := foldCodexRows([]*rowChunk{local}) pairs, _ := codexChunkResponsePairs(gateways, []*rowChunk{local}, duplicates) - for ref := range matchedBlocks(gateways, []*rowChunk{local}, duplicates, pairs, since, false) { + for ref := range matchedBlocks(gateways, []*rowChunk{local}, duplicates, pairs, since, false).all() { matched[ref.Index] = true } - for ref := range duplicates { + for ref := range duplicates.all() { matched[ref.Index] = true } for i, call := range logs { diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go index c4affb25d..bc2e1900f 100644 --- a/internal/usage/ledger.go +++ b/internal/usage/ledger.go @@ -391,16 +391,16 @@ func gatewayMatchesDetails(recs []Record, logs []sessions.Call) (map[int]bool, m } duplicates, actors, compactions := duplicateCodexCalls(logs) pairs := codexResponseMatches(recs, logs, duplicates) - deduplicate := map[rowRef]bool{} + deduplicate := refSet{} for index := range duplicates { - deduplicate[rowRef{local, index}] = true + deduplicate.add(rowRef{local, index}) } responsePairs := make(map[rowRef]rowRef, len(pairs)) for record, call := range pairs { responsePairs[rowRef{gateway, record}] = rowRef{local, call} } matched := map[int]bool{} - for ref := range matchedBlocks([]*rowChunk{gateway}, []*rowChunk{local}, deduplicate, responsePairs, time.Time{}, false) { + for ref := range matchedBlocks([]*rowChunk{gateway}, []*rowChunk{local}, deduplicate, responsePairs, time.Time{}, false).all() { matched[ref.Index] = true } for index := range duplicates { diff --git a/internal/usage/match_chunks_test.go b/internal/usage/match_chunks_test.go index 8302a2c4c..0fae32e0c 100644 --- a/internal/usage/match_chunks_test.go +++ b/internal/usage/match_chunks_test.go @@ -53,7 +53,7 @@ func TestMatchOpensOnlyNamedChunks(t *testing.T) { for _, since := range []time.Time{{}, now.Add(5 * time.Second)} { var opened []*rowChunk matchOpening = func(c *rowChunk) { opened = append(opened, c) } - got := matchedBlocks([]*rowChunk{gateway}, locals, nil, nil, since, false) + got := refMap(matchedBlocks([]*rowChunk{gateway}, locals, nil, nil, since, false)) matchOpening = nil want := matchedLocalLegacy(gateway, locals, nil, since) if !reflect.DeepEqual(got, want) { @@ -84,7 +84,7 @@ func TestMatchOpensAgyChunks(t *testing.T) { var opened []*rowChunk matchOpening = func(c *rowChunk) { opened = append(opened, c) } t.Cleanup(func() { matchOpening = nil }) - got := matchedBlocks([]*rowChunk{gateway}, []*rowChunk{agy, other}, nil, nil, time.Time{}, false) + got := refMap(matchedBlocks([]*rowChunk{gateway}, []*rowChunk{agy, other}, nil, nil, time.Time{}, false)) if !got[rowRef{agy, 0}] || len(got) != 1 { t.Fatalf("matched %v; want the agy step alone", got) } @@ -110,7 +110,7 @@ func TestMatchByIDAllocatesNoSliceAnID(t *testing.T) { local.add(Row{Record: r, Source: "log"}, "", int64(i), false) } local.serial = nextChunkSerial() - got := matchedBlocks([]*rowChunk{gateway}, []*rowChunk{local}, nil, nil, time.Time{}, false) + got := refMap(matchedBlocks([]*rowChunk{gateway}, []*rowChunk{local}, nil, nil, time.Time{}, false)) if want := matchedLocalLegacy(gateway, []*rowChunk{local}, nil, time.Time{}); !reflect.DeepEqual(got, want) { t.Fatalf("%d matches, want %d", len(got), len(want)) } diff --git a/internal/usage/pair_bench_test.go b/internal/usage/pair_bench_test.go index 4934c2c93..d26dcd623 100644 --- a/internal/usage/pair_bench_test.go +++ b/internal/usage/pair_bench_test.go @@ -40,8 +40,8 @@ func BenchmarkPairRows(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { ps := pairRows(All, now, gateways, locals, nil, nil) - if len(ps.matched) != 200000 { - b.Fatal(len(ps.matched)) + if ps.matched.count() != 200000 { + b.Fatal(ps.matched.count()) } } } diff --git a/internal/usage/pair_scratch_test.go b/internal/usage/pair_scratch_test.go index 7d9837346..4214a1235 100644 --- a/internal/usage/pair_scratch_test.go +++ b/internal/usage/pair_scratch_test.go @@ -20,8 +20,8 @@ func TestPairScratchKeepsNothingBetweenCalls(t *testing.T) { // for each call matched := func(g, l []*rowChunk) map[[2]uint64]bool { out := map[[2]uint64]bool{} - for r, v := range pairRows(All, now, g, l, nil, nil).matched { - out[[2]uint64{r.Chunk.serial, uint64(r.Index)}] = v + for r := range pairRows(All, now, g, l, nil, nil).matched.all() { + out[[2]uint64{r.Chunk.serial, uint64(r.Index)}] = true } return out } @@ -70,7 +70,7 @@ func TestMatchScratchForgetsTheLastCall(t *testing.T) { // another gateway, where req-a is the sixth id other := chunk(false, call("req-0", 9), call("req-1", 8), call("req-2", 7), call("req-3", 6), call("req-4", 5), call("req-a", 4)) match := func(gateway, local *rowChunk, pairs map[rowRef]rowRef) bool { - return matchedBlocks([]*rowChunk{gateway}, []*rowChunk{local}, nil, pairs, time.Time{}, false)[rowRef{local, 0}] + return matchedBlocks([]*rowChunk{gateway}, []*rowChunk{local}, nil, pairs, time.Time{}, false).has(rowRef{local, 0}) } ReleaseScratch() if !match(gateway, unnamed, nil) || !match(gateway, named, nil) { diff --git a/internal/usage/refset.go b/internal/usage/refset.go new file mode 100644 index 000000000..0732451c7 --- /dev/null +++ b/internal/usage/refset.go @@ -0,0 +1,58 @@ +package usage + +import ( + "iter" + "math/bits" +) + +// refSet is a set of rows, a bit a row of each chunk it holds. As a +// map[rowRef]bool a row was ~40 bytes, and a cold start pairing the +// whole history holds a set of most of its rows several times over; as +// bits a million rows are 125 KB (#2278). +type refSet map[*rowChunk][]uint64 + +func (s refSet) has(r rowRef) bool { + b := s[r.Chunk] + w := r.Index >> 6 + return w < len(b) && b[w]&(1<<(r.Index&63)) != 0 +} + +func (s refSet) add(r rowRef) { + b := s[r.Chunk] + w := r.Index >> 6 + if w >= len(b) { + grown := make([]uint64, max(w+1, 2*len(b), (r.Chunk.Count+63)>>6, (len(r.Chunk.Rows)+63)>>6)) + copy(grown, b) + b = grown + s[r.Chunk] = b + } + b[w] |= 1 << (r.Index & 63) +} + +// count is how many rows s holds. +func (s refSet) count() int { + n := 0 + for _, b := range s { + for _, w := range b { + n += bits.OnesCount64(w) + } + } + return n +} + +// all is each row s holds, in no order but each chunk's. +func (s refSet) all() iter.Seq[rowRef] { + return func(yield func(rowRef) bool) { + for c, b := range s { + for w, word := range b { + for word != 0 { + i := bits.TrailingZeros64(word) + word &= word - 1 + if !yield(rowRef{c, w<<6 + i}) { + return + } + } + } + } + } +} diff --git a/internal/usage/refset_test.go b/internal/usage/refset_test.go new file mode 100644 index 000000000..044d3e413 --- /dev/null +++ b/internal/usage/refset_test.go @@ -0,0 +1,69 @@ +package usage + +import ( + "testing" +) + +// refMap is s as the map of rows it stood for before it was bits. +func refMap(s refSet) map[rowRef]bool { + out := map[rowRef]bool{} + for r := range s.all() { + out[r] = true + } + return out +} + +// A set is a bit a row: it holds what was added, past a word's and a +// chunk's end too, and nothing else. +func TestRefSet(t *testing.T) { + a, b := &rowChunk{Count: 3}, &rowChunk{} + s := refSet{} + want := []rowRef{{a, 0}, {a, 2}, {a, 63}, {a, 64}, {a, 700}, {b, 5}} + for _, r := range want { + s.add(r) + s.add(r) + } + for _, r := range want { + if !s.has(r) { + t.Fatalf("lost %v", r.Index) + } + } + for _, r := range []rowRef{{a, 1}, {a, 65}, {a, 701}, {a, 5000}, {b, 4}, {&rowChunk{}, 0}} { + if s.has(r) { + t.Fatalf("holds %v, never added", r.Index) + } + } + if got := s.count(); got != len(want) { + t.Fatalf("count %d, want %d", got, len(want)) + } + got := refMap(s) + if len(got) != len(want) { + t.Fatalf("all gave %d rows, want %d", len(got), len(want)) + } + if refSet(nil).has(rowRef{a, 0}) || refSet(nil).count() != 0 { + t.Fatal("a nil set holds rows") + } +} + +// A match key's sum is the same for the same key and differs when any of +// its parts does, the session's end against the tokens' start too. +func TestMatchKeySum(t *testing.T) { + k := matchKey{session: "s", tokens: [3]int64{1, 2, 3}, hasID: true} + if k.sum() != (matchKey{session: "s", tokens: [3]int64{1, 2, 3}, hasID: true}).sum() { + t.Fatal("one key, two sums") + } + for _, o := range []matchKey{ + {session: "t", tokens: [3]int64{1, 2, 3}, hasID: true}, + {session: "s\x01", tokens: [3]int64{0, 2, 3}, hasID: true}, + {session: "s", tokens: [3]int64{1, 2, 4}, hasID: true}, + {session: "s", tokens: [3]int64{1, 2, 3}}, + {session: "s", tokens: [3]int64{1, 2, 3}, hasID: true, failed: true}, + } { + if o.sum() == k.sum() { + t.Fatalf("%+v sums as %+v", o, k) + } + } + if n := testing.AllocsPerRun(100, func() { k.sum() }); n != 0 { + t.Fatalf("a sum allocated %v times", n) + } +} diff --git a/internal/usage/request_cells.go b/internal/usage/request_cells.go index fdfa82ea6..7c3891e3c 100644 --- a/internal/usage/request_cells.go +++ b/internal/usage/request_cells.go @@ -268,10 +268,10 @@ func mix(vs ...uint64) uint64 { // whose chunk has one serial and one sig read the same rows from it. func (ps *pairedRows) sigs(identities map[string]sessions.CodexIdentity) map[*rowChunk]uint64 { out := make(map[*rowChunk]uint64, len(ps.all)) - for ref := range ps.skip { + for ref := range ps.skip.all() { out[ref.Chunk] += mix(1, uint64(ref.Index)) } - for ref := range ps.matched { + for ref := range ps.matched.all() { out[ref.Chunk] += mix(2, uint64(ref.Index)) } actors := map[string]uint64{} diff --git a/internal/usage/request_index_review_test.go b/internal/usage/request_index_review_test.go index a86c2ea3a..37b5f469f 100644 --- a/internal/usage/request_index_review_test.go +++ b/internal/usage/request_index_review_test.go @@ -46,7 +46,7 @@ func TestRequestMatchIndexEquivalent(t *testing.T) { local.add(Row{Record: r, Source: "log"}, "", int64(i), r.Failed()) } for _, since := range []time.Time{{}, now.Add(5 * time.Second)} { - got := matchedLocal(gateway, []*rowChunk{local}, nil, since) + got := refMap(matchedLocal(gateway, []*rowChunk{local}, nil, since)) want := matchedLocalLegacy(gateway, []*rowChunk{local}, nil, since) if !reflect.DeepEqual(got, want) { t.Fatalf("seed %d: %d matches, want %d", seed, len(got), len(want)) @@ -140,7 +140,9 @@ func BenchmarkMatchedLocal(b *testing.B) { for _, impl := range []struct { name string f func(*rowChunk, []*rowChunk, map[rowRef]bool, time.Time) map[rowRef]bool - }{{"indexed", matchedLocal}, {"without_index", matchedLocalLegacy}} { + }{{"indexed", func(g *rowChunk, c []*rowChunk, _ map[rowRef]bool, since time.Time) map[rowRef]bool { + return refMap(matchedLocal(g, c, nil, since)) + }}, {"without_index", matchedLocalLegacy}} { b.Run(fmt.Sprintf("%d/dense=%v/%s", n, dense, impl.name), func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index 2835d5160..a760ff2c3 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -1321,8 +1321,8 @@ func (idx *requestIndex) trim(bound int64) { // localRefs visits first occurrences of Claude message IDs. It stores only // references for matches, never a full hydrated row for every call. -func visibleLocal(chunks []*rowChunk) map[rowRef]bool { - duplicates := map[rowRef]bool{} +func visibleLocal(chunks []*rowChunk) refSet { + duplicates := refSet{} // a message id seen is kept as two 64-bit hashes of it, not a copy of // the decoded chunk's string: a long history's ~400k ids held ~7MB of // copies at the start's peak, and a key of these is a string header's @@ -1349,7 +1349,7 @@ func visibleLocal(chunks []*rowChunk) map[rowRef]bool { } k := [2]uint64{maphash.String(msgSeeds[0], msg), maphash.String(msgSeeds[1], msg)} if _, ok := seen[k]; ok { - duplicates[rowRef{c, i}] = true + duplicates.add(rowRef{c, i}) } else { seen[k] = struct{}{} } @@ -1397,6 +1397,33 @@ type matchKey struct { failed, hasID bool } +// sum is k as two hashes of it, ~1e-28 likely alike for two keys. The +// session is followed by bytes of a fixed length, so two keys never read +// as the same bytes. +func (k matchKey) sum() [2]uint64 { + var tail [26]byte + for i, t := range k.tokens { + binary.LittleEndian.PutUint64(tail[8*i:], uint64(t)) + } + if k.failed { + tail[24] = 1 + } + if k.hasID { + tail[25] = 1 + } + var out [2]uint64 + for i, seed := range matchKeySeeds { + var h maphash.Hash + h.SetSeed(seed) + h.WriteString(k.session) + h.Write(tail[:]) + out[i] = h.Sum64() + } + return out +} + +var matchKeySeeds = [2]maphash.Seed{maphash.MakeSeed(), maphash.MakeSeed()} + // matchTokens is what a call's tokens are matched by: its input with what it // wrote to the cache in it, its output and what it read from the cache. The // two logs needn't split a cache write out of the input alike (#589): a @@ -1433,14 +1460,14 @@ type matchCandidate struct { // kept until ReleaseScratch, which the window calls once its reads rest, // or until no pairing has used it for scratchLinger. type matchScratch struct { - reserved map[rowRef]bool + reserved refSet byID map[string]int32 calls []idCalls ids map[uint32]struct{} found []idLocal - used map[rowRef]bool + used refSet refs []timedRef - groupOf map[matchKey]int32 + groupOf map[[2]uint64]int32 groups []matchGroup ks []int32 ends []matchEnd @@ -1545,17 +1572,18 @@ const agyMatchSession = "\x00agy" // second, where every other session file's time is when its call ended. const agyStepLongest = 30 * time.Minute -func matchedLocal(gateway *rowChunk, chunks []*rowChunk, skip map[rowRef]bool, since time.Time) map[rowRef]bool { +func matchedLocal(gateway *rowChunk, chunks []*rowChunk, skip refSet, since time.Time) refSet { return matchedBlocks([]*rowChunk{gateway}, chunks, skip, nil, since, true) } -func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]bool, responsePairs map[rowRef]rowRef, since time.Time, newestIDs bool) map[rowRef]bool { +func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip refSet, responsePairs map[rowRef]rowRef, since time.Time, newestIDs bool) refSet { scratch := matchScratchFor() defer scratch.release() - scratch.reserved = mapFor(scratch.reserved, len(responsePairs)*2) + scratch.reserved = mapFor(scratch.reserved, 0) reserved := scratch.reserved for gateway, local := range responsePairs { - reserved[gateway], reserved[local] = true, true + reserved.add(gateway) + reserved.add(local) } gatewaySince := since if !since.IsZero() { @@ -1584,7 +1612,7 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo for _, gateway := range gateways { for i := range gateway.Rows { ref := rowRef{gateway, i} - if reserved[ref] || !matchable(gateway, i) { + if reserved.has(ref) || !matchable(gateway, i) { continue } p := &gateway.Rows[i] @@ -1621,7 +1649,7 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo for i := range open.Rows { p := &open.Rows[i] ref := rowRef{c, i} - if skip[ref] || reserved[ref] || p.Time.Before(since) { + if skip.has(ref) || reserved.has(ref) || p.Time.Before(since) { continue } if open.text(p, 11) == 0 { @@ -1633,13 +1661,11 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo } } } - // made once the calls matched by id are known: grown from the response - // pairs alone, it was ~300 MB of what 80 s of polls allocated - matched := make(map[rowRef]bool, len(responsePairs)+len(found)) + matched := refSet{} for _, local := range responsePairs { - matched[local] = true + matched.add(local) } - scratch.used = mapFor(scratch.used, len(found)) + scratch.used = mapFor(scratch.used, 0) used := scratch.used refs := scratch.refs defer func() { scratch.refs = refs }() @@ -1664,13 +1690,14 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo if j >= calls[k].len() { break } - matched[ref.rowRef], used[calls[k].at(j)] = true, true + matched.add(ref.rowRef) + used.add(calls[k].at(j)) } } // keyOf is the key of a gateway call the local calls left without a // request id may match, ok false for one they never do keyOf := func(gateway *rowChunk, i int) (matchKey, bool) { - if reserved[rowRef{gateway, i}] || used[rowRef{gateway, i}] { + if reserved.has(rowRef{gateway, i}) || used.has(rowRef{gateway, i}) { return matchKey{}, false } p := &gateway.Rows[i] @@ -1697,8 +1724,14 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo } } } + // a key's place in groups, by its sum: keyed by the key, a session + // header, three counts and two flags, a whole history's calls held + // ~29 MB of the start's peak, kept with the scratch (#2278) scratch.groupOf = mapFor(scratch.groupOf, kept) - groupOf := scratch.groupOf // a key's place in groups + groupOf := scratch.groupOf + // the sessions the groups name + scratch.named = mapFor(scratch.named, 0) + named := scratch.named groups := scratch.groups defer func() { scratch.groups = groups }() ks := slices.Grow(scratch.ks, kept) // each kept call's group, in the order read @@ -1708,11 +1741,13 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo if !ok { continue } - k, ok := groupOf[key] + sum := key.sum() + k, ok := groupOf[sum] if !ok { k = int32(len(groups)) - groupOf[key] = k + groupOf[sum] = k groups = append(groups, matchGroup{}) + named[matchHash(key.session)] = struct{}{} } groups[k].n++ ks = append(ks, k) @@ -1744,11 +1779,6 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo } counts := sized(scratch.counts, len(ends)+len(groups)) scratch.counts = counts - scratch.named = mapFor(scratch.named, len(groups)) - named := scratch.named - for key := range groupOf { - named[matchHash(key.session)] = struct{}{} - } candidates := scratch.candidates defer func() { scratch.candidates = candidates }() for n, chunk := range chunks { @@ -1762,7 +1792,7 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo for j := range c.Rows { p := &c.Rows[j] ref := rowRef{chunk, j} - if skip[ref] || reserved[ref] || matched[ref] || p.Time.Before(since) { + if skip.has(ref) || reserved.has(ref) || matched.has(ref) || p.Time.Before(since) { continue } failed := p.Flags&16 != 0 @@ -1782,7 +1812,7 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo continue } key.hasID = hasID - k, ok := groupOf[key] + k, ok := groupOf[key.sum()] if !ok { continue } @@ -1818,7 +1848,7 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo } for _, c := range candidates { if unique[c.at] { - matched[c.ref] = true + matched.add(c.ref) } } return matched @@ -1899,15 +1929,15 @@ func ownStrings(v reflect.Value) { } // pairedRows are the page's rows of p: each gateway call told the Codex -// thread of the session file's call it is paired with (pairs), and the -// session files' calls a gateway call matched, or another file's copy, -// left out (matched, skip). visit hands each row on in all's order. The -// chunks are copies, so the cached ones are left as they are. +// thread of the session file's call it is paired with, and the session +// files' calls a gateway call matched, or another file's copy, left out +// (matched, skip). visit hands each row on in all's order. The chunks are +// copies, so the cached ones are left as they are. The pairs themselves +// are told the chunks and not kept: nothing read them, and a whole +// history's were held while its rows were visited (#2278). type pairedRows struct { all []*rowChunk - skip, matched map[rowRef]bool - pairs map[rowRef]rowRef - compactions map[rowRef]*bool + skip, matched refSet since, until time.Time } @@ -1932,8 +1962,8 @@ func pairRowsIn(since, until time.Time, gateways, chunks, others []*rowChunk, id } } skip := visibleLocal(chunks) - for ref := range duplicateSkip { - skip[ref] = true + for ref := range duplicateSkip.all() { + skip.add(ref) } matched := matchedBlocks(gateways, chunks, skip, pairs, since, true) for gateway, local := range pairs { @@ -1941,7 +1971,7 @@ func pairRowsIn(since, until time.Time, gateways, chunks, others []*rowChunk, id gateway.Chunk.setCodexCompaction(gateway.Index, compactions[local]) } all := append(append(slices.Clone(gateways), chunks...), others...) - return &pairedRows{all: all, skip: skip, matched: matched, pairs: pairs, compactions: compactions, since: since, until: until} + return &pairedRows{all: all, skip: skip, matched: matched, since: since, until: until} } // visitActors is visit of the rows of the chunks a Codex thread is known @@ -1972,7 +2002,7 @@ func (ps *pairedRows) visitChunk(rows *chunkRows, c *rowChunk, r *Row, fn func(t for i := range open.Rows { pr := &open.Rows[i] // not a copy: a row is 216 bytes ref := rowRef{c, i} - if pr.Time.Before(ps.since) || after(ps.until, pr.Time) || len(ps.skip) > 0 && ps.skip[ref] || len(ps.matched) > 0 && ps.matched[ref] { + if pr.Time.Before(ps.since) || after(ps.until, pr.Time) || ps.skip.has(ref) || ps.matched.has(ref) { continue } *r = open.row(i) diff --git a/internal/usage/request_page_test.go b/internal/usage/request_page_test.go index 6a5261160..c55c73bd3 100644 --- a/internal/usage/request_page_test.go +++ b/internal/usage/request_page_test.go @@ -324,7 +324,7 @@ func TestVisibleLocalLeavesOutRepeatedMessages(t *testing.T) { b.add(Row{}, "msg_3", 2, false) b.add(Row{}, "msg_2", 3, false) a, b = a.pack(), b.pack() - got := visibleLocal([]*rowChunk{a, b}) + got := refMap(visibleLocal([]*rowChunk{a, b})) if len(got) != 2 || !got[rowRef{b, 0}] || !got[rowRef{b, 3}] { t.Fatalf("left out %v, want b's rows 0 and 3 only", got) } diff --git a/internal/usage/request_pairs.go b/internal/usage/request_pairs.go index e79c798e4..7fd1f59d3 100644 --- a/internal/usage/request_pairs.go +++ b/internal/usage/request_pairs.go @@ -17,16 +17,11 @@ type pairMemo struct { // serials are the chunks' in pairRows' order, each set ended by a 0; // a chunk without a serial (the probes') is named by its rows instead serials []uint64 - skip, matched []serialRef + skip, matched map[uint64][]uint64 // refSets, by serial actors map[uint64]codexActors compactions map[uint64]map[int]*bool } -type serialRef struct { - serial uint64 - index int -} - // pairSerials names the chunks of a pairing, or is false when two have // no serial and so can't be told apart. func pairSerials(sets ...[]*rowChunk) ([]uint64, bool) { @@ -98,10 +93,10 @@ func memoOf(ps *pairedRows, serials []uint64, originals []*rowChunk) *pairMemo { m.compactions[serials[k-1]] = c.codexCompactions } } - refs := func(set map[rowRef]bool) []serialRef { - out := make([]serialRef, 0, len(set)) - for ref := range set { - out = append(out, serialRef{named[ref.Chunk], ref.Index}) + refs := func(set refSet) map[uint64][]uint64 { + out := make(map[uint64][]uint64, len(set)) + for c, b := range set { + out[named[c]] = slices.Clone(b) } return out } @@ -128,10 +123,10 @@ func (m *pairMemo) apply(serials []uint64, identities map[string]sessions.CodexI } k++ } - refs := func(list []serialRef) map[rowRef]bool { - out := make(map[rowRef]bool, len(list)) - for _, ref := range list { - out[rowRef{by[ref.serial], ref.index}] = true + refs := func(set map[uint64][]uint64) refSet { + out := make(refSet, len(set)) + for s, b := range set { + out[by[s]] = slices.Clone(b) } return out }