gui: a same-tagged answer is written twice, never held whole (#2278)

writeSame wrote each answer into a buffer to hash and send it, and kept
two such buffers between polls (answerLinger). The Sessions tab's stats
answers are ~6 MB each over a full history, so 12.5 MB of a warm start's
169 MB live heap was those buffers (heap profile, bytes.growSlice under
statsAnswer). Now write is given an io.Writer and called twice: once into
the hash for the tag, and once straight to rw (32 KB bufio) when the page
hasn't got that answer. statsAnswer encodes a part at a time into a small
buffer. The stats route still answers "same" from its kept tag without
encoding at all when nothing changed, so the second encode costs only on
a changed answer. answerBuffers, answerBuffer, keepAnswer go.

Run on mote (M5 Pro), from this tree:
- go vet ./internal/gui ok; gofmt -l clean.
- go test -count=1 ./internal/gui: FAIL only TestSettingsSaveKeepsWhatItDoesNotSend
  (#4514) and TestMainWindowCorners/macOS_26_SDK (#3949), both filed, both
  untouched by this change. TestStatsAnswerWritesWhatEncodeDid (bytes are
  the whole Encoder's) and the new TestSameAnswerNotHeldWhole pass.
- Broken by hand: writeSame's bufio sized 64 MB, TestSameAnswerNotHeldWhole
  red ("allocated 67117776 bytes for a 4194304-byte answer").
- Warm start on a copy of the owner's real history (11,925 Codex .zst,
  4,696 Claude .jsonl, 5,000 listed sessions), the page's 10 reads every
  5s, interleaved, load ~25-34:
    before (bb5eb83c3): footprint peak 267, 269, 274 MB; cpu 9.6-10.1s
    after:              footprint peak 255, 257, 258 MB; cpu 9.9-10.2s

Not tried: a cold start A/B (the buffers matter once polls begin).
This commit is contained in:
yetone
2026-10-31 20:31:26 +08:00
parent 3561697a40
commit d9845432f7
3 changed files with 94 additions and 94 deletions
+14 -56
View File
@@ -15,6 +15,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"maps"
"mime"
@@ -2899,20 +2900,21 @@ 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 {
return writeSame(rw, r, func(b *bytes.Buffer) error { return json.NewEncoder(b).Encode(v) })
return writeSame(rw, r, func(w io.Writer) error { return json.NewEncoder(w).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 {
// writeSame is writeJSONSame of the answer write writes to the writer it
// is given, called twice: once into the hash, for the tag, and once
// straight to rw when the page hasn't got it. The answer is never held
// whole: the stats' ~6 MB each, in buffers kept between polls, were
// 12.5 MB of a warm start's 169 MB live heap over a full history (#2278).
func writeSame(rw http.ResponseWriter, r *http.Request, write func(w io.Writer) error) string {
h := sha256.New()
if err := write(h); err != nil {
fail(rw, err)
return ""
}
sum := sha256.Sum256(b.Bytes())
tag := hex.EncodeToString(sum[:16])
tag := hex.EncodeToString(h.Sum(nil)[:16])
rw.Header().Set("X-Magpie-Tag", tag)
if r.Header.Get("X-Magpie-Had") == tag {
rw.Header().Set("X-Magpie-Same", "1")
@@ -2920,7 +2922,9 @@ func writeSame(rw http.ResponseWriter, r *http.Request, write func(b *bytes.Buff
return tag
}
rw.Header().Set("Content-Type", "application/json")
_, _ = rw.Write(b.Bytes())
out := bufio.NewWriterSize(rw, 32<<10)
_ = write(out) // as the first time: it was written without a fault
_ = out.Flush()
return tag
}
@@ -2935,52 +2939,6 @@ 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)
}
// writeJSONRows is writeJSONSame for an answer that is a long list, key,
// beside the fields of rest: one asked with the tag of a list sent before
// that changed since gets X-Magpie-Delta: key, and its list holds only the
+45 -21
View File
@@ -5,6 +5,7 @@ import (
"cmp"
"encoding/json"
"errors"
"io"
"maps"
"math"
"net/http"
@@ -192,7 +193,7 @@ func sessionRoutes(mux *http.ServeMux, w Windows) {
rw.WriteHeader(http.StatusOK)
return
}
tag := writeSame(rw, r, func(b *bytes.Buffer) error { return statsAnswer(b, st, agents) })
tag := writeSame(rw, r, func(w io.Writer) error { return statsAnswer(w, st, agents) })
if tag != "" {
statsTags.Lock()
if statsTags.m == nil || len(statsTags.m) >= statsMemoMost {
@@ -966,52 +967,75 @@ 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)
// statsAnswer writes the stats answer to w as an Encoder of
// struct{ sessions.Stats; Agents } does, a part 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, and a
// buffer kept for the next held it between polls (#2278).
func statsAnswer(w io.Writer, st sessions.Stats, agents map[string]string) error {
var part bytes.Buffer
enc := json.NewEncoder(&part)
// v as Marshal writes it: Encode ends it with a newline
put := func(v any) error {
part.Reset()
if err := enc.Encode(v); err != nil {
return err
}
b.Truncate(b.Len() - 1)
return nil
_, err := w.Write(part.Bytes()[:part.Len()-1])
return err
}
text := func(s string) error {
_, err := io.WriteString(w, s)
return err
}
if err := text(`{"from":`); err != nil {
return err
}
b.WriteString(`{"from":`)
if err := put(st.From); err != nil {
return err
}
b.WriteString(`,"to":`)
if err := text(`,"to":`); err != nil {
return err
}
if err := put(st.To); err != nil {
return err
}
b.WriteString(`,"days":`)
if err := text(`,"days":`); err != nil {
return err
}
if st.Days == nil {
b.WriteString("null")
if err := text("null"); err != nil {
return err
}
} else {
b.WriteByte('[')
if err := text("["); err != nil {
return err
}
for i := range st.Days {
if i > 0 {
b.WriteByte(',')
if err := text(","); err != nil {
return err
}
}
if err := put(&st.Days[i]); err != nil {
return err
}
}
b.WriteByte(']')
if err := text("]"); err != nil {
return err
}
}
if err := text(`,"keys":`); err != nil {
return err
}
b.WriteString(`,"keys":`)
if err := put(st.Keys); err != nil {
return err
}
b.WriteString(`,"agents":`)
if err := text(`,"agents":`); err != nil {
return err
}
if err := put(agents); err != nil {
return err
}
b.WriteString("}\n")
return nil
return text("}\n")
}
+35 -17
View File
@@ -2,7 +2,10 @@ package gui
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"net/http/httptest"
"runtime"
"testing"
@@ -44,26 +47,41 @@ func TestStatsAnswerWritesWhatEncodeDid(t *testing.T) {
}
}
// 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)
// writeSame holds no answer-sized buffer, and keeps none for the next:
// the stats' answers were 12.5 MB of a warm start's live heap (#2278).
// What it sends, and its tag, are the bytes write gave.
func TestSameAnswerNotHeldWhole(t *testing.T) {
big := bytes.Repeat([]byte("x"), 4<<20)
write := func(w io.Writer) error {
for i := 0; i < len(big); i += 64 << 10 {
if _, err := w.Write(big[i : i+64<<10]); err != nil {
return err
}
}
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())
w := httptest.NewRecorder()
tag := writeSame(w, httptest.NewRequest("GET", "/x", nil), write) // warm
sum := sha256.Sum256(big)
if !bytes.Equal(w.Body.Bytes(), big) || tag != hex.EncodeToString(sum[:16]) {
t.Fatalf("answer of %d bytes, tag %q: not what write gave", w.Body.Len(), tag)
}
var before, after runtime.MemStats
w = httptest.NewRecorder()
w.Body.Grow(len(big) + 1<<20) // the recorder's copy isn't magpie's
runtime.ReadMemStats(&before)
writeSame(w, httptest.NewRequest("GET", "/x", nil), write)
runtime.ReadMemStats(&after)
if got := after.TotalAlloc - before.TotalAlloc; got > uint64(len(big)/4) {
t.Fatalf("writeSame allocated %d bytes for a %d-byte answer", got, len(big))
}
same := httptest.NewRequest("GET", "/x", nil)
same.Header.Set("X-Magpie-Had", tag)
w = httptest.NewRecorder()
writeSame(w, same, write)
if w.Header().Get("X-Magpie-Same") != "1" || w.Body.Len() != 0 {
t.Fatalf("asked with its own tag: same %q, %d bytes", w.Header().Get("X-Magpie-Same"), w.Body.Len())
}
keepAnswer(b)
}
// writeJSONRows holds no answer-sized buffer: the list goes out a row at a