mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
fix: harden stale-reasoning retry per review
- Only treat a retry as success on 2xx; on non-2xx/transport failure close the retry response and restore the original 400 body, logging reasoning_reference_retry_failed with the retry status. - Always close the original network body after caching its bytes, and hand downstream a fresh in-memory reader (also on read errors). - Narrow the matcher to explicit 'reasoning item/reference ... not found/expired' errors; add negative cases (unknown reasoning field, bad reasoning_effort, unrelated 400s). - Thread a cumulative attempt offset through doUpstreamTiers and the anonymous path so retry attempts keep numbering [1 2] per request. - Add HTTP-level tests via httptest upstream: retry success (with stripped-payload assertion), retry non-2xx restore, non-matching passthrough, no-op (nothing to strip), cumulative attempt numbers.
This commit is contained in:
1 parent
462a6c8e36
commit
74348cb46f
2 files changed
+266
-23
No files matched your search
+36
-22
@@ -371,12 +371,18 @@ func (g *Gateway) prepareRouteBodies(from Protocol, route modelRoute, input map[
|
||||
}
|
||||
|
||||
func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, bodies map[Tier][]byte, ids requestIDs) (*http.Response, modelRoute, error) {
|
||||
resp, effectiveRoute, err := g.doUpstreamTiers(ctx, route, bodies, ids)
|
||||
resp, effectiveRoute, attempts, err := g.doUpstreamTiers(ctx, route, bodies, ids, 0)
|
||||
if err != nil || resp == nil || resp.StatusCode != http.StatusBadRequest {
|
||||
return resp, effectiveRoute, err
|
||||
}
|
||||
errBody, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
origBody := resp.Body
|
||||
errBody, readErr := io.ReadAll(io.LimitReader(origBody, 1<<20))
|
||||
// The original network body is always closed here: the retry path below
|
||||
// reuses the connection, otherwise downstream receives a fresh in-memory
|
||||
// reader over the cached bytes.
|
||||
drainAndClose(origBody)
|
||||
if readErr != nil {
|
||||
resp.Body = io.NopCloser(bytes.NewReader(errBody))
|
||||
return resp, effectiveRoute, nil
|
||||
}
|
||||
// Restore the body so downstream error handling still sees the original
|
||||
@@ -392,30 +398,38 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, bodies map[T
|
||||
// The referenced reasoning items belong to an upstream chain this session
|
||||
// can no longer address (e.g. an interrupted stream). Replay once without
|
||||
// them under a fresh upstream session instead of failing the client
|
||||
// request outright.
|
||||
drainAndClose(resp.Body)
|
||||
// request outright. Attempt numbering continues from the first round so
|
||||
// monitoring never shows duplicate attempt numbers for one request.
|
||||
retryIDs := ids
|
||||
retryIDs.Session = randomID("ses", 12)
|
||||
g.logger.Info("retrying upstream without stale reasoning references", "component", "upstream", "event", "reasoning_reference_retry", "request_id", ids.Request, "model", route.ID, "tier", effectiveRoute.Tier)
|
||||
retryResp, retryRoute, retryErr := g.doUpstreamTiers(ctx, effectiveRoute, stripped, retryIDs)
|
||||
if retryErr != nil || retryResp == nil {
|
||||
g.logger.Warn("reasoning reference retry failed; returning original error", "component", "upstream", "event", "reasoning_reference_retry_failed", "request_id", ids.Request, "model", route.ID, "tier", effectiveRoute.Tier, "error", retryErr)
|
||||
g.logger.Info("retrying upstream without stale reasoning references", "component", "upstream", "event", "reasoning_reference_retry", "request_id", ids.Request, "model", route.ID, "tier", effectiveRoute.Tier, "attempt_offset", attempts)
|
||||
retryResp, retryRoute, _, retryErr := g.doUpstreamTiers(ctx, effectiveRoute, stripped, retryIDs, attempts)
|
||||
if retryErr != nil || retryResp == nil || retryResp.StatusCode/100 != 2 {
|
||||
retryStatus := 0
|
||||
if retryResp != nil {
|
||||
retryStatus = retryResp.StatusCode
|
||||
drainAndClose(retryResp.Body)
|
||||
}
|
||||
g.logger.Warn("reasoning reference retry failed; returning original error", "component", "upstream", "event", "reasoning_reference_retry_failed", "request_id", ids.Request, "model", route.ID, "tier", effectiveRoute.Tier, "error", retryErr, "retry_status", retryStatus)
|
||||
fallback := *resp
|
||||
fallback.Body = io.NopCloser(bytes.NewReader(errBody))
|
||||
return &fallback, effectiveRoute, nil
|
||||
}
|
||||
return retryResp, retryRoute, retryErr
|
||||
return retryResp, retryRoute, nil
|
||||
}
|
||||
|
||||
// isStaleReasoningReference reports whether an upstream 400 body describes a
|
||||
// reasoning reference the server no longer recognizes, such as
|
||||
// reasoning item/reference the server no longer recognizes, such as
|
||||
// "Referenced reasoning item 'rs_...' was not found or has expired".
|
||||
// Generic validation errors that merely mention reasoning (e.g. "unknown
|
||||
// reasoning field") must NOT match, so both the target phrase and the
|
||||
// gone/expired marker are required.
|
||||
func isStaleReasoningReference(body []byte) bool {
|
||||
text := strings.ToLower(string(body))
|
||||
if !strings.Contains(text, "reasoning") {
|
||||
if !strings.Contains(text, "reasoning item") && !strings.Contains(text, "reasoning reference") {
|
||||
return false
|
||||
}
|
||||
for _, marker := range []string{"not found", "expir", "unknown", "no longer", "does not exist", "invalid reference"} {
|
||||
for _, marker := range []string{"not found", "expir", "does not exist", "no longer"} {
|
||||
if strings.Contains(text, marker) {
|
||||
return true
|
||||
}
|
||||
@@ -473,16 +487,16 @@ func stripStaleReasoningInputs(route modelRoute, bodies map[Tier][]byte) (map[Ti
|
||||
return out, changed
|
||||
}
|
||||
|
||||
func (g *Gateway) doUpstreamTiers(ctx context.Context, route modelRoute, bodies map[Tier][]byte, ids requestIDs) (*http.Response, modelRoute, error) {
|
||||
func (g *Gateway) doUpstreamTiers(ctx context.Context, route modelRoute, bodies map[Tier][]byte, ids requestIDs, attemptOffset int) (*http.Response, modelRoute, int, error) {
|
||||
var lastResponse *http.Response
|
||||
var lastErr error
|
||||
effectiveRoute := route
|
||||
attempts := 0
|
||||
attempts := attemptOffset
|
||||
if route.Anonymous {
|
||||
resp, err, used := g.doAnonymousUpstream(ctx, route, bodies, ids)
|
||||
resp, err, used := g.doAnonymousUpstream(ctx, route, bodies, ids, attempts)
|
||||
attempts += used
|
||||
if err == nil && resp != nil && resp.StatusCode/100 == 2 {
|
||||
return resp, route, nil
|
||||
return resp, route, attempts, nil
|
||||
}
|
||||
lastResponse, lastErr = resp, err
|
||||
if len(route.KeyTiers) > 0 {
|
||||
@@ -507,24 +521,24 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route modelRoute, bodies
|
||||
resp, err, used := g.doKeyUpstream(ctx, keyRoute, bodies, ids, attempts)
|
||||
attempts += used
|
||||
if err == nil && resp != nil && resp.StatusCode/100 == 2 {
|
||||
return resp, keyRoute, nil
|
||||
return resp, keyRoute, attempts, nil
|
||||
}
|
||||
lastResponse, lastErr = resp, err
|
||||
}
|
||||
if lastResponse != nil {
|
||||
return lastResponse, effectiveRoute, nil
|
||||
return lastResponse, effectiveRoute, attempts, nil
|
||||
}
|
||||
if lastErr == nil {
|
||||
lastErr = errors.New("no usable upstream route")
|
||||
}
|
||||
return nil, effectiveRoute, lastErr
|
||||
return nil, effectiveRoute, attempts, lastErr
|
||||
}
|
||||
|
||||
// doAnonymousUpstream tries every currently available proxy at most once. Any
|
||||
// failure, including an HTTP error response, advances to the next proxy. Only a
|
||||
// successful response ends the anonymous phase; exhausting the proxy cursor
|
||||
// returns control to the preferred authenticated tiers.
|
||||
func (g *Gateway) doAnonymousUpstream(ctx context.Context, route modelRoute, bodies map[Tier][]byte, ids requestIDs) (*http.Response, error, int) {
|
||||
func (g *Gateway) doAnonymousUpstream(ctx context.Context, route modelRoute, bodies map[Tier][]byte, ids requestIDs, attemptOffset int) (*http.Response, error, int) {
|
||||
var lastResponse *http.Response
|
||||
var lastErr error
|
||||
cursor := g.anonymous.CursorFor(ids.Session)
|
||||
@@ -541,7 +555,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route modelRoute, bod
|
||||
}
|
||||
attempts++
|
||||
if meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta); meta != nil {
|
||||
meta.Attempts = attempts
|
||||
meta.Attempts = attemptOffset + attempts
|
||||
meta.Tier = string(TierZen)
|
||||
}
|
||||
if lastResponse != nil {
|
||||
@@ -561,7 +575,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route modelRoute, bod
|
||||
status = resp.StatusCode
|
||||
}
|
||||
g.syncProxyResult(ctx, node.proxy, status, err)
|
||||
g.recordUpstreamAttempt(route, ids, attempts, "anonymous", "anonymous", true, node.proxy, resp, err, duration)
|
||||
g.recordUpstreamAttempt(route, ids, attemptOffset+attempts, "anonymous", "anonymous", true, node.proxy, resp, err, duration)
|
||||
if err == nil && resp.StatusCode/100 == 2 {
|
||||
g.anonymous.MarkSuccess(node)
|
||||
g.logger.Debug("anonymous upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", TierZen, "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", redactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds())
|
||||
|
||||
+230
-1
@@ -1,7 +1,14 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -12,8 +19,12 @@ func TestIsStaleReasoningReference(t *testing.T) {
|
||||
}{
|
||||
{`{"error":{"message":"Upstream request failed: [invalid_request_error] Referenced reasoning item 'rs_7145a5ca29c1537d081efdb1' was not found or has expired.", "type":"invalid_request_error"}}`, true},
|
||||
{`{"error":{"message":"reasoning item rs_abc has expired", "type":"invalid_request_error"}}`, true},
|
||||
{`{"error":{"message":"Reasoning reference rs_xyz does not exist", "type":"invalid_request_error"}}`, true},
|
||||
// Negative cases: generic errors that merely mention reasoning must not match.
|
||||
{`{"error":{"message":"Model is unavailable.", "type":"upstream_error"}}`, false},
|
||||
{`{"error":{"message":"invalid_request_error: missing field 'model'", "type":"invalid_request_error"}}`, false},
|
||||
{`{"error":{"message":"unknown reasoning field 'foo'", "type":"invalid_request_error"}}`, false},
|
||||
{`{"error":{"message":"invalid reasoning_effort value 'high'", "type":"invalid_request_error"}}`, false},
|
||||
{`{"error":{"message":"request body must be a JSON object", "type":"invalid_request_error"}}`, false},
|
||||
{`not json at all`, false},
|
||||
{``, false},
|
||||
}
|
||||
@@ -62,3 +73,221 @@ func TestStripStaleReasoningInputs(t *testing.T) {
|
||||
t.Error("expected changed=false when no reasoning references exist")
|
||||
}
|
||||
}
|
||||
|
||||
const retryTestStaleError = `{"error":{"message":"Upstream request failed: [invalid_request_error] Referenced reasoning item 'rs_old' was not found or has expired.", "type":"invalid_request_error"}}`
|
||||
|
||||
func retryTestUpstreamBody() []byte {
|
||||
return []byte(`{"model":"test-model","previous_response_id":"resp_123","input":[{"type":"reasoning","id":"rs_old","summary":[{"type":"summary_text","text":"thinking"}]},{"type":"message","role":"user","content":"hi"}]}`)
|
||||
}
|
||||
|
||||
func newRetryTestGateway(t *testing.T, upstreamURL string) *Gateway {
|
||||
t.Helper()
|
||||
cfg := Config{
|
||||
ServerKeys: []string{"test-key"},
|
||||
Anonymous: true,
|
||||
Proxies: []string{"direct"},
|
||||
Upstream: UpstreamConfig{Zen: upstreamURL, Go: upstreamURL},
|
||||
Retry: RetryConfig{MaxAttempts: 3, TimeoutSeconds: 30},
|
||||
Performance: PerformanceConfig{MaxIdleConns: 32, MaxIdleConnsPerHost: 8, ConnectTimeoutSeconds: 5, FailureCooldownSeconds: 1},
|
||||
Prefer: TierZen,
|
||||
Models: ModelsConfig{RefreshSeconds: 300, Protocols: map[string]string{}},
|
||||
Logging: LoggingConfig{Level: "error", RingSize: 100},
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
g, err := NewGateway(cfg, logger, NewMonitor())
|
||||
if err != nil {
|
||||
t.Fatalf("NewGateway: %v", err)
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
func retryTestRoute() modelRoute {
|
||||
return modelRoute{
|
||||
ID: "test-model",
|
||||
Tier: TierZen,
|
||||
Protocol: ProtocolResponses,
|
||||
Protocols: map[Tier]Protocol{TierZen: ProtocolResponses},
|
||||
Anonymous: true,
|
||||
}
|
||||
}
|
||||
|
||||
func retryTestIDs() requestIDs {
|
||||
return requestIDs{Session: "ses_test", Request: "req_test", Project: "prj_test"}
|
||||
}
|
||||
|
||||
func upstreamInputHasReasoning(t *testing.T, raw []byte) bool {
|
||||
t.Helper()
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||||
t.Fatalf("upstream request is not valid JSON: %v", err)
|
||||
}
|
||||
if _, ok := payload["previous_response_id"]; ok {
|
||||
return true
|
||||
}
|
||||
for _, item := range sliceAt(payload, "input") {
|
||||
if m, ok := item.(map[string]any); ok && stringAt(m, "type") == "reasoning" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestDoUpstreamRetriesStaleReasoningSuccess(t *testing.T) {
|
||||
var hits atomic.Int64
|
||||
var secondBody atomic.Value
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
n := hits.Add(1)
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
if n == 1 {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(retryTestStaleError))
|
||||
return
|
||||
}
|
||||
secondBody.Store(body)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"id":"resp_1","status":"completed"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
g := newRetryTestGateway(t, server.URL)
|
||||
resp, _, err := g.doUpstream(context.Background(), retryTestRoute(), map[Tier][]byte{TierZen: retryTestUpstreamBody()}, retryTestIDs())
|
||||
if err != nil {
|
||||
t.Fatalf("doUpstream: %v", err)
|
||||
}
|
||||
defer drainAndClose(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("expected 200 after retry, got %d", resp.StatusCode)
|
||||
}
|
||||
if hits.Load() != 2 {
|
||||
t.Fatalf("expected 2 upstream hits, got %d", hits.Load())
|
||||
}
|
||||
raw, _ := secondBody.Load().([]byte)
|
||||
if upstreamInputHasReasoning(t, raw) {
|
||||
t.Errorf("retry request still carries reasoning references: %s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoUpstreamRetryNon2xxRestoresOriginal(t *testing.T) {
|
||||
var hits atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if hits.Add(1) == 1 {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(retryTestStaleError))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = w.Write([]byte(`{"error":{"message":"boom", "type":"server_error"}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
g := newRetryTestGateway(t, server.URL)
|
||||
resp, _, err := g.doUpstream(context.Background(), retryTestRoute(), map[Tier][]byte{TierZen: retryTestUpstreamBody()}, retryTestIDs())
|
||||
if err != nil {
|
||||
t.Fatalf("doUpstream: %v", err)
|
||||
}
|
||||
defer drainAndClose(resp.Body)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected original 400, got %d", resp.StatusCode)
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if strings.TrimSpace(string(body)) != retryTestStaleError {
|
||||
t.Errorf("expected original error body restored, got %q", body)
|
||||
}
|
||||
if hits.Load() != 2 {
|
||||
t.Fatalf("expected 2 upstream hits, got %d", hits.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoUpstreamNonMatching400PassesThrough(t *testing.T) {
|
||||
var hits atomic.Int64
|
||||
const unavailable = `{"error":{"message":"Model is unavailable.", "type":"upstream_error"}}`
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits.Add(1)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(unavailable))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
g := newRetryTestGateway(t, server.URL)
|
||||
resp, _, err := g.doUpstream(context.Background(), retryTestRoute(), map[Tier][]byte{TierZen: retryTestUpstreamBody()}, retryTestIDs())
|
||||
if err != nil {
|
||||
t.Fatalf("doUpstream: %v", err)
|
||||
}
|
||||
defer drainAndClose(resp.Body)
|
||||
if hits.Load() != 1 {
|
||||
t.Fatalf("expected no retry, got %d upstream hits", hits.Load())
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if strings.TrimSpace(string(body)) != unavailable {
|
||||
t.Errorf("expected passthrough body, got %q", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoUpstreamStaleErrorWithoutReasoningNoRetry(t *testing.T) {
|
||||
var hits atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits.Add(1)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(retryTestStaleError))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
g := newRetryTestGateway(t, server.URL)
|
||||
clean := []byte(`{"model":"test-model","input":[{"type":"message","role":"user","content":"hi"}]}`)
|
||||
resp, _, err := g.doUpstream(context.Background(), retryTestRoute(), map[Tier][]byte{TierZen: clean}, retryTestIDs())
|
||||
if err != nil {
|
||||
t.Fatalf("doUpstream: %v", err)
|
||||
}
|
||||
defer drainAndClose(resp.Body)
|
||||
if hits.Load() != 1 {
|
||||
t.Fatalf("expected no retry when payload has nothing to strip, got %d hits", hits.Load())
|
||||
}
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoUpstreamRetryAttemptsAreCumulative(t *testing.T) {
|
||||
var hits atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if hits.Add(1) == 1 {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(retryTestStaleError))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"id":"resp_1","status":"completed"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
monitor := NewMonitor()
|
||||
cfg := Config{
|
||||
ServerKeys: []string{"test-key"},
|
||||
Anonymous: true,
|
||||
Proxies: []string{"direct"},
|
||||
Upstream: UpstreamConfig{Zen: server.URL, Go: server.URL},
|
||||
Retry: RetryConfig{MaxAttempts: 3, TimeoutSeconds: 30},
|
||||
Performance: PerformanceConfig{MaxIdleConns: 32, MaxIdleConnsPerHost: 8, ConnectTimeoutSeconds: 5, FailureCooldownSeconds: 1},
|
||||
Prefer: TierZen,
|
||||
Models: ModelsConfig{RefreshSeconds: 300, Protocols: map[string]string{}},
|
||||
Logging: LoggingConfig{Level: "error", RingSize: 100},
|
||||
}
|
||||
g, err := NewGateway(cfg, slog.New(slog.NewTextHandler(io.Discard, nil)), monitor)
|
||||
if err != nil {
|
||||
t.Fatalf("NewGateway: %v", err)
|
||||
}
|
||||
resp, _, err := g.doUpstream(context.Background(), retryTestRoute(), map[Tier][]byte{TierZen: retryTestUpstreamBody()}, retryTestIDs())
|
||||
if err != nil {
|
||||
t.Fatalf("doUpstream: %v", err)
|
||||
}
|
||||
drainAndClose(resp.Body)
|
||||
var numbers []int
|
||||
for _, attempt := range monitor.Snapshot().Upstream.Recent {
|
||||
if attempt.RequestID == "req_test" {
|
||||
numbers = append(numbers, attempt.Attempt)
|
||||
}
|
||||
}
|
||||
if len(numbers) != 2 || numbers[0] != 1 || numbers[1] != 2 {
|
||||
t.Errorf("expected cumulative attempt numbers [1 2], got %v", numbers)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user