Merge pull request #9034 from r266-tech/codex/shorten-proxy-network-cooldown

fix(openai): recover sooner after transport reachability failures
This commit is contained in:
Wesley Liddick authored and GitHub committed 2026-11-26 11:46:38 +08:00
commit a55adce0aa
7 files changed
+105 -98

No files matched your search

@@ -12,8 +12,7 @@ import (
)
// gatewayTransportErrorTempUnschedDuration is how long an account is temporarily
// unscheduled after a durable transport failure (matches the OpenAI-side
// openAITransportErrorTempUnschedDuration).
// unscheduled after a durable transport failure on the Anthropic, Bedrock, or Gemini path.
const gatewayTransportErrorTempUnschedDuration = 10 * time.Minute
// gatewayTransportFailoverBody is the Anthropic-format error body attached to
@@ -63,7 +62,7 @@ func (s *GatewayService) handleUpstreamTransportError(ctx context.Context, c *gi
// Transport attempt left local validation; count Ollama Cloud activity.
scheduleOllamaCloudUsageActivity(s.deferredService, account)
if classifyUpstreamTransportError(err).Persistent {
if classifyUpstreamTransportError(err) != upstreamTransportTransient {
s.tempUnscheduleTransportError(ctx, account, safeErr)
}
@@ -45,7 +45,7 @@ func (s *GeminiMessagesCompatService) handleUpstreamTransportError(ctx context.C
return err
}
if classifyUpstreamTransportError(err).Persistent {
if classifyUpstreamTransportError(err) != upstreamTransportTransient {
tempUnscheduleAccountForTransportError(ctx, s.accountRepo, account, safeErr)
}
@@ -14,9 +14,10 @@ import (
"go.uber.org/zap"
)
// openAITransportErrorTempUnschedDuration is how long an account is temporarily
// unscheduled after a durable transport failure (matches tokenRefreshTempUnschedDuration).
const openAITransportErrorTempUnschedDuration = 10 * time.Minute
const (
openAITransportReachabilityCooldown = 30 * time.Second
openAITransportProxyAuthCooldown = 10 * time.Minute
)
// openAITransportFailoverBody is the OpenAI-format error body attached to the
// failover error for a transport-level failure. Kept identical to the legacy
@@ -27,68 +28,51 @@ var openAITransportFailoverBody = []byte(`{"error":{"type":"upstream_error","mes
// upstreamTransportErrorClass describes how to react to a transport-level upstream
// failure — i.e. the HTTP round-trip never completed (proxy / DNS / TCP / TLS
// error, no HTTP status code received).
type upstreamTransportErrorClass struct {
// Persistent marks failures where retrying the same proxy/account is
// pointless: expired or rejected proxy credentials, a dead proxy endpoint,
// or DNS/routing failure. Such accounts should be temporarily unscheduled
// (and alerted on) instead of being repeatedly scheduled into hard failures.
Persistent bool
}
type upstreamTransportErrorClass uint8
// persistentUpstreamTransportErrorMarkers are substrings (matched case-insensitively
// against the raw transport error) that indicate a durable proxy/network fault.
// Matched signals are intentionally specific failure *reasons*, not the operation
// (e.g. we match "connection refused", not "proxyconnect") so that a transient
// failure of the same operation (a proxy timeout) is NOT misclassified as durable.
var persistentUpstreamTransportErrorMarkers = []string{
"authentication failed", // SOCKS5 RFC1929 / proxy credentials rejected (expired account)
"proxy authentication required", // HTTP proxy 407
"connection refused", // proxy/upstream endpoint down
const (
upstreamTransportTransient upstreamTransportErrorClass = iota
upstreamTransportReachability
upstreamTransportProxyAuth
)
// Match specific reachability errors so a proxy timeout keeps its transient classification.
var upstreamReachabilityErrorMarkers = []string{
"connection refused",
"no route to host",
"network is unreachable",
"no such host", // DNS resolution failure (bad/expired proxy hostname)
"no such host",
}
// classifyUpstreamTransportError decides whether a transport-level upstream error
// is durable (Persistent — evict the account + alert) or a transient blip
// (fail over to a healthy account but keep this one schedulable).
//
// Motivating incident: a SOCKS5 proxy whose subscription lapsed returned
// `username/password authentication failed`; the account was nonetheless
// rescheduled on every request, hard-failing users with 502s.
//
// Classification strategy (mirrors sanitizeStreamError in gateway_service.go):
// 1. Typed-error checks first (syscall constants, *net.DNSError) — portable and
// unambiguous.
// 2. String-marker fallback for errors that have no typed form (e.g. the plain
// string returned by golang.org/x/net/proxy for SOCKS5 credential rejection).
// The network-layer string markers ("connection refused", "no route to host",
// "network is unreachable", "no such host") are kept as a cross-platform safety
// net even though the typed checks should cover them on modern Go+Linux.
// classifyUpstreamTransportError distinguishes reachability failures that can
// recover when the network returns from rejected proxy credentials that require
// operator intervention. Prefer typed errors and fall back to transport messages.
func classifyUpstreamTransportError(err error) upstreamTransportErrorClass {
if err == nil {
return upstreamTransportErrorClass{}
return upstreamTransportTransient
}
// — Typed checks (preferred) ——————————————————————————————————————————————
if errors.Is(err, syscall.ECONNREFUSED) ||
errors.Is(err, syscall.EHOSTUNREACH) ||
errors.Is(err, syscall.ENETUNREACH) {
return upstreamTransportErrorClass{Persistent: true}
return upstreamTransportReachability
}
var dnsErr *net.DNSError
if errors.As(err, &dnsErr) && dnsErr.IsNotFound {
return upstreamTransportErrorClass{Persistent: true}
return upstreamTransportReachability
}
// — String-marker fallback ————————————————————————————————————————————————
// SOCKS5 and HTTP CONNECT report rejected credentials as plain errors.
msg := strings.ToLower(err.Error())
for _, marker := range persistentUpstreamTransportErrorMarkers {
if strings.Contains(msg, "authentication failed") || strings.Contains(msg, "proxy authentication required") {
return upstreamTransportProxyAuth
}
for _, marker := range upstreamReachabilityErrorMarkers {
if strings.Contains(msg, marker) {
return upstreamTransportErrorClass{Persistent: true}
return upstreamTransportReachability
}
}
return upstreamTransportErrorClass{}
return upstreamTransportTransient
}
// isClientCanceledTransportError reports whether a transport-level failure was
@@ -103,9 +87,8 @@ func isClientCanceledTransportError(ctx context.Context, err error) bool {
// (Do/DoWithTLS returned a non-HTTP error: proxy/DNS/TCP/TLS). It:
// 1. records the failure in Ops error logs (status 0, kind=request_error),
// except when the client disconnected (see isClientCanceledTransportError);
// 2. for durable faults (expired/rejected proxy creds, dead proxy, DNS/routing)
// temporarily unschedules the account (DB + in-memory) and logs a stable
// warn event that alert rules can key on;
// 2. temporarily unschedules the account (DB + in-memory) for reachability
// failures and rejected proxy credentials, with a cooldown for each class;
// 3. returns an error that is *UpstreamFailoverError (so the handler fails over
// to a healthy account) for all non-canceled errors, or a plain error for
// context.Canceled (client gone — no failover, no eviction).
@@ -150,8 +133,11 @@ func (s *OpenAIGatewayService) handleOpenAIUpstreamTransportError(ctx context.Co
return err
}
if classifyUpstreamTransportError(err).Persistent {
s.tempUnscheduleOpenAITransportError(ctx, account, safeErr)
switch classifyUpstreamTransportError(err) {
case upstreamTransportReachability:
s.tempUnscheduleOpenAITransportError(ctx, account, safeErr, openAITransportReachabilityCooldown)
case upstreamTransportProxyAuth:
s.tempUnscheduleOpenAITransportError(ctx, account, safeErr, openAITransportProxyAuthCooldown)
}
return &UpstreamFailoverError{
@@ -161,7 +147,7 @@ func (s *OpenAIGatewayService) handleOpenAIUpstreamTransportError(ctx context.Co
}
// tempUnscheduleOpenAITransportError marks an account temporarily unschedulable
// after a durable transport failure, both persistently (DB, survives restart)
// after a transport failure, both persistently (DB, survives restart)
// and in-memory (immediate scheduler effect before the DB/account cache propagates).
//
// Log semantics:
@@ -171,14 +157,14 @@ func (s *OpenAIGatewayService) handleOpenAIUpstreamTransportError(ctx context.Co
// accountRepo is nil (in-memory only; no persistence).
// - "openai.account_temp_unscheduled_transport_failed" — DB write attempted
// but returned an error.
func (s *OpenAIGatewayService) tempUnscheduleOpenAITransportError(ctx context.Context, account *Account, safeErr string) {
func (s *OpenAIGatewayService) tempUnscheduleOpenAITransportError(ctx context.Context, account *Account, safeErr string, cooldown time.Duration) {
if s == nil || account == nil {
return
}
if s.cfg != nil && s.cfg.Gateway.DisableOpenAITransportErrorCooldown {
return
}
until := time.Now().Add(openAITransportErrorTempUnschedDuration)
until := time.Now().Add(cooldown)
reason := "upstream transport error (proxy/network): " + safeErr
// Immediate in-memory block so this process skips the account until the
@@ -10,7 +10,9 @@ import (
"net/http"
"net/http/httptest"
"net/url"
"syscall"
"testing"
"testing/synctest"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
@@ -49,7 +51,7 @@ func TestHandleOpenAIUpstreamTransportError_DNSCooldownConfig(t *testing.T) {
Err: "no such host", Name: "chatgpt.com", Server: "127.0.0.11:53", IsNotFound: true,
}},
}
require.True(t, classifyUpstreamTransportError(transportErr).Persistent)
require.Equal(t, upstreamTransportReachability, classifyUpstreamTransportError(transportErr))
for _, testCase := range []struct {
name string
cfg *config.Config
@@ -104,13 +106,13 @@ func TestHandleOpenAIUpstreamTransportError_DNSCooldownConfig(t *testing.T) {
} else {
blockUntil, exists := svc.openaiAccountRuntimeBlockUntil.Load(account.ID)
require.True(t, exists)
require.WithinRange(t, blockUntil.(time.Time), before.Add(10*time.Minute), after.Add(10*time.Minute))
require.WithinRange(t, blockUntil.(time.Time), before.Add(30*time.Second), after.Add(30*time.Second))
}
if withRepo && !testCase.disabled {
require.Len(t, repo.tempUnschedCalls, 1)
call := repo.tempUnschedCalls[0]
require.Equal(t, account.ID, call.accountID)
require.WithinRange(t, call.until, before.Add(10*time.Minute), after.Add(10*time.Minute))
require.WithinRange(t, call.until, before.Add(30*time.Second), after.Add(30*time.Second))
require.Contains(t, call.reason, "no such host")
} else {
require.Empty(t, repo.tempUnschedCalls)
@@ -121,13 +123,38 @@ func TestHandleOpenAIUpstreamTransportError_DNSCooldownConfig(t *testing.T) {
}
}
func TestHandleOpenAIUpstreamTransportError_RefusedProxyAllowsPromptRecovery(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
repo := &openaiTransportAccountRepoStub{}
svc := &OpenAIGatewayService{accountRepo: repo}
account := &Account{ID: 9006, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true}
c, _ := newOpenAITransportErrTestContext()
transportErr := &url.Error{
Op: "Post",
URL: "https://upstream.example.test/v1/responses",
Err: &net.OpError{Op: "proxyconnect", Net: "tcp", Err: syscall.ECONNREFUSED},
}
var failover *UpstreamFailoverError
require.ErrorAs(t, svc.handleOpenAIUpstreamTransportError(context.Background(), c, account, transportErr, false), &failover)
require.Len(t, repo.tempUnschedCalls, 1)
account.TempUnschedulableUntil = &repo.tempUnschedCalls[0].until
require.False(t, account.IsSchedulable())
require.True(t, svc.isOpenAIAccountRuntimeBlocked(account))
time.Sleep(31 * time.Second)
require.True(t, account.IsSchedulable(), "a recovered proxy should become eligible after the reachability cooldown")
require.False(t, svc.isOpenAIAccountRuntimeBlocked(account))
})
}
func TestTempUnscheduleOpenAITransportError_DisabledPreservesExistingState(t *testing.T) {
for _, paused := range []bool{false, true} {
t.Run(fmt.Sprintf("paused=%t", paused), func(t *testing.T) {
repo := &openaiTransportAccountRepoStub{}
svc := &OpenAIGatewayService{accountRepo: repo, cfg: &config.Config{}}
account := &Account{ID: 8541, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: !paused}
svc.tempUnscheduleOpenAITransportError(context.Background(), account, "previous failure")
svc.tempUnscheduleOpenAITransportError(context.Background(), account, "previous failure", openAITransportProxyAuthCooldown)
require.Len(t, repo.tempUnschedCalls, 1)
previousCall := repo.tempUnschedCalls[0]
persistedUntil := previousCall.until
@@ -139,7 +166,7 @@ func TestTempUnscheduleOpenAITransportError_DisabledPreservesExistingState(t *te
previousGeneration, _ := svc.openaiAccountRuntimeBlockGeneration.Load(account.ID)
svc.cfg.Gateway.DisableOpenAITransportErrorCooldown = true
svc.tempUnscheduleOpenAITransportError(context.Background(), account, "new failure")
svc.tempUnscheduleOpenAITransportError(context.Background(), account, "new failure", openAITransportReachabilityCooldown)
require.Equal(t, []tempUnschedCall{previousCall}, repo.tempUnschedCalls)
require.Equal(t, previousAccount, *account)
@@ -205,8 +232,7 @@ func TestHandleOpenAIUpstreamTransportError_PersistentEvictsAndFailsOver(t *test
require.Len(t, repo.tempUnschedCalls, 1)
require.Equal(t, int64(4627), repo.tempUnschedCalls[0].accountID)
require.Contains(t, repo.tempUnschedCalls[0].reason, "authentication failed")
require.True(t, repo.tempUnschedCalls[0].until.After(before.Add(openAITransportErrorTempUnschedDuration-time.Second)))
require.True(t, repo.tempUnschedCalls[0].until.Before(after.Add(openAITransportErrorTempUnschedDuration+time.Second)))
require.WithinRange(t, repo.tempUnschedCalls[0].until, before.Add(10*time.Minute), after.Add(10*time.Minute))
// Immediate in-memory effect so subsequent requests skip it before DB/cache catches up.
require.True(t, svc.isOpenAIAccountRuntimeBlocked(account))
@@ -293,7 +319,7 @@ func TestTempUnscheduleOpenAITransportError_NilAccountRepo_InMemoryBlockOnly(t *
svc := &OpenAIGatewayService{accountRepo: nil}
account := &Account{ID: 55, Name: "no-db", Platform: PlatformOpenAI}
svc.tempUnscheduleOpenAITransportError(context.Background(), account, "proxy refused")
svc.tempUnscheduleOpenAITransportError(context.Background(), account, "proxy refused", openAITransportReachabilityCooldown)
// In-memory block must still happen.
require.True(t, svc.isOpenAIAccountRuntimeBlocked(account),
@@ -11,33 +11,29 @@ import (
"testing"
)
// TestClassifyUpstreamTransportError pins which transport-level upstream failures
// are "persistent" (retrying the same proxy/account is pointless — evict + alert)
// versus "transient" (a blip — fail over to a healthy account but do not evict).
//
// The motivating incident: a SOCKS5 proxy whose credentials expired returned
// `username/password authentication failed`, yet the account kept being scheduled.
// TestClassifyUpstreamTransportError covers proxy authentication and network
// reachability failures in both typed errors and transport error messages.
func TestClassifyUpstreamTransportError(t *testing.T) {
cases := []struct {
name string
err error
persistent bool
name string
err error
want upstreamTransportErrorClass
}{
// Durable — config/credential/routing problems. Retrying same proxy won't help.
{"socks5 proxy credential rejected", errors.New(`Post "https://chatgpt.com/backend-api/codex/responses": socks connect tcp 85.255.176.68:12324->chatgpt.com:443: username/password authentication failed`), true},
{"proxy connection refused", errors.New(`proxyconnect tcp: dial tcp 1.2.3.4:1080: connect: connection refused`), true},
{"no route to host", errors.New(`dial tcp 1.2.3.4:443: connect: no route to host`), true},
{"dns resolution failure", errors.New(`dial tcp: lookup proxy.example.com: no such host`), true},
{"network unreachable", errors.New(`dial tcp 1.2.3.4:443: connect: network is unreachable`), true},
{"socks5 proxy credential rejected", errors.New(`socks connect: username/password authentication failed`), upstreamTransportProxyAuth},
{"HTTP CONNECT proxy credential rejected", errors.New(`Proxy Authentication Required`), upstreamTransportProxyAuth},
{"proxy connection refused", errors.New(`proxyconnect tcp: dial tcp 1.2.3.4:1080: connect: connection refused`), upstreamTransportReachability},
{"no route to host", errors.New(`dial tcp 1.2.3.4:443: connect: no route to host`), upstreamTransportReachability},
{"dns resolution failure", errors.New(`dial tcp: lookup proxy.example.com: no such host`), upstreamTransportReachability},
{"network unreachable", errors.New(`dial tcp 1.2.3.4:443: connect: network is unreachable`), upstreamTransportReachability},
// Transient — a temporary blip. Fail over, but do NOT evict the account.
{"client timeout", errors.New(`Post "https://chatgpt.com/...": context deadline exceeded (Client.Timeout exceeded while awaiting headers)`), false},
{"i/o timeout", errors.New(`dial tcp 1.2.3.4:443: i/o timeout`), false},
{"connection reset by peer", errors.New(`read tcp 10.0.0.1:5->2.2.2.2:443: read: connection reset by peer`), false},
{"unexpected eof", errors.New(`unexpected EOF`), false},
{"broken pipe", errors.New(`write tcp 10.0.0.1:5->2.2.2.2:443: write: broken pipe`), false},
{"client timeout", errors.New(`Post "https://chatgpt.com/...": context deadline exceeded (Client.Timeout exceeded while awaiting headers)`), upstreamTransportTransient},
{"i/o timeout", errors.New(`dial tcp 1.2.3.4:443: i/o timeout`), upstreamTransportTransient},
{"connection reset by peer", errors.New(`read tcp 10.0.0.1:5->2.2.2.2:443: read: connection reset by peer`), upstreamTransportTransient},
{"unexpected eof", errors.New(`unexpected EOF`), upstreamTransportTransient},
{"broken pipe", errors.New(`write tcp 10.0.0.1:5->2.2.2.2:443: write: broken pipe`), upstreamTransportTransient},
{"nil error", nil, false},
{"nil error", nil, upstreamTransportTransient},
// ── Typed-error cases ──────────────────────────────────────────────
// ECONNREFUSED wrapped in the canonical net.OpError shape Go produces.
@@ -48,37 +44,37 @@ func TestClassifyUpstreamTransportError(t *testing.T) {
Net: "tcp",
Err: &os.SyscallError{Syscall: "connect", Err: syscall.ECONNREFUSED},
},
true,
upstreamTransportReachability,
},
// Bare syscall error (errors.Is traverses the chain).
{"ECONNREFUSED bare", syscall.ECONNREFUSED, true},
{"EHOSTUNREACH bare", syscall.EHOSTUNREACH, true},
{"ENETUNREACH bare", syscall.ENETUNREACH, true},
{"ECONNREFUSED bare", syscall.ECONNREFUSED, upstreamTransportReachability},
{"EHOSTUNREACH bare", syscall.EHOSTUNREACH, upstreamTransportReachability},
{"ENETUNREACH bare", syscall.ENETUNREACH, upstreamTransportReachability},
// *net.DNSError with IsNotFound — permanent DNS lookup failure.
{
"DNS not found (IsNotFound=true)",
&net.DNSError{Err: "no such host", Name: "proxy.example.com", IsNotFound: true},
true,
upstreamTransportReachability,
},
// *net.DNSError with IsNotFound=false — transient DNS timeout (not persistent).
{
"DNS timeout (IsNotFound=false)",
&net.DNSError{Err: "i/o timeout", Name: "proxy.example.com", IsTimeout: true},
false,
upstreamTransportTransient,
},
// context.Canceled — client gone; NOT classified as persistent.
{"context.Canceled", context.Canceled, false},
{"context.Canceled", context.Canceled, upstreamTransportTransient},
// context.DeadlineExceeded — slow upstream; NOT persistent.
{"context.DeadlineExceeded", context.DeadlineExceeded, false},
{"context.DeadlineExceeded", context.DeadlineExceeded, upstreamTransportTransient},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := classifyUpstreamTransportError(tc.err).Persistent
if got != tc.persistent {
t.Fatalf("classifyUpstreamTransportError(%q).Persistent = %v, want %v", errString(tc.err), got, tc.persistent)
got := classifyUpstreamTransportError(tc.err)
if got != tc.want {
t.Fatalf("classifyUpstreamTransportError(%q) = %v, want %v", errString(tc.err), got, tc.want)
}
})
}
+1 -1
View File
@@ -307,7 +307,7 @@ GATEWAY_OPENAI_COMPACT_MODEL=gpt-5.5
SUB2API_IMAGES_MAIN_MODEL=gpt-5.6-luna
# OpenAI/Codex 等待上游响应头超时(秒);0 表示不使用本地响应头超时截断。
GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=0
# Disable only the fixed 10-minute account cooldown for persistent OpenAI DNS/proxy/network failures.
# Disable OpenAI gateway transport cooldowns (30 seconds for network reachability, 10 minutes for rejected proxy credentials).
# YAML: gateway.disable_openai_transport_error_cooldown; false preserves the default protection.
# Ops/errors and bounded failover remain; other cooldowns, existing state and admin pauses are unchanged.
# Later requests retry broken shared egress; this is not a DNS/proxy repair or a model speed guarantee.
+1 -1
View File
@@ -239,7 +239,7 @@ gateway:
# OpenAI/Codex upstream response header timeout (seconds, 0=disabled)
# OpenAI/Codex 等待上游响应头超时时间(秒,0=禁用本地响应头超时)
openai_response_header_timeout: 0
# Opt out of the fixed 10-minute account cooldown for persistent OpenAI transport failures (DNS/proxy/network).
# Opt out of OpenAI gateway transport cooldowns (30 seconds for network reachability, 10 minutes for rejected proxy credentials).
# Env: GATEWAY_DISABLE_OPENAI_TRANSPORT_ERROR_COOLDOWN=true; default false retains protection.
# Errors/Ops and bounded request failover remain; HTTP 401/403/429, quota/model limits,
# stream timeouts and token-refresh cooldowns are unchanged. Existing cooldowns and admin pauses are not cleared.