mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 00:01:05 +00:00
fix: cool accounts after non-streaming idle responses
This commit is contained in:
1 parent
17cc78391e
commit
d7fca59d68
15 files changed
+516
-12
No files matched your search
@@ -180,7 +180,9 @@ func newTransportUpstreamFailure(err error, accountID uint64, accountName string
|
||||
if neterrorpkg.IsResponseHeaderTimeout(err) {
|
||||
status, code, message = http.StatusGatewayTimeout, "upstream_header_timeout", "等待上游响应头超时"
|
||||
} else if neterrorpkg.IsUpstreamStreamIdleTimeout(err) {
|
||||
status, code, message = http.StatusGatewayTimeout, "upstream_stream_idle_timeout", "上游流式响应长时间无数据"
|
||||
status, code, message = http.StatusGatewayTimeout, "upstream_stream_idle_timeout", "上游响应长时间无数据"
|
||||
} else if neterrorpkg.IsUpstreamResponseEmpty(err) {
|
||||
status, code, message = http.StatusBadGateway, "upstream_response_empty", "上游响应为空"
|
||||
} else if errors.Is(err, errQualityEmptyStream) {
|
||||
status, code, message = http.StatusBadGateway, "upstream_stream_empty", "上游流式响应为空"
|
||||
} else if errors.Is(err, context.DeadlineExceeded) {
|
||||
|
||||
@@ -31,6 +31,13 @@ func TestTransportUpstreamFailureClassifiesProviderStreamIdleTimeout(t *testing.
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransportUpstreamFailureClassifiesEmptyResponse(t *testing.T) {
|
||||
failure := newTransportUpstreamFailure(neterror.ErrUpstreamResponseEmpty, 42, "build")
|
||||
if failure.HTTPStatus != http.StatusBadGateway || failure.Code != "upstream_response_empty" || failure.AccountScoped {
|
||||
t.Fatalf("failure = %#v", failure)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransportUpstreamFailureClassifiesResponseHeaderTimeout(t *testing.T) {
|
||||
failure := newTransportUpstreamFailure(responseHeaderTimeoutTestError{}, 42, "build")
|
||||
if failure.HTTPStatus != http.StatusGatewayTimeout || failure.Code != "upstream_header_timeout" || failure.PublicMessage != "等待上游响应头超时" || failure.AuditCode() != "upstream_header_timeout" {
|
||||
|
||||
@@ -1324,9 +1324,25 @@ attemptLoop:
|
||||
if !isRetryableTransportFailure(credential.Provider, err) {
|
||||
break
|
||||
}
|
||||
if !neterrorpkg.IsUpstreamStreamIdleTimeout(err) {
|
||||
responseFailure := false
|
||||
if status, retryAfter, classified := upstreamResponseErrorHealthPenalty(err, holdCfg.IdleAccountCooldown); classified {
|
||||
responseFailure = true
|
||||
writeCtx, writeCancel := context.WithTimeout(context.WithoutCancel(ctx), finalizationTimeout)
|
||||
markErr := s.selector.MarkFailureAfterSuccess(writeCtx, credential, status, retryAfter)
|
||||
writeCancel()
|
||||
if markErr != nil {
|
||||
s.logger.Warn("upstream_response_health_write_failed", "request_id", input.RequestID, "account_id", credential.ID, "error", markErr)
|
||||
} else {
|
||||
s.logger.Warn("upstream_response_health_retry", "request_id", input.RequestID, "account_id", credential.ID, "status", status, "minimum_cooldown", retryAfter)
|
||||
}
|
||||
} else {
|
||||
s.selector.MarkFailure(ctx, credential, 0, 0)
|
||||
}
|
||||
// The failed response is safe to retry on another account only when
|
||||
// doing so cannot repeat an upstream-hosted tool side effect.
|
||||
if responseFailure && qualityRequestHasReplayUnsafeHostedTools(input.Body) {
|
||||
break attemptLoop
|
||||
}
|
||||
if shouldStopForNonAccountFingerprint(failureFingerprints, lastFailure) {
|
||||
break
|
||||
}
|
||||
@@ -1729,7 +1745,7 @@ attemptLoop:
|
||||
|
||||
func isUpstreamStreamFailure(errorCode string) bool {
|
||||
switch errorCode {
|
||||
case "upstream_stream_incomplete", "upstream_stream_interrupted", "upstream_stream_idle_timeout":
|
||||
case "upstream_stream_incomplete", "upstream_stream_interrupted", "upstream_stream_idle_timeout", "upstream_response_empty":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
@@ -1737,15 +1753,39 @@ func isUpstreamStreamFailure(errorCode string) bool {
|
||||
}
|
||||
|
||||
func streamFailureHealthPenalty(errorCode string, usage Usage, idleCooldown time.Duration) (int, time.Duration) {
|
||||
if errorCode == "upstream_stream_idle_timeout" && !usage.OutputObserved && usage.OutputTokens == 0 && usage.ReasoningTokens == 0 {
|
||||
if (errorCode == "upstream_stream_idle_timeout" || errorCode == "upstream_response_empty") && !usage.OutputObserved && usage.OutputTokens == 0 && usage.ReasoningTokens == 0 {
|
||||
if idleCooldown <= 0 {
|
||||
idleCooldown = qualityIdleAccountCooldown
|
||||
}
|
||||
if errorCode == "upstream_response_empty" {
|
||||
return http.StatusBadGateway, idleCooldown
|
||||
}
|
||||
return http.StatusGatewayTimeout, idleCooldown
|
||||
}
|
||||
return 0, 0
|
||||
}
|
||||
|
||||
// upstreamResponseErrorHealthPenalty classifies failures that happen after a
|
||||
// successful response header but before a usable non-streaming body exists.
|
||||
// A truly empty response receives the configured long cooldown. If some body
|
||||
// bytes arrived before an idle timeout, retain only the ordinary short network
|
||||
// cooldown by returning a zero status/retry pair.
|
||||
func upstreamResponseErrorHealthPenalty(err error, idleCooldown time.Duration) (int, time.Duration, bool) {
|
||||
switch {
|
||||
case neterrorpkg.IsUpstreamResponseEmpty(err):
|
||||
status, cooldown := streamFailureHealthPenalty("upstream_response_empty", Usage{}, idleCooldown)
|
||||
return status, cooldown, true
|
||||
case neterrorpkg.IsUpstreamStreamIdleTimeout(err):
|
||||
if neterrorpkg.IdleTimeoutObservedData(err) {
|
||||
return 0, 0, true
|
||||
}
|
||||
status, cooldown := streamFailureHealthPenalty("upstream_stream_idle_timeout", Usage{}, idleCooldown)
|
||||
return status, cooldown, true
|
||||
default:
|
||||
return 0, 0, false
|
||||
}
|
||||
}
|
||||
|
||||
// auditRequestSucceeded keeps transport truth (the HTTP status) separate from
|
||||
// the terminal request outcome. A stream that fails after 2xx headers is not a
|
||||
// successful request even though its HTTP status remains 2xx.
|
||||
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/runtime/memory"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
neterrorpkg "github.com/chenyme/grok2api/backend/internal/pkg/neterror"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/requestmeta"
|
||||
"github.com/chenyme/grok2api/backend/internal/repository"
|
||||
)
|
||||
@@ -593,6 +594,113 @@ func TestGatewayBuildResponseHeaderTimeoutDoesNotSwitchAccounts(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayNonStreamingEmptyIdleCoolsAccountAndSwitches(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "gateway-non-stream-idle.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accountRepo := relational.NewAccountRepository(database)
|
||||
modelRepo := relational.NewModelRepository(database)
|
||||
auditRepo := relational.NewAuditRepository(database)
|
||||
responseRepo := relational.NewResponseRepository(database)
|
||||
keyRepo := relational.NewClientKeyRepository(database)
|
||||
credentials := make([]account.Credential, 0, 2)
|
||||
for index, name := range []string{"empty-idle", "healthy"} {
|
||||
credential, _, createErr := accountRepo.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderBuild, Name: name, SourceKey: name, EncryptedAccessToken: "encrypted-" + name,
|
||||
ExpiresAt: time.Now().Add(time.Hour), Enabled: true, AuthStatus: account.AuthStatusActive,
|
||||
Priority: 200 - index*100, MaxConcurrent: 1,
|
||||
})
|
||||
if createErr != nil {
|
||||
t.Fatal(createErr)
|
||||
}
|
||||
credentials = append(credentials, credential)
|
||||
}
|
||||
const model = "grok-non-stream-idle"
|
||||
if err := modelRepo.UpsertDiscovered(ctx, account.ProviderBuild, []string{model}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, credential := range credentials {
|
||||
if err := modelRepo.ReplaceAccountCapabilities(ctx, credential.ID, []string{model}, time.Now().UTC()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
key, err := keyRepo.Create(ctx, clientkey.Key{
|
||||
Name: "non-stream-idle", Prefix: "idle", SecretHash: strings.Repeat("8", 64), EncryptedSecret: "encrypted",
|
||||
Enabled: true, RPMLimit: 60, MaxConcurrent: 4,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
adapter := &failoverAdapter{transportErrorIDs: map[uint64]error{credentials[0].ID: &neterrorpkg.IdleTimeoutError{}}}
|
||||
registry := provider.NewRegistry(adapter)
|
||||
sticky := memory.NewStickyStore()
|
||||
accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil)
|
||||
selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute)
|
||||
service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(keyRepo, nil, nil, 60, 4, nil), registry, selector, responseRepo, 3)
|
||||
service.UpdateQualityRetry(QualityRetryRuntime{Enabled: false, IdleAccountCooldown: 7 * time.Minute})
|
||||
|
||||
result, err := service.CreateResponse(ctx, Input{
|
||||
RequestID: "req-non-stream-idle", ClientKey: key, PublicModel: model,
|
||||
Body: []byte(`{"model":"grok-non-stream-idle","input":"hello","stream":false}`), Streaming: false,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = io.ReadAll(result.Body)
|
||||
result.Finalize(Usage{}, "resp-non-stream-idle", "")
|
||||
_ = result.Body.Close()
|
||||
if len(adapter.attempts) != 2 || adapter.attempts[0] != credentials[0].ID || adapter.attempts[1] != credentials[1].ID {
|
||||
t.Fatalf("attempts = %#v", adapter.attempts)
|
||||
}
|
||||
cooled, err := accountRepo.Get(ctx, credentials[0].ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cooled.FailureCount != 1 || cooled.CooldownUntil == nil || cooled.LastError != "upstream status 504" {
|
||||
t.Fatalf("cooled account = %#v", cooled)
|
||||
}
|
||||
remaining := time.Until(*cooled.CooldownUntil)
|
||||
if remaining < 6*time.Minute || remaining > 8*time.Minute {
|
||||
t.Fatalf("idle cooldown = %s, want about 7m", remaining)
|
||||
}
|
||||
|
||||
// The same health penalty must apply without replaying a hosted tool, whose
|
||||
// execution may already have started upstream before the response went idle.
|
||||
if err := accountRepo.UpdateHealth(ctx, credentials[0].ID, account.ProviderBuild, 0, nil, "", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
adapter.resetAttempts()
|
||||
unsafeSticky := memory.NewStickyStore()
|
||||
unsafeAccountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), unsafeSticky, registry, testCipher(t), nil)
|
||||
unsafeSelector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), unsafeSticky, registry, time.Hour, time.Second, time.Minute)
|
||||
unsafeService := NewService(modelRepo, auditRepo, unsafeAccountService, clientkeyapp.NewService(keyRepo, nil, nil, 60, 4, nil), registry, unsafeSelector, responseRepo, 3)
|
||||
unsafeService.UpdateQualityRetry(QualityRetryRuntime{Enabled: false, IdleAccountCooldown: 7 * time.Minute})
|
||||
|
||||
_, err = unsafeService.CreateResponse(ctx, Input{
|
||||
RequestID: "req-non-stream-idle-hosted-tool", ClientKey: key, PublicModel: model,
|
||||
Body: []byte(`{"model":"grok-non-stream-idle","input":"hello","stream":false,"tools":[{"type":"web_search"}]}`), Streaming: false,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected hosted-tool idle failure")
|
||||
}
|
||||
if len(adapter.attempts) != 1 || adapter.attempts[0] != credentials[0].ID {
|
||||
t.Fatalf("hosted-tool attempts = %#v, want only account %d", adapter.attempts, credentials[0].ID)
|
||||
}
|
||||
cooled, err = accountRepo.Get(ctx, credentials[0].ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cooled.CooldownUntil == nil || cooled.LastError != "upstream status 504" {
|
||||
t.Fatalf("hosted-tool account health = %#v", cooled)
|
||||
}
|
||||
}
|
||||
|
||||
type blockingHealthAccountRepository struct {
|
||||
repository.AccountRepository
|
||||
started chan struct{}
|
||||
@@ -4565,6 +4673,9 @@ func TestIsUpstreamStreamFailureIncludesIdleTimeout(t *testing.T) {
|
||||
if !isUpstreamStreamFailure("upstream_stream_interrupted") || !isUpstreamStreamFailure("upstream_stream_incomplete") {
|
||||
t.Fatal("existing stream-failure codes must stay classified")
|
||||
}
|
||||
if !isUpstreamStreamFailure("upstream_response_empty") {
|
||||
t.Fatal("empty non-streaming response must update account health after handoff")
|
||||
}
|
||||
if isUpstreamStreamFailure("") || isUpstreamStreamFailure("quality_degraded") {
|
||||
t.Fatal("non-stream codes must not look like mid-stream failures")
|
||||
}
|
||||
@@ -4590,4 +4701,26 @@ func TestStreamFailureHealthPenaltyOnlyLongCoolsTrulyEmptyIdle(t *testing.T) {
|
||||
t.Fatalf("non-empty idle usage %#v received long penalty (%d, %s)", usage, status, cooldown)
|
||||
}
|
||||
}
|
||||
status, cooldown = streamFailureHealthPenalty("upstream_response_empty", Usage{}, 15*time.Minute)
|
||||
if status != http.StatusBadGateway || cooldown != 15*time.Minute {
|
||||
t.Fatalf("empty response penalty = (%d, %s)", status, cooldown)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpstreamResponseErrorHealthPenaltyDistinguishesPartialIdle(t *testing.T) {
|
||||
status, cooldown, ok := upstreamResponseErrorHealthPenalty(&neterrorpkg.IdleTimeoutError{}, 15*time.Minute)
|
||||
if !ok || status != http.StatusGatewayTimeout || cooldown != 15*time.Minute {
|
||||
t.Fatalf("empty idle penalty = (%d, %s, %t)", status, cooldown, ok)
|
||||
}
|
||||
status, cooldown, ok = upstreamResponseErrorHealthPenalty(&neterrorpkg.IdleTimeoutError{DataObserved: true}, 15*time.Minute)
|
||||
if !ok || status != 0 || cooldown != 0 {
|
||||
t.Fatalf("partial idle penalty = (%d, %s, %t)", status, cooldown, ok)
|
||||
}
|
||||
status, cooldown, ok = upstreamResponseErrorHealthPenalty(neterrorpkg.ErrUpstreamResponseEmpty, 15*time.Minute)
|
||||
if !ok || status != http.StatusBadGateway || cooldown != 15*time.Minute {
|
||||
t.Fatalf("empty body penalty = (%d, %s, %t)", status, cooldown, ok)
|
||||
}
|
||||
if _, _, ok = upstreamResponseErrorHealthPenalty(context.DeadlineExceeded, 15*time.Minute); ok {
|
||||
t.Fatal("ordinary timeout must not look like a confirmed response-body failure")
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,9 @@ import (
|
||||
infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider/conversation"
|
||||
providerstreamidle "github.com/chenyme/grok2api/backend/internal/infra/provider/streamidle"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
neterrorpkg "github.com/chenyme/grok2api/backend/internal/pkg/neterror"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/reasoningreplay"
|
||||
)
|
||||
|
||||
@@ -421,6 +423,9 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
if readErr != nil {
|
||||
return nil, readErr
|
||||
}
|
||||
if len(bytes.TrimSpace(data)) == 0 {
|
||||
return nil, neterrorpkg.ErrUpstreamResponseEmpty
|
||||
}
|
||||
if len(data) > maxCompatibleResponseBytes {
|
||||
return nil, fmt.Errorf("上游兼容 Responses 响应超过 128 MiB")
|
||||
}
|
||||
@@ -451,6 +456,9 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
if readErr != nil {
|
||||
return nil, readErr
|
||||
}
|
||||
if resp.StatusCode >= 200 && resp.StatusCode < 300 && len(bytes.TrimSpace(data)) == 0 {
|
||||
return nil, neterrorpkg.ErrUpstreamResponseEmpty
|
||||
}
|
||||
if resp.StatusCode >= 200 && resp.StatusCode < 300 && len(data) > 64<<20 {
|
||||
return nil, fmt.Errorf("上游对话响应超过 64 MiB")
|
||||
}
|
||||
@@ -553,10 +561,35 @@ func (a *Adapter) doResponseRequest(ctx context.Context, request provider.Respon
|
||||
if request.IdempotencyID != "" {
|
||||
req.Header.Set("Idempotency-Key", request.IdempotencyID)
|
||||
}
|
||||
// Streaming requests already receive transport/semantic idle protection.
|
||||
// Non-streaming text inference needs its own cancel-cause-aware body timer:
|
||||
// ResponseHeaderTimeout stops once headers arrive and cannot interrupt a
|
||||
// server that then leaves the JSON body silent indefinitely. Create the
|
||||
// derived context only after every fallible request-construction step so
|
||||
// every remaining path either cancels it or transfers ownership to the body.
|
||||
var responseIdleCancel context.CancelCauseFunc
|
||||
responseIdle := a.config().StreamIdleTimeout
|
||||
if !request.Streaming && responseIdle > 0 {
|
||||
requestCtx, responseIdleCancel = context.WithCancelCause(requestCtx)
|
||||
req = req.WithContext(requestCtx)
|
||||
}
|
||||
resp, err := a.http.Do(req)
|
||||
if err != nil {
|
||||
if responseIdleCancel != nil {
|
||||
responseIdleCancel(nil)
|
||||
}
|
||||
return nil, "", err
|
||||
}
|
||||
if responseIdleCancel != nil {
|
||||
switch {
|
||||
case resp.Body == nil:
|
||||
responseIdleCancel(nil)
|
||||
case isHTTPSuccess(resp.StatusCode):
|
||||
resp.Body = providerstreamidle.New(resp.Body, responseIdle, responseIdleCancel)
|
||||
default:
|
||||
resp.Body = &cancelOnCloseReadCloser{ReadCloser: resp.Body, cancel: responseIdleCancel}
|
||||
}
|
||||
}
|
||||
return resp, req.URL.String(), nil
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider/conversation"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/runtime/memory"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/neterror"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/reasoningreplay"
|
||||
)
|
||||
|
||||
@@ -98,6 +99,84 @@ func TestAdapterDefaultsStreamIdleTimeout(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNonStreamingConversationResponseHealthBoundaries(t *testing.T) {
|
||||
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
encrypted, err := cipher.Encrypt("access-token")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := provider.ResponseResourceRequest{
|
||||
Credential: account.Credential{ID: 7, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted},
|
||||
Method: http.MethodPost, Path: "/responses", Model: "grok-4.5", Operation: conversation.OperationChat,
|
||||
NormalizeBody: true, Streaming: false,
|
||||
Body: []byte(`{"model":"grok-4.5","messages":[{"role":"user","content":"hello"}]}`),
|
||||
}
|
||||
|
||||
t.Run("internal idle deadline", func(t *testing.T) {
|
||||
adapter := NewAdapter(Config{BaseURL: "https://build.example/v1", StreamIdleTimeout: 25 * time.Millisecond}, cipher)
|
||||
adapter.http.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK, Status: "200 OK", Header: http.Header{"Content-Type": {"application/json"}},
|
||||
Body: &contextBlockingResponseBody{ctx: req.Context()}, Request: req,
|
||||
}, nil
|
||||
})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
|
||||
defer cancel()
|
||||
started := time.Now()
|
||||
_, err := adapter.ForwardResponse(ctx, request)
|
||||
if !errors.Is(err, neterror.ErrUpstreamStreamIdleTimeout) || neterror.IdleTimeoutObservedData(err) {
|
||||
t.Fatalf("idle error = %#v, observed=%t", err, neterror.IdleTimeoutObservedData(err))
|
||||
}
|
||||
if elapsed := time.Since(started); elapsed >= 250*time.Millisecond {
|
||||
t.Fatalf("idle timeout took %s; parent deadline was used", elapsed)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("client cancellation remains cancellation", func(t *testing.T) {
|
||||
adapter := NewAdapter(Config{BaseURL: "https://build.example/v1", StreamIdleTimeout: time.Second}, cipher)
|
||||
adapter.http.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK, Status: "200 OK", Header: http.Header{"Content-Type": {"application/json"}},
|
||||
Body: &contextBlockingResponseBody{ctx: req.Context()}, Request: req,
|
||||
}, nil
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
time.AfterFunc(20*time.Millisecond, cancel)
|
||||
_, err := adapter.ForwardResponse(ctx, request)
|
||||
if !errors.Is(err, context.Canceled) || neterror.IsUpstreamStreamIdleTimeout(err) {
|
||||
t.Fatalf("client cancellation error = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty successful body", func(t *testing.T) {
|
||||
adapter := NewAdapter(Config{BaseURL: "https://build.example/v1", StreamIdleTimeout: time.Second}, cipher)
|
||||
adapter.http.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK, Status: "200 OK", Header: http.Header{"Content-Type": {"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader("")), Request: req,
|
||||
}, nil
|
||||
})
|
||||
_, err := adapter.ForwardResponse(context.Background(), request)
|
||||
if !errors.Is(err, neterror.ErrUpstreamResponseEmpty) {
|
||||
t.Fatalf("empty body error = %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type contextBlockingResponseBody struct {
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func (b *contextBlockingResponseBody) Read([]byte) (int, error) {
|
||||
<-b.ctx.Done()
|
||||
return 0, b.ctx.Err()
|
||||
}
|
||||
|
||||
func (*contextBlockingResponseBody) Close() error { return nil }
|
||||
|
||||
func TestCredentialMetadataMarksNumericBotFlagOneOrTwo(t *testing.T) {
|
||||
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
|
||||
if err != nil {
|
||||
|
||||
@@ -3,6 +3,7 @@ package cli
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
providerstreamidle "github.com/chenyme/grok2api/backend/internal/infra/provider/streamidle"
|
||||
@@ -33,3 +34,17 @@ type idleTimeoutReadCloser = providerstreamidle.ReadCloser
|
||||
func newIdleTimeoutReadCloser(body io.ReadCloser, idle time.Duration, cancel context.CancelCauseFunc) *idleTimeoutReadCloser {
|
||||
return providerstreamidle.New(body, idle, cancel)
|
||||
}
|
||||
|
||||
// cancelOnCloseReadCloser keeps a derived HTTP request context alive while a
|
||||
// non-success response body is inspected, then releases it with the body.
|
||||
// Successful inference bodies use idleTimeoutReadCloser instead.
|
||||
type cancelOnCloseReadCloser struct {
|
||||
io.ReadCloser
|
||||
cancel context.CancelCauseFunc
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (r *cancelOnCloseReadCloser) Close() error {
|
||||
r.once.Do(func() { r.cancel(nil) })
|
||||
return r.ReadCloser.Close()
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider/conversation"
|
||||
providerstreamidle "github.com/chenyme/grok2api/backend/internal/infra/provider/streamidle"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
neterrorpkg "github.com/chenyme/grok2api/backend/internal/pkg/neterror"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
@@ -136,7 +137,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
cfg := a.config()
|
||||
requestCtx, totalCancel := context.WithTimeout(ctx, time.Duration(cfg.TimeoutSeconds)*time.Second)
|
||||
var idleCancel context.CancelCauseFunc
|
||||
if request.Streaming && cfg.StreamIdleTimeoutSeconds > 0 {
|
||||
if cfg.StreamIdleTimeoutSeconds > 0 {
|
||||
requestCtx, idleCancel = context.WithCancelCause(requestCtx)
|
||||
}
|
||||
cancel := func() {
|
||||
@@ -157,7 +158,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
if request.Streaming && idleCancel != nil && response.StatusCode >= 200 && response.StatusCode < 300 && response.Body != nil {
|
||||
if idleCancel != nil && response.StatusCode >= 200 && response.StatusCode < 300 && response.Body != nil {
|
||||
response.Body = providerstreamidle.New(response.Body, time.Duration(cfg.StreamIdleTimeoutSeconds)*time.Second, idleCancel)
|
||||
}
|
||||
responseBodyTruncated := false
|
||||
@@ -226,6 +227,9 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
if readErr != nil {
|
||||
return nil, readErr
|
||||
}
|
||||
if response.StatusCode >= 200 && response.StatusCode < 300 && len(bytes.TrimSpace(data)) == 0 {
|
||||
return nil, neterrorpkg.ErrUpstreamResponseEmpty
|
||||
}
|
||||
if response.StatusCode >= 200 && response.StatusCode < 300 && len(data) > 64<<20 {
|
||||
return nil, fmt.Errorf("Console 对话响应超过 64 MiB")
|
||||
}
|
||||
|
||||
@@ -1085,7 +1085,7 @@ func TestAdapterForwardsConsoleHeadersAndNormalizedBody(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdapterScopesStreamIdleTimeoutToConsoleTextStreams(t *testing.T) {
|
||||
func TestAdapterAppliesIdleTimeoutToConsoleTextResponses(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if serveTestDPoPToken(t, writer, request) {
|
||||
return
|
||||
@@ -1117,8 +1117,8 @@ func TestAdapterScopesStreamIdleTimeoutToConsoleTextStreams(t *testing.T) {
|
||||
t.Fatalf("response body = %T, want *releaseBody", response.Body)
|
||||
}
|
||||
_, wrapped := released.ReadCloser.(*providerstreamidle.ReadCloser)
|
||||
if wrapped != streaming {
|
||||
t.Fatalf("stream-idle wrapper present = %t, streaming = %t", wrapped, streaming)
|
||||
if !wrapped {
|
||||
t.Fatalf("text response idle wrapper missing for streaming=%t", streaming)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1152,6 +1152,55 @@ func TestConsoleStreamingReadReturnsIdleTimeout(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleNonStreamingConversationReadReturnsIdleTimeout(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if serveTestDPoPToken(t, writer, request) {
|
||||
return
|
||||
}
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
writer.WriteHeader(http.StatusOK)
|
||||
writer.(http.Flusher).Flush()
|
||||
<-request.Context().Done()
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
adapter, credential := newConsoleTestAdapter(t, server.URL)
|
||||
adapter.UpdateConfig(Config{BaseURL: server.URL, TimeoutSeconds: 5, StreamIdleTimeoutSeconds: 1})
|
||||
started := time.Now()
|
||||
_, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{
|
||||
Credential: credential, Method: http.MethodPost, Path: "/responses", Model: "grok-4.3",
|
||||
Operation: conversation.OperationChat, Streaming: false, NormalizeBody: true,
|
||||
Body: []byte(`{"model":"grok-4.3","messages":[{"role":"user","content":"hello"}]}`),
|
||||
})
|
||||
if !errors.Is(err, neterror.ErrUpstreamStreamIdleTimeout) || neterror.IdleTimeoutObservedData(err) {
|
||||
t.Fatalf("body read error = %#v, observed=%t", err, neterror.IdleTimeoutObservedData(err))
|
||||
}
|
||||
if elapsed := time.Since(started); elapsed >= 3*time.Second {
|
||||
t.Fatalf("non-streaming idle timeout took %s", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleNonStreamingConversationRejectsEmptySuccess(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if serveTestDPoPToken(t, writer, request) {
|
||||
return
|
||||
}
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
writer.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
adapter, credential := newConsoleTestAdapter(t, server.URL)
|
||||
_, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{
|
||||
Credential: credential, Method: http.MethodPost, Path: "/responses", Model: "grok-4.3",
|
||||
Operation: conversation.OperationChat, Streaming: false, NormalizeBody: true,
|
||||
Body: []byte(`{"model":"grok-4.3","messages":[{"role":"user","content":"hello"}]}`),
|
||||
})
|
||||
if !errors.Is(err, neterror.ErrUpstreamResponseEmpty) {
|
||||
t.Fatalf("empty response error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyChromiumClientHintsSkipsNonChromiumUserAgent(t *testing.T) {
|
||||
header := make(http.Header)
|
||||
applyChromiumClientHints(header, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Version/18.0 Safari/605.1.15")
|
||||
|
||||
@@ -18,6 +18,7 @@ type ReadCloser struct {
|
||||
timer *time.Timer
|
||||
cancel context.CancelCauseFunc
|
||||
timedOut atomic.Bool
|
||||
observed atomic.Bool
|
||||
}
|
||||
|
||||
func New(body io.ReadCloser, idle time.Duration, cancel context.CancelCauseFunc) *ReadCloser {
|
||||
@@ -32,10 +33,11 @@ func New(body io.ReadCloser, idle time.Duration, cancel context.CancelCauseFunc)
|
||||
func (r *ReadCloser) Read(buffer []byte) (int, error) {
|
||||
n, err := r.ReadCloser.Read(buffer)
|
||||
if n > 0 {
|
||||
r.observed.Store(true)
|
||||
r.timer.Reset(r.idle)
|
||||
}
|
||||
if err != nil && r.timedOut.Load() {
|
||||
return n, neterror.ErrUpstreamStreamIdleTimeout
|
||||
return n, &neterror.IdleTimeoutError{DataObserved: r.observed.Load()}
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
@@ -48,6 +48,27 @@ func TestReadCloserResetsDeadlineOnProgress(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadCloserReportsProgressBeforeIdleTimeout(t *testing.T) {
|
||||
ctx, cancel := context.WithCancelCause(context.Background())
|
||||
reader, writer := io.Pipe()
|
||||
wrapper := New(reader, 30*time.Millisecond, cancel)
|
||||
defer wrapper.Close()
|
||||
|
||||
go func() {
|
||||
_, _ = writer.Write([]byte("{"))
|
||||
<-ctx.Done()
|
||||
_ = writer.CloseWithError(ctx.Err())
|
||||
}()
|
||||
|
||||
buffer := make([]byte, 1)
|
||||
if n, err := wrapper.Read(buffer); n != 1 || err != nil {
|
||||
t.Fatalf("first read = (%d, %v), want one byte", n, err)
|
||||
}
|
||||
if _, err := wrapper.Read(buffer); !errors.Is(err, neterror.ErrUpstreamStreamIdleTimeout) || !neterror.IdleTimeoutObservedData(err) {
|
||||
t.Fatalf("idle error = %#v, observed=%t", err, neterror.IdleTimeoutObservedData(err))
|
||||
}
|
||||
}
|
||||
|
||||
type pacedReader struct {
|
||||
chunks int
|
||||
gap time.Duration
|
||||
|
||||
@@ -13,6 +13,12 @@ const responseHeaderTimeoutMarker = "timeout awaiting response headers"
|
||||
// configured idle window.
|
||||
var ErrUpstreamStreamIdleTimeout = errors.New("upstream stream idle timeout")
|
||||
|
||||
// ErrUpstreamResponseEmpty identifies a successful upstream response whose
|
||||
// body reached EOF before producing any bytes. It is separate from malformed
|
||||
// JSON and client cancellation so callers may apply the empty-response health
|
||||
// policy without penalizing ordinary request aborts.
|
||||
var ErrUpstreamResponseEmpty = errors.New("upstream response body is empty")
|
||||
|
||||
// ErrBuildStreamIdleTimeout is retained as a compatibility alias for callers
|
||||
// introduced before stream-idle protection became provider-neutral.
|
||||
var ErrBuildStreamIdleTimeout = ErrUpstreamStreamIdleTimeout
|
||||
@@ -41,3 +47,26 @@ func IsBuildStreamIdleTimeout(err error) bool {
|
||||
func IsUpstreamStreamIdleTimeout(err error) bool {
|
||||
return errors.Is(err, ErrUpstreamStreamIdleTimeout)
|
||||
}
|
||||
|
||||
// IsUpstreamResponseEmpty reports whether a successful upstream response
|
||||
// completed without a response body.
|
||||
func IsUpstreamResponseEmpty(err error) bool {
|
||||
return errors.Is(err, ErrUpstreamResponseEmpty)
|
||||
}
|
||||
|
||||
// IdleTimeoutError retains whether any response bytes arrived before an idle
|
||||
// deadline. A zero-byte idle may use the long account cooldown; a partial
|
||||
// response should receive only the ordinary transient failure penalty.
|
||||
type IdleTimeoutError struct {
|
||||
DataObserved bool
|
||||
}
|
||||
|
||||
func (e *IdleTimeoutError) Error() string { return ErrUpstreamStreamIdleTimeout.Error() }
|
||||
func (e *IdleTimeoutError) Unwrap() error { return ErrUpstreamStreamIdleTimeout }
|
||||
|
||||
// IdleTimeoutObservedData returns true only for an idle timeout that records
|
||||
// response-body progress before the deadline.
|
||||
func IdleTimeoutObservedData(err error) bool {
|
||||
var idle *IdleTimeoutError
|
||||
return errors.As(err, &idle) && idle.DataObserved
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package neterror
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
@@ -38,3 +40,20 @@ func TestIsUpstreamStreamIdleTimeout(t *testing.T) {
|
||||
t.Fatal("generic context deadline was misclassified as stream-idle timeout")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdleTimeoutErrorRetainsBodyProgress(t *testing.T) {
|
||||
empty := &IdleTimeoutError{}
|
||||
if !IsUpstreamStreamIdleTimeout(empty) || IdleTimeoutObservedData(empty) {
|
||||
t.Fatalf("empty idle classification = idle:%t observed:%t", IsUpstreamStreamIdleTimeout(empty), IdleTimeoutObservedData(empty))
|
||||
}
|
||||
partial := fmt.Errorf("read body: %w", &IdleTimeoutError{DataObserved: true})
|
||||
if !IsUpstreamStreamIdleTimeout(partial) || !IdleTimeoutObservedData(partial) {
|
||||
t.Fatalf("partial idle classification = idle:%t observed:%t", IsUpstreamStreamIdleTimeout(partial), IdleTimeoutObservedData(partial))
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsUpstreamResponseEmpty(t *testing.T) {
|
||||
if !IsUpstreamResponseEmpty(fmt.Errorf("read body: %w", ErrUpstreamResponseEmpty)) || IsUpstreamResponseEmpty(io.EOF) {
|
||||
t.Fatal("empty response sentinel classification failed")
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package inference
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -1259,6 +1260,27 @@ func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, st
|
||||
}
|
||||
return
|
||||
}
|
||||
body := io.Reader(result.Body)
|
||||
if !stream && result.StatusCode >= http.StatusOK && result.StatusCode < http.StatusMultipleChoices {
|
||||
var peekErr error
|
||||
body, peekErr = peekNonEmptyJSONBody(result.Body)
|
||||
if peekErr != nil {
|
||||
status, code, message := http.StatusBadGateway, "stream_interrupted", "读取上游响应失败"
|
||||
switch {
|
||||
case neterror.IsUpstreamStreamIdleTimeout(peekErr):
|
||||
status, code, message = http.StatusGatewayTimeout, "upstream_stream_idle_timeout", "上游响应长时间无数据"
|
||||
case neterror.IsUpstreamResponseEmpty(peekErr):
|
||||
status, code, message = http.StatusBadGateway, "upstream_response_empty", "上游响应为空"
|
||||
}
|
||||
errorCode = code
|
||||
if anthropic {
|
||||
writeAnthropicError(c, status, "api_error", message, code)
|
||||
} else {
|
||||
writeOpenAIError(c, status, code, message)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
transferLimit := int64(maxJSONResponseTransferBytes)
|
||||
if stream {
|
||||
transferLimit = maxStreamResponseTransferBytes
|
||||
@@ -1281,7 +1303,7 @@ func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, st
|
||||
result.RecordStreamFailure(*metadata.StreamFailure)
|
||||
}
|
||||
} else {
|
||||
metadata, copyErr := copyJSON(c.Writer, result.Body, protocol)
|
||||
metadata, copyErr := copyJSON(c.Writer, body, protocol)
|
||||
usage, responseID, err = metadata.Usage, metadata.ResponseID, copyErr
|
||||
}
|
||||
if err != nil {
|
||||
@@ -1294,6 +1316,8 @@ func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, st
|
||||
errorCode = "upstream_stream_incomplete"
|
||||
case errors.Is(err, neterror.ErrUpstreamStreamIdleTimeout):
|
||||
errorCode = "upstream_stream_idle_timeout"
|
||||
case errors.Is(err, neterror.ErrUpstreamResponseEmpty):
|
||||
errorCode = "upstream_response_empty"
|
||||
case errors.Is(err, errUpstreamStreamRead):
|
||||
errorCode = "upstream_stream_interrupted"
|
||||
default:
|
||||
@@ -1302,6 +1326,21 @@ func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, st
|
||||
}
|
||||
}
|
||||
|
||||
// peekNonEmptyJSONBody delays the downstream 2xx status until the upstream has
|
||||
// produced at least one response byte. This lets an idle/empty non-streaming
|
||||
// response become a real 502/504 instead of an empty 200 while preserving a
|
||||
// streaming copy for large valid JSON bodies.
|
||||
func peekNonEmptyJSONBody(source io.Reader) (io.Reader, error) {
|
||||
reader := bufio.NewReaderSize(source, responseCopyBufferBytes)
|
||||
if _, err := reader.Peek(1); err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return nil, neterror.ErrUpstreamResponseEmpty
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return reader, nil
|
||||
}
|
||||
|
||||
type responseMetadata struct {
|
||||
Usage gateway.Usage
|
||||
cacheCreationInputTokens int64
|
||||
@@ -1577,12 +1616,15 @@ func copyJSON(writer gin.ResponseWriter, source io.Reader, protocol streamProtoc
|
||||
}
|
||||
if readErr != nil {
|
||||
if errors.Is(readErr, io.EOF) {
|
||||
if transferred == 0 {
|
||||
return responseMetadata{}, neterror.ErrUpstreamResponseEmpty
|
||||
}
|
||||
if metadataComplete {
|
||||
return normalizeMetadataUsage(extractMetadata(metadataBody), protocol), nil
|
||||
}
|
||||
return responseMetadata{}, nil
|
||||
}
|
||||
return responseMetadata{}, readErr
|
||||
return responseMetadata{Usage: gateway.Usage{OutputObserved: transferred > 0}}, readErr
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -424,6 +424,35 @@ func TestDirectUpstreamCredentialResponsesAreRewritten(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNonStreamingEmptyAndIdleResponsesFailBeforeCommittingSuccess(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := NewHandler(nil, nil, 1<<20)
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
body io.ReadCloser
|
||||
wantStatus int
|
||||
wantCode string
|
||||
}{
|
||||
{name: "empty", body: io.NopCloser(strings.NewReader("")), wantStatus: http.StatusBadGateway, wantCode: "upstream_response_empty"},
|
||||
{name: "idle", body: io.NopCloser(idleErrorReader{}), wantStatus: http.StatusGatewayTimeout, wantCode: "upstream_stream_idle_timeout"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
finalCode := ""
|
||||
result := &gateway.Result{
|
||||
StatusCode: http.StatusOK, Status: "200 OK", Header: http.Header{"Content-Type": {"application/json"}}, Body: test.body,
|
||||
Finalize: func(_ gateway.Usage, _, code string) { finalCode = code },
|
||||
}
|
||||
router := gin.New()
|
||||
router.GET("/", func(c *gin.Context) { handler.writeResult(c, result, false, streamProtocolResponses) })
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
if recorder.Code != test.wantStatus || finalCode != test.wantCode || !strings.Contains(recorder.Body.String(), `"`+test.wantCode+`"`) {
|
||||
t.Fatalf("status=%d body=%s finalize=%q", recorder.Code, recorder.Body.String(), finalCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMediaResultRejectsActiveContentAndRedirects(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := NewHandler(nil, nil, 1<<20)
|
||||
|
||||
Reference in new issue
Block a user