gui: the Sessions list and stats answers are written into buffers kept between polls, the stats a day at a time (#2278)

With the Sessions tab open, every poll grew each long answer's buffer
from nothing: writeJSONRows' `whole` (~8 MB of rows) and writeJSONSame's
buffer plus encoding/json's own encodeState for the stats (~6 MB of
days), which the Encoder grows to the whole value after each
collection. In 90 s of polls while an agent worked, writeJSONRows was
245 MB and the stats' writeJSONSame 209 MB of 2702 MB allocated.

- answerBuffer/keepAnswer keep two buffers, dropped 30 s after the last
  answer (as the usage scratch lingers). A ResponseWriter copies what
  it is written, and only the rows' sums outlive the call, so nothing
  reads a buffer once it is put back.
- writeSame is writeJSONSame over a write func; writeJSONRows and the
  stats handler use the kept buffers.
- statsAnswer encodes the stats a Day at a time, byte for byte the
  Encoder of struct{ sessions.Stats; Agents } (the page's tag rests on
  those bytes).

Bench (mote, ~/r2278/full, hmw.sh: a gateway call every 3 s, 10
endpoints polled every 5 s with X-Magpie-Had; second runs compared),
e13 = 3bce283df, e14 = this:
  total alloc 2702 -> 2308 MB, writeJSONRows 245 -> 110 MB,
  stats encoding 209 -> 46 MB, /api/sessions/stats handler 306 -> 128 MB,
  GCs in 90 s 85 -> 71, fp_peak 347 -> 360 MB (noise band 345-370).
  Polls 170 x 200 in both. One e14 run (y14) had 60 answers of "400 Bad
  Request" (15 bytes, <6 ms): Go's net/http refusing a malformed request
  header from the bench's tag file; y12 at the old code had the same 60,
  and a rerun had none. That run is not compared.

Tests: TestStatsAnswerWritesWhatEncodeDid (nil/empty/HTML/U+2028 days,
keys, agents, a hidden Sessions), TestAnswerBufferKeptForTheNext
(writeSame and writeJSONRows put a buffer back that the next answer
takes). Broken by hand, each red: writeSame without keepAnswer (red),
writeJSONRows without keepAnswer (red), statsAnswer keeping Encode's
newline (red).

At 9d6461416 rebased on 9e73f69af (mote): gofmt clean; go vet -tags nogui
./internal/gui/ ./internal/sessions/ for linux, windows, darwin ok;
go test ./internal/gui/ -run 'TestStatsAnswer|TestAnswerBuffer|
TestWriteJSONRows|Sessions|Stats|Same' ok; go test ./internal/sessions/ ok.

