gateway: a Responses stream magpie ends is a whole response.failed (plugins#852)

When a Responses stream ended short or was cut, passthrough wrote a
response.failed with only object, status and error. Grok Build reads
the Responses stream through async-openai's types. Their Response needs
id, created_at, model, object, output and status, and the event needs
sequence_number. So a Grok plugin stream cut by the vendor ended in
"serialization error: missing field `created_at`" instead of the error
(lxyer's report behind plugins#852).

Now passthrough writes a whole response.failed:
- usageSniffer keeps the stream's response id, created_at and the next
  sequence_number;
- if responsesTextCalls renumbered the events on the way out, the
  failure follows the last number the client got;
- id, created_at, model and the error are filled in.
Before any event there is a fresh resp_ id and the time now.
The Chat and Gemini failures are unchanged. The translator paths
already end through responsesEncoder, which writes a whole response,
and nothing else writes a Responses streamFailure.

Run:
- On mote, at this tree: gofmt -l; go vet ./... on darwin, linux nogui
  and windows; builds for all three; go test -tags nogui -timeout 45m
  ./...: 87 packages ok, one red,
  TestCancelledSignInEndsItsFetch in internal/plugin, which this change
  doesn't reach (open as #5264). That run was at the base 0fc3455e2.
  Rebased on 00198b26e (#5655, gateway): gofmt -l, vet on all three
  systems and go test ./internal/gateway again: ok. Rebased again on
  cdf734757 (automode text, OpenMausBot): vet, build and
  -run 'StreamFailure|AutoMode|Automode|Anthropic' ./internal/gateway ok.
- Red on the old code (the tests at 0fc3455e2's gateway.go and
  sniff.go): TestResponsesStreamFailureIsAWholeResponse ("no
  sequence_number", "response.created_at missing") and
  TestResponsesStreamFailureBeforeAnyEvent.
- Real Grok Build 1.0.67 on mote (`grok -p`, api_backend responses)
  against a fake server replaying each ending:
  - the old frame: "missing field 'created_at'";
  - a whole response without sequence_number: "missing field
    'sequence_number'";
  - the new frame, after text, after response.created, and bare: read,
    and retried as server_error, with no serde error.

Not tried: Grok Build 1.0.77 (the reporter's), and a live Grok stream
cut by the vendor.
This commit is contained in:
yetone
2026-11-08 11:03:09 +08:00
parent cdf734757a
commit 29bfd5dc8b
3 changed files with 176 additions and 9 deletions
+27 -2
View File
@@ -7228,7 +7228,14 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
// event the upstream left is dropped (#2580): a client
// reading it dies on its JSON before the error is reached
dropHalf()
w.Write(append(apart(), streamFailure(proto, failed)...))
tail := sniff.resp
if rc, ok := written.(*responsesTextCalls); ok && int64(rc.seq) >= tail.next {
// the stream's events were numbered again on their way
// out: the failure follows the last the client got
tail.next = int64(rc.seq) + 1
}
tail.model = cmp.Or(sniff.served, model)
w.Write(append(apart(), streamFailureAt(proto, failed, tail)...))
if proto == provider.Chat && rerr != nil && rerr != io.EOF {
// a Chat stream the upstream severed ends on [DONE] too: a
// client that reads to it stops there and says the error it
@@ -7315,6 +7322,17 @@ func noteSaidStatus(w http.ResponseWriter, status int) {
// streamFailure is an error event ending a stream in proto, as each
// protocol's own server sends one mid-reply.
func streamFailure(proto provider.Protocol, msg string) []byte {
return streamFailureAt(proto, msg, respTail{})
}
// streamFailureAt is streamFailure after what a Responses stream said of
// its response (tail). A response.failed is a whole Response, as OpenAI's
// own is: Grok Build reads it as async-openai's, which needs the
// response's id, created_at, model and output, and the event's
// sequence_number (one without created_at was "serialization error:
// missing field `created_at`", plugins#852). The response is the one the
// stream began, numbered after its last event.
func streamFailureAt(proto provider.Protocol, msg string, tail respTail) []byte {
var name string
var v map[string]any
switch proto {
@@ -7322,7 +7340,14 @@ func streamFailure(proto provider.Protocol, msg string) []byte {
v = map[string]any{"error": map[string]any{"message": msg, "type": "api_error"}}
case provider.Responses:
name = "response.failed"
v = map[string]any{"type": name, "response": map[string]any{"object": "response", "status": "failed",
id := cmp.Or(tail.id, "resp_"+newID())
created := tail.created
if created <= 0 {
created = time.Now().Unix()
}
v = map[string]any{"type": name, "sequence_number": tail.next, "response": map[string]any{
"id": id, "object": "response", "created_at": created, "status": "failed",
"model": tail.model, "output": []any{}, "parallel_tool_calls": true, "tool_choice": "auto", "tools": []any{},
"error": map[string]any{"code": "server_error", "message": msg}}}
case provider.Gemini:
// Gemini's own mid-stream error, as geminiEncoder writes it: a
+33 -7
View File
@@ -33,6 +33,19 @@ type usageSniffer struct {
tail chatTail
// found: the searches the reply ran by itself (searchTally)
found searchTally
// resp: the Responses stream's own response, as far as it went: what
// a response.failed magpie ends it with carries (streamFailure)
resp respTail
}
// respTail is what a Responses stream said of its response before it
// ended: the id and created_at its events named, and the sequence_number
// the next event takes; model is the caller's, the one that answered.
type respTail struct {
id string
created int64
next int64
model string
}
func newSniffer(proto provider.Protocol, contentType string) *usageSniffer {
@@ -190,14 +203,18 @@ func (s *usageSniffer) parse(b []byte) {
}
case provider.Responses:
var v struct {
ID string `json:"id"`
Type string `json:"type"`
Model string `json:"model"`
Usage *rUsage `json:"usage"`
ID string `json:"id"`
Type string `json:"type"`
Model string `json:"model"`
Usage *rUsage `json:"usage"`
// numbers read as float64: a vendor's odd one (a fractional
// created_at) must not cost the usage in the same event
Seq *float64 `json:"sequence_number"`
Response struct {
ID string `json:"id"`
Model string `json:"model"`
Usage *rUsage `json:"usage"`
ID string `json:"id"`
Model string `json:"model"`
Created float64 `json:"created_at"`
Usage *rUsage `json:"usage"`
} `json:"response"`
}
if json.Unmarshal(b, &v) == nil {
@@ -205,6 +222,15 @@ func (s *usageSniffer) parse(b []byte) {
s.u.add(Usage{ResponseID: v.ID})
} else if strings.HasPrefix(v.Type, "response.") {
s.u.add(Usage{ResponseID: v.Response.ID})
if v.Response.ID != "" {
s.resp.id = v.Response.ID
}
if v.Response.Created > 0 {
s.resp.created = int64(v.Response.Created)
}
if v.Seq != nil && int64(*v.Seq) >= s.resp.next {
s.resp.next = int64(*v.Seq) + 1
}
}
s.saw(v.Response.Model)
s.saw(v.Model)
@@ -0,0 +1,116 @@
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// lastResponsesEvent is the last data line of a Responses stream, parsed.
func lastResponsesEvent(t *testing.T, body string) map[string]any {
t.Helper()
var last string
for _, line := range strings.Split(body, "\n") {
if d, ok := strings.CutPrefix(line, "data: "); ok && strings.HasPrefix(d, "{") {
last = d
}
}
var v map[string]any
if err := json.Unmarshal([]byte(last), &v); err != nil {
t.Fatalf("last event %q: %v\n%s", last, err, body)
}
return v
}
// wholeFailedResponse checks a response.failed as async-openai's
// ResponseFailedEvent reads it (Grok Build's serde): the event's
// sequence_number, and a Response with id, object, created_at, model,
// output and status. Grok Build 1.0.67 said "missing field `created_at`"
// and then "missing field `sequence_number`" for each one gone.
func wholeFailedResponse(t *testing.T, v map[string]any) map[string]any {
t.Helper()
if v["type"] != "response.failed" {
t.Fatalf("last event is %v, not response.failed: %v", v["type"], v)
}
if _, ok := v["sequence_number"].(float64); !ok {
t.Errorf("no sequence_number: %v", v)
}
r, _ := v["response"].(map[string]any)
for _, k := range []string{"id", "object", "status"} {
if s, _ := r[k].(string); s == "" {
t.Errorf("response.%s missing: %v", k, r)
}
}
if _, ok := r["model"].(string); !ok {
t.Errorf("response.model missing: %v", r)
}
if c, _ := r["created_at"].(float64); c <= 0 {
t.Errorf("response.created_at missing: %v", r)
}
if _, ok := r["output"].([]any); !ok {
t.Errorf("response.output not a list: %v", r)
}
if e, _ := r["error"].(map[string]any); e["message"] == nil {
t.Errorf("response.error missing: %v", r)
}
return r
}
// A Responses stream that ends short after its output began is ended
// with a response.failed a Responses client can read: the response the
// stream began (its id and created_at), numbered after its last event.
// magpie's own had only object, status and error, and Grok Build failed
// the turn on it with "serialization error: missing field `created_at`"
// instead of saying the error (plugins#852).
func TestResponsesStreamFailureIsAWholeResponse(t *testing.T) {
fresh(t)
up := &scripted{replies: []reply{{200, "text/event-stream", sse(
`event: response.created`,
`data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_up1","object":"response","created_at":1762000000,"status":"in_progress","model":"m","output":[]}}`,
`event: response.output_item.added`,
`data: {"type":"response.output_item.added","sequence_number":1,"output_index":0,"item":{"id":"msg_1","type":"message","role":"assistant","status":"in_progress","content":[]}}`,
`event: response.output_text.delta`,
`data: {"type":"response.output_text.delta","sequence_number":2,"item_id":"msg_1","output_index":0,"content_index":0,"delta":"pong"}`,
)}}}
scriptedOn(t, "a", provider.Responses, up)
gw := httptest.NewServer(New().Handler())
t.Cleanup(gw.Close)
req, _ := http.NewRequest("POST", gw.URL+"/v1/responses", strings.NewReader(`{"model":"a/m","stream":true,"input":"hi"}`))
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
b, _ := io.ReadAll(res.Body)
body := string(b)
if res.StatusCode != 200 || !strings.Contains(body, "pong") {
t.Fatalf("%d %s", res.StatusCode, body)
}
v := lastResponsesEvent(t, body)
r := wholeFailedResponse(t, v)
if r["id"] != "resp_up1" || r["created_at"] != float64(1762000000) {
t.Errorf("not the response the stream began: %v", r)
}
if v["sequence_number"] != float64(3) {
t.Errorf("sequence_number %v, want 3 (after the stream's last)", v["sequence_number"])
}
}
// With nothing of the response said yet, the failure is still whole: an
// id and created_at of its own, numbered first.
func TestResponsesStreamFailureBeforeAnyEvent(t *testing.T) {
b := streamFailure(provider.Responses, "x: connection lost mid-reply (unexpected EOF)")
r := wholeFailedResponse(t, lastResponsesEvent(t, string(b)))
if id, _ := r["id"].(string); !strings.HasPrefix(id, "resp_") {
t.Errorf("id %q", id)
}
if !strings.HasPrefix(string(b), "event: response.failed\n") {
t.Errorf("%s", b)
}
}