Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

gateway: a conversation's turn count and folder come from one parse of it, not one each (yg6888 on X: ~1 GB)

yetone41147956d2f5
diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go
index 4352c4d6f..a30da86dd 100644
--- a/internal/gateway/affinity.go
+++ b/internal/gateway/affinity.go
@@ -320,11 +320,8 @@ func saveSticks() {
// turnOf counts the user's turns in a request's conversation, and says
// whether it is the agent handing tool results back within one.
func turnOf(from provider.Protocol, body []byte) (turn int, within bool) {
- req, err := parse(from, body)
- if err != nil {
- return 0, false
- }
- return turnIn(req)
+ f := factsOf(from, body)
+ return f.turn, f.within
}
// turnIn is turnOf for a request already parsed. The last of the user's
diff --git a/internal/gateway/fastjson.go b/internal/gateway/fastjson.go
index 092fdfcb3..e5e278e4b 100644
--- a/internal/gateway/fastjson.go
+++ b/internal/gateway/fastjson.go
@@ -80,6 +80,8 @@ func decodeJSON(data []byte, dst any) error {
var heldBodies struct {
sync.Mutex
list atomic.Pointer[[][]byte]
+ // facts: a held body's bodyFacts, by the body's first byte (factsOf)
+ facts map[*byte]heldFacts
}
// heldBodiesMost bounds heldBodies: a body past it is decoded with copies, as
@@ -121,6 +123,7 @@ func holdBody(ctx context.Context, body []byte) {
if i < 0 {
return
}
+ delete(heldBodies.facts, unsafe.SliceData(body))
next := slices.Delete(slices.Clone(cur), i, i+1)
heldBodies.list.Store(&next)
})
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index 3c23bd89f..c05a0a1b7 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -1833,9 +1833,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// works in; one that says none is outside every folder
folder := ""
if provider.PausesByFolder(g, ms) {
- if req, err := parse(from, body); err == nil {
- folder = workDir(req)
- }
+ folder = factsOf(from, body).dir
}
ms, paused = provider.PausedOut(g, ms, agent, folder, ruleClock())
if len(ms) == 0 && len(paused) > 0 {
diff --git a/internal/gateway/parse_memo.go b/internal/gateway/parse_memo.go
new file mode 100644
index 000000000..a7d326cac
--- /dev/null
+++ b/internal/gateway/parse_memo.go
@@ -0,0 +1,77 @@
+package gateway
+
+import (
+ "unsafe"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// bodyFacts is what the readers of a request's conversation that only
+// read it take from it: the turn count (turnOf), the folder its agent
+// works in and whether that is a git repository, as the text says
+// (dirOf, tellWorkPlace). A body that doesn't parse says none of them.
+type bodyFacts struct {
+ turn int
+ within bool
+ dir, git string
+}
+
+// factsOf is bodyFacts of body, read in protocol proto. Each of its
+// readers parsed the whole conversation, every message and tool output
+// decoded into strings of its own, one just after the other: a 2 MB
+// conversation was decoded twice over on every request for a number and
+// a folder (yg6888 on X: ~1 GB).
+//
+// For a body being served (holdBody), the facts are kept while the body
+// is held, so it is parsed for them once: they are a few words, kept
+// whole, where keeping the parse itself would keep a copy of the
+// conversation for the request's life.
+func factsOf(proto provider.Protocol, body []byte) bodyFacts {
+ if len(body) < validMemoMin {
+ return readFacts(proto, body)
+ }
+ key := unsafe.SliceData(body)
+ heldBodies.Lock()
+ e, ok := heldBodies.facts[key]
+ heldBodies.Unlock()
+ if ok && e.n == len(body) && e.proto == proto {
+ return e.facts
+ }
+ f := readFacts(proto, body)
+ heldBodies.Lock()
+ defer heldBodies.Unlock()
+ // only while body is held, whole: one released may be freed, and its
+ // memory given to another body that would read as this one. A body
+ // read in two protocols keeps the last.
+ if l := heldBodies.list.Load(); l != nil {
+ for _, b := range *l {
+ if unsafe.SliceData(b) == key && len(b) == len(body) {
+ if heldBodies.facts == nil {
+ heldBodies.facts = map[*byte]heldFacts{}
+ }
+ heldBodies.facts[key] = heldFacts{n: len(body), proto: proto, facts: f}
+ break
+ }
+ }
+ }
+ return f
+}
+
+// readFacts parses body for its bodyFacts.
+func readFacts(proto provider.Protocol, body []byte) bodyFacts {
+ req, err := parse(proto, body)
+ if err != nil {
+ return bodyFacts{}
+ }
+ var f bodyFacts
+ f.turn, f.within = turnIn(req)
+ f.dir, f.git = workPlace(req)
+ return f
+}
+
+// heldFacts is a held body's bodyFacts (factsOf).
+type heldFacts struct {
+ n int
+ proto provider.Protocol
+ facts bodyFacts
+}
diff --git a/internal/gateway/parse_memo_test.go b/internal/gateway/parse_memo_test.go
new file mode 100644
index 000000000..9798cf673
--- /dev/null
+++ b/internal/gateway/parse_memo_test.go
@@ -0,0 +1,129 @@
+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")
+ }
+}
diff --git a/internal/gateway/turndone.go b/internal/gateway/turndone.go
index e815eb73d..4e3fd2c19 100644
--- a/internal/gateway/turndone.go
+++ b/internal/gateway/turndone.go
@@ -240,9 +240,6 @@ func agentTurnOf(r *http.Request, kind string) (bool, *toolScan) {
// dirOf reads the folder body says its agent works in, when asked.
func dirOf(proto provider.Protocol, body []byte) func() string {
return func() string {
- if req, err := parse(proto, body); err == nil {
- return workDir(req)
- }
- return ""
+ return factsOf(proto, body).dir
}
}
diff --git a/internal/gateway/workdir.go b/internal/gateway/workdir.go
index 36b160a45..583acbf1c 100644
--- a/internal/gateway/workdir.go
+++ b/internal/gateway/workdir.go
@@ -80,11 +80,8 @@ func workPlace(req *Request) (dir, git string) {
func tellWorkPlace(h http.Header, to provider.Protocol, body []byte) {
h.Del(provider.WorkDirHeader)
h.Del(provider.WorkGitHeader)
- req, err := parse(to, body)
- if err != nil {
- return
- }
- dir, git := workPlace(req)
+ f := factsOf(to, body)
+ dir, git := f.dir, f.git
if dir == "" {
return
}