usage: the Requests page keeps its chunks while it is open

Every new call is a new page key, so the open Requests tab works its
page out again on each 5s refresh. The session files' packed chunks
were held to 24 MB. A history of 416,000 calls has 63 MB of them, so
each rebuild read 2,679 shards again (39 MB), gob-decoded them, priced
each call and packed it again, and dropped them again after.

Now the chunks are held to 128 MB while the page is asked for. After 2
minutes with no ask (requestIdle), a timer cuts them back to the 24 MB
they were held to before (requestIdleBytes), so an unopened page holds
what it held before.

Measured on the real sandbox data (sbmem, 416,665 rows):
- zzbench, one QueryPage of period=all and six rebuilds at new offsets,
  alternated with v0.1.1439's code at load ~150-200: user CPU
  17.26 / 16.09 s before, 10.79 / 10.21 s after; sys 3.41 / 3.01 ->
  1.98 / 2.14 s; peak RSS 604 / 664 MB -> 566 / 543 MB. A debug count
  showed 2,679 shards read per rebuild before and 1-2 after (the
  files that grew).
- A running magpie (`web --gateway` under sbmem), /api/usage/requests
  period=all at offsets 1-5, warm file cache, load ~175: rebuilds
  1.98 / 1.99 / 1.50 / 1.69 / 1.52 s on v0.1.1439, 1.30 / 1.18 / 1.09 /
  1.07 / 1.07 s now. Cold (the first run after building), one rebuild
  took 23 s; v0.1.1439's cold rebuilds took 5.5-8.0 s, and the warm
  reruns didn't show it again.
- Heap in use on that server, by /v1/magpie/heap: after the builds
  175.7 MB (v0.1.1439) and 199.1 MB (now); after 140 s unasked 161.7
  and 149.8 MB. Footprint 339 -> 286 MB and 302 -> 254 MB.