Full internal/gui on mote at the pre-rebase tree: every test ok but ten
real-window AppKit tests killed at their 20-40 s deadline (dock order,
panel close/space, plugin page, dock reopen, titlebar corners/RTL, tray
shown, released panel, window up), mote's #4125 / #2645, which this
change doesn't reach.
This commit is contained in:
yetone
2026-10-30 19:05:17 +08:00
parent 9e73f69af4
commit bed604efb3
3 changed files with 184 additions and 9 deletions
+59 -5
View File
@@ -2746,8 +2746,15 @@ func writeJSON(rw http.ResponseWriter, v any) {
// WebView2 is sent no If-None-Match, and Wails turns its 304 into a 505.
// It returns the tag, or "" when v could not be written.
func writeJSONSame(rw http.ResponseWriter, r *http.Request, v any) string {
var b bytes.Buffer
if err := json.NewEncoder(&b).Encode(v); err != nil {
return writeSame(rw, r, func(b *bytes.Buffer) error { return json.NewEncoder(b).Encode(v) })
}
// writeSame is writeJSONSame of the answer write puts in b, a kept buffer
// (answerBuffer).
func writeSame(rw http.ResponseWriter, r *http.Request, write func(b *bytes.Buffer) error) string {
b := answerBuffer()
defer keepAnswer(b)
if err := write(b); err != nil {
fail(rw, err)
return ""
}
@@ -2775,6 +2782,52 @@ var sentRows struct {
const sentRowsKept = 4
// answerBuffers are the buffers a long answer is written in, kept between
// polls: grown from nothing for each, the Sessions tab's list and its
// stats, ~6 MB each, were ~110 MB of 90 s of polls while an agent worked
// (#2278). They go answerLinger after the last answer.
var answerBuffers struct {
sync.Mutex
free []*bytes.Buffer
t *time.Timer
}
const answerBuffersKept = 2
var answerLinger = 30 * time.Second
// answerBuffer is a kept buffer, empty, or a new one
func answerBuffer() *bytes.Buffer {
answerBuffers.Lock()
defer answerBuffers.Unlock()
if n := len(answerBuffers.free); n > 0 {
b := answerBuffers.free[n-1]
answerBuffers.free = answerBuffers.free[:n-1]
return b
}
return new(bytes.Buffer)
}
// keepAnswer puts b back once its answer is written: nothing reads it
// after, a ResponseWriter copies what it is given.
func keepAnswer(b *bytes.Buffer) {
b.Reset()
answerBuffers.Lock()
defer answerBuffers.Unlock()
if len(answerBuffers.free) < answerBuffersKept {
answerBuffers.free = append(answerBuffers.free, b)
}
if answerBuffers.t == nil {
answerBuffers.t = time.AfterFunc(answerLinger, func() {
answerBuffers.Lock()
answerBuffers.free = nil
answerBuffers.Unlock()
})
return
}
answerBuffers.t.Reset(answerLinger)
}
// rowsSize is the size of the last answer writeJSONRows wrote of each key,
// what the next one's buffer is made for.
var rowsSize sync.Map
@@ -2796,14 +2849,15 @@ func writeJSONRows[T any](rw http.ResponseWriter, r *http.Request, key string, r
// the rows are written once, into the answer itself: each row's
// Marshal, their Join and the answer's buffer were three copies of the
// ~8 MB list a poll, and the buffer grew to it from nothing
var whole bytes.Buffer
whole := answerBuffer()
defer keepAnswer(whole)
if n, ok := rowsSize.Load(key); ok {
whole.Grow(n.(int) + n.(int)/8)
}
whole.WriteByte('{')
whole.Write(k)
whole.WriteString(":[")
enc := json.NewEncoder(&whole)
enc := json.NewEncoder(whole)
ends := make([]int, len(rows)+1)
ends[0] = whole.Len()
for i := range rows {
@@ -2828,7 +2882,7 @@ func writeJSONRows[T any](rw http.ResponseWriter, r *http.Request, key string, r
}
b.WriteByte('\n')
}
end(&whole)
end(whole)
rowsSize.Store(key, whole.Len())
all := whole.Bytes()
raw := make([][]byte, len(rows))
+51 -4
View File
@@ -189,10 +189,7 @@ func sessionRoutes(mux *http.ServeMux, w Windows) {
rw.WriteHeader(http.StatusOK)
return
}
tag := writeJSONSame(rw, r, struct {
sessions.Stats
Agents map[string]string `json:"agents"`
}{st, agents})
tag := writeSame(rw, r, func(b *bytes.Buffer) error { return statsAnswer(b, st, agents) })
if tag != "" {
statsTags.Lock()
if statsTags.m == nil || len(statsTags.m) >= statsMemoMost {
@@ -789,3 +786,53 @@ func viaOf(x usage.ViaIndex, s sessions.Session) []usage.Via {
}
return nil
}
// statsAnswer writes the stats answer into b as an Encoder of
// struct{ sessions.Stats; Agents } does, its days one at a time: encoded
// whole, the Encoder's own buffer grew to the ~6 MB answer from nothing
// after each collection, ~200 MB of 90 s of polls while an agent worked
// (#2278).
func statsAnswer(b *bytes.Buffer, st sessions.Stats, agents map[string]string) error {
enc := json.NewEncoder(b)
// v as Marshal writes it: Encode ends it with a newline
put := func(v any) error {
if err := enc.Encode(v); err != nil {
return err
}
b.Truncate(b.Len() - 1)
return nil
}
b.WriteString(`{"from":`)
if err := put(st.From); err != nil {
return err
}
b.WriteString(`,"to":`)
if err := put(st.To); err != nil {
return err
}
b.WriteString(`,"days":`)
if st.Days == nil {
b.WriteString("null")
} else {
b.WriteByte('[')
for i := range st.Days {
if i > 0 {
b.WriteByte(',')
}
if err := put(&st.Days[i]); err != nil {
return err
}
}
b.WriteByte(']')
}
b.WriteString(`,"keys":`)
if err := put(st.Keys); err != nil {
return err
}
b.WriteString(`,"agents":`)
if err := put(agents); err != nil {
return err
}
b.WriteString("}\n")
return nil
}
+74
View File
@@ -0,0 +1,74 @@
package gui
import (
"bytes"
"encoding/json"
"net/http/httptest"
"testing"
"github.com/yetone/magpie/internal/sessions"
)
// statsAnswer writes the stats answer a day at a time, and the answer is
// byte for byte what the Encoder of the whole gave: the page's tag rests
// on those bytes. A field added to Stats shows here as a difference.
func TestStatsAnswerWritesWhatEncodeDid(t *testing.T) {
day := func(date string) sessions.Day {
return sessions.Day{Date: date,
Usage: []sessions.Usage{{Agent: "codex", Cwd: "/a<b>&c", Model: "gpt
x", Tokens: sessions.Tokens{Input: 3, CacheWrite1h: 1}, Cost: 1e21, Priced: true}},
Active: []sessions.Active{{Agent: "claude", Cwd: "引号\"", Seconds: 61, Hours: []int64{1, 2}}}}
}
for _, c := range []struct {
st sessions.Stats
agents map[string]string
}{
{sessions.Stats{}, nil},
{sessions.Stats{From: "2026-10-01", To: "2026-10-30", Days: []sessions.Day{}, Keys: []string{}}, map[string]string{}},
{sessions.Stats{From: "<", To: "&", Days: []sessions.Day{day("2026-10-29"), {Date: "2026-10-30"}, day("x")}, Keys: []string{"codex:1", "a<b"}, Sessions: []sessions.Summary{{Key: "hidden"}}}, map[string]string{"codex": "Codex", "z": "<Z>"}},
} {
var want bytes.Buffer
if err := json.NewEncoder(&want).Encode(struct {
sessions.Stats
Agents map[string]string `json:"agents"`
}{c.st, c.agents}); err != nil {
t.Fatal(err)
}
var got bytes.Buffer
if err := statsAnswer(&got, c.st, c.agents); err != nil {
t.Fatal(err)
}
if !bytes.Equal(got.Bytes(), want.Bytes()) {
t.Fatalf("\n got %s\nwant %s", got.Bytes(), want.Bytes())
}
}
}
// A long answer is written into a buffer kept from the last, not one grown
// from nothing each poll.
func TestAnswerBufferKeptForTheNext(t *testing.T) {
answerBuffers.Lock()
answerBuffers.free = nil
answerBuffers.Unlock()
big := bytes.Repeat([]byte("x"), 1<<20)
w := httptest.NewRecorder()
writeSame(w, httptest.NewRequest("GET", "/x", nil), func(b *bytes.Buffer) error {
b.Write(big)
return nil
})
if !bytes.Equal(w.Body.Bytes(), big) {
t.Fatalf("answer of %d bytes, want %d", w.Body.Len(), len(big))
}
b := answerBuffer()
if b.Len() != 0 || b.Cap() < len(big) {
t.Fatalf("next buffer holds %d, room for %d: not the last answer's", b.Len(), b.Cap())
}
keepAnswer(b)
rows := []rowsBufRow{{Name: string(big)}}
writeJSONRows(httptest.NewRecorder(), httptest.NewRequest("GET", "/x", nil), "kept-test", rows, struct{}{})
answerBuffers.Lock()
n := len(answerBuffers.free)
answerBuffers.Unlock()
if n == 0 {
t.Fatal("writeJSONRows kept no buffer for the next answer")
}
}