diff --git a/internal/gui/page_memory.go b/internal/gui/page_memory.go index 1df7aa942..2de27075b 100644 --- a/internal/gui/page_memory.go +++ b/internal/gui/page_memory.go @@ -4,6 +4,8 @@ import ( "runtime/debug" "sync" "time" + + "github.com/yetone/magpie/internal/usage" ) // A Sessions or Usage page's poll reads every session file's listing and @@ -70,6 +72,8 @@ func releaseIfPagesRest() { } release := pageReads.release pageReads.Unlock() + // what the request matching keeps for a poll's next read goes too + usage.ReleaseScratch() if release != nil { release() return diff --git a/internal/usage/codex_identity.go b/internal/usage/codex_identity.go index b213bb1ee..8507aa983 100644 --- a/internal/usage/codex_identity.go +++ b/internal/usage/codex_identity.go @@ -5,6 +5,7 @@ import ( "slices" "strings" "sync" + "sync/atomic" "time" "github.com/yetone/magpie/internal/sessions" @@ -182,20 +183,43 @@ func cloneCodexChunks(chunks []*rowChunk) []*rowChunk { // rowResponseID is rowText's slot of Record.ResponseID. const rowResponseID = 25 +// responsePick is what codexChunkResponsePairs knows of one response id +type responsePick struct { + gateways, locals int + gateway, local rowRef + gatewayOK, localOK bool + compaction *bool +} + +// pickScratch is what one codexChunkResponsePairs call works in, kept for +// the next as matchScratch is: made afresh on every poll, its maps and +// slab were ~775 MB of what 80 s of polls allocated while calls came in +// (#2278). +type pickScratch struct { + picks map[string]int32 + slab []responsePick + picked map[uint64]bool +} + +var keptPicks atomic.Pointer[pickScratch] + +// release empties s, so it holds no chunk of this call, and keeps it +func (s *pickScratch) release() { + clear(s.picks) + clear(s.picked) + clear(s.slab) + s.slab = s.slab[:0] + keptPicks.Store(s) +} + // codexChunkResponsePairs are the Codex calls the gateway and a session file // 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) { - type pick struct { - gateways, locals int - gateway, local rowRef - gatewayOK, localOK bool - compaction *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). - // Both are made the size of the gateway's ids, and a gateway call is + // The slab holds the gateway's ids, and a gateway call is // judged by the few strings that decide it, not made a Row: grown // from nothing, and a Row each, they were ~2.4 GB of what 80 s of // polls allocated while calls came in, on a year's history. @@ -210,8 +234,15 @@ func codexChunkResponsePairs(gateways, locals []*rowChunk, duplicateLocal map[ro } } } - picks := make(map[string]int32, withID) - slab := make([]pick, 0, withID) + scratch := keptPicks.Swap(nil) + if scratch == nil { + scratch = &pickScratch{} + } + defer scratch.release() + scratch.picks = mapFor(scratch.picks, withID) + picks := scratch.picks + slab := slices.Grow(scratch.slab, withID) + defer func() { scratch.slab = slab }() for _, chunk := range gateways { open := rows.of(chunk) for i := range open.Rows { @@ -224,7 +255,7 @@ func codexChunkResponsePairs(gateways, locals []*rowChunk, duplicateLocal map[ro if !ok { k = int32(len(slab)) picks[id] = k - slab = append(slab, pick{}) + slab = append(slab, responsePick{}) } pk := &slab[k] pk.gateways++ @@ -237,7 +268,8 @@ func codexChunkResponsePairs(gateways, locals []*rowChunk, duplicateLocal map[ro // a local chunk is read only when one of its ids may be a pick's: on a // page's poll every session file of the period was decoded again for // the few the gateway named - picked := make(map[uint64]bool, len(picks)) + scratch.picked = mapFor(scratch.picked, len(picks)) + picked := scratch.picked for id := range picks { picked[foldHash(id)] = true } diff --git a/internal/usage/pair_scratch_test.go b/internal/usage/pair_scratch_test.go new file mode 100644 index 000000000..2232cb7c6 --- /dev/null +++ b/internal/usage/pair_scratch_test.go @@ -0,0 +1,93 @@ +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") + } +} diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index 36d56ee5f..0aadaf5a9 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -22,6 +22,7 @@ import ( "sort" "strings" "sync" + "sync/atomic" "time" "unsafe" @@ -1338,6 +1339,90 @@ type matchGroup struct { off, n int32 } +// matchCandidate is a local call with one gateway call in its range, and +// that call's place in ends +type matchCandidate struct { + ref rowRef + at int32 +} + +// matchScratch is what one matchedBlocks call works in, kept for the +// next. Every poll while an agent works matches a year's history again, +// and growing these afresh each time was ~1.9 of the ~2.2 GB the matcher +// allocated in 80 s of polls (#2278). A sync.Pool kept nothing: a poll +// collects several times a second, and each collection empties it. One is +// kept until ReleaseScratch, which the window calls once its reads rest. +type matchScratch struct { + reserved map[rowRef]bool + byID map[string]int32 + calls []idCalls + ids map[uint32]struct{} + found []idLocal + used map[rowRef]bool + refs []timedRef + groupOf map[matchKey]int32 + groups []matchGroup + ks []int32 + ends []matchEnd + counts []int32 + named map[uint64]struct{} + unique []bool + candidates []matchCandidate +} + +var keptMatch atomic.Pointer[matchScratch] + +// matchScratchFor is the kept scratch, or a new one when another call has +// it or none is kept +func matchScratchFor() *matchScratch { + if s := keptMatch.Swap(nil); s != nil { + return s + } + return &matchScratch{} +} + +// mapFor is m, or a new map made for n when there is none yet +func mapFor[K comparable, V any](m map[K]V, n int) map[K]V { + if m == nil { + return make(map[K]V, n) + } + return m +} + +// ReleaseScratch lets go of what the request matching keeps between calls. +func ReleaseScratch() { + keptMatch.Store(nil) + keptPicks.Store(nil) +} + +// sized is s[:n], zeroed, in s's array when it holds n +func sized[T any](s []T, n int) []T { + if cap(s) < n { + return make([]T, n) + } + s = s[:n] + clear(s) + return s +} + +// release empties s, so it holds no chunk of this call, and keeps it +func (s *matchScratch) release() { + clear(s.reserved) + clear(s.byID) + clear(s.ids) + clear(s.used) + clear(s.groupOf) + clear(s.named) + clear(s.calls) + clear(s.found) + clear(s.refs) + clear(s.ends) + clear(s.candidates) + s.calls, s.found, s.refs, s.groups, s.ks = s.calls[:0], s.found[:0], s.refs[:0], s.groups[:0], s.ks[:0] + s.ends, s.counts, s.unique, s.candidates = s.ends[:0], s.counts[:0], s.unique[:0], s.candidates[:0] + keptMatch.Store(s) +} + // agyMatchSession stands for the session of an Antigravity CLI (agy) call // on both sides: agy sends the gateway no session header, so its gateway // records name none, and its transcript's steps are matched to them by @@ -1354,11 +1439,12 @@ func matchedLocal(gateway *rowChunk, chunks []*rowChunk, skip map[rowRef]bool, s } func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]bool, responsePairs map[rowRef]rowRef, since time.Time, newestIDs bool) map[rowRef]bool { - reserved := make(map[rowRef]bool, len(responsePairs)*2) - matched := make(map[rowRef]bool, len(responsePairs)) + scratch := matchScratchFor() + defer scratch.release() + scratch.reserved = mapFor(scratch.reserved, len(responsePairs)*2) + reserved := scratch.reserved for gateway, local := range responsePairs { reserved[gateway], reserved[local] = true, true - matched[local] = true } gatewaySince := since if !since.IsZero() { @@ -1380,8 +1466,10 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo } } } - byID := make(map[string]int32, withID) - calls := make([]idCalls, 0, withID) + scratch.byID = mapFor(scratch.byID, withID) + byID := scratch.byID + calls := slices.Grow(scratch.calls, withID) + defer func() { scratch.calls = calls }() for _, gateway := range gateways { for i := range gateway.Rows { ref := rowRef{gateway, i} @@ -1401,11 +1489,13 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo } // the local calls that name an id, chained from its calls[k].last in // the order they were found - var found []idLocal + found := scratch.found + defer func() { scratch.found = found }() rows := lentRows() // a key is looked up defer rows.release() hints := hintsOf(chunks, &rows) - ids := make(map[uint32]struct{}, len(byID)) + scratch.ids = mapFor(scratch.ids, len(byID)) + ids := scratch.ids for id := range byID { ids[uint32(matchHash(id))] = struct{}{} } @@ -1432,8 +1522,16 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo } } } - used := make(map[rowRef]bool, len(found)) - var refs []timedRef + // 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)) + for _, local := range responsePairs { + matched[local] = true + } + scratch.used = mapFor(scratch.used, len(found)) + used := scratch.used + refs := scratch.refs + defer func() { scratch.refs = refs }() for k := range calls { refs = refs[:0] for j := calls[k].last; j != 0; j = found[j-1].before { @@ -1488,9 +1586,11 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo } } } - groupOf := make(map[matchKey]int32, kept) // a key's place in groups - var groups []matchGroup - ks := make([]int32, 0, kept) // each kept call's group, in the order read + scratch.groupOf = mapFor(scratch.groupOf, kept) + groupOf := scratch.groupOf // a key's place in groups + groups := scratch.groups + defer func() { scratch.groups = groups }() + ks := slices.Grow(scratch.ks, kept) // each kept call's group, in the order read for _, gateway := range gateways { for i := range gateway.Rows { key, ok := keyOf(gateway, i) @@ -1512,7 +1612,8 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo groups[k].off, off = off, off+groups[k].n groups[k].n = 0 } - ends := make([]matchEnd, len(ks)) + ends := sized(scratch.ends, len(ks)) + scratch.ends, scratch.ks = ends, ks next := 0 for _, gateway := range gateways { for i := range gateway.Rows { @@ -1526,23 +1627,19 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo g.n++ } } - ks = nil for k := range groups { g := groups[k] slices.SortFunc(ends[g.off:g.off+g.n], func(a, b matchEnd) int { return a.at.Compare(b.at) }) } - counts := make([]int32, len(ends)+len(groups)) - named := make(map[uint64]struct{}, len(groups)) + 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{}{} } - // a local call with one gateway call in its range, and that call's - // place in ends - type candidate struct { - ref rowRef - at int32 - } - var candidates []candidate + candidates := scratch.candidates + defer func() { scratch.candidates = candidates }() for n, chunk := range chunks { if hints[n].latest.Before(since) || !namesAny(hints[n].sessions, named) { continue @@ -1592,11 +1689,12 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo } } if count == 1 { - candidates = append(candidates, candidate{ref, at}) + candidates = append(candidates, matchCandidate{ref, at}) } } } - unique := make([]bool, len(ends)) + unique := sized(scratch.unique, len(ends)) + scratch.unique = unique for k := range groups { g := groups[k] count := int32(0)