Tests: TestRequestChunksTrimmedWhenIdle checks that three chunks over
the idle bound are kept while the page is asked for, and dropped once
it goes unasked. It waits for that state, not for a time. Broken by hand
both ways: without the idle trim it fails ("3 chunks kept after the
page went unasked"), and with the build trimming to the idle bound it
fails ("0 chunks kept while the page is asked for"). It also passes
with -race -count=3.

Run at this head: go test -count=1 ./internal/usage ./internal/gui ok
(16.1s, 201.8s); go vet -tags nogui for GOOS=linux and windows on
internal/usage ok; gofmt -l clean. Not run: the full suite (other
sessions' suites hold the machine).
This commit is contained in:
yetone
2026-10-25 03:58:02 +08:00
parent 511c4a765e
commit 8b460833e0
2 changed files with 92 additions and 7 deletions
+50
View File
@@ -5,9 +5,12 @@ import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/sessions"
)
func TestUsageSameSizeAndMtimeRewrite(t *testing.T) {
@@ -413,3 +416,50 @@ func TestUsageLedgerReadsTheIndexNotTheFile(t *testing.T) {
t.Fatalf("the ledger parsed the whole log %d times", n)
}
}
// While the page is asked for, the session files' chunks are kept to
// requestCacheBytes, so a refresh after a new call reads none of them again;
// once it goes unasked for requestIdle they are held to requestIdleBytes
// (#3493).
func TestRequestChunksTrimmedWhenIdle(t *testing.T) {
pageHome(t)
now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local))
oldIdle, oldIdleBytes := requestIdle, requestIdleBytes
t.Cleanup(func() {
requestCache.Lock()
requestIdle, requestIdleBytes = oldIdle, oldIdleBytes
requestCache.Unlock()
})
cacheBudget(t, 1<<30)
requestCache.Lock()
requestIdle, requestIdleBytes = time.Hour, 1
requestCache.Unlock()
dir := filepath.Join(sessions.CodexDir(), "sessions")
os.MkdirAll(dir, 0700)
for i := range 3 {
meta := fmt.Sprintf(`{"type":"session_meta","payload":{"id":"s%d","model_provider":"custom"}}`, i) + "\n" + `{"type":"turn_context","payload":{"model":"m"}}` + "\n"
line := fmt.Sprintf(`{"timestamp":%q,"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":10,"output_tokens":1},"last_token_usage":{"input_tokens":10,"output_tokens":1}}}}`+"\n", now.Add(-time.Duration(i)*time.Minute).Format(time.RFC3339Nano))
os.WriteFile(filepath.Join(dir, fmt.Sprintf("rollout-2026-09-30T00-00-0%d-s%d.jsonl", i, i)), []byte(meta+line), 0600)
}
chunks := func() int {
requestCache.Lock()
defer requestCache.Unlock()
return len(requestCache.chunks)
}
if p := QueryPage(All, Filter{}, 0, 100); p.Total != 3 {
t.Fatalf("total %d, want 3", p.Total)
}
if n := chunks(); n != 3 {
t.Fatalf("%d chunks kept while the page is asked for, want 3", n)
}
requestCache.Lock()
requestIdle = time.Millisecond
requestCache.Unlock()
QueryPage(All, Filter{}, 0, 100) // asked again: the idle wait starts over
for deadline := time.Now().Add(10 * time.Second); chunks() != 0; {
if time.Now().After(deadline) {
t.Fatalf("%d chunks kept after the page went unasked, want 0", chunks())
}
time.Sleep(5 * time.Millisecond)
}
}
+42 -7
View File
@@ -473,6 +473,8 @@ type requestIndex struct {
// heats are the heatmap's last pages, kept while the agents' session
// files are all that changed (heatFresh)
heats map[pageKey]heatPage
// idle trims the chunks once the page goes unasked (keepWhileAsked)
idle *time.Timer
}
// heatPage is a heatmap's page, of the gateway log's snapshot version,
@@ -506,7 +508,18 @@ type pageFlight struct {
var requestCache requestIndex
var requestCacheBytes int64 = 24 << 20
// requestCacheBytes bounds the session files' chunks kept while the
// Requests page is in use, and requestIdleBytes once it has gone unasked
// for requestIdle. Every new call is a new page key, so the open page
// is worked out again each refresh, and a chunk dropped is a shard read,
// decoded and priced again for each: at 24 MB a history of 416,000 calls
// (63 MB of chunks) read 2,679 shards again on every refresh, a third of
// its CPU (#3493). Idle, it is held to what it was before.
var (
requestCacheBytes int64 = 128 << 20
requestIdleBytes int64 = 24 << 20
requestIdle = 2 * time.Minute
)
func statKey(path string) string {
s, e := os.Stat(path)
@@ -613,6 +626,7 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
version, meta, key, root := snapshot.version, st.meta, st.key, st.root
idx := &requestCache
idx.Lock()
idx.keepWhileAsked()
if idx.root != root || idx.meta != meta {
idx.root, idx.meta = root, meta
@@ -826,15 +840,37 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
}
shared.heats[q] = heatPage{page: page, version: version, at: began}
}
// The session files' chunks are bounded; the gateway's index is not
// counted here, as it is kept whatever its size (log_index.go).
shared.trim(requestCacheBytes)
return page
}
// keepWhileAsked holds the chunks to requestCacheBytes while the page is
// asked for, and to requestIdleBytes once it has gone unasked for
// requestIdle. idx is locked.
func (idx *requestIndex) keepWhileAsked() {
if idx.idle != nil {
idx.idle.Reset(requestIdle)
return
}
idx.idle = time.AfterFunc(requestIdle, func() {
idx.Lock()
defer idx.Unlock()
idx.trim(requestIdleBytes)
})
}
// trim drops the chunks used longest ago until the rest are within bound.
// The session files' chunks are bounded; the gateway's index is not
// counted here, as it is kept whatever its size (log_index.go). idx is
// locked.
func (idx *requestIndex) trim(bound int64) {
var bytes int64
type cachedChunk struct {
path string
row *rowChunk
}
var kept []cachedChunk
for path, c := range shared.chunks {
for path, c := range idx.chunks {
bytes += c.Bytes
kept = append(kept, cachedChunk{path: path, row: c})
}
@@ -848,13 +884,12 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
return strings.Compare(a.path, b.path)
})
for _, c := range kept {
if bytes <= requestCacheBytes {
if bytes <= bound {
break
}
delete(shared.chunks, c.path)
delete(idx.chunks, c.path)
bytes -= c.row.Bytes
}
return page
}
// localRefs visits first occurrences of Claude message IDs. It stores only