Files
magpie/internal/usage/kept_strings_test.go
T
yetone 2fcd4b33c4 usage: one Vias index answers every since, instead of a rebuild from the whole log whenever the since changes (#2776)
Vias kept the lists for one since. The Sessions list asks from its
oldest listed session's start, each agent's manage page from that
agent's oldest, and a session's detail from that session's start, so
an open page's polls almost never asked the kept since, and each ask
read and grouped the whole log again. Idle with an open Sessions page
on the 720k-call sandbox, buildVias allocated 9.1 GB in 8 minutes,
78% of everything allocated, which is most of why the idle process
churned its heap and grew.

The cache now keeps one index from the whole log and each session's
first call. A session whose calls all came at or after the since is
answered from it. A session with calls before its since is answered
from one kept window for that since, built only when such a session
is read. Len counts the sessions with a call since the index's time.
Both are kept per log version and agent list, as before.

TestViasAnswerEverySinceFromOneIndex writes 20,001 sessions and asks
from three sinces in turn, as the three pages do: 2,677 bytes an ask.
On the old cache: red, 11,580,100 bytes an ask. It also checks that a
session with a call on each side of a since counts only the one after
it, and what Len says for a window and for every session.
TestGatewaySessionsCachePricesWindowsAndRewrite's window check and
TestUsageViasSkipsOldHistory stay green.

720k-call sandbox, idle with an open page's polls every 15 s (the
Sessions list, stats, Claude's manage page, Requests, state), before
and after side by side for 12 minutes, load ~170-250. Allocated from
minute 4 to minute 12: buildVias 9,100 MB before, 0 after (built once,
before minute 4). The faster answers let the poll loop run about twice
as often, so the totals (11.6 GB and 10.5 GB) aren't per poll. The
live heap ran 352-641 MB before and 514-724 MB after, and RSS 730-962
and 555-1217 MB; both swing with where a poll is when the snapshot is
taken and the machine's load, and neither shows a trend in 12 minutes.

Run: go test -p 4 -count=1 ./internal/usage/ -run
'Vias|KeptStrings|GatewaySessionsCachePrices|Incremental|Review': ok.

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:19 +08:00

77 lines
2.2 KiB
Go

package usage
import (
"bufio"
"crypto/rand"
"encoding/hex"
"encoding/json"
"os"
"path/filepath"
"runtime"
"testing"
"time"
)
// An unpacked block's strings share one allocation, so a cache that keeps a
// session id or a model name read from a block must copy it out, or it keeps
// every string of that block: over a long history, the decoded text of all
// of it. This test fills each block with 1 KB of unique error text and gives
// each block its own session, then measures what the Sessions and Routing
// caches hold once the log index itself is let go.
func TestSessionCachesHoldNoDecodedBlocks(t *testing.T) {
resetUsageTest(t)
const blocks, text = 16, 1024
path := Path()
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
t.Fatal(err)
}
f, err := os.Create(path)
if err != nil {
t.Fatal(err)
}
w := bufio.NewWriter(f)
at := time.Now().Add(-time.Hour)
noise := make([]byte, text/2)
for b := range blocks {
for range logBlockRows {
rand.Read(noise)
line, _ := json.Marshal(Record{Time: at, Agent: "codex", Session: "s" + string(rune('a'+b)), Provider: "p", Model: "m", Effort: "high", Input: 10, Output: 2, Status: 200, Error: hex.EncodeToString(noise)})
w.Write(append(line, '\n'))
}
}
if err := w.Flush(); err != nil {
t.Fatal(err)
}
f.Close()
held := func() uint64 {
var m runtime.MemStats
runtime.GC()
runtime.GC()
runtime.ReadMemStats(&m)
return m.HeapAlloc
}
if got := GatewaySessions(time.Time{}, nil); len(got) != blocks {
t.Fatalf("sessions: %d, want %d", len(got), blocks)
}
if got := Vias(time.Time{}); got.Len() != blocks {
t.Fatalf("vias: %d, want %d", got.Len(), blocks)
}
// the index is kept by design; only what the caches hold is measured
logIndex.Lock()
logIndex.snapshot = nil
logIndex.Unlock()
withCaches := held()
gatewayCache.Lock()
gatewayCache.entry = nil
gatewayCache.Unlock()
viasCache.Lock()
viasCache.all, viasCache.window.m = nil, nil
viasCache.Unlock()
without := held()
decoded := uint64(blocks * logBlockRows * text)
if withCaches > without && withCaches-without > decoded/8 {
t.Fatalf("the caches hold %d KB for %d sessions: the decoded text of their blocks (%d KB)", (withCaches-without)>>10, blocks, decoded>>10)
}
}