Files
magpie/internal/usage/match_chunks.go
T
yetone b5d2858f41 usage: matching gateway calls decodes only the session files they can match (#2278)
matchedBlocks paired the gateway's calls with the session files' by
request id, then by session, tokens and time, and decoded every session
file of the period for each pass: twice per poll, for the few sessions
the gateway had calls of. In a 24s heap profile of a fed sandbox it was
0.77 GB of the 5.3 GB allocated, and 5.4s of a minute's 42s of CPU.

Each local chunk's hints are now kept by its serial (match_chunks.go,
as chunkIDs keeps Codex's response ids): a 32-bit hash of each request
id it names, a hash of each session a call of it can be matched in
(agy's as agyMatchSession, rows of no tokens and no failure left out,
as the pass does), and its last call's time. A pass decodes a chunk
only when one of its ids or sessions is the gateway's and its last call
is in the period. A hash that matches only decodes the chunk, so the
matches are exact. Hints live 8 matchings past their last use.

Run at this head (cb167fcbd + this change), on mote:
- TestMatchOpensOnlyNamedChunks (new): 20 seeds of 12 session files, the
  gateway naming four sessions and one id in a fifth file; the matches
  equal matchedLocalLegacy's and only named files are decoded. Red with
  namesAny always true ("matching decoded /local/session-4").
- TestMatchOpensAgyChunks (new): an agy step is matched with its file
  alone decoded.
- go test ./internal/usage -timeout 45m: ok (26.9s).
- go vet -tags nogui ./internal/usage for darwin, linux and windows:
  clean.

A/B on mote, the sandbox of #2278's synthetic history (34k sessions,
3000 with gateway records), 10 page endpoints polled every 5s and 4
gateway appends a second, 230s each, old = dc6f6d902 (v0.1.1927):
                       old        new
  all polls mean     4.93s      3.15s
  heatmap mean      11.86s      7.24s
  footprint peak    707.2M     632.4M
  avg CPU after feed  90.0%      79.6%
mote's load was ~100 from other sessions' suites through both arms, so
the times are slower than an idle machine's; the arms ran back to back.
Then rebased onto b119f8777, which changes an internal/gateway test and
LESSONS.md only.

Not tried: the user's own history.
2026-10-29 00:25:57 +08:00

120 lines
3.1 KiB
Go

package usage
import (
"hash/maphash"
"slices"
"sync"
"time"
)
// matchHints are what matchedBlocks needs to know of a local chunk before
// decoding it, kept by the chunk's serial: the request ids its calls name,
// the sessions its calls can be matched in, and its last call's time. A
// poll matched the gateway's calls against every session file of the
// period, decoding each twice to find the few sessions the gateway had
// calls of: ~0.8 GB a minute and seconds of CPU while an agent worked
// (#2278). A chunk none of whose ids or sessions the gateway names can
// match nothing, and is not decoded.
var matchHints struct {
sync.Mutex
by map[uint64]*chunkHints
turn uint64
}
type chunkHints struct {
ids []uint32 // matchHash of each request id, sorted, once each
sessions []uint64 // matchHash of each session a call can match in
latest time.Time
turn uint64
}
// hintsKept is how many matchings a chunk's hints outlive the last that
// read them: the page, the Sessions pages and the ledger match chunks of
// their own.
const hintsKept = 8
var matchSeed = maphash.MakeSeed()
func matchHash(s string) uint64 { return maphash.String(matchSeed, s) }
// matchOpening, in tests, is told each local chunk matchedBlocks decodes.
var matchOpening func(*rowChunk)
// hintsOf are chunks' hints, read from a chunk only when none are kept for
// its serial.
func hintsOf(chunks []*rowChunk, rows *chunkRows) []*chunkHints {
matchHints.Lock()
matchHints.turn++
turn := matchHints.turn
out := make([]*chunkHints, len(chunks))
for i, c := range chunks {
if h := matchHints.by[c.serial]; c.serial != 0 && h != nil {
h.turn = turn
out[i] = h
}
}
matchHints.Unlock()
made := map[uint64]*chunkHints{}
for i, c := range chunks {
if out[i] != nil {
continue
}
h := &chunkHints{turn: turn}
open := rows.of(c)
for j := range open.Rows {
p := &open.Rows[j]
if p.Time.After(h.latest) {
h.latest = p.Time
}
if id := open.Strings[open.text(p, 11)]; id != "" {
h.ids = append(h.ids, uint32(matchHash(id)))
}
if p.Tokens[0]+p.Tokens[1]+p.Tokens[2]+p.Tokens[3] == 0 && p.Flags&16 == 0 {
continue
}
session := open.Strings[open.text(p, 13)]
if open.Strings[open.text(p, 0)] == "agy" {
session = agyMatchSession
}
if s := matchHash(session); len(h.sessions) == 0 || h.sessions[len(h.sessions)-1] != s {
h.sessions = append(h.sessions, s)
}
}
slices.Sort(h.ids)
h.ids = slices.Clip(slices.Compact(h.ids))
slices.Sort(h.sessions)
h.sessions = slices.Clip(slices.Compact(h.sessions))
out[i] = h
if c.serial != 0 {
made[c.serial] = h
}
}
matchHints.Lock()
if matchHints.by == nil {
matchHints.by = map[uint64]*chunkHints{}
}
for serial, h := range made {
matchHints.by[serial] = h
}
for serial, h := range matchHints.by {
if h.turn+hintsKept < matchHints.turn {
delete(matchHints.by, serial)
}
}
matchHints.Unlock()
return out
}
// namesAny says some id of ids is in set
func namesAny[T comparable](ids []T, set map[T]struct{}) bool {
if len(set) == 0 {
return false
}
for _, id := range ids {
if _, ok := set[id]; ok {
return true
}
}
return false
}