Files
magpie/internal/usage/pair_scratch_test.go
T
yetone 49d4d0f7ab usage: the request matcher keeps its maps for the next call, and gives them back once the window rests (#2278)
Every poll while an agent works matches a year's history again:
matchedBlocks and codexChunkResponsePairs grew their maps (byID,
reserved, used, groupOf, picks, picked, ...) and slices from nothing on
each call. They were ~3.0 GB of the ~40 GB a poll-heavy 80 s allocated
on the real-history harness (d1951 heap diff, 120 s to 200 s).

A sync.Pool was tried first and kept nothing in real use: under
tightenGC a poll collects 4-5 times a second (1029 GCs in 230 s), each
collection empties the pool, and the matcher's flat allocation went
only from 2241 to 1840 MB. So one scratch of each is kept in an
atomic.Pointer, emptied after a call (clear() keeps the maps' buckets,
and drops every chunk the call saw), and let go by usage.ReleaseScratch,
which releaseIfPagesRest calls before FreeOSMemory: once the window's
reads have rested 3 s, what the matching kept goes back with the rest.
A call that finds the scratch taken makes its own, sized as before.
matchedBlocks' result map is now made once the id matches are known,
not grown from the response pairs alone.

Measured on mote (Apple M5 Pro), at aeacc6358 + this change:
- BenchmarkPairRows (2000 files x 100 calls), -count 3: 100.8 MB/op,
  7,056 allocs/op at aeacc6358; 48.4 MB/op, 5,458 allocs/op after.
- Real history (copy of the user's usage.jsonl, sandbox HOME, polls +
  appended calls, run2278d.sh 230 s), heap alloc 120 s to 200 s:
  matchedBlocks flat 2241 -> 1295 MB, codexChunkResponsePairs flat
  806 -> 143 MB, of a total about the same (39.8 vs 39.3 GB). That run
  was before the result-map change. Its CPU and peak RSS (974 MiB vs
  936) aren't comparable: mote's load went from ~25 to 50-88 from other
  sessions during it.

Tests:
- New TestPairScratchKeepsNothingBetweenCalls (pairRows on one history
  after another matches what a first call does; ReleaseScratch lets go)
  and TestMatchScratchForgetsTheLastCall (a gateway call one call used by
  id or reserved by a response pair is matched in the next; ids the last
  call looked up in another gateway aren't).
- Broken by hand, each red: without clear of byID (index out of range),
  used ("the last call's id match held the gateway's call"), reserved
  ("the last call's response pair held"), groupOf and picks (index out
  of range). ids, named and picked only choose which chunks are opened,
  so a stale entry there costs a read, not a match.
- go test -count=1 -timeout 45m ./internal/usage/ ./internal/usageapi/
  ./internal/sessions/ ./internal/gui/ at aeacc6358 + this change: usage,
  usageapi, sessions ok; gui red in TestMainWindowCorners/macOS_26_SDK
  alone, mote's macOS 27 (#3949). An earlier gui run there had ten
  AppKit window tests killed at their 20-40 s deadlines at load ~40-88
  (#2645).
- GOOS=linux, windows, darwin go vet -tags nogui ./internal/usage/
  ./internal/gui/ ./internal/usageapi/: ok.

Rebased onto origin/main fe05f0a72 (library and Claude-account changes,
nothing in internal/usage or page_memory.go); after the rebase
./internal/usage/ and ./internal/usageapi/ ran again at the pushed
tree: ok, and go build . ok.
2026-10-29 04:33:14 +08:00

94 lines
3.3 KiB
Go

package usage
import (
"fmt"
"maps"
"testing"
"time"
"github.com/yetone/magpie/internal/sessions"
)
// The matcher keeps its maps and slices from one call for the next
// (#2278): a call after another, on other chunks or on the same ones,
// matches what a first call does.
func TestPairScratchKeepsNothingBetweenCalls(t *testing.T) {
now := time.Date(2026, 10, 1, 13, 0, 0, 0, time.UTC)
xg, xl := pairFixture(40, 30)
yg, yl := pairFixture(12, 9)
// what was matched, by chunk serial and row: Codex chunks are copied
// 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
}
return out
}
ReleaseScratch()
fresh := matched(yg, yl)
if len(fresh) != 12*9 {
t.Fatalf("a first call matched %d of %d", len(fresh), 12*9)
}
matched(xg, xl)
for round := range 2 {
if got := matched(yg, yl); !maps.Equal(got, fresh) {
t.Fatalf("round %d after another call matched %d, a first call %d", round, len(got), len(fresh))
}
}
if keptMatch.Load() == nil || keptPicks.Load() == nil {
t.Fatal("nothing kept for the next call")
}
ReleaseScratch()
if keptMatch.Load() != nil || keptPicks.Load() != nil {
t.Fatal("ReleaseScratch kept the scratch")
}
}
// What one call reserved, used or looked up by id never holds in the next
// call's matching of the same calls.
func TestMatchScratchForgetsTheLastCall(t *testing.T) {
now := time.Date(2026, 10, 1, 13, 0, 0, 0, time.UTC)
call := func(id string, i int) Record {
return Record{Time: now.Add(-time.Duration(i) * time.Minute), Agent: "claude", Provider: "relay", Session: "s", Input: 100 + i, Output: 5, Millis: 1000, RequestID: id}
}
chunk := func(source bool, rs ...Record) *rowChunk {
c := &rowChunk{serial: nextChunkSerial()}
for i, r := range rs {
row := Row{Record: r}
if source {
c.Source, row.Source = sessions.CallSource{Path: fmt.Sprint("/local/", c.serial)}, "log"
}
c.add(row, "", int64(i), false)
}
return c
}
// the gateway's call req-a, and a local call that names it or one that
// names no id, each the same call by session and tokens
gateway := chunk(false, call("req-a", 0))
named, unnamed := chunk(true, call("req-a", 0)), chunk(true, call("", 0))
// 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}]
}
ReleaseScratch()
if !match(gateway, unnamed, nil) || !match(gateway, named, nil) {
t.Fatal("a first call left a local call unmatched")
}
// named's id used the gateway's call: unnamed still matches it after
if !match(gateway, unnamed, nil) {
t.Fatal("the last call's id match held the gateway's call")
}
// a response pair reserved the gateway's call
match(gateway, unnamed, map[rowRef]rowRef{{gateway, 0}: {named, 0}})
if !match(gateway, unnamed, nil) {
t.Fatal("the last call's response pair held the gateway's call")
}
// req-a was the other gateway's sixth id
match(other, chunk(true, call("req-a", 4)), nil)
if !match(gateway, named, nil) {
t.Fatal("the last call's ids were looked up")
}
}