Files
magpie/internal/gui/page_memory.go
T
yetone 1829cd52ff sessions: a poll while a session grows makes only the rows it shows
VeryBTC on X (tweet 2117104179454091396) reported RSS that rises and
stays up while the window is open and a long-context session is active.
In that case every Sessions poll sees a changed file and rebuilds the
list. That rebuild copied every gateway-only session three times
(GatewaySessions, listedGateway, gatewayListed) and made each one a
Session row before EachMerged stopped at its 5000-row limit. It also
made every Claude Code file's path and key again.

- usage.EachGatewaySession walks the projection without copying it.
  gui's listedExternal stops at the list's limit and skips hidden
  sessions and sessions without an agent or id, as listedGateway did.
- sessions.EachMerged sorts indexes and makes a row only when the merge
  reaches it. The order is unchanged: newest first, stable on ties.
- listCCFiles reuses the last listing's path and key strings while a
  folder lists the same names. One file new or gone is stepped over.
  This holds ~32 B per file (~480 KB at 15k files), and the strings are
  shared with the listing it already held.
- page_memory.go's ~330 MB comment now has current numbers.
  gateway-sessions.md describes the lazy rows.

Per poll, on mote (go test probe through the real /api/sessions
handler, TotalAlloc):
  15k sessions x 10 turns, 400k ledger rows
    after a session file grows  150.6 MB, 201 ms -> 109.9 MB, 170 ms
    unchanged (warm)             17.2 MB         ->  12.0 MB
  3k sessions x 40 turns, 150k rows (no gateway-only rows past the cap)
    after a session file grows   31.3 MB         ->  29.6 MB
    unchanged (warm)              4.5 MB         ->   3.4 MB
  /api/usage is unchanged at 0.4 MB.

Tests:
- TestSessionsListMakesOnlyTheGatewayRowsItShows (gui) uses 3 natives,
  6000 gateway sessions in tied pairs, one hidden and one carrying a
  native's id. At limits 5, 40 and 6010, and with no limit, the rows
  equal the old pipeline's (listedGateway + gatewayListed +
  MergeExternal) after the JSON round trip. A grown native comes first
  with its new Last. The poll's allocation stays under 6000 rows' size.
- TestEachMergedMakesOnlyTheRowsItReaches (sessions): 15000 externals
  and 20 rows give MergeExternal's first 20, with allocation under a
  tenth of the rows.
- TestCCListingKeepsItsNames (sessions): a second listing of 3000 files
  is equal to the first, in at most 3n mallocs. A file added, files
  removed, and a folder gone with another new each list as a fresh
  listing does. Another agent's keys keep their own prefix.

Broken by hand, each red:
- EachMerged building every row first: 8.8 MB, the sessions test fails.
- The GUI handler back on the listedGateway(GatewaySessions) loop, with
  the lazy merge kept: 13.7 MB, the gui test fails.
- The gui test on origin/main's code: 23 MB, fails.
- The ccNames reuse turned off: 12197 mallocs, the listing test fails.

Run on mote (mote-run) at 73a1b8769, rebased on origin/main 07f4d46c5:
gofmt -l internal (empty), go vet ./..., GOOS=linux go vet -tags nogui
./..., GOOS=windows go vet ./... all clean. go test -count=1 -timeout
45m ./internal/sessions ./internal/usage ./internal/gui: sessions ok,
usage ok. gui is ok except TestMainWindowCorners/macOS_26_SDK, which is
#3949 (red on mote's macOS 27, an AppKit title bar test this change
doesn't reach). It was red the same way in the run before the rebase.

Not tried:
- A real app window with RSS measured over time. The numbers are
  allocation per poll from a probe.
- The rest of a changed poll: statsKept re-sums every session (~26 MB at
  15k), listing (~24 MB) and byKey (~9 MB). None was a cheap, safe
  change.
- Windows and Linux test runs (vet only).
- A gateway title store in the fixture. GatewayTitler's ReadDirs now run
  only for the rows shown.
2026-11-02 17:19:23 +08:00

89 lines
2.8 KiB
Go

package gui
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
// the request ledger again. That was ~330 MB allocated every 15 s to keep
// ~105 MB; over 15k sessions and 400k calls (11-02) an unchanged poll is
// ~12 MB of Sessions' and ~0.4 MB of Usage's, and one while a session
// grows, which re-sums every session's stats, ~110 MB. Go keeps the pages
// that freed, and its scavenger hands them back only
// slowly, never while the next collection's goal covers them, so an open
// window sat at ~340 MB in Activity Monitor between polls. The gateway
// hands its requests' pages back once it rests (#3472), but the window's
// reads aren't its requests. So once those reads have rested for
// pageRest, what they left goes back at once, as the warm-up's does.
// pageRest is how long the page reads rest before that. It outlasts the
// pages' polls (Usage every 10 s, Sessions every 15 s), so the pages go
// back once a window stops polling, not between an open window's polls:
// at 3 s every poll took back the pages the last one handed back, and
// madvise and the collections it drove were ~40% of the CPU (#2278).
const pageRest = 30 * time.Second
var pageReads struct {
sync.Mutex
n int // reads in flight
last time.Time // when the latest ended
due *time.Timer // the release to come, or nil
rest time.Duration
// debug.FreeOSMemory, or a test's count
release func()
}
// readingPage counts a page read until done is called, and has what it
// left handed back once no read has been in flight for pageRest.
func readingPage() (done func()) {
pageReads.Lock()
pageReads.n++
pageReads.Unlock()
return sync.OnceFunc(func() {
pageReads.Lock()
defer pageReads.Unlock()
pageReads.last = time.Now()
if pageReads.n--; pageReads.n == 0 && pageReads.due == nil {
pageReads.due = time.AfterFunc(pageRestFor(), releaseIfPagesRest)
}
})
}
// pageRestFor is pageRest, or a test's. Called under pageReads' lock.
func pageRestFor() time.Duration {
if pageReads.rest > 0 {
return pageReads.rest
}
return pageRest
}
// releaseIfPagesRest hands memory back when no page read has been in
// flight for pageRest. A read in flight arms it again when it ends, and a
// rest not long enough yet waits out the rest of it.
func releaseIfPagesRest() {
pageReads.Lock()
pageReads.due = nil
if pageReads.n != 0 {
pageReads.Unlock()
return
}
if wait := pageRestFor() - time.Since(pageReads.last); wait > 0 {
pageReads.due = time.AfterFunc(wait, releaseIfPagesRest)
pageReads.Unlock()
return
}
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
}
debug.FreeOSMemory()
}