fix(upstream): stop retrying request-level rejections and ignore placeholder keys

A free-tier 400 (context_length_exceeded, invalid_request_error) was
treated as retryable: the gateway walked the second anonymous lane, then
the keyed tier, and the client received whatever the last tier answered.
With the documented placeholder in zen_keys, a 941 KB request that only
needed compaction came back as "401 Invalid credential".

- classify request-level rejections (400/422 with invalid_request_error,
  context_length_exceeded, maximum context length, string_above_max_length
  or prompt is too long) and end the request after the first attempt on
  both the anonymous and keyed lanes, forwarding the original status and
  body; 401/403/429 stay retryable because they can be key-specific;
- read the body once with peekResponseBody so classification does not
  consume what the client eventually receives;
- drop documented placeholder keys (sk-your-zen-key, change-this-local-key)
  during config normalization: they never authenticate, and keeping them
  turns every free-tier fallback into a 401 that hides the real error.

Verified end to end by replaying the recorded request against the built
binary with the original configuration: 400 with the upstream message,
one upstream attempt, an anonymous key_id, and zen/go pools of 0.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
CheerCandClaude Code committed 2026-10-20 21:22:25 +08:00
1 parent 3e8318578d
commit fa9a25577e
5 files changed
+271 -13

No files matched your search

