Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

perf(gateway): remove per-call body copies and pool callout body buffers (#1269)

kyle-elliott-asymptote65937b1b915b
diff --git a/CLAUDE.md b/CLAUDE.md
index 0b54fc99..528bf8e9 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -733,7 +733,7 @@ developer mode.
- When adding a new signal, include stable identifiers/counts/hashes alongside any retained raw content, and route raw fields through redaction, sanitization, truncation, and event-size controls.
- Keep the dashboard read-only. It should inspect local status and JSONL events but must not mutate endpoint configuration or telemetry.
- A few no-op extension points let a separately distributed build compile in files of its own: `claudeExtraHookGroups` and `claudeSettingsChanged` (`cli/beacon/internal/endpoint/hooks/claude.go`), `cursorExtraHooks` and `cursorHooksChanged` (`cursor.go`; an event the map names with no entries is still stripped of Beacon's, which is how a build stops installing a hook there), `codexExtraHookGroups` and `codexHooksChanged` (`codex.go`), `declaredPlatform` in the hook adapter (`cli/beacon-hooks/cmd/helpers.go`: the `--platform` a hook was invoked with, kept when a Cursor payload on a Claude Code hook switches `platformFlag`; the public adapter also reads it to skip those duplicate runs), `version.Edition` (both modules; reported by `beacon version`, `endpoint status --json` and the inventory heartbeat only when it is not `community`), and `updatecheck.PublicReleases` (false turns off the startup notice, `beacon version check` and the self-updater). In this repository they stay unset, and with them unset Beacon must behave exactly as before: `TestInstallClaudeSettingsUnchangedWithoutExtensions`, `TestCursorHooksGolden` and `TestCodexHooksGolden` compare what the installer writes (and an uninstall leaves) to golden files, with the points cleared by `withoutHookExtensions` so they hold in a build that fills them. Keep them neutral, with no product logic behind them here, and CI refuses any file built only with an `enterprise` tag. The one exception is `beacon endpoint enforcement enable` (`cli/beacon/cmd/endpoint_enforcement.go`), the public installer for the enterprise edition: on an Apple Silicon Mac connected in system mode, with no user-mode Beacon running for the console user, it asks `<dashboard>/api/cli/enforcement/download` for the enterprise package (`internal/endpoint/edition`), installs it with `selfupdate.Applier.InstallPackage` (the self-updater's steps after discovery, with no version gate; the package must match the checksum, be signed by the Apple team pinned in `edition.AppleTeamID`, pass Gatekeeper and report the version and `enterprise` edition once installed, or it is rolled back), then runs the installed binary's own `enable`. A build that carries enforcement sets `activateEnforcement`, which `enable` runs instead, and adds its other subcommands to `endpointEnforcementCmd`. It contains no enforcement logic, never runs from hooks or in the background, and with `activateEnforcement` unset nothing else changes.
-- The gateway module (`gateway/`, its own Go module; `gateway/README.md`) has the same kind of no-op extension points, in `gateway/cmd/beacon-gateway/extend.go`: `analyzerFactories` (by name, each built from its own `analyzers.<name>` node and run after the events analyzer), `policyFactory` (nil keeps `pipeline.AllowAll`), `storeFactories` (by `store.type`; `memory` is built in) `observerFactories` (by name, `observers.<name>`) and `sinkFactories` (by an output's `type`; `jsonl` is built in, and an entry with only `jsonl: <path>` is one). The open config parser names none of an extension's keys. With them empty every call is allowed, and since nothing can change a verdict the pipeline answers each call at admission and analyzes it afterwards (`pipeline.Inline` or a policy turns that off). Gateway events carry `harness.collection_method=gateway`; the events analyzer builds them once and leaves them on `pipeline.Turn.Events` for analyzers after it; ids come from `asymptoteobserve.EventID` when an event is written or cited, never on the call path, and so do the fields no rule can address (content markers, gen_ai message copies, tool-call arguments: `pipeline.Event.Complete`, applied by `Written()`, which an analyzer that needs them calls). A tool call is recorded as the action it asks for (`command.executed`, `file.read`, `mcp.tool_invoked`, `tool.invoked`) before the harness acts; a read's or MCP tool's result repeats the action but never carries the call's target (no `file.path`, no `mcp` block or `tool.name`, which are what `dedupeTarget` reads; the call's arguments go on `gen_ai.tool.call.arguments` instead), so call and result never share an event id whatever replica saw the call, and a target rule fires once. Block rendering in every adapter is exercised by the test-only decider in `gateway/internal/gatewaytest`. Validate with `cd gateway && go vet ./... && go test ./... && go test -race ./pipeline/... ./events/... ./litellm/... ./envoy/... ./portkey/... ./llm/...`.
+- The gateway module (`gateway/`, its own Go module; `gateway/README.md`) has the same kind of no-op extension points, in `gateway/cmd/beacon-gateway/extend.go`: `analyzerFactories` (by name, each built from its own `analyzers.<name>` node and run after the events analyzer), `policyFactory` (nil keeps `pipeline.AllowAll`), `storeFactories` (by `store.type`; `memory` is built in) `observerFactories` (by name, `observers.<name>`) and `sinkFactories` (by an output's `type`; `jsonl` is built in, and an entry with only `jsonl: <path>` is one). The open config parser names none of an extension's keys. With them empty every call is allowed, and since nothing can change a verdict the pipeline answers each call at admission and analyzes it afterwards (`pipeline.Inline` or a policy turns that off). The HTTP callout adapters read bodies into pooled buffers (`gateway.ReadBody`) that the pipeline hands back through `Call.Release` once it has read the call, and the LiteLLM adapter builds a request's body over its payload: no extension may keep a `pipeline.Turn`, its `Call`, or anything sliced from `Call.Body` past `Analyze`, `Observe` or `Decide` (`TestReleasedBodiesAreNotRead` poisons every released buffer and checks the records). Gateway events carry `harness.collection_method=gateway`; the events analyzer builds them once and leaves them on `pipeline.Turn.Events` for analyzers after it; ids come from `asymptoteobserve.EventID` when an event is written or cited, never on the call path, and so do the fields no rule can address (content markers, gen_ai message copies, tool-call arguments: `pipeline.Event.Complete`, applied by `Written()`, which an analyzer that needs them calls). A tool call is recorded as the action it asks for (`command.executed`, `file.read`, `mcp.tool_invoked`, `tool.invoked`) before the harness acts; a read's or MCP tool's result repeats the action but never carries the call's target (no `file.path`, no `mcp` block or `tool.name`, which are what `dedupeTarget` reads; the call's arguments go on `gen_ai.tool.call.arguments` instead), so call and result never share an event id whatever replica saw the call, and a target rule fires once. Block rendering in every adapter is exercised by the test-only decider in `gateway/internal/gatewaytest`. Validate with `cd gateway && go vet ./... && go test ./... && go test -race ./pipeline/... ./events/... ./litellm/... ./envoy/... ./portkey/... ./llm/...`.
- The local trace history (`~/.beacon/endpoint/history.db`, `cli/beacon/internal/endpoint/dashboard/history_*.go`) is opt-in: only `beacon endpoint traces reindex`, a yes to the first-run prompt, or (later) `beacon mcp setup` creates it, and nothing non-interactive is ever prompted. Once it exists, `list`, `search` and `show` must return exactly what the JSONL scan returns for the same log (`TestHistoryAnswersExactlyLikeTheJSONLScan`), so it stores every event and projects it with the same code. A change to the trace projection bumps `historyDerivationVersion`, which rebuilds derived data from the stored lines. The stored lines keep only the raw keys in `historyRawKeys`, and a test fails if the dashboard reads one that is missing. The line dictionary (`historyLineDictionary`) must never change without a new codec.
- The Asymptote device key has exactly one home, `<BaseDir>/asymptote/vector-secrets.json`, read by Vector's `secret` file backend. Never copy it into `config.json`, `vector.toml`, a service unit, an environment variable, a log line, or a `--json` result. Besides Vector, only the root CLI reads it, into memory, to authenticate the one request `beacon endpoint enforcement enable` makes to the platform (and that a build carrying enforcement makes to turn it on or update it); `HasSecretDestinations` is unchanged because the key is not in `config.json`. `internal/auth` is flow-agnostic (PKCE, loopback callback server with an injected exchange function, browser opener, `PostJSON`); new browser flows reuse it rather than adding a second callback server. `connect` must fail before opening a browser when Vector or a service manager is missing, or when Vector rejects the rendered config, so no key is minted or rotated that cannot be used; enrollment rotates a connected device's key in place, so every local check runs ahead of it; the steps that can only fail after the exchange (storing the key, writing the config and unit, starting the service) are covered by the `asymptote/connect-pending` marker, written as soon as the key arrives and removed only when connect finishes, so status reports an incomplete connect instead of the previous connection. A failed first connect stops and removes any partial forwarder before returning, which keeps a later local-only onboarding choice local.
- Keep the release readiness guidance in `README.md` up to date when install, packaging, collector, or dashboard behavior changes.
diff --git a/gateway/README.md b/gateway/README.md
index 69d4f226..db8d82a3 100644
--- a/gateway/README.md
+++ b/gateway/README.md
@@ -125,6 +125,11 @@ registers none beyond the in-memory store and the `jsonl` output: every call is
nothing that could change a verdict the pipeline answers each call as soon as it is admitted and
records it afterwards.
+An analyzer, policy or observer sees a call only for the length of its own method: the callout
+adapters read bodies into pooled buffers that the pipeline returns once it has read the call
+(`gateway.Call.Release`), so none may keep the `pipeline.Turn`, its `Call`, or bytes of the
+`Call.Body` afterwards. Everything the pipeline decodes from a body is a copy.
+
An output is an entry of `outputs`, naming its type and the record kinds it receives:
```yaml
diff --git a/gateway/envoy/envoy.go b/gateway/envoy/envoy.go
index 0911f3e6..622ab7e7 100644
--- a/gateway/envoy/envoy.go
+++ b/gateway/envoy/envoy.go
@@ -212,6 +212,8 @@ type body struct {
overflow bool
done bool
buf []byte
+ // declared is the length the body's headers declared, -1 when they declared none.
+ declared int64
// held is the memory reserved for the body at admission, released by free.
held int64
releases []func()
@@ -225,7 +227,10 @@ func (b *body) free() {
b.releases, b.held = nil, 0
}
-// add appends a chunk and reports whether it completed a body to analyze.
+// add appends a chunk and reports whether it completed a body to analyze. A chunk is the bytes of
+// its message, which gRPC decodes into a buffer of their own that nothing else holds: a body that
+// arrives whole (BUFFERED) is kept as that buffer rather than copied, and one that arrives in
+// chunks is gathered in a buffer sized to its declared length.
func (b *body) add(chunk []byte, end bool, limit int) bool {
if b.skip || b.done {
return false
@@ -233,12 +238,17 @@ func (b *body) add(chunk []byte, end bool, limit int) bool {
if !end {
b.streamed = true
}
- if !b.overflow {
- if len(b.buf)+len(chunk) > limit {
- b.overflow, b.buf = true, nil
- } else {
- b.buf = append(b.buf, chunk...)
+ switch {
+ case b.overflow:
+ case len(b.buf)+len(chunk) > limit:
+ b.overflow, b.buf = true, nil
+ case b.buf == nil && end:
+ b.buf = chunk
+ default:
+ if b.buf == nil && b.declared > 0 {
+ b.buf = make([]byte, 0, min(b.declared, int64(limit)))
}
+ b.buf = append(b.buf, chunk...)
}
b.done = end
return end
@@ -365,6 +375,7 @@ func (x *exchange) admit(ctx context.Context, b *body, declared int64) (gateway.
return gateway.Verdict{}, true
}
n := declared
+ b.declared = declared
switch {
case declared < 0:
n = min(unknownBody, int64(x.a.cfg.MaxBody))
diff --git a/gateway/gateway.go b/gateway/gateway.go
index 80324227..8985e8b8 100644
--- a/gateway/gateway.go
+++ b/gateway/gateway.go
@@ -77,6 +77,15 @@ type Call struct {
// it exactly as it named the request's, so the reply joins its request's session without
// waiting for the request's analysis or asking the store.
RequestBody []byte
+ // Release, when set, is called by the Handler once, when it will read nothing of Body or
+ // RequestBody again, which may be after Handle returns. An adapter that reads bodies into
+ // pooled buffers returns them here (ReadBody); nothing derived from a body refers to it.
+ Release func()
+ // BodyBytes, when set, is the memory Body and RequestBody keep until Release: the buffers
+ // they are slices of, each counted once (one pooled buffer may hold both, and more than
+ // either). A Handler still reading the bodies after Handle returns counts it against its
+ // body budget until then; unset, it counts the bodies' lengths.
+ BodyBytes int64
}
// Client is what the gateway knows about who made the call.
@@ -141,7 +150,9 @@ type Verdict struct {
//
// Handle may answer before analysis ends, when nothing analysis finds could change the verdict;
// the pipeline then keeps reading the Call. An adapter hands over a Call and everything it points
-// to (Body, Client.Headers, Request, Response) and never modifies or reuses them afterwards.
+// to (Body, Client.Headers, Request, Response) and never modifies or reuses them afterwards; it
+// reuses the Body's buffer only once the Handler calls Release, which it does exactly once for
+// every Call handed to Handle.
type Handler interface {
Admit(ctx context.Context, size int64) (release func(), refused Verdict, ok bool)
Handle(ctx context.Context, c *Call) Verdict
diff --git a/gateway/litellm/litellm.go b/gateway/litellm/litellm.go
index 06084306..25d22ce8 100644
--- a/gateway/litellm/litellm.go
+++ b/gateway/litellm/litellm.go
@@ -102,21 +102,39 @@ func (a *adapter) guardrail(w http.ResponseWriter, r *http.Request, h gateway.Ha
return
}
defer release()
- body, err := gateway.ReadBody(r, maxBody)
+ body, free, err := gateway.ReadBody(r, maxBody)
if err != nil {
http.Error(w, "read body: "+err.Error(), http.StatusBadRequest)
return
}
+ // The pipeline returns the body's buffer once it has read the call (Call.Release); a payload
+ // that never reaches it is returned here, after anything that may still format part of it.
+ handed := false
+ defer func() {
+ if !handed {
+ free()
+ }
+ }()
var req request
if err := decodeRequest(body, &req); err != nil {
http.Error(w, "decode body: "+err.Error(), http.StatusBadRequest)
return
}
- c, err := a.call(req)
+ c, err := a.call(req, body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
+ // A request built over its payload keeps the payload until the pipeline has read it. Any other
+ // body (a reply, a texts-only request, one the payload had no room for) is a copy and refers
+ // to none of the payload, which goes back to the pool at once.
+ if len(body) > 0 && len(c.Body) > 0 && &c.Body[0] == &body[0] {
+ c.Release, c.BodyBytes = free, int64(cap(body))
+ } else {
+ free()
+ c.BodyBytes = int64(cap(c.Body) + cap(c.RequestBody))
+ }
+ handed = true
writeVerdict(w, h.Handle(r.Context(), c))
}
@@ -166,7 +184,9 @@ func writeVerdict(w http.ResponseWriter, v gateway.Verdict) {
_ = jsonv1.NewEncoder(w).Encode(resp)
}
-func (a *adapter) call(req request) (*gateway.Call, error) {
+// call builds the call from the decoded payload; a request's body is built over the payload's
+// buffer (requestBody), so nothing may read req's raw members, or the payload, afterwards.
+func (a *adapter) call(req request, payload []byte) (*gateway.Call, error) {
rd := req.RequestData
c := &gateway.Call{
Gateway: a.cfg.Name,
@@ -194,7 +214,7 @@ func (a *adapter) call(req request) (*gateway.Call, error) {
switch req.InputType {
case "request":
c.Phase = gateway.PhaseRequest
- c.Body, err = requestBody(req)
+ c.Body, err = requestBody(req, payload)
case "response":
c.Phase = gateway.PhaseResponse
c.Body, err = responseBody(req)
@@ -203,7 +223,7 @@ func (a *adapter) call(req request) (*gateway.Call, error) {
// the request's messages hands them on only for a reply without a trace id, rather than
// copying the whole conversation into a body nothing reads.
if err == nil && req.TraceID == "" && nullable(req.StructuredMessages) != nil {
- c.RequestBody, err = requestBody(req)
+ c.RequestBody, err = requestBody(req, nil)
}
default:
return nil, errors.New("unknown input_type " + req.InputType)
@@ -216,8 +236,18 @@ func (a *adapter) call(req request) (*gateway.Call, error) {
// the codec validates the body it decodes, and re-encoding them would only scan and copy a long
// session's history once more. A payload without structured messages (a texts-only guardrail
// call) becomes user turns.
-func requestBody(req request) ([]byte, error) {
+//
+// payload, when not nil, is the buffer req's members were read from, which nothing reads once the
+// request is built: the request is built over it (inPlace) rather than copied into a second buffer
+// the size of the conversation.
+func requestBody(req request, payload []byte) ([]byte, error) {
msgs := nullable(req.StructuredMessages)
+ tools := nullable(req.Tools)
+ if msgs != nil && payload != nil {
+ if b, ok := inPlace(payload, req.Model, msgs, tools); ok {
+ return b, nil
+ }
+ }
if msgs == nil {
texts, err := decodeTexts(req.Texts)
if err != nil {
@@ -234,7 +264,6 @@ func requestBody(req request) ([]byte, error) {
}
msgs = append(msgs, ']')
}
- tools := nullable(req.Tools)
b := make([]byte, 0, len(`{"model":"","messages":,"tools":}`)+len(req.Model)+len(msgs)+len(tools))
b = append(b, '{')
if req.Model != "" {
@@ -251,6 +280,73 @@ func requestBody(req request) ([]byte, error) {
return append(b, '}'), nil
}
+// inPlace builds requestBody's request over payload, the buffer msgs and tools (nil when absent)
+// are slices of: {"messages":…,"tools":…,"model":…}, with messages and tools in the order they
+// appear in payload. Each then starts no later in the result than it did in payload, where the
+// messages are named "structured_messages" and every member is separated from the one before at
+// least as widely, so moving them left in that order never overwrites one not yet moved; the model
+// is written last, from its decoded copy. Every position is checked before anything is written:
+// when one does not hold, or the result would not fit, it reports false with payload untouched.
+func inPlace(payload []byte, model string, msgs, tools []byte) ([]byte, bool) {
+ type member struct {
+ name string
+ value []byte
+ at int
+ }
+ var members [2]member
+ n := 0
+ for _, m := range []member{{`"messages":`, msgs, 0}, {`"tools":`, tools, 0}} {
+ if m.value == nil {
+ continue
+ }
+ at := cap(payload) - cap(m.value)
+ if at < 0 || at+len(m.value) > len(payload) || &payload[at] != &m.value[0] {
+ return nil, false
+ }
+ m.at = at
+ members[n] = m
+ n++
+ }
+ ms := members[:n]
+ if n == 2 && ms[1].at < ms[0].at {
+ ms[0], ms[1] = ms[1], ms[0]
+ }
+ var quoted []byte
+ if model != "" {
+ quoted, _ = jsontext.AppendQuote(nil, model)
+ }
+ end := 1
+ for i, m := range ms {
+ if i > 0 {
+ end++
+ }
+ if end += len(m.name); end > m.at {
+ return nil, false
+ }
+ end += len(m.value)
+ }
+ if quoted != nil {
+ end += len(`,"model":`) + len(quoted)
+ }
+ if end++; end > len(payload) {
+ return nil, false
+ }
+ w := copy(payload, "{")
+ for i, m := range ms {
+ if i > 0 {
+ w += copy(payload[w:], ",")
+ }
+ w += copy(payload[w:], m.name)
+ w += copy(payload[w:], payload[m.at:m.at+len(m.value)]) // copy moves overlapping bytes correctly
+ }
+ if quoted != nil {
+ w += copy(payload[w:], `,"model":`)
+ w += copy(payload[w:], quoted)
+ }
+ w += copy(payload[w:], "}")
+ return payload[:w], true
+}
+
// responseBody reassembles a Chat Completions reply: LiteLLM sends the reply's text and its tool
// calls.
func responseBody(req request) ([]byte, error) {
diff --git a/gateway/litellm/litellm_test.go b/gateway/litellm/litellm_test.go
index 96614a97..a72c3df0 100644
--- a/gateway/litellm/litellm_test.go
+++ b/gateway/litellm/litellm_test.go
@@ -65,6 +65,28 @@ func post(t *testing.T, h gateway.Handler, payload string) response {
return r
}
+// A payload goes back to the pool only once nothing reads it: a request built over its payload
+// keeps it until the handler releases the call, and a reply's copies keep nothing of it. Reusing
+// the pool with more calls must leave every call already handed over as it was.
+func TestPooledPayloadsAreNotReusedEarly(t *testing.T) {
+ reply := `{"input_type":"response","litellm_call_id":"c1","model":"m","texts":["ok"],"structured_messages":[{"role":"user","content":"fix it"}]}`
+ h := &fakeHandler{}
+ var want [][2][]byte
+ for i, payload := range []string{requestPayload, reply, requestPayload, reply} {
+ post(t, h, payload)
+ c := h.calls[i]
+ want = append(want, [2][]byte{bytes.Clone(c.Body), bytes.Clone(c.RequestBody)})
+ if c.Phase == gateway.PhaseRequest && c.Release == nil {
+ t.Errorf("call %d: a request built over its payload is not released by the handler", i)
+ }
+ }
+ for i, c := range h.calls {
+ if !bytes.Equal(c.Body, want[i][0]) || !bytes.Equal(c.RequestBody, want[i][1]) {
+ t.Errorf("call %d changed after later calls reused the pool:\n%s\n%s", i, c.Body, c.RequestBody)
+ }
+ }
+}
+
// A request payload as LiteLLM 1.106.6 sent it for an Anthropic /v1/messages call: the tool result
// arrives as a tool message and must decode as a result tied to its call.
const requestPayload = `{"input_type":"request","litellm_call_id":"c1","litellm_trace_id":"trace-1","model":"claude-mock",
diff --git a/gateway/litellm/payload_test.go b/gateway/litellm/payload_test.go
index de62bc51..a579f8dc 100644
--- a/gateway/litellm/payload_test.go
+++ b/gateway/litellm/payload_test.go
@@ -1,9 +1,13 @@
package litellm
import (
+ "bytes"
json "encoding/json/v2"
"reflect"
"testing"
+
+ "github.com/asymptote-labs/agent-beacon/gateway/llm"
+ "github.com/asymptote-labs/agent-beacon/gateway/llm/codec"
)
// decodeRequest must decode every valid payload as decoding it whole does: names in any case,
@@ -29,3 +33,63 @@ func TestDecodeRequestMatchesFullDecode(t *testing.T) {
}
}
}
+
+// A request body built over its payload must decode exactly as the one built in a buffer of its
+// own, whatever order, spelling and spacing the payload gives its members.
+func TestRequestBodyInPlaceDecodesAsCopied(t *testing.T) {
+ msgs := `[{"role":"system","content":"SYS"},{"role":"user","content":"hello"},{"role":"assistant","content":null,"tool_calls":[{"id":"tu1","type":"function","function":{"name":"Bash","arguments":"{\"command\":\"ls\"}"}}]},{"role":"tool","content":"a\nb","tool_call_id":"tu1"}]`
+ tools := `[{"type":"function","function":{"name":"Bash","description":"run","parameters":{"type":"object"}}}]`
+ for _, payload := range []string{
+ `{"input_type":"request","model":"gpt-4o","structured_messages":` + msgs + `,"texts":["SYS","hello"],"tools":` + tools + `}`,
+ `{"tools":` + tools + `,"structured_messages":` + msgs + `,"model":"gpt-4o","input_type":"request"}`,
+ `{"structured_messages":` + msgs + `,"tools":` + tools + `}`,
+ `{"structured_messages":` + msgs + `}`,
+ `{"Tools" : ` + tools + ` , "Structured_Messages" :` + msgs + `,"MODEL":"m"}`,
+ `{"structured\u005fmessages":` + msgs + `,"tool\u0073":` + tools + `,"model":"caf\u00e9 \"q\""}`,
+ `{"structured_messages":[1],"structured_messages":` + msgs + `,"tools":null,"model":"m"}`,
+ } {
+ var req request
+ if err := decodeRequest([]byte(payload), &req); err != nil {
+ t.Fatalf("%s: %v", payload, err)
+ }
+ copied, err := requestBody(req, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ buf := []byte(payload)
+ if err := decodeRequest(buf, &req); err != nil {
+ t.Fatal(err)
+ }
+ built, err := requestBody(req, buf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if &built[0] != &buf[0] {
+ t.Errorf("%s: body was not built in place", payload)
+ }
+ want, err := codec.DecodeRequest(llm.OpenAIChat, copied)
+ if err != nil {
+ t.Fatalf("%s: %s: %v", payload, copied, err)
+ }
+ got, err := codec.DecodeRequest(llm.OpenAIChat, built)
+ if err != nil {
+ t.Fatalf("%s: %s: %v", payload, built, err)
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("%s:\n got %s\n %+v\nwant %s\n %+v", payload, built, got, copied, want)
+ }
+ }
+}
+
+// A member that starts too early to be moved left leaves the payload as it was.
+func TestInPlaceRefusesWithoutRoom(t *testing.T) {
+ payload := []byte(`{"x":[1],"tools":[2]}`)
+ orig := bytes.Clone(payload)
+ msgs := payload[5:8] // "messages": needs 11 bytes before it
+ if _, ok := inPlace(payload, "m", msgs, payload[17:20]); ok {
+ t.Fatal("built a body whose messages start too early")
+ }
+ if !bytes.Equal(payload, orig) {
+ t.Fatalf("payload modified: %s", payload)
+ }
+}
diff --git a/gateway/pipeline/analyze.go b/gateway/pipeline/analyze.go
index 5ea1b72c..1d4ad28f 100644
--- a/gateway/pipeline/analyze.go
+++ b/gateway/pipeline/analyze.go
@@ -14,7 +14,9 @@ import (
// Analyzer inspects a turn and reports findings and records. Analyze runs concurrently with
// other calls, including calls of the same session: it must be fast and keep anything that
// outlives the call in Turn.Store, not in its own memory. Analyzers run in order, one at a time
-// per call; the events analyzer runs first and leaves the call's events on the Turn.
+// per call; the events analyzer runs first and leaves the call's events on the Turn. Neither the
+// Turn nor its Call (whose Body buffer is reused once the call is analyzed) may be kept past
+// Analyze; a Policy's and an Observer's arguments likewise only for the call.
type Analyzer interface {
Name() string
Analyze(ctx context.Context, t *Turn) (Report, error)
diff --git a/gateway/pipeline/pipeline.go b/gateway/pipeline/pipeline.go
index b4db35b2..73f76d28 100644
--- a/gateway/pipeline/pipeline.go
+++ b/gateway/pipeline/pipeline.go
@@ -190,6 +190,7 @@ func (p *Pipeline) Stats() Stats {
// Handle implements gateway.Handler.
func (p *Pipeline) Handle(ctx context.Context, c *gateway.Call) gateway.Verdict {
if !p.analyze(ctx) {
+ released(c)
return p.overloaded("analysis slots")
}
if c.Time.IsZero() {
@@ -197,23 +198,37 @@ func (p *Pipeline) Handle(ctx context.Context, c *gateway.Call) gateway.Verdict
}
if !p.answerFirst {
defer p.release()
+ defer released(c)
return p.run(ctx, c)
}
// The adapter releases its reservation for the body when Handle returns; the analysis
// still reading it holds the bytes again until it ends, with the request body a reply
// carries. The two overlap, so the budget is briefly counted twice rather than ever not at
- // all.
- held := p.bodies.hold(int64(len(c.Body) + len(c.RequestBody)))
+ // all. What is held is what the bodies keep in memory, as the adapter states it: a pooled
+ // buffer may hold both bodies, and more than either.
+ n := c.BodyBytes
+ if n <= 0 {
+ n = int64(len(c.Body) + len(c.RequestBody))
+ }
+ held := p.bodies.hold(n)
p.pending.Add(1)
go func() {
defer p.pending.Done()
defer p.release()
defer p.bodies.release(held)
+ defer released(c)
p.run(context.WithoutCancel(ctx), c)
}()
return allow
}
+// released tells the adapter that nothing reads the call's bodies any more (Call.Release).
+func released(c *gateway.Call) {
+ if c.Release != nil {
+ c.Release()
+ }
+}
+
// run analyzes one call and returns its verdict.
func (p *Pipeline) run(ctx context.Context, c *gateway.Call) gateway.Verdict {
start := time.Now()
diff --git a/gateway/pipeline/pipeline_test.go b/gateway/pipeline/pipeline_test.go
index efc2a141..7cedbaf9 100644
--- a/gateway/pipeline/pipeline_test.go
+++ b/gateway/pipeline/pipeline_test.go
@@ -582,6 +582,24 @@ func TestAnswersFirst(t *testing.T) {
}
}
+// An analysis still reading its call after Handle returns holds what the adapter says the bodies
+// keep in memory, once, not their lengths: a pooled payload holding both bodies, larger than either.
+func TestAnswerFirstHoldsBodyBytes(t *testing.T) {
+ g := &gate{entered: make(chan struct{}), release: make(chan struct{}), done: make(chan struct{}, 1)}
+ p := New(Config{Analyzers: []Analyzer{g}})
+ defer p.Close()
+ payload := make([]byte, 4096)
+ n := copy(payload, `{"messages":[{"role":"user","content":"hi"}]}`)
+ c := &gateway.Call{Gateway: "g", ID: "c", Phase: gateway.PhaseResponse, Protocol: llm.OpenAIChat,
+ Body: payload[:n], RequestBody: payload[:n], BodyBytes: int64(cap(payload))}
+ p.Handle(context.Background(), c)
+ <-g.entered
+ if s := p.Stats(); s.BodyBytes != int64(cap(payload)) {
+ t.Errorf("while analysis runs: body_bytes %d, want the payload's %d", s.BodyBytes, cap(payload))
+ }
+ close(g.release)
+}
+
// observer records what it was shown and adds a record of its own.
type observer struct{ seen []Observation }
diff --git a/gateway/pipeline/release_test.go b/gateway/pipeline/release_test.go
new file mode 100644
index 00000000..744c5c04
--- /dev/null
+++ b/gateway/pipeline/release_test.go
@@ -0,0 +1,144 @@
+package pipeline_test
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/gateway"
+ "github.com/asymptote-labs/agent-beacon/gateway/events"
+ "github.com/asymptote-labs/agent-beacon/gateway/llm"
+ "github.com/asymptote-labs/agent-beacon/gateway/pipeline"
+)
+
+const (
+ releaseRequest = `{"model":"claude-x","system":"You are terse.","tools":[{"name":"mcp__notes__get","description":"read a note","input_schema":{"type":"object"}}],` +
+ `"messages":[{"role":"user","content":"look at the build"},` +
+ `{"role":"assistant","content":[{"type":"tool_use","id":"tu1","name":"Bash","input":{"command":"make test"}}]},` +
+ `{"role":"user","content":[{"type":"tool_result","tool_use_id":"tu1","content":"ok 12 tests"},{"type":"text","text":"now read the note"}]}]}`
+ releaseResponse = `{"id":"msg_1","type":"message","role":"assistant","model":"claude-x-2026","content":[{"type":"text","text":"Reading it."},` +
+ `{"type":"tool_use","id":"tu2","name":"mcp__notes__get","input":{"id":"n7"}}],"stop_reason":"tool_use","usage":{"input_tokens":120,"output_tokens":9}}`
+)
+
+type collect struct {
+ mu sync.Mutex
+ got [][]byte
+}
+
+// Write marshals each record now, as a sink does, which is after the call released its body.
+func (s *collect) Write(_ context.Context, b []pipeline.Record) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ for _, r := range b {
+ line, err := json.Marshal(r.Value)
+ if err != nil {
+ return err
+ }
+ s.got = append(s.got, line)
+ }
+ return nil
+}
+
+func (*collect) Close() error { return nil }
+
+type inline struct{}
+
+func (inline) Name() string { return "inline" }
+func (inline) Inline() bool { return true }
+func (inline) Analyze(context.Context, *pipeline.Turn) (pipeline.Report, error) {
+ return pipeline.Report{}, nil
+}
+
+// An adapter reuses a body's buffer once the pipeline releases it, so nothing the pipeline
+// records may refer to the body: overwriting every buffer at release leaves each record as it
+// was. Release comes exactly once per call, whether the pipeline answers first or after analysis.
+func TestReleasedBodiesAreNotRead(t *testing.T) {
+ at := time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC)
+ for _, mode := range []string{"inline", "answer-first"} {
+ run := func(poison bool) ([][]byte, int64) {
+ ev, err := events.New(events.Config{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ analyzers := []pipeline.Analyzer{ev}
+ if mode == "inline" {
+ analyzers = append(analyzers, inline{})
+ }
+ sink := &collect{}
+ p := pipeline.New(pipeline.Config{Analyzers: analyzers, Routes: []pipeline.Route{{Name: "all", Sink: sink}}})
+ var releases atomic.Int64
+ // Each call is handed over once the one before is released, so that, answered first or
+ // not, calls are analyzed in order and record the same sequence numbers in both runs.
+ done := make(chan struct{}, 1)
+ for _, phase := range []gateway.Phase{gateway.PhaseRequest, gateway.PhaseResponse} {
+ c := &gateway.Call{
+ Gateway: "g", ID: "c1", Phase: phase, Enforce: true, Time: at, Protocol: llm.AnthropicMessages,
+ Client: gateway.Client{Headers: map[string]string{"x-claude-code-session-id": "s1"}},
+ Body: []byte(releaseRequest),
+ }
+ if phase == gateway.PhaseResponse {
+ c.Body, c.RequestBody = []byte(releaseResponse), []byte(releaseRequest)
+ }
+ c.Release = func() {
+ releases.Add(1)
+ if poison {
+ for _, b := range [][]byte{c.Body, c.RequestBody} {
+ copy(b, bytes.Repeat([]byte{0xFF}, len(b)))
+ }
+ }
+ done <- struct{}{}
+ }
+ p.Handle(context.Background(), c)
+ <-done
+ }
+ p.Close()
+ return sink.got, releases.Load()
+ }
+ clean, _ := run(false)
+ poisoned, releases := run(true)
+ if releases != 2 {
+ t.Errorf("%s: %d releases for 2 calls", mode, releases)
+ }
+ if len(clean) == 0 {
+ t.Fatalf("%s: nothing recorded", mode)
+ }
+ if len(poisoned) != len(clean) {
+ t.Fatalf("%s: %d records after poisoning, %d without", mode, len(poisoned), len(clean))
+ }
+ for i := range clean {
+ if !bytes.Equal(poisoned[i], clean[i]) {
+ t.Errorf("%s: record %d refers to a released body:\n got %s\nwant %s", mode, i, poisoned[i], clean[i])
+ }
+ }
+ }
+}
+
+// A call refused for want of an analysis slot is released too.
+func TestRefusedCallIsReleased(t *testing.T) {
+ block := make(chan struct{})
+ p := pipeline.New(pipeline.Config{Analyzers: []pipeline.Analyzer{gateAnalyzer{block}}, MaxInFlight: 1, QueueWait: 10 * time.Millisecond})
+ defer p.Close()
+ defer close(block)
+ var releases atomic.Int64
+ call := func() *gateway.Call {
+ return &gateway.Call{Gateway: "g", ID: "c", Phase: gateway.PhaseRequest, Protocol: llm.AnthropicMessages,
+ Body: []byte(releaseRequest), Release: func() { releases.Add(1) }}
+ }
+ p.Handle(context.Background(), call()) // answered first; holds the only slot until block closes
+ p.Handle(context.Background(), call()) // refused
+ if got := releases.Load(); got != 1 {
+ t.Errorf("%d releases while one call is still analyzed and one was refused, want 1", got)
+ }
+}
+
+type gateAnalyzer struct{ block chan struct{} }
+
+func (gateAnalyzer) Name() string { return "gate" }
+func (g gateAnalyzer) Analyze(context.Context, *pipeline.Turn) (pipeline.Report, error) {
+ <-g.block
+ return pipeline.Report{}, nil
+}
diff --git a/gateway/portkey/portkey.go b/gateway/portkey/portkey.go
index f1340ef4..c6f99f27 100644
--- a/gateway/portkey/portkey.go
+++ b/gateway/portkey/portkey.go
@@ -149,11 +149,20 @@ func (a *adapter) handler(h gateway.Handler) http.Handler {
return
}
defer release()
- body, err := gateway.ReadBody(r, maxBody)
+ body, free, err := gateway.ReadBody(r, maxBody)
if err != nil {
http.Error(w, "read body: "+err.Error(), http.StatusBadRequest)
return
}
+ // The pipeline returns the body's buffer once it has read the call (Call.Release); a
+ // payload that never reaches it is returned here, after anything that may still format
+ // part of it.
+ handed := false
+ defer func() {
+ if !handed {
+ free()
+ }
+ }()
var env envelope
if err := decodeEnvelope(body, &env); err != nil {
http.Error(w, "bad webhook payload: "+err.Error(), http.StatusBadRequest)
@@ -164,6 +173,8 @@ func (a *adapter) handler(h gateway.Handler) http.Handler {
writeReply(w, reply{Verdict: true})
return
}
+ // Body and RequestBody are both slices of the one payload buffer.
+ c.Release, c.BodyBytes, handed = free, int64(cap(body)), true
writeVerdict(w, h.Handle(r.Context(), c))
})
return mux
diff --git a/gateway/serve.go b/gateway/serve.go
index 46ef394d..b1fe45f7 100644
--- a/gateway/serve.go
+++ b/gateway/serve.go
@@ -6,8 +6,11 @@ import (
"fmt"
"io"
"log/slog"
+ "math/bits"
"net"
"net/http"
+ "sync"
+ "sync/atomic"
"time"
)
@@ -71,28 +74,79 @@ func DiscardBody(r *http.Request, limit int64) {
}
// BodySize is what an HTTP adapter reserves at admission for a body it reads up to limit bytes of:
-// its declared length, or limit when the length is unknown (chunked) or over the limit.
+// the buffer ReadBody reads a body of that declared length into, which a pooled buffer rounds up,
+// or limit when the length is unknown (chunked) or over the limit.
func BodySize(r *http.Request, limit int64) int64 {
if r.ContentLength < 0 || r.ContentLength > limit {
return limit
}
+ if class, pooled := bodyClass(r.ContentLength); pooled {
+ return 1 << class
+ }
return r.ContentLength
}
// ReadBody reads a request body of up to limit bytes into one buffer of its declared length, when
// it declares one: io.ReadAll grows by doubling, which copied a body of a megabyte several times
// over. A body longer than declared, or than limit, is an error.
-func ReadBody(r *http.Request, limit int64) ([]byte, error) {
+//
+// A body of declared length is read into a pooled buffer: allocating one per call was most of
+// what a callout adapter allocated, and the collections it cost. free returns the buffer to the
+// pool once nothing reads the body or anything sliced from it; an adapter that hands the body to
+// Handle passes free on as Call.Release, and otherwise calls it itself. Calls after the first do
+// nothing. On error the buffer is already returned and free is nil.
+func ReadBody(r *http.Request, limit int64) (body []byte, free func(), err error) {
if n := r.ContentLength; n >= 0 && n <= limit {
- buf := make([]byte, n)
+ buf, free := bodyBuffer(n)
if _, err := io.ReadFull(r.Body, buf); err != nil {
- return nil, err
+ free()
+ return nil, nil, err
}
- return buf, nil
+ return buf, free, nil
}
buf, err := io.ReadAll(io.LimitReader(r.Body, limit+1))
if err == nil && int64(len(buf)) > limit {
err = fmt.Errorf("body exceeds %d bytes", limit)
}
- return buf, err
+ if err != nil {
+ return nil, nil, err
+ }
+ return buf, func() {}, nil
+}
+
+// Body buffers are pooled in power-of-two size classes from 4 KiB to 16 MiB; a larger body is
+// allocated for its call alone, as few are that large and holding them would hold the memory.
+const (
+ minBodyClass = 12
+ maxBodyClass = 24
+)
+
+var bodyPools [maxBodyClass - minBodyClass + 1]sync.Pool
+
+// bodyClass is the size class of a pooled buffer for n bytes, and false when such a buffer is not
+// pooled.
+func bodyClass(n int64) (int, bool) {
+ class := max(bits.Len64(uint64(n-1)), minBodyClass)
+ return class, n > 0 && class <= maxBodyClass
+}
+
+// bodyBuffer returns a buffer of length n and the func that returns it to its pool, at most once
+// however often it is called: a buffer pooled twice would be handed to two calls at once.
+func bodyBuffer(n int64) ([]byte, func()) {
+ class, pooled := bodyClass(n)
+ if !pooled {
+ return make([]byte, n), func() {}
+ }
+ pool := &bodyPools[class-minBodyClass]
+ buf, _ := pool.Get().(*[]byte)
+ if buf == nil {
+ b := make([]byte, 1<<class)
+ buf = &b
+ }
+ var freed atomic.Bool
+ return (*buf)[:n], func() {
+ if !freed.Swap(true) {
+ pool.Put(buf)
+ }
+ }
}
diff --git a/gateway/serve_test.go b/gateway/serve_test.go
new file mode 100644
index 00000000..3108d0f0
--- /dev/null
+++ b/gateway/serve_test.go
@@ -0,0 +1,26 @@
+package gateway
+
+import (
+ "bytes"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+// Admission reserves what ReadBody then holds: the buffer a body is read into, which pooling rounds
+// up, not just the body's length; otherwise a full budget holds up to twice its bytes.
+func TestBodySizeIsTheBufferRead(t *testing.T) {
+ const limit = 64 << 20
+ for _, n := range []int{0, 1, 4096, 4097, 300_000, 1 << 24, 1<<24 + 1} {
+ r := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(make([]byte, n)))
+ reserved := BodySize(r, limit)
+ body, free, err := ReadBody(r, limit)
+ if err != nil {
+ t.Fatalf("%d bytes: %v", n, err)
+ }
+ if len(body) != n || int64(cap(body)) != reserved {
+ t.Errorf("%d bytes: reserved %d, read %d into a buffer of %d", n, reserved, len(body), cap(body))
+ }
+ free()
+ }
+}