Files
magpie/internal/gateway/upstream.go
T
yetone 320af98581 gateway: an upstream's error in a shape its decoder can't read fails the reply, so Codex tries again (#1933, tensornull)
A translated stream whose upstream said it failed, but not in the shape
its protocol's decoder reads, ended as a completed reply with no output
and zero usage. Codex took that as its turn's end (exit 0, no message)
and never used its stream retry. tensornull's three fixtures, on an
Anthropic provider asked from Codex's Responses:

- {"type":"error","error":"fixture upstream failure"}: decodeAnthropic's
  struct wants an object for error, so the event decoded to nothing,
  while upstreamEnds counted the type "error" as the reply's end.
- Messages events with their type left out (named only by "event:"):
  the decoder read nothing, and upstreamStop's delta.stop_reason still
  marked the reply ended.
- A Responses response.failed from the Anthropic endpoint: upstreamEnds
  took any protocol's last event, and the Anthropic decoder ignores it.

Now:
- replyEnds (upstream.go) reads a reply's end in the protocol it was
  asked in: Anthropic's message_stop, error or a message_delta's
  stop_reason; Responses' response.completed/incomplete/failed or error;
  Gemini's finishReason; Chat's finish_reason. The other two fixtures no
  longer read as whole and end as errEndedShort, a failure the gateway
  and the client retry, like the "ping then EOF" control. It replaces
  upstreamEnds in both the streaming loop (continuation.go) and the
  unstreamed one (gateway.go).
- carriedError: every decoder (Anthropic, Responses, Chat, Code
  Assist/Gemini) that can't decode an event still tells an error it
  carries ({"error":"…"}, type error, response.failed) as KError with
  its words. Siblings found the same way: a Chat upstream's
  {"error":"…"} chunk ended a translated reply as completed; a Responses
  upstream's string error or a response.failed with no error object
  (status failed) did too, read as stop.
- An error event with no message says its type or the event itself,
  never "".

One test's fixture changed with it: TestTranslatedEffortLoggedAsSent
served Chat chunks from its Responses upstream, which the Responses
decoder reads as nothing. It "completed" only because a finish_reason
counted as the end, the same empty success this fixes, so it now fails
with errEndedShort. The case gets a Responses reply (responsesHi).

What a whole reply does is unchanged: a valid Messages text reply, and
Claude's empty end_turn (asked of in the report), still complete on the
first ask (TestWellFormedStreamsStillComplete).

Run: the new tests in stream_error_shape_test.go use the report's bytes
(event: lines included). Against origin/main's code (fix reverted, tests
kept) 8 subtests fail: anthropic error string, error object with no
message, events with no type, responses failure on the messages route,
chat error string, both Responses-upstream cases, and the unstreamed
client; the error-object control and the well-formed ones pass on both.
With the fix all pass. go test -tags nogui -timeout 40m ./internal/gateway (sandbox
HOME, caches pinned); gofmt -l; go vet darwin, GOOS=linux -tags nogui,
GOOS=windows. tensornull's reproduce.py against a nogui build of this
tree: error-string now ends response.failed "fixture upstream failure"
after 3 gateway attempts, the same as the error-object control (was
response.completed after 1). Not run: the Codex CLI replay; a Responses
client asking a Responses upstream is passed its bytes as they are, so
that pairing is unchanged.
2026-10-13 14:48:49 +08:00

191 lines
6.2 KiB
Go

