Files
magpie/internal/usage/kept_strings_test.go
T
yetone e7114d3882 usage: one gateway session projection is kept, and a range of days is read out of it (#2776)
The gateway's sessions were projected and kept once per `since`, up to
four at once (all time, and each Sessions stats range: today, 7, 30
days...). With 600k calls the all-time projection alone is ~160 MB in
use (pprof inuse_space of buildGatewaySessions on the sandbox below),
and #2776 counted 148 MB for its copies.

Now only the all-time projection is kept. A range that starts at a
local midnight (every stats range does: combinedSessionStats parses
st.From in time.Local) is derived from it: each session's days from that
date on, with its tokens, models, cost and start/last summed from those
days. Each kept day now carries the first and last time of its requests
(unexported, two time.Time) so the derived start and last are exact.
Any other start is built from the log and not kept. The cache is keyed
on the zone too, since the days are local dates.

TestGatewayWindowsShareOneProjection: six days of calls over three
sessions, priced and unpriced models; the all-time read and five ranges
(0, 1, 2, 3 and 7 days back) build one projection between them, and each
range equals a direct build from its midnight (sessions, start, last,
tokens, models, cost within 1e-9, unpriced, days). Broken by hand:
- the midnight path turned off (a build per range, as before): red,
  "built 6 projections for one log and 5 ranges, want 1".
- the derived start taken from the whole session: red, codex|even's
  Start 2026-10-15 where the build says 2026-10-19.

Cost: the two times per kept day add ~13 MB to the one projection on the
sandbox below (158 -> 171 MB in use), against a whole second projection
(~160 MB) for each range a page asks for.

Measured: the sandbox runs (see the commits before) ask only the 30-day
range, so their heap shows one kept projection on both sides; the
saving is per extra range asked and is shown by the test's build count,
not by those runs.

Run on origin/main 2ceff7370 with all four #2776 commits' changes
(this one and the three beside it), load average 291-568 (nine agents
running suites), macOS:
- go test -p 4 ./... -timeout 45m, 09:35-10:49: 62 packages ok,
  among them agent (2310s), gateway (1707s), provider (764s), usage
  (83s). Red:
  - internal/sessions: TestWSLOmpProfiles, TestWSLStoppedDistroKept,
    TestWSLStoppedSinceNotOpened, TestWSLNoneWithoutHomes, each
    "TempDir: mkdir ...: no space left on device" (the disk filled
    mid-run). After space was freed, ./internal/sessions alone: ok
    (139s).
  - internal/gui: TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
    TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow,
    TestDockReopenKeepsTheWindowsSpace (each killed at 30s) and
    TestMainWindowCorners (86s): the real-window AppKit tests under
    load, already filed as #2645 and #1936. Rerun alone at load ~335:
    all pass, with TestSetAnswersWhileDevinAndProvidersHang (17s).
- gofmt -l: none. go vet: darwin, GOOS=linux -tags nogui and
  GOOS=windows all exit 0.
- No internal/gui/assets file changed, so the GUI Playwright suite was
  not run.
2026-10-19 11:33:00 +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{}); len(got) != blocks {
t.Fatalf("vias: %d, want %d", len(got), 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.value = 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)
}
}