Files
magpie/internal/gateway/prev_response_test.go
T
yetone ba3a7384fb gateway: a Responses request may name the response it follows (previous_response_id, kevinzhow on X)
kevinzhow on X: magpie didn't support previous_response_id on
/v1/responses, so every turn carried the whole conversation, images
included, and each turn was slow.

Before: magpie kept no responses. previous_response_id went on as
sent, so a provider that never made that id (or a route that translates
to Chat or Messages) had nothing but the new input to give the model.

After (prev_response.go, run in serveAgent before anything reads the
body):
- Each Responses reply passed with 200 (not failed/cancelled, not cut at
  64 MB) is kept by its id with input + output, in memory, LRU to 256 MB
  of own bytes, 6h TTL. store:false keeps nothing.
- Kept per caller (prevScope): gateway key, remote magpie, keyless remote
  address. Another caller naming the id is told it isn't there.
- A kept id expands the request to the whole conversation, so routing,
  translation and masking see what they would have seen had the client
  sent it all. Masking runs on each request as it goes (deterministic
  placeholders), so a stored secret is masked the same on every turn;
  TestPreviousResponseMasked.
- An unknown id gets OpenAI's 400 previous_response_not_found on a route
  that translates (and on Claude/Codex accounts), before anything is sent.
  A Responses relay is sent the id as it came.
- Where the provider keeps responses itself (prevKeeps: API key, no
  plugin; api.openai.com, Azure, or Ark /api/v3 pay-as-you-go) and it
  answered the previous turn on the same key, with store not off, only
  the new input goes with the provider's own id (prevDelta). A provider
  that says it doesn't know the id (prevRefused) is sent the whole
  conversation at once.

Codex: its HTTP ResponsesApiRequest has no previous_response_id; only the
websocket's ResponseCreateWsRequest has it (openai/codex 9def09a,
codex-rs/codex-api/src/common.rs:341, client.rs:2284). Over HTTP it sends
store:false with the whole input, so nothing it sends or keeps changes.
No prompt is touched.

Ark checked with a real pay-as-you-go key (10-29): store:true then
previous_response_id returned the stored word; an unknown id answers 400
InvalidParameter.PreviousResponseNotFound (param previous_response_id),
which prevRefused matches.

Tests (prev_response_test.go): GivenWholeToChat (3 turns), NotFound
(unknown, other key, no key, store:false; upstream not called),
UnknownPreviousResponseRelayedAsSent, KeptUpstreamSentNewInputOnly
(200 KB image; delta < 2000 bytes; refusal retried whole), Masked,
PrevStoreBounded.

Broken by hand, each red, then restored:
- previousResponse a no-op: GivenWholeToChat, NotFound, KeptUpstream,
  Masked red.
- prevDelta off: KeptUpstream red (200355 bytes sent, no prev id).
- prevRefused always false: KeptUpstream red at the retry turn (400
  relayed).

