Files
magpie/internal/gateway/parse_memo_test.go
T
yetone 41147956d2 gateway: a conversation's turn count and folder come from one parse of it, not one each (yg6888 on X: ~1 GB)
turnOf (affinity), dirOf (the trace's folder) and tellWorkPlace (a
plugin's work-place headers) each parsed the whole conversation for a
number and a folder. A parse decodes every message and tool output into
strings of its own, so a long conversation was decoded twice over on
every request for them. In the 60-min soak before (dee5c9d75, 4746
requests), parse was 26.4 GB of 106.7 GB allocated: turnOf 11.5 GB and
dirOf 11.4 GB.

factsOf parses once for the turn count, the folder, and whether the
text says it is a git repository (bodyFacts). For a body being served
(holdBody), it keeps those facts, a few words, while the body is held.
The pause-by-folder check reads the same facts.

It keeps the facts, not the parse. A first version kept the *Request
weakly. In the served benchmark the weak pointer was already collected
between turnOf and dirOf on 1 read in 6, and under real load the
collector runs more often. Keeping the parse strongly would keep a copy
of the conversation for the whole request. The facts are kept only
while their body is listed whole; the entry goes when the body is
released, so a body's memory given to another never reads as this one.
A body not held, or read in another protocol, is parsed for its own.

BenchmarkLargeRequest, ~2 MB conversation, B/op before → after:
  anthropic        53.81 → 45.84 MB
  anthropic-group  65.26 → 57.30 MB
  chat             43.27 → 36.61 MB
  responses        53.81 → 46.04 MB
6.7 to 8.0 MB less per request, about 3.5× the body.

Tests (parse_memo_test.go):
- TestReadersOfAHeldBodyParseItOnce: what the three readers say equals
  a parse of their own. Together they allocate at most 1.5× one parse,
  and readers after the first allocate almost nothing. A Chat read of
  the same bytes is its own, and a copy not held is parsed again.
- TestHeldFactsGoWithTheirBody: the entry goes when the request ends,
  a released body is not listed again, and a prefix of a held body is
  not the body.
Broken by hand:
- factsOf always parsing: red, "turnOf, dirOf and tellWorkPlace
  allocate 446064 bytes on a held body, a parse 135096", and "a held
  body's facts were not kept".
- The delete at release removed: red, "a body's facts are still listed
  after its request ended".
TestPauseByFolder, TestRuleByFolder, the WorkDir and WorkPlace tests and
the affinity and turn tests pass, with -race too.
Under -race the readers' byte bound is skipped (raceOn, as
request_zstd_pool_test does): sync.Pool drops a quarter of what is put
in it there, and workDirIn's regexps take their ~37 KB matchers from
one. Five tries read 1.3x to 2.1x a parse, while the parse stayed at
135304 bytes; -race -count=3 went red at 1.57x before the skip.

