Files
magpie/internal/gateway/upstream.go
T
yetoneand卡提希娅可爱捏 efb7cb11d4 gateway: a safety refusal said in a stream is a refusal for a client answered whole too, and rests nobody (#3274, CartethyiaQwQ)
CartethyiaQwQ (#3274): Codex's "safety filter: cyber_policy" refusal
(the Daybreak note) set healthy accounts aside; two such turns benched a
five-account pool for about 17 minutes.

Cause: the HTTP 400 cyber_policy is already a refusal (policyRefusal reads
its code: next account asked, nobody rests), and so is one said in a
stream relayed as a stream. A Codex account is always streamed upstream,
so a stream:false Responses, Chat or Messages request is answered from
that stream whole. There, a response.failed or error event whose error
has a code (cyber_policy) but no invalid_request_error type got no status
from the decoder, and the whole path answered it 502 api_error: retried
on the same account, then every account asked, each one but the last
resting by backoff. A refusal after a few words went to the client as a
finished 200 turn, and the failure after it rested the account.

Fix, at the decoders and the whole path:
- filterRefused (fallback.go): a stream error event refusedCode reads as
  the safety filter's gets status 400 and Said {"error":{type
  invalid_request_error, code}}. Used by every decoder that set
  Code: refusedCode -- Responses (both error sites, after requestRefused),
  Chat, Anthropic and carriedError.
- The whole path (gateway.go) answers a reply the filter cut part way as
  the refusal, not its words so far, and notes it in refusedHeader, since
  Anthropic's error shape drops the code that settle reads.
- restAfterMarked: a 400 whose error object policyRefusal reads as a
  refusal rests nobody and counts no failure (By "off", Why refused), as
  the ZDR refusal does, for any route that reaches it.
- docs/subsystems/gateway-routing.md says so.

Review of the submitted patch (dc6c695db, not taken as is): it matched
`safety filter|cyber_policy|Daybreak access` anywhere in a 400's words,
so a 400 that echoes the user's prompt in its message skipped the rest
too; its fixture was magpie's own refusedError text, which restAfter is
never handed for a 400; and it gated on status 400, while the path that
rested (above) answered 502, so it would not have stopped the rests.
Its restAfter unit tests' shape is kept in TestRestAfterPolicyRefusal.

Run at 21f7f9df2 (origin/main then) plus this change, unless said:
- New TestStreamRefusalAnsweredWholeRestsNobody: {response.failed, error
  event, refusal after text} x {Responses, Chat, Messages answered whole}
  x {next answers, nobody left}; fixture is the reporter's quoted message
  without magpie's 300-char cut. Asserts the client gets 200 from the
  next account or a 400 naming cyber_policy, every try failRefused with
  no Rest, nothing resting.
- New TestRestAfterPolicyRefusal: cyber_policy 400 rests nobody and
  counts 0 failures; a plain 400, and two 400s echoing the reporter's
  words in the message (code string_above_max_length / code null) still
  rest by backoff.
- Red on the old code: all 18 TestStreamRefusalAnsweredWholeRestsNobody
  subtests and TestRestAfterPolicyRefusal/cyber_policy. Broken by hand,
  each went red: filterRefused returning no status (all 18); the
  part-way clause dropped (6 "after some text"); refusedHeader not set
  (6 Messages subtests).
- A scratch matrix before the fix (also streamed Responses/Chat/Messages
  and Codex's own path, HTTP 400 and response.failed): only the whole
  routes rested; the streamed ones and the HTTP 400 already passed.
- gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows
  go vet -tags nogui ./... clean.
- go test -race -timeout 45m ./internal/gateway/: FAIL on two tests
  this change doesn't reach, each ok alone with -race -count=3 and
  filed: TestPluginStreamLongActiveReader (client deadline after 36MB,
  #3286) and TestQuietKeptAliveOnlySoLong (0 keepalives in a 3s pause,
  #3287). Load was 180-280 from other sessions' GUI runs.
- Rebased on ba1dc7f97: gofmt, go vet ./internal/gateway/ and the two
  new tests again: ok.
- go test -timeout 45m ./... at ba1dc7f97 plus this change: ok, 69
  packages, no FAIL (internal/gateway 783s).

Not tried: a real Codex account. Whether the ChatGPT backend sends
cyber_policy as an HTTP 400 or inside a 200 stream, and with or without
an error type, isn't known from the issue; every shape is covered by
tests, not by a live refusal.

Co-authored-by: 卡提希娅可爱捏 <134358478+CartethyiaQwQ@users.noreply.github.com>
2026-10-22 22:53:47 +08:00

214 lines
7.1 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. ClinePass (api.cline.bot)
// names it in a Chat choice's provider_metadata, as
// gateway.routing.finalProvider: under delta in a stream's chunk, under
// message in one body (#2847, smart-lty). Only those places count: a
// choice's content is the model's, and providerAttempts inside routing
// lists every provider tried, not the one that answered.
func upstreamOf(b []byte) string {
if !bytes.Contains(b, []byte(`"provider"`)) && !bytes.Contains(b, []byte(`"finalProvider"`)) {
return ""
}
type routed struct {
ProviderMetadata struct {
Gateway struct {
Routing struct {
FinalProvider json.RawMessage `json:"finalProvider"`
} `json:"routing"`
} `json:"gateway"`
} `json:"provider_metadata"`
}
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"`
Choices []struct {
Delta routed `json:"delta"`
Message routed `json:"message"`
} `json:"choices"`
}
if json.Unmarshal(b, &v) != nil {
return ""
}
raws := []json.RawMessage{v.Provider, v.Message.Provider, v.Response.Provider}
for _, c := range v.Choices {
raws = append(raws, c.Delta.ProviderMetadata.Gateway.Routing.FinalProvider, c.Message.ProviderMetadata.Gateway.Routing.FinalProvider)
}
for _, raw := range raws {
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
}
code, status, said := filterRefused(data)
return Event{Kind: KError, Text: streamErrorText(data, r.Error, v.Error), Code: code, Status: status, Said: said}, 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"
}