Timings on mote (BenchmarkImageRequest / BenchmarkPreviousResponseTurn,
8 images, 20.18 MB conversation):
- whole Responses -> Responses: 277 ms, 145.6 MB/op before; 263 ms,
  145.6 MB/op after (a first version that json.Unmarshal'd the input
  cost 364 ms and +20 MB; it now reads items over the body's bytes).
- whole Responses -> Chat: 273 ms before, 224 ms after.
- previous_response_id to a provider that keeps responses: client sends
  82 B, upstream gets 122 B (was 20.18 MB each way), 309 ms locally.
- previous_response_id to Chat: client sends 83 B, upstream gets the
  whole 20.18 MB, 295 ms.

Run at this head on mote: gofmt -l clean; go vet ./internal/gateway for
darwin, linux, windows ok; go test -count=1 -timeout 45m
./internal/gateway ./internal/redact: gateway ok (464.4s), redact ok (1.8s).

Not tried: a real OpenAI or Azure key (Ark's real key only); Ark's
Coding Plan Responses path (not in prevKeeps). The store is in memory,
so ids are lost on restart (a translated route then answers 400, a relay
passes the id on). A kept-id request is still read and masked whole on
this computer before the delta is cut (~300 ms local for 20 MB).
Doc: docs/subsystems/gateway-routing.md, "A Responses request that names
the response it follows".
2026-10-29 21:25:33 +08:00

264 lines
11 KiB
Go

package gateway
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// prevEnv is a sandbox with one provider, fresh responses kept, and an
// upstream that records every request and answers with answer.
type prevUp struct {
mu sync.Mutex
got [][]byte
srv *httptest.Server
next func(n int, body []byte) (int, string, string) // status, content type, body
}
func (u *prevUp) last() map[string]any {
u.mu.Lock()
defer u.mu.Unlock()
var q map[string]any
json.Unmarshal(u.got[len(u.got)-1], &q)
return q
}
func (u *prevUp) calls() int {
u.mu.Lock()
defer u.mu.Unlock()
return len(u.got)
}
func newPrevUp(t *testing.T, next func(n int, body []byte) (int, string, string)) *prevUp {
u := &prevUp{next: next}
u.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
u.mu.Lock()
u.got = append(u.got, b)
n := len(u.got)
u.mu.Unlock()
code, ct, reply := u.next(n, b)
w.Header().Set("Content-Type", ct)
w.WriteHeader(code)
io.WriteString(w, reply)
}))
t.Cleanup(u.srv.Close)
return u
}
func prevSandbox(t *testing.T, p provider.Provider) *Server {
t.Helper()
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
old := prevResponses
prevResponses = newPrevStore(prevCap, prevTTL)
t.Cleanup(func() { prevResponses = old })
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
return New()
}
// chatSSEReply is a Chat stream that says text.
func chatSSEReply(text string) string {
c, _ := json.Marshal(text)
return "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{\"content\":" + string(c) + "},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":7,\"completion_tokens\":1}}\n\ndata: [DONE]\n\n"
}
func askResponses(t *testing.T, s *Server, keyID string, body string) *httptest.ResponseRecorder {
t.Helper()
ctx := context.Background()
if keyID != "" {
ctx = access.WithIdentity(ctx, access.Identity{KeyID: keyID, KeyName: keyID})
}
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)).WithContext(ctx)
req.RemoteAddr = "127.0.0.1:5555"
s.Handler().ServeHTTP(rec, req)
return rec
}
func responseID(t *testing.T, rec *httptest.ResponseRecorder) string {
t.Helper()
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
var r struct {
ID string `json:"id"`
}
if json.Unmarshal(rec.Body.Bytes(), &r) != nil || r.ID == "" {
t.Fatalf("no id in %s", rec.Body.String())
}
return r.ID
}
// A client that sends only the new input after previous_response_id
// (kevinzhow on X) has the conversation given back whole, here to a
// provider on Chat: the model sees the earlier turn and its own answer.
func TestPreviousResponseGivenWholeToChat(t *testing.T) {
up := newPrevUp(t, func(n int, _ []byte) (int, string, string) {
return 200, "text/event-stream", chatSSEReply(fmt.Sprintf("answer %d", n))
})
s := prevSandbox(t, provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Chat: up.srv.URL + "/v1"})
id := responseID(t, askResponses(t, s, "", `{"model":"fake/m1","instructions":"be brief","input":"my name is Ada"}`))
id2 := responseID(t, askResponses(t, s, "", `{"model":"fake/m1","previous_response_id":"`+id+`","input":[{"role":"user","content":"what is my name?"}]}`))
sent, _ := json.Marshal(up.last()["messages"])
for _, want := range []string{"my name is Ada", "answer 1", "what is my name?"} {
if !strings.Contains(string(sent), want) {
t.Fatalf("turn 2 went without %q: %s", want, sent)
}
}
// instructions go with the request that gives them, as OpenAI does
if strings.Contains(string(sent), "be brief") {
t.Fatalf("turn 1's instructions carried: %s", sent)
}
// and a third turn after the second has all of it
responseID(t, askResponses(t, s, "", `{"model":"fake/m1","previous_response_id":"`+id2+`","input":"and again?"}`))
sent, _ = json.Marshal(up.last()["messages"])
for _, want := range []string{"my name is Ada", "answer 1", "what is my name?", "answer 2", "and again?"} {
if !strings.Contains(string(sent), want) {
t.Fatalf("turn 3 went without %q: %s", want, sent)
}
}
}
// An id magpie doesn't hold, to a provider it would be translated for,
// is OpenAI's own 400; so is one another gateway key's response, and one
// the client asked not be kept (store false).
func TestPreviousResponseNotFound(t *testing.T) {
up := newPrevUp(t, func(int, []byte) (int, string, string) {
return 200, "text/event-stream", chatSSEReply("ok")
})
s := prevSandbox(t, provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Chat: up.srv.URL + "/v1"})
notFound := func(rec *httptest.ResponseRecorder, id string) {
t.Helper()
var e struct {
Error struct{ Message, Type, Param, Code string }
}
json.Unmarshal(rec.Body.Bytes(), &e)
if rec.Code != 400 || e.Error.Code != "previous_response_not_found" || e.Error.Param != "previous_response_id" || e.Error.Type != "invalid_request_error" || !strings.Contains(e.Error.Message, id) {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
}
notFound(askResponses(t, s, "", `{"model":"fake/m1","previous_response_id":"resp_nowhere","input":"hi"}`), "resp_nowhere")
if up.calls() != 0 {
t.Fatalf("sent upstream without its history: %d", up.calls())
}
a := responseID(t, askResponses(t, s, "alice", `{"model":"fake/m1","input":"secret plan"}`))
notFound(askResponses(t, s, "bob", `{"model":"fake/m1","previous_response_id":"`+a+`","input":"what was it?"}`), a)
notFound(askResponses(t, s, "", `{"model":"fake/m1","previous_response_id":"`+a+`","input":"what was it?"}`), a)
responseID(t, askResponses(t, s, "alice", `{"model":"fake/m1","previous_response_id":"`+a+`","input":"what was it?"}`))
off := responseID(t, askResponses(t, s, "", `{"model":"fake/m1","store":false,"input":"forget me"}`))
notFound(askResponses(t, s, "", `{"model":"fake/m1","previous_response_id":"`+off+`","input":"again"}`), off)
}
// An id magpie doesn't hold, to a provider on Responses the request is
// relayed to, goes as it came: a response the provider made before
// magpie restarted is still its own to find.
func TestUnknownPreviousResponseRelayedAsSent(t *testing.T) {
up := newPrevUp(t, func(int, []byte) (int, string, string) {
return 200, "application/json", `{"id":"resp_up","object":"response","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":3,"output_tokens":1}}`
})
s := prevSandbox(t, provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Responses: up.srv.URL + "/v1"})
responseID(t, askResponses(t, s, "", `{"model":"fake/m1","previous_response_id":"resp_before","input":"hi"}`))
if got := up.last()["previous_response_id"]; got != "resp_before" {
t.Fatalf("sent %v", got)
}
}
// A provider that keeps responses (OpenAI's, Ark's) and answered the one
// named is sent the new input alone after its own id: the images it holds
// aren't sent again. One that no longer holds it is sent the whole.
func TestPreviousResponseKeptUpstreamSentNewInputOnly(t *testing.T) {
defer func(old func(provider.Provider) bool) { prevKeptBy = old }(prevKeptBy)
prevKeptBy = func(p provider.Provider) bool { return p.ID == "fake" }
var forget atomic.Bool
up := newPrevUp(t, func(n int, body []byte) (int, string, string) {
if forget.Load() && strings.Contains(string(body), "previous_response_id") {
return 400, "application/json", `{"error":{"message":"Previous response with id 'resp_up1' not found.","type":"invalid_request_error","param":"previous_response_id","code":"previous_response_not_found"}}`
}
return 200, "application/json", fmt.Sprintf(`{"id":"resp_up%d","object":"response","status":"completed","output":[{"type":"message","id":"msg_%d","role":"assistant","content":[{"type":"output_text","text":"answer %d"}]}],"usage":{"input_tokens":3,"output_tokens":1}}`, n, n, n)
})
s := prevSandbox(t, provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Responses: up.srv.URL + "/v1"})
img := `{"type":"message","role":"user","content":[{"type":"input_image","image_url":"data:image/png;base64,` + strings.Repeat("QUFB", 50000) + `"},{"type":"input_text","text":"what is this?"}]}`
id := responseID(t, askResponses(t, s, "", `{"model":"fake/m1","input":[`+img+`]}`))
if id != "resp_up1" {
t.Fatalf("client given %s", id)
}
rec := askResponses(t, s, "", `{"model":"fake/m1","previous_response_id":"`+id+`","input":"and now?"}`)
if responseID(t, rec) != "resp_up2" {
t.Fatal(rec.Body.String())
}
q := up.last()
in, _ := json.Marshal(q["input"])
up.mu.Lock()
sent := len(up.got[1])
up.mu.Unlock()
if q["previous_response_id"] != "resp_up1" || strings.Contains(string(in), "QUFB") || !strings.Contains(string(in), "and now?") || sent > 2000 {
t.Fatalf("sent %d bytes: prev %v input %s", sent, q["previous_response_id"], in)
}
// the upstream lost it: asked again with the conversation whole
forget.Store(true)
responseID(t, askResponses(t, s, "", `{"model":"fake/m1","previous_response_id":"resp_up2","input":"once more"}`))
q = up.last()
in, _ = json.Marshal(q["input"])
if _, has := q["previous_response_id"]; has || !strings.Contains(string(in), "QUFB") || !strings.Contains(string(in), "answer 1") || !strings.Contains(string(in), "and now?") || !strings.Contains(string(in), "once more") {
t.Fatalf("whole: prev %v input %.300s", q["previous_response_id"], in)
}
}
// What a response named brings back is masked as the client's own words
// are: a key in an earlier turn never reaches the vendor.
func TestPreviousResponseMasked(t *testing.T) {
const key = "sk-proj-abcdEFGH1234ijklMNOP5678qrst"
up := newPrevUp(t, func(int, []byte) (int, string, string) {
return 200, "text/event-stream", chatSSEReply("noted")
})
s := prevSandbox(t, provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Chat: up.srv.URL + "/v1"})
if err := settings.Save(settings.Settings{Redact: true}); err != nil {
t.Fatal(err)
}
id := responseID(t, askResponses(t, s, "", `{"model":"fake/m1","input":"my key is `+key+`"}`))
responseID(t, askResponses(t, s, "", `{"model":"fake/m1","previous_response_id":"`+id+`","input":"what was it?"}`))
sent, _ := json.Marshal(up.last())
if strings.Contains(string(sent), key) || !strings.Contains(string(sent), "my key is {{") {
t.Fatalf("sent %s", sent)
}
}
// The kept responses are bounded by bytes and time, the oldest out first.
func TestPrevStoreBounded(t *testing.T) {
st := newPrevStore(100, prevTTL)
item := json.RawMessage(strings.Repeat("x", 40))
for i := range 4 {
st.put(&prevTurn{key: prevKey{"s", fmt.Sprint(i)}, items: []json.RawMessage{item}, own: 40})
}
if _, ok := st.get(prevKey{"s", "0"}); ok {
t.Fatal("oldest kept past the cap")
}
if _, ok := st.get(prevKey{"s", "3"}); !ok || st.size > 100 {
t.Fatalf("newest gone, size %d", st.size)
}
st.put(&prevTurn{key: prevKey{"s", "big"}, own: 60})
if _, ok := st.get(prevKey{"s", "big"}); ok {
t.Fatal("a turn past half the cap kept")
}
now := st.now()
st.now = func() time.Time { return now.Add(prevTTL + 1) }
if _, ok := st.get(prevKey{"s", "3"}); ok {
t.Fatal("kept past its time")
}
}