From 7f2acb9ffa5f9e5af7bc4bb2ddf9cedc61e9512a Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 31 Oct 2026 06:22:53 +0800 Subject: [PATCH] gui: a first start's page asks and warm-up reads take turns (#2278) On a first start with no sums on disk, the window asks the Sessions page's stats and overview and the Usage page's requests and heatmap while the warm-up reads the same history. A heap profile at a live 294 MB, 30.6 s in, had ~147 MB in those asks' handlers (QueryPage 102 MB, session stats 51 MB) beside ~42 MB in the warm-up's session scan. Each was a first read of the history held beside the others. Until the warm-up ends, each warm-up step and each ask of /api/sessions, /api/sessions/stats, /api/sessions/overview, /api/usage, /api/usage/requests and /api/usage/heatmap take one turn at a time (coldTurns). Each read comes after the one before it has kept what it read, so most find it kept. held's sessions.Ask still makes the warm-up read at full speed while a page waits. No page waits more than 2 minutes for its turn, so a stuck warm-up can't hold the pages. Once the warm-up is over, nothing waits. Tests don't take turns (coldTurnsTaken). Bench on mote (M5 Pro), a real 390k-call history, cold (no caches), poll.sh asking what an open window asks every 5 s, the poll loop killed between runs (advgcp2.sh); phys_footprint peak: before (bca0d6d69): 456 494 500 469 424 424 416 410 MB after: 392 396 394 404 389 393 392 MB live heap max: ~293-338 before, ~276-288 after slowest requests/heatmap answer: 31-46 s before, 30-39 s after; every poll answered 200 in the last three runs (100 of 100) Also tried and not shipped: reading the warm-up's 0 and 30 day session stats in one pass, with asks for a range being read waiting for it. Its peaks were 408 480 463 405 MB against 424 424 416 410 MB. Run at bca0d6d69, rebased onto c59c547c5, whose two commits touch no file here (claudetui, gateway, provider, and app.js/i18n.js strings): - go vet ./internal/gui (darwin) and GOOS=windows: clean. - go test -count=1 ./internal/gui on mote: ok except TestCoveredWindowStaysUp, a real AppKit window killed at its 30 s deadline. That is #4125: mote's AppKit tests hang. - go test -race -count=3 of TestColdTurnsTaken, TestWarmUp*, TestStats*, SessionStats, Overview, Heatmap: ok. - Broken by hand: with coldTurn's turn skipped, TestColdTurnsTaken fails with "the page was answered while the warm-up's step read". Not run: Linux go vet. Cross-compiling needs cgo for Wails, and the WSL distro has no gtk4 or webkitgtk-6.0 dev packages. The change has no OS-specific code. --- internal/gui/sessions.go | 56 +++++++++++++++++++++---- internal/gui/usage.go | 12 +++--- internal/gui/warm_turns_test.go | 73 +++++++++++++++++++++++++++++++++ 3 files changed, 128 insertions(+), 13 deletions(-) create mode 100644 internal/gui/warm_turns_test.go diff --git a/internal/gui/sessions.go b/internal/gui/sessions.go index 4cacae71e..6a82ec51a 100644 --- a/internal/gui/sessions.go +++ b/internal/gui/sessions.go @@ -82,7 +82,7 @@ func gatewaySession(g usage.GatewaySession) sessions.Session { func sessionRoutes(mux *http.ServeMux, w Windows) { warmSessions() - mux.HandleFunc("GET /api/sessions", func(rw http.ResponseWriter, r *http.Request) { + mux.HandleFunc("GET /api/sessions", coldTurn(func(rw http.ResponseWriter, r *http.Request) { // the list and the Codex threads' effort each list every session file defer sessions.OneListing()() n, _ := strconv.Atoi(r.URL.Query().Get("limit")) @@ -158,11 +158,11 @@ func sessionRoutes(mux *http.ServeMux, w Windows) { Terminal bool `json:"terminal"` Dirs []string `json:"dirs"` }{out.Terminal, out.Dirs}) - }) + })) // stats is every session's usage by day over the last ?days=N days // (every day when 0 or none), cut by agent, folder and model for the // page to filter; names are the agents' as the page shows them. - mux.HandleFunc("GET /api/sessions/stats", func(rw http.ResponseWriter, r *http.Request) { + mux.HandleFunc("GET /api/sessions/stats", coldTurn(func(rw http.ResponseWriter, r *http.Request) { defer sessions.ShareListing()() n, _ := strconv.Atoi(r.URL.Query().Get("days")) st, gen := statsForGen(n) @@ -199,11 +199,11 @@ func sessionRoutes(mux *http.ServeMux, w Windows) { statsTags.m[n] = statsTag{gen, agents, tag} statsTags.Unlock() } - }) + })) // overview sums up the range's sessions under the page's filters: // how many, what the middle one spent, how many each day, and the ones // that spent the most. - mux.HandleFunc("GET /api/sessions/overview", func(rw http.ResponseWriter, r *http.Request) { + mux.HandleFunc("GET /api/sessions/overview", coldTurn(func(rw http.ResponseWriter, r *http.Request) { defer sessions.ShareListing()() q := r.URL.Query() n, _ := strconv.Atoi(q.Get("days")) @@ -234,7 +234,7 @@ func sessionRoutes(mux *http.ServeMux, w Windows) { } } writeJSON(rw, out) - }) + })) // progress is how far the reading of the session files has got, for // the page to show while its first read takes a while. mux.HandleFunc("GET /api/sessions/progress", func(rw http.ResponseWriter, r *http.Request) { @@ -705,12 +705,54 @@ func warmUp(steps ...func()) { // that asks: an empty sandbox's warm-up looked at settings.json ~300 // times on Windows (#1665); a write still reads the disk (edit.Read) defer filememo.Hold()() + defer coldTurns.over.Store(true) for _, step := range steps { - step() + func() { + coldTurns.turn <- struct{}{} + defer func() { <-coldTurns.turn }() + step() + }() } debug.FreeOSMemory() } +// coldTurns has the warm-up's reads and the pages' first asks take turns +// until the warm-up is over. A first start's window asks the Sessions +// page's stats and the Usage page's requests and heatmap while the +// warm-up reads the same history, each a first read of it held beside the +// others: ~150 MB of the asks' and ~40 MB of the warm-up's at once, a +// ~300 MB live heap and a 420–480 MB footprint (#2278). Each reads after +// the one before it has kept what it read, and most then find it kept. +var coldTurns = struct { + turn chan struct{} + over atomic.Bool +}{turn: make(chan struct{}, 1)} + +// coldTurnMost is how long a page waits for its turn: a warm-up stuck on +// one read never keeps the pages from answering. +const coldTurnMost = 2 * time.Minute + +// coldTurnsTaken is false in tests, whose pages and warm-ups are their own. +var coldTurnsTaken = !testing.Testing() + +// coldTurn is h taking its turn while the warm-up isn't over; the +// warm-up's reading goes at full speed while it waits (held's +// sessions.Ask). +func coldTurn(h http.HandlerFunc) http.HandlerFunc { + return func(rw http.ResponseWriter, r *http.Request) { + if coldTurnsTaken && !coldTurns.over.Load() { + t := time.NewTimer(coldTurnMost) + select { + case coldTurns.turn <- struct{}{}: + defer func() { <-coldTurns.turn }() + case <-t.C: + } + t.Stop() + } + h(rw, r) + } +} + // underTightGC runs fn letting the heap grow by a quarter of what it holds // before a collection, not Go's default of all of it, and then puts back // what was set; a GOGC the user set lower, or off, is kept. The usage diff --git a/internal/gui/usage.go b/internal/gui/usage.go index 57d5e08c5..905db8bad 100644 --- a/internal/gui/usage.go +++ b/internal/gui/usage.go @@ -98,10 +98,10 @@ func requestContent(agent, session string, from, to, at time.Time) contentJSON { } func usageRoutes(mux *http.ServeMux, w Windows) { - mux.HandleFunc("GET /api/usage", func(rw http.ResponseWriter, r *http.Request) { + mux.HandleFunc("GET /api/usage", coldTurn(func(rw http.ResponseWriter, r *http.Request) { // the days and hours of the reader's zone, which the page names writeJSON(rw, usageState(periodOf(r.URL.Query().Get("period")), usageapi.ZoneOf(r))) - }) + })) // the providers a deleted one's calls can be merged into: those there // are now and shown, by name mux.HandleFunc("GET /api/usage/deleted/into", func(rw http.ResponseWriter, r *http.Request) { @@ -176,17 +176,17 @@ func usageRoutes(mux *http.ServeMux, w Windows) { writeJSON(rw, map[string]bool{"ok": true}) }) // the ledger: the period's calls, newest first, a page at a time - mux.HandleFunc("GET /api/usage/requests", func(rw http.ResponseWriter, r *http.Request) { + mux.HandleFunc("GET /api/usage/requests", coldTurn(func(rw http.ResponseWriter, r *http.Request) { q := r.URL.Query() offset, _ := strconv.Atoi(q.Get("offset")) limit, _ := strconv.Atoi(q.Get("limit")) writeJSON(rw, ledgerPage(periodOf(q.Get("period")), ledgerFilter(r), offset, limit)) - }) + })) // the heatmap (#1369): the last 53 weeks a day each, of the requests the // page's filters keep, read from the same index as the page - mux.HandleFunc("GET /api/usage/heatmap", func(rw http.ResponseWriter, r *http.Request) { + mux.HandleFunc("GET /api/usage/heatmap", coldTurn(func(rw http.ResponseWriter, r *http.Request) { writeJSON(rw, usage.HeatmapOf(ledgerFilter(r))) - }) + })) // what was said in one request, read from the agent's session file when the // row is opened, between two times (the call's own, or a gateway request's // span): magpie keeps no copy diff --git a/internal/gui/warm_turns_test.go b/internal/gui/warm_turns_test.go new file mode 100644 index 000000000..fb6e81f65 --- /dev/null +++ b/internal/gui/warm_turns_test.go @@ -0,0 +1,73 @@ +package gui + +import ( + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" +) + +// Until the warm-up is over, a page's first ask and each of its reads +// take turns: none holds a first read of the history beside another +// (#2278). Once it is over, a page asks at once. +func TestColdTurnsTaken(t *testing.T) { + coldTurnsTaken = true + coldTurns.over.Store(false) + t.Cleanup(func() { coldTurnsTaken = false; coldTurns.over.Store(false) }) + var inStep, inPage, both atomic.Int32 + asked, release := make(chan struct{}), make(chan struct{}) + page := coldTurn(func(http.ResponseWriter, *http.Request) { + inPage.Add(1) + if inStep.Load() > 0 { + both.Add(1) + } + inPage.Add(-1) + }) + ask := func() { + page(httptest.NewRecorder(), httptest.NewRequest("GET", "/api/usage/heatmap", nil)) + } + warmed := make(chan struct{}) + go func() { + defer close(warmed) + warmUp(func() { + inStep.Add(1) + defer inStep.Add(-1) + <-asked + <-release + }, func() { + inStep.Add(1) + defer inStep.Add(-1) + if inPage.Load() > 0 { + both.Add(1) + } + }) + }() + answered := make(chan struct{}) + go func() { + close(asked) + ask() + close(answered) + }() + select { + case <-answered: + t.Fatal("the page was answered while the warm-up's step read") + case <-time.After(50 * time.Millisecond): + } + close(release) + <-answered + <-warmed + if both.Load() != 0 { + t.Fatal("a page and a warm-up step read at once") + } + // once the warm-up is over, nothing waits + coldTurns.turn <- struct{}{} + defer func() { <-coldTurns.turn }() + done := make(chan struct{}) + go func() { ask(); close(done) }() + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("a page after the warm-up waited for a turn") + } +}