Files
magpie/internal/gui/stats_answer_test.go
T
yetone bb5eb83c3e gui: the Sessions list goes out a row at a time, never held whole (#2278)
writeJSONRows built the whole answer in a buffer to hash it and send it.
Over the owner's full history (16,600 sessions, 5.8 MB list) that buffer
grew to 25 MB, was kept between polls, and was 25 MB of a warm start's
183 MB live heap. Now a first pass encodes each row into one small
buffer for its hash and the answer's tag. What is sent is encoded again,
straight to the ResponseWriter through a 32 KiB bufio.Writer, and a delta
holds only the rows the page hasn't got. The bytes and the tag are the
same as before, so the page's delta and "same" answers don't change.

Run on mote (macOS 27), real history copy (~16,600 session files):
- warm start, 75 s of poll.sh (what an open window asks every 5 s):
  - before (v0.1.2382): steady footprint 240-265 MB, live heap 183-193 MB;
  - after: steady footprint 216-233 MB, live heap 168-178 MB.
  - The phys_footprint peak is about the same (257-267 vs 264-289 MB over
    3 interleaved pairs): a poll's own spike still sets it.
- /api/sessions from each binary on the same history: the same tag
  06a661d3…, the same sha256 of 5,842,606 bytes, X-Magpie-Same on its
  tag, and the full list for an unknown tag.
- TestJSONRowsNotHeldWhole is new: red on the old writeJSONRows (9.5 MB
  allocated for a 4.2 MB answer), green now. TestWriteJSONRowsWritesWhatMarshalDid
  (bytes and delta) is green.
- go test ./internal/gui: ok except three reds that are already filed.
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestMainWindowCorners
  (#3949) are red the same way with the old api.go in the same copy.
  TestColdTurnsTaken (#4510) was red in the full run and passed 3 of 3
  alone.
Not run: the GUI (Playwright) suite. app.js isn't touched and the
answer's bytes are the same.
2026-10-31 20:15:15 +08:00

90 lines
3.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package gui
import (
"bytes"
"encoding/json"
"net/http/httptest"
"runtime"
"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)
}
// writeJSONRows holds no answer-sized buffer: the list goes out a row at a
// time, and the whole answer was 25 MB of a warm start's live heap (#2278).
func TestJSONRowsNotHeldWhole(t *testing.T) {
big := string(bytes.Repeat([]byte("x"), 64<<10))
rows := make([]rowsBufRow, 64)
for i := range rows {
rows[i] = rowsBufRow{Name: big, N: float64(i)}
}
w := httptest.NewRecorder()
writeJSONRows(w, httptest.NewRequest("GET", "/x", nil), "rows", rows, struct{}{}) // warm
var before, after runtime.MemStats
w = httptest.NewRecorder()
w.Body.Grow(len(rows)*len(big) + 1<<20) // the recorder's copy isn't magpie's
runtime.ReadMemStats(&before)
writeJSONRows(w, httptest.NewRequest("GET", "/x", nil), "rows", rows, struct{}{})
runtime.ReadMemStats(&after)
answer := uint64(w.Body.Len())
if got := after.TotalAlloc - before.TotalAlloc; got > answer/4 {
t.Fatalf("writeJSONRows allocated %d bytes for a %d-byte answer", got, answer)
}
}