gateway: a kept previous response holds its input, not the body it came in

previousResponse kept each turn's input items as views into the request
body, so every response kept for previous_response_id held its whole
body: tools, instructions and anything else the client sent. own counted
only the items, so prevCap's 256 MB bounded far less than was held. The
input is now copied out (ownItems, as the Codex socket does since
ec0a11d47) and own counts the bytes copied.

Run:
- Real zcode account (plugin), sandbox HOME with no network to anything
  else: 30 HTTP /v1/responses turns, store true, chained by
  previous_response_id, ~600 KB per body. Live heap before -> after:
  old (ec0a11d47) 23.9 -> 101.1 MB; this change 24.0 -> 42.9 MB, and 30
  more turns 41.6 -> 43.9 MB.
- mote: go test -run 'Prev|Previous|KeptTurn|HeldTurn|Socket'
  ./internal/gateway ok. TestKeptTurnOwnsItsInput is red with the copy
  taken out by hand ("kept after the body was written over").
- GOOS=linux and GOOS=windows go vet ./internal/gateway ok; gofmt clean.

Not run: the full suite before the push (the gateway package runs right
after it).
This commit is contained in:
yetone
2026-11-01 12:58:45 +08:00
parent ef8bd98fba
commit ed5872d186
2 changed files with 44 additions and 9 deletions
+13 -9
View File
@@ -258,13 +258,17 @@ func previousResponse(w http.ResponseWriter, r *http.Request, from provider.Prot
if json.Unmarshal(q["store"], &store) == nil && !store {
return w, r, body, nothing // the client asked that nothing be kept
}
// what this turn adds: its whole body, which its items hold
own := len(body)
// what this turn adds: its input, copied out of the body. A view held
// the whole body, tools and instructions with it, on every turn kept,
// while own counted only the items, so the cap bounded far less than
// was held.
kept := ownItems(fresh)
if ask.known {
own = 0
for _, it := range fresh {
own += len(it)
}
kept = append(prior[:len(prior):len(prior)], kept...)
}
own := 0
for _, it := range fresh {
own += len(it)
}
if ask.id == "" {
// the answer note is wanted for a request naming none too
@@ -289,7 +293,7 @@ func previousResponse(w http.ResponseWriter, r *http.Request, from provider.Prot
for _, it := range output {
own += len(it)
}
t := &prevTurn{key: prevKey{scope, id}, items: append(input[:len(input):len(input)], output...), own: own}
t := &prevTurn{key: prevKey{scope, id}, items: append(kept, output...), own: own}
ask.mu.Lock()
if ask.answered != "" {
t.upstreamID, t.route = id, ask.answered
@@ -301,8 +305,8 @@ func previousResponse(w http.ResponseWriter, r *http.Request, from provider.Prot
// prevInput is a Responses input as items: a string is one user message.
// fresh is nil for an input that is neither. The items share the body's
// bytes, which nothing writes once read: a turn kept holds its body, not
// a copy of it.
// bytes, which nothing writes once read; what is kept past the request
// copies them (ownItems).
func prevInput(raw json.RawMessage) (all, fresh []json.RawMessage) {
raw = bytes.TrimSpace(raw)
if len(raw) == 0 {
+31
View File
@@ -261,3 +261,34 @@ func TestPrevStoreBounded(t *testing.T) {
t.Fatal("kept past its time")
}
}
// TestKeptTurnOwnsItsInput: a kept response holds its input, not the body
// it was read from with the request's tools and instructions, and counts
// what it holds.
func TestKeptTurnOwnsItsInput(t *testing.T) {
old := prevResponses
prevResponses = newPrevStore(prevCap, prevTTL)
t.Cleanup(func() { prevResponses = old })
body := []byte(`{"model":"m","instructions":"` + strings.Repeat("rules ", 1000) + `","input":[{"type":"message","role":"user","content":"hi"}]}`)
r := httptest.NewRequest("POST", "/v1/responses", nil)
r.RemoteAddr = "127.0.0.1:5555"
w, r, _, done := previousResponse(httptest.NewRecorder(), r, provider.Responses, body)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
io.WriteString(w, `{"id":"resp_1","object":"response","status":"completed","output":[{"type":"message","role":"assistant","content":"ok"}]}`)
done()
for i := range body {
body[i] = 'x'
}
kept, ok := prevResponses.get(prevKey{prevScope(r), "resp_1"})
if !ok {
t.Fatal("nothing kept")
}
want := `[{"type":"message","role":"user","content":"hi"},{"type":"message","role":"assistant","content":"ok"}]`
if got, _ := json.Marshal(kept.items); string(got) != want {
t.Fatalf("kept after the body was written over: %s", got)
}
if n := len(want) - len("[,]"); kept.own != n {
t.Fatalf("own %d, want the %d bytes kept", kept.own, n)
}
}