Files
magpie/internal/sessions/stats_kept.go
T
yetone aef89edf10 sessions: a listing over unchanged files is the one made last
The Sessions page lists every session every 15 s. Between two polls the
files mostly haven't changed, yet each listing grouped, sorted and
assembled all of them again (byKey, the key sort, ccFamily, assemble with
subagents and resume commands).

listSessions now keeps what it made last (keptList, beside keptStats) and
gives a copy of it out when nothing it was made from has changed:
- every listed file's path, size, time and parse (keptFileOf, the same
  check the stats use, factored out as keptStill);
- the cache generation and the limit asked for;
- the prices, Codex thread names and Claude Desktop names the listing got,
  asked again;
- the command an agy row resumes with (AgyStart), when agy is listed.
What a row shows beside those (an agent to carry it to being installed, a
Claude Code subagent's meta, a Kimi wire file) is looked at again at most
a minute later (listKeptFor). refresh now runs before the grouping, which
it never read. Reset forgets the kept listing.

Measured with the real ~17k sessions (APFS clones of ~/.codex/sessions
and ~/.claude/projects in a sandbox HOME), 30 polls of /api/sessions,
/api/sessions/stats and /api/sessions/overview, X-Magpie-Had as the page
sends it:
- before (21882a68d): ~185 ms CPU a poll, /api/sessions median 89 ms,
  List 1.42 s of the handler's 1.93 s profiled;
- after: ~151 ms CPU a poll, median 70 ms, List 0.98 s of 1.39 s, no
  assemble in the profile. What is left of List is listing the folders
  (getattrlistbulk, ~26 ms a poll).
Measured before the agy check was added; that adds one AgyStart call a
poll when agy is listed.

Run on mote at the rebased head:
- go test ./internal/sessions: ok; -count=3 of TestListKept,
  TestAgySessions and TestStatsKept: ok.
- go test ./internal/cli ./internal/davsync ./internal/otlp ./internal/tui
  ./internal/tune: ok. ./internal/usage: ok (before the rebase).
- ./internal/gui: TestSettingsSaveKeepsWhatItDoesNotSend (#4739) and
  TestMainWindowCorners (#3949) red, the same on origin/main 788057340;
  everything else ok.

Broken by hand, each red:
- dropping the keptStill check: TestListKeptBetweenPolls "output 170
  after the file grew, 170 before";
- giving out the kept slice itself: "a caller's write reached the kept
  listing";
- never using the kept listing: "unchanged files listed again 1 times";
- dropping the AgyStart check: TestAgySessions "wired resume ... agy
  --conversation", the wired command wanted.

Not run: internal/agent and internal/gateway (they list sessions only
through the same List), the GUI browser suite (no page code changed).

Then rebased onto f2f75ee4a (provider: Volcengine Ark's System One API, in beta, as a dec); not rerun.
2026-11-01 14:18:44 +08:00

168 lines
4.9 KiB
Go

package sessions
import (
"reflect"
"slices"
"time"
"github.com/yetone/magpie/internal/catalog"
)
// keptStats are the ranges statsReadAll last read, and what they were read
// from. The Usage page asks for its range every 10 s and the Sessions page
// for 7, 30 and every day every 15 s; between two polls the files mostly
// haven't changed, and each read put every session of every range together
// again: ~1.1 GB a minute and a third, a fifth of all magpie allocated
// (#2278). Guarded by mu.
var keptStats struct {
files []keptFile
today time.Time
gen uint64
ranges map[int]Stats
// native is every listed session's agent|id, nil when no read asked
// for it; shared, so read only
native map[string]bool
// the answers the reads got from the prices, Codex's names and Claude
// Desktop's, asked again before the ranges are given out
prices map[string]*catalog.Price
titles map[string]string
desktop map[string]string
}
// keptFile is what of a listed file a range's stats are made from: its
// parse (a published parse is never written, a changed file gets a new
// one), and what the listing says of it.
type keptFile struct {
path, key, agent, wsl string
size int64
mod int64
main, readOnly bool
st *state
}
func keptFileOf(f file) keptFile {
return keptFile{path: f.path, key: f.key, agent: f.agent, wsl: f.m().wsl, size: f.size, mod: f.mod.UnixNano(),
main: f.main, readOnly: f.readOnly, st: cache[f.path]}
}
// keptFor reports whether the kept ranges were read from files as they
// are now, today, with the prices and names they got still the same. When
// they weren't, what was kept is let go.
func keptFor(files []file, today time.Time, price func(string) *catalog.Price, titles func(string) string) bool {
k := &keptStats
same := k.ranges != nil && k.gen == cacheGeneration && k.today.Equal(today) &&
keptStill(k.files, files, k.prices, k.titles, k.desktop, price, titles)
if !same {
forgetKeptStats()
k.files, k.today, k.gen = make([]keptFile, len(files)), today, cacheGeneration
for i, f := range files {
k.files[i] = keptFileOf(f)
}
k.ranges, k.prices, k.titles, k.desktop = map[int]Stats{}, map[string]*catalog.Price{}, map[string]string{}, map[string]string{}
}
return same
}
// keptStill reports whether kept was taken of files as they are now, and
// prices, titles and desktop, the answers what was made from them got, are
// still what price, titles and Claude Desktop's names answer.
func keptStill(kept []keptFile, files []file, prices map[string]*catalog.Price, names, desktop map[string]string,
price func(string) *catalog.Price, titles func(string) string) bool {
if len(kept) != len(files) {
return false
}
for i := range files {
if kept[i] != keptFileOf(files[i]) {
return false
}
}
for model, p := range prices {
if !reflect.DeepEqual(price(model), p) {
return false
}
}
for id, t := range names {
if titles(id) != t {
return false
}
}
if len(desktop) > 0 {
ids := make([]string, 0, len(desktop))
for id := range desktop {
ids = append(ids, id)
}
return reflect.DeepEqual(DesktopTitles(ids), desktopKnown(desktop))
}
return true
}
// keptRanges is how many ranges are kept: the page asks for three, and a
// days= of any other number is not kept beside them for ever.
const keptRanges = 8
// keepRange keeps st as days' Stats, letting go of a range asked is not
// among when there are keptRanges already.
func keepRange(days int, st Stats, asked []int) {
if len(keptStats.ranges) >= keptRanges {
for d := range keptStats.ranges {
if !slices.Contains(asked, d) {
delete(keptStats.ranges, d)
break
}
}
}
keptStats.ranges[days] = st
}
// desktopKnown is names without the ids that have none, as DesktopTitles
// gives them.
func desktopKnown(names map[string]string) map[string]string {
out := map[string]string{}
for id, n := range names {
if n != "" {
out[id] = n
}
}
return out
}
// keptPrice and keptTitle answer as price and titles do, and note the
// answer for keptFor.
func keptPrice(price func(string) *catalog.Price) func(string) *catalog.Price {
return func(model string) *catalog.Price {
p := price(model)
keptStats.prices[model] = p
return p
}
}
func keptTitle(titles func(string) string) func(string) string {
return func(id string) string {
t := titles(id)
keptStats.titles[id] = t
return t
}
}
// keepDesktop notes the Claude Desktop names a range's sessions got.
func keepDesktop(st Stats) {
var ids []string
for _, s := range st.Sessions {
if s.Agent == "claude-desktop" {
ids = append(ids, s.ID)
}
}
if len(ids) == 0 {
return
}
names := DesktopTitles(ids)
for _, id := range ids {
keptStats.desktop[id] = names[id]
}
}
func forgetKeptStats() {
keptStats.files, keptStats.ranges, keptStats.native = nil, nil, nil
keptStats.prices, keptStats.titles, keptStats.desktop = nil, nil, nil
}