From e044ea862f55f7e2e5a16566ef5bbab1d1d5bb77 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 12 Oct 2026 02:44:48 +0800 Subject: [PATCH] sessions: the warm-up at start reads with a quarter of the cores unless a page waits, and a long first read keeps what it read (#1665, laowangba233) #1665: magpie pegs the CPU on every start (Windows Task Manager showed 95.8%). Three seconds after start, warmSessions indexes every Claude/Codex session file and reads every file's calls for usage. refresh() ran min(max(8, 2*NumCPU), 32) parsers at once and usage's prefetch 8 more, so the background warm-up took every core while nobody was looking at the result. Two goals, in one commit because they touch the same loop in refresh(): 1. Quiet warm-up (quiet.go). gui's warmSessions runs inside sessions.Warm. While a warm-up runs and no request waits, every parse in refresh() and every readCalls takes one of max(1, NumCPU/4) slots. A request to /api/sessions* or /api/usage* (gui's held middleware) calls sessions.Ask(), which lifts the limit for as long as it runs, so a page the user opened isn't slowed down. A waiting reader re-checks every 50ms, so Ask takes effect mid-read. 2. Checkpoints. refresh() saved sessions.json only once all files were parsed. Quitting magpie before that (a slow machine, or the user closing it because the CPU is pegged) kept nothing, and the next start parsed every file again. Now every 5s (checkpointEvery) the files done so far are published and saved, if the cache generation still matches. Measured on a Mac (14 cores) with a sandbox HOME holding 8.9 GB of real sessions (copied read-only), sessions.json and calls-v11 removed, sampling ps every 2s: - cold start before: 41.2 CPU-s, peak 580-600%, done ~14s - cold start after: 34.7 CPU-s, peak ~300-360%, done ~16s - quit mid-index, before: quit at 6s (13.5 CPU-s spent) left no sessions.json and no calls files; the next start spent 41 CPU-s again. - quit mid-index, after: quit at 12s left a 1.3 MB sessions.json (of 3.0 MB); the next start spent 26.6 CPU-s instead of 34.7. Tests (each red with its part undone, script-checked: refresh's slot replaced by a no-op, readCalls' slot removed, the checkpoint block removed): - TestWarmReadsOnlyInItsSlots: with every slot held, neither the index nor the calls read anything for 300ms; Ask() lets both finish. - TestReadSlotOnlyWhileWarming: outside Warm, or while asked, reads don't wait. - TestLongReadKeepsWhatItRead: a read held after its 3rd file has saved sessions.json with fewer files than it has to do. Run: go test -tags nogui ./internal/sessions ./internal/gui ./internal/library ./internal/usage; gofmt -l; GOOS=linux and GOOS=windows go vet of sessions, gui, library; full go test ./... before push. Not tried: the reporter's machine or data volume; a Windows re-measure. --- internal/gui/api.go | 6 ++ internal/gui/sessions.go | 14 ++-- internal/sessions/call_cache.go | 3 + internal/sessions/quiet.go | 70 ++++++++++++++++++ internal/sessions/quiet_test.go | 126 ++++++++++++++++++++++++++++++++ internal/sessions/sessions.go | 70 ++++++++++++++---- 6 files changed, 271 insertions(+), 18 deletions(-) create mode 100644 internal/sessions/quiet.go create mode 100644 internal/sessions/quiet_test.go diff --git a/internal/gui/api.go b/internal/gui/api.go index 191d22e1c..99ab6c053 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -43,6 +43,7 @@ import ( "github.com/yetone/magpie/internal/profile" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/redact" + "github.com/yetone/magpie/internal/sessions" "github.com/yetone/magpie/internal/settings" "github.com/yetone/magpie/internal/update" ) @@ -1826,6 +1827,11 @@ func held(h http.Handler) http.Handler { // and the files read, not looked at again for each look-up defer filememo.Hold()() } + if strings.HasPrefix(r.URL.Path, "/api/sessions") || strings.HasPrefix(r.URL.Path, "/api/usage") { + // a page waits on the session files: the warm-up reading + // them reads at full speed meanwhile + defer sessions.Ask()() + } if !(api && r.Method == http.MethodGet) { // anything that may have written drops what was held, once it // has answered with it diff --git a/internal/gui/sessions.go b/internal/gui/sessions.go index 4e6024fee..6ce6ee603 100644 --- a/internal/gui/sessions.go +++ b/internal/gui/sessions.go @@ -407,11 +407,15 @@ func warmSessions() { } go func() { time.Sleep(3 * time.Second) - warmUp( - func() { statsFor(0) }, - func() { statsFor(30) }, - func() { usage.QueryPage(usage.All, usage.Filter{}, 0, 50) }, - ) + // with few readers, as nobody waits on it yet: after an update + // that reads every file again, it held every core (#1665) + sessions.Warm(func() { + warmUp( + func() { statsFor(0) }, + func() { statsFor(30) }, + func() { usage.QueryPage(usage.All, usage.Filter{}, 0, 50) }, + ) + }) }() } diff --git a/internal/sessions/call_cache.go b/internal/sessions/call_cache.go index f9f3b0fe7..7e69e0af6 100644 --- a/internal/sessions/call_cache.go +++ b/internal/sessions/call_cache.go @@ -206,6 +206,9 @@ func readCalls(f file) *callFile { } return &callFile{Path: f.path, Agent: f.agent} } + // a file to read: few at once while only the warm-up asks (quiet.go) + defer readSlot()() + defer readBegin()() // Agents whose calls are read whole rather than line by line: a session // that changed is read again, and one that did not is kept. OpenCode's // and ZCode's are rows of a database or JSON documents; dsh's file is diff --git a/internal/sessions/quiet.go b/internal/sessions/quiet.go new file mode 100644 index 000000000..dd40f7e34 --- /dev/null +++ b/internal/sessions/quiet.go @@ -0,0 +1,70 @@ +package sessions + +import ( + "runtime" + "sync" + "sync/atomic" + "time" +) + +// The warm-up at start (Warm) reads every changed session file before any +// page asks for them. After an update that changes how a file is read, that +// is every file again: 8.9 GB of Claude Code and Codex sessions took ~40 s +// of CPU, and with twice as many readers as cores it held every core for +// the first ~15 s of magpie's start (#1665, laowangba233: the CPU full on +// each start). Nobody waits on the warm-up, so it reads with a quarter of +// the cores; a page that asks for sessions meanwhile (Ask) has the reading +// go at full speed again, as it then waits on it. + +var ( + warming, asking atomic.Int32 + quietSlots = make(chan struct{}, quietReaders()) +) + +// quietReaders is how many files the warm-up reads at once. +func quietReaders() int { return max(1, runtime.NumCPU()/4) } + +// Warm runs fn, the reads nobody waits on yet, with few readers. +func Warm(fn func()) { + warming.Add(1) + defer warming.Add(-1) + fn() +} + +// Ask marks a page waiting on sessions until done is called: reading goes +// at full speed while it waits. +func Ask() (done func()) { + asking.Add(1) + return sync.OnceFunc(func() { asking.Add(-1) }) +} + +func quiet() bool { return warming.Load() > 0 && asking.Load() == 0 } + +// readSlot waits, while only the warm-up reads, for one of the warm-up's +// few reading slots; release gives it back. A page asking meanwhile lets +// the reader go at once. +func readSlot() (release func()) { + if !quiet() { + return func() {} + } + t := time.NewTicker(50 * time.Millisecond) + defer t.Stop() + for quiet() { + select { + case quietSlots <- struct{}{}: + return sync.OnceFunc(func() { <-quietSlots }) + case <-t.C: + } + } + return func() {} +} + +// reading and readPeak count files being read at once, for a test. +var reading, readPeak atomic.Int32 + +func readBegin() (end func()) { + n := reading.Add(1) + for p := readPeak.Load(); n > p && !readPeak.CompareAndSwap(p, n); p = readPeak.Load() { + } + return func() { reading.Add(-1) } +} diff --git a/internal/sessions/quiet_test.go b/internal/sessions/quiet_test.go new file mode 100644 index 000000000..3a6a9b392 --- /dev/null +++ b/internal/sessions/quiet_test.go @@ -0,0 +1,126 @@ +package sessions + +import ( + "fmt" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" +) + +// moreSessions adds n Claude Code sessions to setup's. +func moreSessions(t *testing.T, claude string, n int) { + t.Helper() + dir := filepath.Join(claude, "projects", "-work-many") + os.MkdirAll(dir, 0o755) + for i := range n { + p := filepath.Join(dir, fmt.Sprintf("33333333-2222-3333-4444-%012d.jsonl", i)) + os.WriteFile(p, []byte(ccMsg(fmt.Sprintf("m%d", i), "2026-09-21T10:00:00.000Z", 100, 10)), 0o644) + } +} + +// holdQuietSlots takes every one of the warm-up's reading slots, and gives +// them back when the test ends. +func holdQuietSlots(t *testing.T) { + for range cap(quietSlots) { + quietSlots <- struct{}{} + } + t.Cleanup(func() { + for len(quietSlots) > 0 { + <-quietSlots + } + }) +} + +// The warm-up at start reads every changed file before anyone asks for +// them; after an update that reads them all again it held every core +// (#1665). It reads only with the warm-up's few slots: with all of them +// taken, neither the index (Stats) nor the calls (ReadCallSource) read a +// file, and a page asking has them read at once. +func TestWarmReadsOnlyInItsSlots(t *testing.T) { + inZone(t, 0) + claude, _ := setup(t) + moreSessions(t, claude, 12) + holdQuietSlots(t) + warm := func(what string, read func()) { + t.Helper() + readPeak.Store(0) + done := make(chan struct{}) + go Warm(func() { read(); close(done) }) + time.Sleep(300 * time.Millisecond) + if n := readPeak.Load(); n != 0 { + t.Fatalf("%s: the warm-up read %d files at once with no slot free", what, n) + } + // a page asks: read at full speed, slots or not + asked := Ask() + defer asked() + select { + case <-done: + case <-time.After(20 * time.Second): + t.Fatalf("%s: a page asking didn't have the warm-up's reading go on", what) + } + if readPeak.Load() == 0 { + t.Fatalf("%s: nothing read", what) + } + } + warm("the index", func() { statsAt(0, statsNow) }) + if got := len(List(0)); got < 12 { + t.Fatalf("%d sessions listed", got) + } + warm("the calls", func() { + for _, s := range CallSources() { + ReadCallSource(s) + } + }) +} + +// Outside the warm-up the slots don't hold anything up. +func TestReadSlotOnlyWhileWarming(t *testing.T) { + holdQuietSlots(t) + got := make(chan struct{}) + go func() { readSlot()(); close(got) }() + select { + case <-got: + case <-time.After(10 * time.Second): + t.Fatal("a read outside the warm-up waited for a slot") + } +} + +// A long first read keeps what it has read on disk as it goes: a magpie +// quit before the end (its CPU full on a slow disk, #1665) kept nothing of +// a minutes-long read, so the next start read it all again. The files after +// the first three wait until a save is written with files still to read. +func TestLongReadKeepsWhatItRead(t *testing.T) { + inZone(t, 0) + claude, _ := setup(t) + moreSessions(t, claude, 12) + old := checkpointEvery + checkpointEvery = 5 * time.Millisecond + early := make(chan struct{}) + var once sync.Once + saveHook = func() { + if progress.files.Load() < progress.todo.Load() { + once.Do(func() { close(early) }) + } + } + var parsed atomic.Int32 + parseHook = func() { + if parsed.Add(1) > 3 { + select { + case <-early: + case <-time.After(5 * time.Second): + } + } + } + t.Cleanup(func() { checkpointEvery, saveHook, parseHook = old, nil, nil }) + + statsAt(0, statsNow) + Saved() + select { + case <-early: + default: + t.Fatal("nothing kept on disk until every file was read") + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index d48e267a8..e576b2eef 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -728,41 +728,85 @@ func refresh(want, all []file) { } generation := cacheGeneration mu.Unlock() - var wg sync.WaitGroup ch := make(chan int) + finished := make(chan int, len(jobs)) for i := 0; i < min(max(8, 2*runtime.NumCPU()), 32, len(todo)); i++ { - wg.Add(1) go func() { - defer wg.Done() for i := range ch { j := &jobs[i] + release := readSlot() + end := readBegin() + if parseHook != nil { + parseHook() + } j.parsed = parse(j.f, j.old) + end() + release() if (j.parsed.Claude != nil && !windows[j.f.path]) || (j.parsed.Claude == nil && !recentRevision(j.parsed.Mod, j.parsed.revisionWeight(), time.Now())) { j.parsed = j.parsed.withoutRevisions() } progress.files.Add(1) progress.read.Add(left[j.f.path]) + finished <- i } }() } - for i := range jobs { - ch <- i - } - close(ch) - wg.Wait() - mu.Lock() - for _, j := range jobs { - // A concurrent read may already have published a newer parse. - if generation == cacheGeneration && cache[j.f.path] == j.old { - cache[j.f.path] = j.parsed + go func() { + for i := range jobs { + ch <- i + } + close(ch) + }() + // publish puts the parses finished since last time in the cache. + publish := func(done []int) { + for _, i := range done { + j := &jobs[i] + // A concurrent read may already have published a newer parse. + if generation == cacheGeneration && cache[j.f.path] == j.old { + cache[j.f.path] = j.parsed + } } } + // What is read is kept on disk every checkpointEvery, not only at the + // end: a first read of a long history on a slow disk runs for minutes, + // and a magpie quit before the end (its CPU full, #1665) kept nothing + // of it, so the next start read it all again. + tick := time.NewTicker(checkpointEvery) + defer tick.Stop() + var done []int + for n := 0; n < len(jobs); { + select { + case i := <-finished: + done = append(done, i) + n++ + case <-tick.C: + if len(done) == 0 { + continue + } + mu.Lock() + publish(done) + if generation == cacheGeneration { + saveCache() + } + mu.Unlock() + done = done[:0] + } + } + mu.Lock() + publish(done) progress.finish() if generation == cacheGeneration { saveCache() } } +// checkpointEvery is how often a long read of changed files keeps what it +// has read so far on disk. +var checkpointEvery = 5 * time.Second + +// parseHook, when a test sets it, runs before each changed file is parsed. +var parseHook func() + // progress is how far the reading of changed files has got, for the page to // show while it waits: files and bytes read of those to read. var progress indexing