Files
magpie/internal/gateway/body_room.go
T
yinwu01 fd85c0a1e9 gateway: a test's memory root reads nothing of the machine it runs on (#5118)
TestCodexBodyLimitFromMemory's "unknown" case is red on every Linux
machine with more than 8 GiB: ubuntu CI ("unknown: 998 MiB" in the Test
job at 0a5dc40ab), the Linux box under WSL ("unknown: 1994 MiB") and
this one ("unknown: 2048 MiB"). The case points memLimit at an empty
root with memGOOS "linux". codexBodyLimit, bodyRoomSize and
claudeRunBudget fall back to proc.MemTotal() whenever memGOOS is this
system's, which held for a test's root too, so on Linux the fixture
read the test machine's own memory. Elsewhere the GOOS differs: macOS
CI at 0a5dc40ab doesn't fail this test (its job is red on others).

The three now fall back only when memOwn: memGOOS is this system's and
memRoot is "/", the only root magpie itself sets. The magpie binary
behaves as before; a test's root no longer reaches the machine's
memory.

What was run (tree 039a3044, on origin/main 43849d51, go1.26.8,
linux/amd64, Linux 5.15), outside graftcp, umask 077:
- TestAFixtureRootIsNotThisComputer (new): an empty root naming this
  computer's GOOS leaves bodyRoomSize, claudeRunBudget and
  codexBodyLimit at their unknown values. With memOwn put back to the
  GOOS check alone: red on all three ("body room 16111 MiB (a
  thirty-second of 515578 MiB (the computer's memory)), want none",
  "run budget 64447 MiB (...), want the unknown 4096 MiB", "Codex turn
  limit 2048 MiB, want 512 MiB"), and TestCodexBodyLimitFromMemory
  "unknown: 2048 MiB". With claude_rss.go's fallback alone put back as
  it was, only the run budget. With the change, with
  TestCodexBodyLimitFromMemory, TestBodyRoomSize,
  TestClaudeRunBudgetScalesWithMemory, TestClaudeMemRuns* and
  TestClaudeRunsMost*: -count=3 21 of 21 ok, and -race -count=3 21 of
  21 ok.
- gofmt -l clean. go vet -tags nogui for linux and windows, go vet for
  windows, go build -tags nogui for linux and darwin and go build for
  windows: exit 0 each. GOOS=darwin go vet -tags nogui: exit 1 at
  internal/gui/traywindows_darwin_test.go (trayImagePNG is darwin &&
  cgo, and a cross vet has no cgo), the same at origin/main 43849d51.
  go vet and go build without the tag on linux: exit 1 (no libsoup-3.0
  or gio-unix-2.0 pkg-config here).
- go test -tags nogui -count=1 -timeout 45m ./... (Bun 1.4.2): 84
  packages ok, gateway among them; red in three, each red the same run
  alone at origin/main 43849d51: sessions' TestCCListingKeepsItsNames
  (#4925), agent's TestDshACPSettingsGetTheRoute (this box's umask 077,
  #5238), provider's TestOpenCodeProjectIs225s and
  TestOpenCodeEnvironmentIs225s (an empty /tmp/.git on this box,
  #5239).

Not tried: a Mac or Windows. There the new test should be red on the
old code too, as the fallback took that machine's memory the same way;
it was run only here.

Reviewed and landed by yetone at origin/main d17a0b3ca (patch hash
639baff3... checked against the one posted on #5118). CI went red on
this at 4a9cfb52e (run 41865226839, ubuntu). Run at this tree:
- Linux (wsl-run, magpie-desktop, go1.26.8, -tags nogui): with memOwn
  put back to `memGOOS == runtime.GOOS` alone, TestCodexBodyLimitFromMemory
  "unknown: 1994 MiB" and TestAFixtureRootIsNotThisComputer red on all
  three readers (body room 997 MiB, run budget 3989 MiB, Codex turn
  limit 1994 MiB). With the change, the memory tests (TestCodexBodyLimit-
  FromMemory, TestAFixtureRootIsNotThisComputer, TestBodyRoomSize,
  TestClaudeRunBudgetScalesWithMemory, TestClaudeMemRuns*,
  TestClaudeRunsMost*): ok.
- macOS (mote): with memOwn put back, TestAFixtureRootIsNotThisComputer
  red on all three (2048/8192/2048 MiB from mote's 64 GiB);
  TestCodexBodyLimitFromMemory passes there either way (memGOOS
  "linux" differs). With the change, the same set -race: ok.
- gofmt -l, go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet
  (internal/gateway), go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build: clean on mote.
Not tried: Windows; the full suite (run once after this batch).
2026-11-05 00:57:55 +08:00

180 lines
5.3 KiB
Go

package gateway
import (
"context"
"fmt"
"log"
"slices"
"sync"
"time"
"github.com/yetone/magpie/internal/proc"
)
// bodyRoom bounds the decoded request bytes the gateway serves at once.
// One request's limit (defaultBodyLimit) bounds no sum: each body is held
// while its request is served, with what is made from it, the model
// rewritten, a translation to Chat, a plugin's base64 line, several times
// its size. On a 2 GiB server Codex turns of ~45 MiB, one after another
// and side by side, held the Go heap at ~500 MiB and the plugin host at
// ~500 MiB, into swap (jihuayu, #4004).
//
// A body of bodyRoomFree or more takes room for its size until its
// request ends. With too little left it waits its turn, first come first
// served, for requests to end, bodyRoomWait at most, and is answered 503
// with the provider not asked. A body bigger than the whole room runs
// alone. Small bodies, an agent's ordinary turns, pass without counting.
type bodyRoomT struct {
mu sync.Mutex
// room is the most held at once; 0 no bound. sized says room was set.
room int64
why string
sized bool
held int64
// by is what each request being served holds, by its context, so a
// body read twice in one request takes its room once
by map[context.Context]int64
queue []*bodyWaiter
}
type bodyWaiter struct {
ctx context.Context
n int64
in chan struct{} // closed when let in
}
var bodyRoom = &bodyRoomT{}
// bodyRoomFree is the size a body takes room from; smaller ones pass.
const bodyRoomFree = 1 << 20
// bodyRoomWait is how long a body waits for room before its request is
// answered 503: within unroutedMost, which the wait counts toward
// (noteWait), so the answer says why.
var bodyRoomWait = 100 * time.Second
// bodyRoomFloor is the least room, however small the machine.
const bodyRoomFloor = 64 << 20
// bodyRoomSize is a thirty-second of what magpie's processes may use
// (memLimit on Linux, the computer's memory elsewhere), bodyRoomFloor at
// least: a 44 MiB Responses turn sent on as Chat peaked at ~700 MiB of Go
// heap on its way, garbage not yet collected included, and a plugin's host
// holds more. Where neither is known there is no bound: a limit not known
// is not a small one.
func bodyRoomSize() (int64, string) {
limit, why := memLimit(memGOOS, memRoot)
if limit <= 0 && memOwn() {
limit, why = proc.MemTotal(), "the computer's memory"
}
if limit <= 0 {
return 0, ""
}
return max(limit/32, bodyRoomFloor), fmt.Sprintf("a thirty-second of %d MiB (%s)", limit>>20, why)
}
// bodyFull is the error of a body that found no room in bodyRoomWait.
type bodyFull struct {
n, held, room int64
why string
waited time.Duration
}
func (e *bodyFull) Error() string {
return fmt.Sprintf("magpie is serving %d MiB of request bodies at once, as much as it holds (%d MiB, %s), "+
"and none of them ended within %s to make room for this %d MiB one; the provider was not asked",
e.held>>20, e.room>>20, e.why, e.waited, e.n>>20)
}
// take holds n bytes of room for the request ctx belongs to until ctx is
// done, waiting its turn for it. A request takes it on its Content-Length
// before its body is read, so the ones waiting don't hold theirs, and
// again on the body read, which only adds what that is over the first. A
// ctx that is never done (a caller's own) takes nothing, since nothing
// would give it back.
func (b *bodyRoomT) take(ctx context.Context, n int64) error {
if n < bodyRoomFree || ctx.Done() == nil {
return nil
}
b.mu.Lock()
if !b.sized {
b.sized = true
b.room, b.why = bodyRoomSize()
}
if h, ok := b.by[ctx]; ok || b.room <= 0 {
if ok && n > h {
// the body read is bigger than its request said, a compressed
// one: it holds what it is, let in already
b.held += n - h
b.by[ctx] = n
}
b.mu.Unlock()
return nil
}
w := &bodyWaiter{ctx: ctx, n: n, in: make(chan struct{})}
b.queue = append(b.queue, w)
b.letIn()
held, room, why := b.held, b.room, b.why
b.mu.Unlock()
select {
case <-w.in:
return nil
default:
}
start := time.Now()
log.Printf("gateway: a %d MiB request body waits for room: %d MiB of %d MiB held (%s)", n>>20, held>>20, room>>20, why)
defer noteWait(ctx, "body room")()
timer := time.NewTimer(bodyRoomWait)
defer timer.Stop()
var err error
select {
case <-w.in:
return nil
case <-ctx.Done():
err = ctx.Err()
case <-timer.C:
}
b.mu.Lock()
defer b.mu.Unlock()
select {
case <-w.in:
return nil // let in as it gave up: it holds the room, and ctx gives it back
default:
}
b.queue = slices.DeleteFunc(b.queue, func(q *bodyWaiter) bool { return q == w })
b.letIn() // one ahead gone may let the next in
if err != nil {
return err
}
return &bodyFull{n: n, held: b.held, room: b.room, why: b.why, waited: time.Since(start).Round(time.Second)}
}
// letIn lets in, in order, each waiter there is room for: one bigger than
// the room when nothing is held. b.mu is held.
func (b *bodyRoomT) letIn() {
for len(b.queue) > 0 {
w := b.queue[0]
if b.held > 0 && b.held+w.n > b.room {
return
}
b.queue = b.queue[1:]
if b.by == nil {
b.by = map[context.Context]int64{}
}
b.held += w.n
b.by[w.ctx] = w.n
close(w.in)
ctx := w.ctx
context.AfterFunc(ctx, func() { b.give(ctx) })
}
}
// give returns what ctx's request held.
func (b *bodyRoomT) give(ctx context.Context) {
b.mu.Lock()
defer b.mu.Unlock()
b.held -= b.by[ctx]
delete(b.by, ctx)
b.letIn()
}