+3
View File
@@ -217,6 +217,9 @@ func Normalize(path string, cfg Config) (Config, error) {
trimList(&cfg.ZenKeys)
trimList(&cfg.GoKeys)
// A placeholder copied from the documentation is not a credential. Treating
// it as one routes every free-model failure into a 401 from the keyed tier.
cfg = DropPlaceholderKeys(cfg)
cfg.ProxyFile = strings.TrimSpace(cfg.ProxyFile)
if err := resolveProxyFiles(path, &cfg); err != nil {
return Config{}, err
+49
View File
@@ -0,0 +1,49 @@
package config
import "strings"
// placeholderKeys are the example values the shipped documentation uses. They
// are not secrets and no upstream accepts them: a configuration that still
// carries one has simply not been filled in yet.
var placeholderKeys = []string{
"sk-your-zen-key",
"change-this-local-key",
}
// IsPlaceholderKey reports whether key is a documented placeholder rather than
// a real credential. Comparison is case-insensitive and ignores surrounding
// whitespace.
func IsPlaceholderKey(key string) bool {
trimmed := strings.ToLower(strings.TrimSpace(key))
for _, placeholder := range placeholderKeys {
if trimmed == placeholder {
return true
}
}
return false
}
// DropPlaceholderKeys removes placeholder credentials from the key pools. A
// placeholder can never authenticate, so keeping it only turns every fallback
// that reaches the keyed tiers into a 401 — which then hides the real error
// (the cause of the failover) from the client. Callers still see the configured
// list through the management API; the pools simply behave as if the tier was
// left empty.
func DropPlaceholderKeys(cfg Config) Config {
drop := func(keys []string) []string {
if len(keys) == 0 {
return keys
}
kept := keys[:0]
for _, key := range keys {
if IsPlaceholderKey(key) {
continue
}
kept = append(kept, key)
}
return kept
}
cfg.ZenKeys = drop(cfg.ZenKeys)
cfg.GoKeys = drop(cfg.GoKeys)
return cfg
}
+52 -11
View File
@@ -66,22 +66,63 @@ func isNetworkAbuseBlock(status int, body []byte) bool {
strings.Contains(text, "from your current network")
}
// peekNetworkAbuseBlock classifies a response without consuming its body:
// the bytes it reads are put back in front of the rest so downstream error
// handling, and a retry on another exit, still see the full payload.
func peekNetworkAbuseBlock(resp *http.Response) bool {
if resp == nil || resp.Body == nil || resp.StatusCode != http.StatusForbidden {
return false
// peekResponseBody reads the start of a response body and puts it back in
// front of the rest, so classification and downstream error handling both see
// the full payload.
func peekResponseBody(resp *http.Response) []byte {
if resp == nil || resp.Body == nil {
return nil
}
prefix, err := io.ReadAll(io.LimitReader(resp.Body, abuseProbeLimit))
resp.Body = replayBody(prefix, resp.Body)
if err != nil {
// The body is unusable; restore what was read and let the ordinary
// error path deal with the response.
resp.Body = replayBody(prefix, resp.Body)
return nil
}
return prefix
}
// peekNetworkAbuseBlock classifies a response without consuming its body.
func peekNetworkAbuseBlock(resp *http.Response) bool {
if resp == nil || resp.StatusCode != http.StatusForbidden {
return false
}
resp.Body = replayBody(prefix, resp.Body)
return isNetworkAbuseBlock(resp.StatusCode, prefix)
return isNetworkAbuseBlock(resp.StatusCode, peekResponseBody(resp))
}
// errDeterministicClientRejection reports that the upstream rejected the
// request itself: the body is malformed, too long for the model, or fails the
// same validation on every credential. Retrying on another key, lane or tier
// cannot change that, so the request must end and the original 4xx must reach
// the client. Without this, the first tier's real error is replaced by
// whatever the next tier answers — typically a 401 from an unconfigured key,
// which tells the client to re-authenticate instead of compacting.
var errDeterministicClientRejection = errors.New("upstream rejected the request deterministically")
// deterministicMarkers are the error types and codes an upstream uses for a
// request that will fail identically everywhere. The status must be 400 or 422
// as well: a 401, 403 or 429 can be specific to the credential or the moment.
var deterministicMarkers = []string{
"invalid_request_error",
"invalid_request",
"context_length_exceeded",
"maximum context length",
"string_above_max_length",
"prompt is too long",
}
// isDeterministicClientResponse reports whether status and body describe a
// request-level rejection rather than a credential or availability problem.
func isDeterministicClientResponse(status int, body []byte) bool {
if status != http.StatusBadRequest && status != http.StatusUnprocessableEntity {
return false
}
text := strings.ToLower(string(body))
for _, marker := range deterministicMarkers {
if strings.Contains(text, marker) {
return true
}
}
return false
}
// replayBody returns a body that yields prefix and then the rest of original.
+133
View File
@@ -0,0 +1,133 @@
package gateway
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"opencode2api/internal/config"
"opencode2api/internal/models"
wire "opencode2api/internal/protocol"
)
// contextLengthBody is the free tier's answer when a request exceeds the
// model's context window. Retrying it on another key or tier cannot succeed.
const contextLengthBody = `{"error":{"message":"Your request resulted in more tokens than this model's maximum context length allows. Please reduce the length of the messages or run compaction.","type":"invalid_request_error","code":"context_length_exceeded"}}`
// respondClient answers every request with the given status and body.
func respondClient(counter *atomic.Int64, status int, body string) *http.Client {
return &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
counter.Add(1)
return &http.Response{
StatusCode: status,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(body)),
Request: r,
}, nil
})}
}
func keyedRoute() models.Route {
route := testFreeRoute()
route.KeyTiers = []config.Tier{config.TierZen}
return route
}
// TestDoUpstreamTiersStopsAtContextLength pins that a deterministic client error
// ends the request: another key or tier cannot make an over-long context fit,
// and replaying it buries the real cause behind a later authentication error.
func TestDoUpstreamTiersStopsAtContextLength(t *testing.T) {
var requests atomic.Int64
g, transports := newBlockTestGateway(t, 1)
attachTestClient(transports, 0, respondClient(&requests, http.StatusBadRequest, contextLengthBody))
g.zenNodes = &upstreamNodes{transports: transports, nodes: []*upstreamNode{{key: "sk-zen"}}}
resp, _, _, err := g.doUpstreamTiers(context.Background(), keyedRoute(), testBodies(), testRequestIDs(), 0)
if err != nil {
t.Fatalf("error = %v, want the upstream 400 returned as a response", err)
}
if resp == nil {
t.Fatal("response = nil")
}
defer resp.Body.Close()
if requests.Load() != 1 {
t.Fatalf("upstream requests = %d, want 1 (no keyed retry of a deterministic 400)", requests.Load())
}
body, _ := io.ReadAll(resp.Body)
if !strings.Contains(string(body), "context_length_exceeded") {
t.Fatalf("body = %q, want the upstream 400 body preserved", body)
}
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400", resp.StatusCode)
}
}
// TestDoUpstreamTiersKeepsAuthErrorsRetryable pins the boundary of the rule
// above: a 401 can be specific to one key, so it must still reach the next key.
func TestDoUpstreamTiersKeepsAuthErrorsRetryable(t *testing.T) {
var requests atomic.Int64
g, transports := newBlockTestGateway(t, 1)
attachTestClient(transports, 0, respondClient(&requests, http.StatusUnauthorized, `{"error":{"message":"Invalid credential"}}`))
g.zenNodes = &upstreamNodes{transports: transports, nodes: []*upstreamNode{{key: "sk-zen"}}}
g.cfg.Retry.MaxAttempts = 2
resp, _, _, err := g.doUpstreamTiers(context.Background(), keyedRoute(), testBodies(), testRequestIDs(), 0)
if err != nil {
t.Fatalf("error = %v", err)
}
if resp == nil {
t.Fatal("response = nil")
}
_ = resp.Body.Close()
if requests.Load() < 2 {
t.Fatalf("upstream requests = %d, want a second key attempt after a 401", requests.Load())
}
}
// TestIsDeterministicClientResponse pins the classification the rule uses.
func TestIsDeterministicClientResponse(t *testing.T) {
cases := []struct {
name string
status int
body string
want bool
}{
{"context length", http.StatusBadRequest, contextLengthBody, true},
{"generic invalid_request", http.StatusBadRequest, `{"error":{"type":"invalid_request_error","message":"messages: at least one message is required"}}`, true},
{"validation error", http.StatusUnprocessableEntity, `{"error":{"type":"invalid_request_error","message":"bad shape"}}`, true},
{"auth", http.StatusUnauthorized, `{"error":{"message":"Invalid credential"}}`, false},
{"forbidden", http.StatusForbidden, ipAbuseBody, false},
{"rate limit", http.StatusTooManyRequests, `{"error":{"message":"slow down"}}`, false},
{"server", http.StatusInternalServerError, `{"error":{"message":"boom"}}`, false},
{"empty body", http.StatusBadRequest, ``, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := isDeterministicClientResponse(tc.status, []byte(tc.body)); got != tc.want {
t.Fatalf("isDeterministicClientResponse(%d, %q) = %v, want %v", tc.status, tc.body, got, tc.want)
}
})
}
}
// TestCopyErrorResponseKeepsUpstreamStatus pins that the client sees the
// upstream status and message, so a 400 is not reported as a 401.
func TestCopyErrorResponseKeepsUpstreamStatus(t *testing.T) {
resp := &http.Response{
StatusCode: http.StatusBadRequest,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(contextLengthBody)),
}
recorder := httptest.NewRecorder()
copyErrorResponse(recorder, wire.Chat, resp, "req_test")
if recorder.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400", recorder.Code)
}
if !strings.Contains(recorder.Body.String(), "maximum context length") {
t.Fatalf("body = %s, want the upstream message", recorder.Body.String())
}
}
+34 -2
View File
@@ -237,6 +237,14 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
return resp, route, attempts, nil
}
lastResponse, lastErr = resp, err
if errors.Is(err, errDeterministicClientRejection) {
// The request itself was rejected. Another lane or key gets the same
// answer, and retrying only buries this error under the next one, so
// hand the upstream 4xx back as the response (nil error) and let the
// normal error path forward its status and body unchanged.
g.logger.Warn("upstream rejected the request; not retrying on other tiers", "component", "upstream", "event", "deterministic_rejection", "request_id", ids.Request, "attempts", attempts, "model", route.ID)
return lastResponse, effectiveRoute, attempts, nil
}
if errors.Is(err, errFreeTierIPBlocked) {
// The free tier flagged the egress IP. A keyed tier leaves from the
// same network and gets the same answer, so stop here instead of
@@ -280,6 +288,15 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
return resp, keyRoute, attempts, nil
}
if resp != nil {
if isDeterministicClientResponse(resp.StatusCode, peekResponseBody(resp)) {
// Same request-level rejection as on the anonymous lane: no
// other tier can fix it, so return it as is.
g.logger.Warn("upstream rejected the request; not trying other tiers", "component", "upstream", "event", "deterministic_rejection", "request_id", ids.Request, "attempts", attempts, "tier", keyRoute.Tier, "status", resp.StatusCode)
if lastResponse != nil {
httpx.DrainAndClose(lastResponse.Body)
}
return resp, keyRoute, attempts, nil
}
if lastResponse != nil {
httpx.DrainAndClose(lastResponse.Body)
}
@@ -316,6 +333,10 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
// result then reports errFreeTierIPBlocked even when no exit was left to
// try, so the caller does not fall through to the keyed tiers.
blocked := false
// halted records that the upstream rejected the request itself. The result
// then reports errDeterministicClientRejection so the caller keeps this
// 4xx instead of replacing it with a later tier's answer.
halted := false
cursor := g.anonymous.CursorFor(ids.Session)
limit := g.anonymous.Len()
if g.anonymous.HasPool() && g.cfg.Retry.MaxAttempts > limit {
@@ -424,6 +445,13 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
blocked = true
g.logger.Warn("free tier blocked the egress IP; cooling the exit", "component", "upstream", "event", "free_tier_ip_blocked", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "proxy", config.RedactURL(node.proxy.name), "block_for", g.freeTierBlockTTL().String())
break
} else if isDeterministicClientResponse(resp.StatusCode, peekResponseBody(resp)) {
// The request is too long, malformed, or otherwise invalid on
// every lane. Stop here and hand this 4xx to the client.
lastErr = errDeterministicClientRejection
halted = true
g.logger.Warn("upstream rejected the request; not trying other upstreams", "component", "upstream", "event", "deterministic_rejection", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "status", resp.StatusCode, "duration_ms", duration.Milliseconds())
break
} else {
g.logger.Debug("anonymous upstream returned an error response; trying the next upstream or proxy", "component", "upstream", "event", "anonymous_attempt_response_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds())
}
@@ -437,11 +465,15 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
g.observeAnonymousResult(ctx, node, nodeResp, nodeErr)
}
if lastResponse != nil {
// The caller keeps and forwards this response; a block only changes
// the error so the keyed tiers are skipped.
// The caller keeps and forwards this response; a block or a
// deterministic rejection only changes the error so the keyed tiers
// are skipped.
if blocked {
return lastResponse, errFreeTierIPBlocked, attempts
}
if halted {
return lastResponse, errDeterministicClientRejection, attempts
}
return lastResponse, nil, attempts
}
if blocked {