package gateway
import (
"bytes"
"encoding/json"
"strings"
"github.com/yetone/magpie/internal/provider"
)
// upstreamOf is the provider an aggregator's reply (a JSON body, or one
// event of its stream) says answered behind it, "" when it says none.
// OpenRouter names it in a top-level "provider" — a Chat body and every
// chunk of its stream, an Anthropic Messages body — and in a Messages
// stream's message_start, as message.provider (seen 2026-10-05: DeepInfra,
// StreamLake). Its Responses replies name none.
func upstreamOf(b []byte) string {
if !bytes.Contains(b, []byte(`"provider"`)) {
return ""
}
var v struct {
Provider json.RawMessage `json:"provider"`
Message struct {
Provider json.RawMessage `json:"provider"`
} `json:"message"`
Response struct {
Provider json.RawMessage `json:"provider"`
} `json:"response"`
}
if json.Unmarshal(b, &v) != nil {
return ""
}
for _, raw := range []json.RawMessage{v.Provider, v.Message.Provider, v.Response.Provider} {
var s string // a request's provider options echoed back are an object
if json.Unmarshal(raw, &s) == nil {
if s = strings.TrimSpace(s); s != "" && len(s) <= 64 {
return s
}
}
}
return ""
}
// upstreamStop is why a reply (a JSON body, or one event of its stream)
// says it ended, in the upstream's own words: an Anthropic stop_reason, a
// Chat finish_reason, a Responses reply's status and the reason it was
// incomplete. Kept with the request, so a reply that ended too soon shows
// what the upstream said of it — a relay's "end_turn" after a few words,
// or nothing at all (蓝猫 on Discord). "" when this one says none.
func upstreamStop(b []byte) string {
if !bytes.Contains(b, []byte(`stop_reason"`)) && !bytes.Contains(b, []byte(`finish_reason"`)) && !bytes.Contains(b, []byte(`"response.`)) {
return ""
}
var v struct {
Type string `json:"type"`
StopReason string `json:"stop_reason"`
Delta struct {
StopReason string `json:"stop_reason"`
} `json:"delta"`
Choices []struct {
FinishReason string `json:"finish_reason"`
} `json:"choices"`
Response struct {
Status string `json:"status"`
IncompleteDetails *struct {
Reason string `json:"reason"`
} `json:"incomplete_details"`
} `json:"response"`
}
if json.Unmarshal(b, &v) != nil {
return ""
}
switch {
case v.Delta.StopReason != "":
return v.Delta.StopReason
case v.StopReason != "":
return v.StopReason
case strings.HasPrefix(v.Type, "response.") && v.Response.Status != "" && v.Response.Status != "in_progress" && v.Response.Status != "queued":
if d := v.Response.IncompleteDetails; d != nil && d.Reason != "" {
return v.Response.Status + ": " + d.Reason
}
return v.Response.Status
}
for _, c := range v.Choices {
if c.FinishReason != "" {
return c.FinishReason
}
}
return ""
}
// replyEnds says whether an upstream's event ends the reply, read as the
// protocol it was asked in, stop being what upstreamStop read of it: an
// Anthropic message_stop or error, or a message_delta's stop_reason; a
// Responses response.completed, response.incomplete, response.failed or
// error; a Gemini chunk's finishReason (geminiEnds); a Chat
// finish_reason. Another protocol's end, or Anthropic's events with their
// type left out, end nothing: the decoder reads nothing of them, and a
// stream told whole on one became a completed reply that said nothing,
// which the agent took as its turn's end and didn't ask again (#1933).
func replyEnds(proto provider.Protocol, data, stop string) bool {
switch {
case proto == provider.Anthropic:
t := eventType(data)
return t == "message_stop" || t == "error" || t == "message_delta" && stop != ""
case proto == provider.Responses:
t := eventType(data)
return t == "error" || strings.HasPrefix(t, "response.") && (lastEvent(t) || stop != "")
case geminiKin(proto):
return stop != "" || geminiEnds([]byte(data))
}
return stop != ""
}
// eventType is an event's own "type", "" when it names none.
func eventType(data string) string {
var v struct {
Type json.RawMessage `json:"type"`
}
var t string
if json.Unmarshal([]byte(data), &v) != nil || json.Unmarshal(v.Type, &t) != nil {
return ""
}
return t
}
// carriedError is the error an upstream's event carries where its
// protocol's decoder can't read it: an error that is a string,
// {"type":"error","error":"…"} (#1933), or one whose other fields aren't
// the shape the protocol gives them. Read as nothing, the stream went on
// to end as a whole reply with nothing in it, and the agent didn't try
// again. ok is false for an event that carries no error.
func carriedError(data string) (ev Event, ok bool) {
var v struct {
Type json.RawMessage `json:"type"`
Error json.RawMessage `json:"error"`
Response json.RawMessage `json:"response"`
}
if json.Unmarshal([]byte(data), &v) != nil {
return Event{}, false
}
var t string
json.Unmarshal(v.Type, &t)
var r struct {
Error json.RawMessage `json:"error"`
}
json.Unmarshal(v.Response, &r)
if t != "error" && t != "response.failed" && !carries(v.Error) && !carries(r.Error) {
return Event{}, false
}
return Event{Kind: KError, Text: streamErrorText(data, r.Error, v.Error), Code: refusedCode(data)}, true
}
// streamErrorText is what an upstream's error event says: the message of
// the first of errs that has one (an object's message or type, or a
// string), else the event as provider.APIError reads it. Never "": an
// error said with no words is still told as one.
func streamErrorText(data string, errs ...json.RawMessage) string {
for _, raw := range errs {
if !carries(raw) {
continue
}
var s string
if json.Unmarshal(raw, &s) == nil {
if s = strings.TrimSpace(s); s != "" {
return s
}
continue
}
var e struct {
Message string `json:"message"`
Type string `json:"type"`
}
if json.Unmarshal(raw, &e) == nil {
if m := strings.TrimSpace(e.Message); m != "" {
return m
}
if e.Type != "" {
return e.Type
}
}
}
return provider.APIError([]byte(data), "the upstream reported an error")
}
// carries says whether a JSON value is there and not null.
func carries(raw json.RawMessage) bool {
s := bytes.TrimSpace(raw)
return len(s) > 0 && string(s) != "null"
}