Files
magpie/internal/gateway/workdir.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

132 lines
4.0 KiB
Go

package gateway
// The folder an agent works in, as it tells its model in the request — for
// a group's rule by folder (provider.Rule.Folders). Each agent says it its
// own way, every format here taken from the agent's own request:
//
// - Claude Code (2.1.296): its environment, " - Primary working
// directory: /x", in the system prompt or a system message; when the
// folder changes, "Primary working directory: /y (was /x)". < and > in
// the path come as &lt; and &gt;.
// - Codex (0.162): a user message's <environment_context> with
// "<cwd>/x</cwd>", the path's &, < and > as entities.
// - Pi (1.1): the system prompt's "<cwd>\n/x\n</cwd>", backslashes as /.
// - OpenCode (2.0): "<env>\n Working directory: /x\n…</env>", in the
// system prompt or, when it changes, a later message.
//
// Of those it says, the last one goes: an agent that moved says so after.
// An agent that says none of them has no folder: a rule by folder doesn't
// match it.
import (
"html"
"net/http"
"net/url"
"regexp"
"strings"
"github.com/yetone/magpie/internal/provider"
)
var (
ccWorkDir = regexp.MustCompile(`(?m)^(?: - )?Primary working directory: (.+)$`)
// the folder a <cwd> holds: Codex's on its line, Pi's on its own
cwdTag = regexp.MustCompile(`<cwd>\s*([^<\n]+?)\s*</cwd>`)
envDir = regexp.MustCompile(`(?m)^\s*Working directory: (.+)$`)
wasDir = regexp.MustCompile(` \(was .*\)$`)
)
// workDir is the folder the request says its agent works in; "" when it
// doesn't say.
func workDir(req *Request) string {
dir, _ := workPlace(req)
return dir
}
// workPlace is the folder the request says its agent works in, and
// whether that folder is in a git repository as the text that says the
// folder says it: "yes", "no", or "" when it doesn't say.
func workPlace(req *Request) (dir, git string) {
if req == nil {
return "", ""
}
look := func(text string) {
if d := workDirIn(text, ""); d != "" {
dir, git = d, provider.GitSaid(text)
}
}
look(req.System)
for _, m := range req.Messages {
if m.Role == "assistant" {
continue // the model's words, not the agent's
}
for _, p := range m.Parts {
if p.Kind == Text {
look(p.Text)
}
}
}
return dir, git
}
// tellWorkPlace puts on a request to a plugin's provider the folder its
// agent works in (provider.WorkDirHeader, percent-encoded) and whether
// it is in a git repository (provider.WorkGitHeader), as far as body, in
// protocol to, says: a plugin that tells its vendor the user's
// environment, as ZCode's Start Plan does, says the agent's own and not
// magpie's (magpie-community/plugins#86). A folder not said leaves both
// off: unknown. Whether it is a git repository is the agent's word, else
// looked at on disk.
func tellWorkPlace(h http.Header, to provider.Protocol, body []byte) {
h.Del(provider.WorkDirHeader)
h.Del(provider.WorkGitHeader)
f := factsOf(to, body)
dir, git := f.dir, f.git
if dir == "" {
return
}
if git == "" {
git = provider.GitOnDisk(dir)
}
h.Set(provider.WorkDirHeader, url.PathEscape(dir))
if git != "" {
h.Set(provider.WorkGitHeader, git)
}
}
// workDirIn is the last folder text says, else dir.
func workDirIn(text, dir string) string {
if !strings.Contains(text, "irectory: ") && !strings.Contains(text, "<cwd>") {
return dir
}
at := -1
take := func(i int, v string) {
if v = strings.TrimSpace(html.UnescapeString(v)); v != "" && i > at {
at, dir = i, v
}
}
for _, m := range ccWorkDir.FindAllStringSubmatchIndex(text, -1) {
take(m[0], wasDir.ReplaceAllString(text[m[2]:m[3]], ""))
}
for _, m := range cwdTag.FindAllStringSubmatchIndex(text, -1) {
take(m[0], text[m[2]:m[3]])
}
// OpenCode's, only within its <env>
for rest, off := text, 0; ; {
i := strings.Index(rest, "<env>")
if i < 0 {
break
}
j := strings.Index(rest[i:], "</env>")
if j < 0 {
break
}
block := rest[i : i+j]
if m := envDir.FindStringSubmatchIndex(block); m != nil {
take(off+i+m[0], block[m[2]:m[3]])
}
rest, off = rest[i+j:], off+i+j
}
return dir
}