Run (darwin arm64, go1.26.8, sandbox HOME, load 40 to 90 from other
sessions' suites):
- go test ./... -count=1 -timeout 45m on the series' final tree at
  ba319a758: exit 0, all 68 packages ok (gateway 1498s, agent 1633s).
- After the rebase onto b855cfee9 (two redact commits): go test
  ./internal/redact ./internal/gateway -count=1 -timeout 45m, both ok
  (gateway 917s).
- go test -race -count=3 on the Held, ReadersOfAHeldBody, RecentRing,
  RequestBody, CaptureRequest, folder, WorkPlace, WorkDir and Turn
  tests: ok, after
  TestReadersOfAHeldBodyParseItOnce's byte bound was skipped under
  -race (the third commit says why); that test and
  TestHeldFactsGoWithTheirBody then passed -count=30 with and without
  -race.
- Each commit alone: go vet ./internal/gateway and gofmt -l clean.
- Final tree: gofmt -l clean; go vet ./... for darwin, GOOS=windows and
  GOOS=linux -tags nogui, all exit 0.
Not tried: a second 60-minute soak after the series (the one before is
the "before" here; the "after" numbers are the benchmark's), the GUI
suite (nothing in it changed), Windows and Linux test runs (vet only).
2026-10-21 19:17:09 +08:00

130 lines
4.7 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 gateway
import (
"bytes"
"context"
"net/http"
"net/url"
"strings"
"testing"
"time"
"unsafe"
"github.com/yetone/magpie/internal/provider"
)
// parseMemoBody is a Claude Code conversation in a folder, long enough to
// be held, with a tool result in it.
func parseMemoBody(tag string) []byte {
return []byte(`{"model":"` + tag + `","system":" - Primary working directory: /work/` + tag + `\n","messages":[` +
`{"role":"user","content":"fix it"},` +
`{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Read","input":{"path":"a"}}]},` +
`{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"` + strings.Repeat("line of a file\\n", 4000) + `"}]}]}`)
}
// The turn count (turnOf) and the folder (dirOf, tellWorkPlace) of a
// request being served are read from one parse of its body, not one each:
// each decoded every message and tool output of a long conversation again
// (yg6888 on X: ~1 GB). What they say is what a parse of their own says.
func TestReadersOfAHeldBodyParseItOnce(t *testing.T) {
ctx, done := context.WithCancel(context.Background())
defer done()
body := parseMemoBody(t.Name())
holdBody(ctx, body)
want, err := parse(provider.Anthropic, bytes.Clone(body))
if err != nil {
t.Fatal(err)
}
wantDir := "/work/" + t.Name()
if workDir(want) != wantDir {
t.Fatalf("the fixture's folder reads %q", workDir(want))
}
wantTurn, wantWithin := turnIn(want)
var turn int
var within bool
var dir string
h := http.Header{}
readers := allocated(func() {
turn, within = turnOf(provider.Anthropic, body)
dir = dirOf(provider.Anthropic, body)()
tellWorkPlace(h, provider.Anthropic, body)
})
if turn != wantTurn || within != wantWithin || turn != 1 || !within {
t.Fatalf("turnOf = %d %v, a parse of its own says %d %v", turn, within, wantTurn, wantWithin)
}
if dir != wantDir {
t.Fatalf("dirOf = %q, want %q", dir, wantDir)
}
if got, _ := url.PathUnescape(h.Get(provider.WorkDirHeader)); got != wantDir {
t.Fatalf("tellWorkPlace said %q, want %q", got, wantDir)
}
whole := allocated(func() { parse(provider.Anthropic, body) })
// Under -race, sync.Pool drops a quarter of what is put in it, and
// workDirIn's regexps take their matchers (~37 KB for this body) from
// one, so the readers' bytes swing by whole matchers: 1.3× to 2.1×
// a parse over five tries, against a parse's steady 135 KB.
if !raceOn && readers > whole*3/2 {
t.Fatalf("turnOf, dirOf and tellWorkPlace allocate %d bytes on a held body, a parse %d: they parse it each", readers, whole)
}
// and again, nothing: what was read is kept while the body is held
if again := allocated(func() { turnOf(provider.Anthropic, body); dirOf(provider.Anthropic, body)() }); again > whole/8 {
t.Fatalf("a held body's second readers allocate %d bytes, a parse %d", again, whole)
}
// another protocol's reading of the same bytes is its own
if got, want := factsOf(provider.Chat, body), readFacts(provider.Chat, body); got != want {
t.Fatalf("a held body read as Chat says %+v, a parse of its own %+v", got, want)
}
if got := factsOf(provider.Anthropic, body); got.dir != wantDir || got.turn != 1 {
t.Fatalf("read as Messages again after Chat: %+v", got)
}
// a body not held, of the same bytes, is parsed afresh: nothing says
// its memory isn't written over
clone := bytes.Clone(body)
if fresh := allocated(func() { factsOf(provider.Anthropic, clone) }); fresh < whole/2 {
t.Fatalf("a body not held read %d bytes, a parse %d: it got a held body's facts", fresh, whole)
}
}
// What is kept goes when the request ends, so the body's memory, given to
// another body, never reads as this one, and a body no longer held is not
// listed again.
func TestHeldFactsGoWithTheirBody(t *testing.T) {
ctx, done := context.WithCancel(context.Background())
body := parseMemoBody(t.Name())
holdBody(ctx, body)
factsOf(provider.Anthropic, body)
key := unsafe.SliceData(body)
listed := func() bool {
heldBodies.Lock()
defer heldBodies.Unlock()
_, ok := heldBodies.facts[key]
return ok
}
if !listed() {
t.Fatal("a held body's facts were not kept for its next reader")
}
done()
for deadline := time.Now().Add(5 * time.Second); listed(); {
if time.Now().After(deadline) {
t.Fatal("a body's facts are still listed after its request ended")
}
time.Sleep(time.Millisecond)
}
if f := factsOf(provider.Anthropic, body); f.dir != "/work/"+t.Name() {
t.Fatalf("a released body reads %+v", f)
}
if listed() {
t.Fatal("a body no longer held got its facts listed")
}
// a part of a held body is not the body
ctx2, done2 := context.WithCancel(context.Background())
defer done2()
holdBody(ctx2, body)
factsOf(provider.Anthropic, body[:len(body)-1])
if listed() {
t.Fatal("a held body's prefix got facts listed under the body")
}
}