Files
magpie/internal/gui/stats_answer_test.go
T
yetone bed604efb3 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.
2026-10-30 19:05:17 +08:00

75 lines
2.6 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"
"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")
}
}