From ff06dab68d956f4767232ad6204a2ca7c3b3a671 Mon Sep 17 00:00:00 2001 From: debug-zhang <34176152+debug-zhang@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:17:11 +0800 Subject: [PATCH] fix(openai): scope stream circuit per account and cache no-account diagnostics Root cause: - The OpenAI proxy stream circuit was keyed only on proxy_id. One account whose Responses SSE streams kept disconnecting quarantined every healthy account sharing that egress proxy, emptying the pool for 10 minutes (#5010). - Every 'no available accounts' response called DiagnoseModelAvailabilityForPlatform, which ran a candidates query per request; retrying clients turned that into a database query storm. Change: - Key the circuit on (account_id, proxy_id) and pass the owning account at every record/clear/check call site. The failure threshold (2 in 60s) and 10-minute quarantine TTL are unchanged, as is fail-open selection. - Add a bounded in-process TTL (5s) cache with singleflight for the model availability diagnosis on both gateway services. Keys include platform, group, model and, for the context-sensitive generic check, request-scoped composite-route/thinking inputs. Lookup failures are not cached so callers keep the conservative 503 fallback and retry the database. - Update the circuit config doc comment and the scheduler tests that relied on proxy-wide quarantine. Tests: - go test ./internal/service -run 'TestOpenAIProxyStream' -count=1 - go test -tags=unit ./internal/service -run 'TestDiagnoseModelAvailabilityForPlatform|TestOpenAIDiagnoseModelAvailability|TestGatewayDiagnoseModelAvailability|TestModelAvailabilityDiagnosisCache|TestOpenAIProxyStream|TestOpenAIGatewayService_SelectAccountWithScheduler_(SkipsQuarantinedSharedProxy|QuarantinedAccountKeepsPeerOnSharedProxy|FailsOpenWhenAllProxiesQuarantined)|TestSelectAccountWithSchedulerForImages_UnspecifiedSizePrefersHealthyProxyOverQuarantinedUnrestricted' -count=1 - go test -tags=unit ./internal/handler -run 'TestClassifyNoAccount|TestClassifySelectionFailure|TestGPT55Retirement' -count=1 - go build ./... and gofmt -l are clean. --- backend/internal/config/config.go | 10 +- .../service/gateway_model_availability.go | 72 ++++--- backend/internal/service/gateway_service.go | 3 + .../model_availability_diagnosis_cache.go | 174 ++++++++++++++++ ...model_availability_diagnosis_cache_test.go | 187 ++++++++++++++++++ .../service/openai_account_scheduler_test.go | 48 ++++- .../openai_gateway_model_availability.go | 89 +++++---- .../service/openai_gateway_service.go | 1 + .../service/openai_image_size_routing_test.go | 2 +- .../openai_legacy_scheduler_decision_test.go | 6 +- .../service/openai_proxy_stream_circuit.go | 101 ++++++---- .../openai_proxy_stream_circuit_test.go | 85 +++++--- 12 files changed, 633 insertions(+), 145 deletions(-) create mode 100644 backend/internal/service/model_availability_diagnosis_cache.go create mode 100644 backend/internal/service/model_availability_diagnosis_cache_test.go diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 4ba5e58f08..e63c41ca37 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -1290,15 +1290,17 @@ type GatewayOpenAIHTTP2Config struct { } // GatewayOpenAIProxyStreamCircuitConfig controls the bounded, in-process -// proxy-ID circuit used for incomplete OpenAI Responses SSE streams. +// account+proxy circuit used for incomplete OpenAI Responses SSE streams. +// Entries are scoped to the account that owned the stream, so one account +// cannot quarantine other accounts that share the same egress proxy. type GatewayOpenAIProxyStreamCircuitConfig struct { - // Disabled: 完全关闭代理断流熔断(默认开启)。 + // Disabled: 完全关闭账号+代理断流熔断(默认开启)。 Disabled bool `mapstructure:"disabled"` - // FailureThreshold: 统计窗口内多少次断流后隔离代理。 + // FailureThreshold: 统计窗口内多少次断流后隔离该账号在该代理上的熔断项。 FailureThreshold int `mapstructure:"failure_threshold"` // WindowSeconds: 断流统计窗口(秒)。 WindowSeconds int `mapstructure:"window_seconds"` - // TTLSeconds: 代理隔离持续时间(秒)。 + // TTLSeconds: 熔断项隔离持续时间(秒)。 TTLSeconds int `mapstructure:"ttl_seconds"` } diff --git a/backend/internal/service/gateway_model_availability.go b/backend/internal/service/gateway_model_availability.go index 71c36d6dc4..3e65998de8 100644 --- a/backend/internal/service/gateway_model_availability.go +++ b/backend/internal/service/gateway_model_availability.go @@ -99,41 +99,53 @@ func (s *GatewayService) DiagnoseModelAvailabilityForPlatform( includeGrouped = true } - accounts, err := s.accountRepo.ListModelAvailabilityCandidates(ctx, queryGroupID, platforms, includeGrouped) - if err != nil { - // Conservative fallback: pretend everything is fine so the caller - // returns 503 (we don't want to flip to 404 just because a lookup - // hiccup'd). - return ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true} + key := modelAvailabilityDiagnosisCacheKey{ + platform: platform, + model: requestedModel, + noGroup: queryGroupID == nil, + grouped: includeGrouped, + contextKey: modelAvailabilityDiagnosisContextKey(ctx), } - - diag := ModelAvailabilityDiagnosis{} - var earliestRecovery time.Duration - // A supporting account with no persisted cooldown is waiting on a runtime - // filter (quota, RPM, window cost, ...) whose recovery time is unknown, so - // the pool-level hint must be omitted rather than inflated by a cooling peer. - hasUncooledCandidate := false - for i := range accounts { - if useMixed && accounts[i].Platform == PlatformAntigravity && !accounts[i].IsMixedSchedulingEnabled() { - continue + if queryGroupID != nil { + key.groupID = *queryGroupID + } + return s.modelAvailabilityDiagCache.getOrLoad(key, func() (ModelAvailabilityDiagnosis, bool) { + accounts, err := s.accountRepo.ListModelAvailabilityCandidates(ctx, queryGroupID, platforms, includeGrouped) + if err != nil { + // Conservative fallback: pretend everything is fine so the caller + // returns 503 (we don't want to flip to 404 just because a lookup + // hiccup'd). Do not cache the failure: the next request retries. + return ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true}, false } - diag.HasAccountsInPool = true - if s.isModelSupportedByAccountWithContext(ctx, &accounts[i], requestedModel) { - diag.HasModelSupport = true - if remaining := accountCooldownRemaining(ctx, &accounts[i], requestedModel); remaining > 0 { - if earliestRecovery == 0 || remaining < earliestRecovery { - earliestRecovery = remaining + + diag := ModelAvailabilityDiagnosis{} + var earliestRecovery time.Duration + // A supporting account with no persisted cooldown is waiting on a runtime + // filter (quota, RPM, window cost, ...) whose recovery time is unknown, so + // the pool-level hint must be omitted rather than inflated by a cooling peer. + hasUncooledCandidate := false + for i := range accounts { + if useMixed && accounts[i].Platform == PlatformAntigravity && !accounts[i].IsMixedSchedulingEnabled() { + continue + } + diag.HasAccountsInPool = true + if s.isModelSupportedByAccountWithContext(ctx, &accounts[i], requestedModel) { + diag.HasModelSupport = true + if remaining := accountCooldownRemaining(ctx, &accounts[i], requestedModel); remaining > 0 { + if earliestRecovery == 0 || remaining < earliestRecovery { + earliestRecovery = remaining + } + } else { + hasUncooledCandidate = true } - } else { - hasUncooledCandidate = true } } - } - if hasUncooledCandidate { - earliestRecovery = 0 - } - diag.RetryAfterSeconds = ceilRetryAfterSeconds(earliestRecovery, DownstreamRetryAfterMaxSeconds(s.cfg)) - return diag + if hasUncooledCandidate { + earliestRecovery = 0 + } + diag.RetryAfterSeconds = ceilRetryAfterSeconds(earliestRecovery, DownstreamRetryAfterMaxSeconds(s.cfg)) + return diag, true + }) } // accountCooldownRemaining reports how long an account stays unschedulable diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 7fa89e8da3..38d1f32c8d 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -901,6 +901,9 @@ type GatewayService struct { userGroupRateSF singleflight.Group modelsListCache *gocache.Cache modelsListCacheTTL time.Duration + + modelAvailabilityDiagCache modelAvailabilityDiagnosisCache + settingService *SettingService responseHeaderFilter *responseheaders.CompiledHeaderFilter debugModelRouting atomic.Bool diff --git a/backend/internal/service/model_availability_diagnosis_cache.go b/backend/internal/service/model_availability_diagnosis_cache.go new file mode 100644 index 0000000000..8689b3f836 --- /dev/null +++ b/backend/internal/service/model_availability_diagnosis_cache.go @@ -0,0 +1,174 @@ +package service + +import ( + "context" + "strconv" + "strings" + "sync" + "time" + + "golang.org/x/sync/singleflight" +) + +const ( + // defaultModelAvailabilityDiagnosisCacheTTL bounds how stale a cached + // "no available accounts" diagnosis may be. The diagnosis is read-only and + // only chooses between 404 and 503, so a short TTL is safe: it keeps a + // client retry storm from issuing one accounts-table query per request + // (#5010) while a configuration fix becomes visible again within seconds. + defaultModelAvailabilityDiagnosisCacheTTL = 5 * time.Second + // modelAvailabilityDiagnosisCacheMaxEntries bounds memory even when + // arbitrary, attacker-controlled model names reach the diagnosis path. + modelAvailabilityDiagnosisCacheMaxEntries = 1024 +) + +// modelAvailabilityDiagnosisCacheKey identifies one cached diagnosis. The +// platform, group and model are mandatory: results for different pools or +// models must never be served from the same entry. contextKey is empty for +// context-independent diagnoses; it carries the request-scoped inputs that +// the generic (Anthropic/Gemini) support check reads, so a cached result is +// never reused under a different composite-route or thinking configuration. +type modelAvailabilityDiagnosisCacheKey struct { + platform string + model string + groupID int64 + noGroup bool + grouped bool + contextKey string +} + +func (k modelAvailabilityDiagnosisCacheKey) singleflightKey() string { + return strings.Join([]string{ + strconv.Quote(k.platform), + strconv.Quote(k.model), + strconv.Quote(k.contextKey), + strconv.FormatInt(k.groupID, 10), + strconv.FormatBool(k.noGroup), + strconv.FormatBool(k.grouped), + }, "|") +} + +type modelAvailabilityDiagnosisCacheEntry struct { + diagnosis ModelAvailabilityDiagnosis + expiresAt time.Time +} + +// modelAvailabilityDiagnosisCache is an in-process, TTL-bounded cache with +// singleflight de-duplication for the "no available accounts" diagnosis. +// Concurrent misses for the same key share one database query instead of each +// issuing its own. The zero value is ready to use. +type modelAvailabilityDiagnosisCache struct { + mu sync.Mutex + ttl time.Duration + entries map[modelAvailabilityDiagnosisCacheKey]modelAvailabilityDiagnosisCacheEntry + sf singleflight.Group +} + +// getOrLoad returns the cached diagnosis for key, loading it through load() +// on a miss. load reports whether its result is cacheable: lookup failures +// must stay uncached so the caller keeps the conservative 503 fallback and +// the next request retries the database. +func (c *modelAvailabilityDiagnosisCache) getOrLoad( + key modelAvailabilityDiagnosisCacheKey, + load func() (ModelAvailabilityDiagnosis, bool), +) ModelAvailabilityDiagnosis { + if load == nil { + return ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true} + } + if c == nil { + diagnosis, _ := load() + return diagnosis + } + if diagnosis, ok := c.get(key, time.Now()); ok { + return diagnosis + } + value, _, _ := c.sf.Do(key.singleflightKey(), func() (any, error) { + now := time.Now() + if diagnosis, ok := c.get(key, now); ok { + return diagnosis, nil + } + diagnosis, cacheable := load() + if cacheable { + c.set(key, diagnosis, now) + } + return diagnosis, nil + }) + if diagnosis, ok := value.(ModelAvailabilityDiagnosis); ok { + return diagnosis + } + diagnosis, _ := load() + return diagnosis +} + +func (c *modelAvailabilityDiagnosisCache) get(key modelAvailabilityDiagnosisCacheKey, now time.Time) (ModelAvailabilityDiagnosis, bool) { + c.mu.Lock() + defer c.mu.Unlock() + entry, ok := c.entries[key] + if !ok { + return ModelAvailabilityDiagnosis{}, false + } + if !now.Before(entry.expiresAt) { + delete(c.entries, key) + return ModelAvailabilityDiagnosis{}, false + } + return entry.diagnosis, true +} + +func (c *modelAvailabilityDiagnosisCache) set(key modelAvailabilityDiagnosisCacheKey, diagnosis ModelAvailabilityDiagnosis, now time.Time) { + ttl := c.ttl + if ttl <= 0 { + ttl = defaultModelAvailabilityDiagnosisCacheTTL + } + c.mu.Lock() + defer c.mu.Unlock() + if c.entries == nil { + c.entries = make(map[modelAvailabilityDiagnosisCacheKey]modelAvailabilityDiagnosisCacheEntry) + } + if len(c.entries) >= modelAvailabilityDiagnosisCacheMaxEntries { + for cachedKey, entry := range c.entries { + if !now.Before(entry.expiresAt) { + delete(c.entries, cachedKey) + } + } + } + if len(c.entries) >= modelAvailabilityDiagnosisCacheMaxEntries { + var oldestKey modelAvailabilityDiagnosisCacheKey + var oldest time.Time + found := false + for cachedKey, entry := range c.entries { + if !found || entry.expiresAt.Before(oldest) { + oldestKey = cachedKey + oldest = entry.expiresAt + found = true + } + } + if found { + delete(c.entries, oldestKey) + } + } + c.entries[key] = modelAvailabilityDiagnosisCacheEntry{diagnosis: diagnosis, expiresAt: now.Add(ttl)} +} + +// modelAvailabilityDiagnosisContextKey captures the request-scoped inputs that +// GatewayService's model-support check reads. Keeping them in the cache key +// prevents a result computed under one composite route or thinking flag from +// being reused under another. +func modelAvailabilityDiagnosisContextKey(ctx context.Context) string { + if ctx == nil { + return "" + } + var b strings.Builder + if source, ok := CompositeRouteSourceFromContext(ctx); ok { + _, _ = b.WriteString("source=") + _, _ = b.WriteString(source) + } + if model, ok := RequestedPublicModelFromContext(ctx); ok { + _, _ = b.WriteString(";public_model=") + _, _ = b.WriteString(model) + } + if enabled, ok := ThinkingEnabledFromContext(ctx); ok { + _, _ = b.WriteString(";thinking=") + _, _ = b.WriteString(strconv.FormatBool(enabled)) + } + return b.String() +} diff --git a/backend/internal/service/model_availability_diagnosis_cache_test.go b/backend/internal/service/model_availability_diagnosis_cache_test.go new file mode 100644 index 0000000000..1a1e5b172c --- /dev/null +++ b/backend/internal/service/model_availability_diagnosis_cache_test.go @@ -0,0 +1,187 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "strconv" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +type countingModelAvailabilityRepo struct { + *mockAccountRepoForPlatform + calls atomic.Int64 + err error +} + +func (r *countingModelAvailabilityRepo) ListModelAvailabilityCandidates( + ctx context.Context, + groupID *int64, + platforms []string, + includeGrouped bool, +) ([]Account, error) { + r.calls.Add(1) + if r.err != nil { + return nil, r.err + } + return r.mockAccountRepoForPlatform.ListModelAvailabilityCandidates(ctx, groupID, platforms, includeGrouped) +} + +func newCountingModelAvailabilityRepo() (*countingModelAvailabilityRepo, int64) { + groupID := int64(42) + return &countingModelAvailabilityRepo{ + mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ + accounts: []Account{ + { + ID: 1, + Platform: PlatformOpenAI, + Status: StatusActive, + Schedulable: true, + AccountGroups: []AccountGroup{ + {GroupID: groupID}, + }, + Credentials: map[string]any{ + "model_mapping": map[string]any{"gpt-5": "gpt-5"}, + }, + }, + }, + accountsByID: map[int64]*Account{}, + }, + }, groupID +} + +func TestOpenAIDiagnoseModelAvailabilityCachesRepeatedQueries(t *testing.T) { + repo, groupID := newCountingModelAvailabilityRepo() + svc := &OpenAIGatewayService{accountRepo: repo, cfg: testConfig()} + ctx := context.Background() + + first := svc.DiagnoseModelAvailabilityForPlatform(ctx, &groupID, "gpt-5.1-codex-mini", PlatformOpenAI) + require.True(t, first.HasAccountsInPool) + require.False(t, first.HasModelSupport) + + for i := 0; i < 10; i++ { + again := svc.DiagnoseModelAvailabilityForPlatform(ctx, &groupID, "gpt-5.1-codex-mini", PlatformOpenAI) + require.Equal(t, first, again) + } + require.Equal(t, int64(1), repo.calls.Load(), "repeated identical diagnoses must share one database query") +} + +func TestOpenAIDiagnoseModelAvailabilityCacheSeparatesKeys(t *testing.T) { + repo, groupID := newCountingModelAvailabilityRepo() + svc := &OpenAIGatewayService{accountRepo: repo, cfg: testConfig()} + ctx := context.Background() + + svc.DiagnoseModelAvailabilityForPlatform(ctx, &groupID, "gpt-5.1-codex-mini", PlatformOpenAI) + require.Equal(t, int64(1), repo.calls.Load()) + + // A different model must not reuse the cached result. + svc.DiagnoseModelAvailabilityForPlatform(ctx, &groupID, "gpt-5.6-sol", PlatformOpenAI) + require.Equal(t, int64(2), repo.calls.Load()) + + // A different group must not reuse it either. + otherGroupID := int64(43) + svc.DiagnoseModelAvailabilityForPlatform(ctx, &otherGroupID, "gpt-5.1-codex-mini", PlatformOpenAI) + require.Equal(t, int64(3), repo.calls.Load()) + + // A different OpenAI-compatible platform is a different candidate pool. + svc.DiagnoseModelAvailabilityForPlatform(ctx, &groupID, "gpt-5.1-codex-mini", PlatformGrok) + require.Equal(t, int64(4), repo.calls.Load()) +} + +func TestOpenAIDiagnoseModelAvailabilityCacheRefreshesAfterTTL(t *testing.T) { + repo, groupID := newCountingModelAvailabilityRepo() + svc := &OpenAIGatewayService{accountRepo: repo, cfg: testConfig()} + svc.modelAvailabilityDiagCache.ttl = 5 * time.Millisecond + ctx := context.Background() + + svc.DiagnoseModelAvailabilityForPlatform(ctx, &groupID, "gpt-5.1-codex-mini", PlatformOpenAI) + require.Equal(t, int64(1), repo.calls.Load()) + + time.Sleep(20 * time.Millisecond) + + svc.DiagnoseModelAvailabilityForPlatform(ctx, &groupID, "gpt-5.1-codex-mini", PlatformOpenAI) + require.Equal(t, int64(2), repo.calls.Load(), "an expired entry must be refreshed from the database") +} + +func TestOpenAIDiagnoseModelAvailabilityCacheSingleflight(t *testing.T) { + repo, groupID := newCountingModelAvailabilityRepo() + svc := &OpenAIGatewayService{accountRepo: repo, cfg: testConfig()} + ctx := context.Background() + + const workers = 32 + start := make(chan struct{}) + results := make([]ModelAvailabilityDiagnosis, workers) + var wg sync.WaitGroup + wg.Add(workers) + for i := 0; i < workers; i++ { + go func(index int) { + defer wg.Done() + <-start + results[index] = svc.DiagnoseModelAvailabilityForPlatform(ctx, &groupID, "gpt-5.1-codex-mini", PlatformOpenAI) + }(i) + } + close(start) + wg.Wait() + + require.Equal(t, int64(1), repo.calls.Load(), "concurrent identical diagnoses must collapse into one query") + for _, result := range results { + require.True(t, result.HasAccountsInPool) + require.False(t, result.HasModelSupport) + } +} + +func TestOpenAIDiagnoseModelAvailabilityLookupFailureIsNotCached(t *testing.T) { + repo, groupID := newCountingModelAvailabilityRepo() + svc := &OpenAIGatewayService{accountRepo: repo, cfg: testConfig()} + ctx := context.Background() + + repo.err = errors.New("accounts query failed") + fallback := svc.DiagnoseModelAvailabilityForPlatform(ctx, &groupID, "gpt-5.1-codex-mini", PlatformOpenAI) + require.True(t, fallback.HasAccountsInPool, "lookup failure must keep the caller on 503") + require.True(t, fallback.HasModelSupport) + require.Equal(t, int64(1), repo.calls.Load()) + + repo.err = nil + recovered := svc.DiagnoseModelAvailabilityForPlatform(ctx, &groupID, "gpt-5.1-codex-mini", PlatformOpenAI) + require.True(t, recovered.HasAccountsInPool) + require.False(t, recovered.HasModelSupport, "the next request must retry the database instead of reusing the failure") + require.Equal(t, int64(2), repo.calls.Load()) +} + +func TestModelAvailabilityDiagnosisCacheBoundsEntries(t *testing.T) { + cache := &modelAvailabilityDiagnosisCache{} + now := time.Now() + for i := 0; i < modelAvailabilityDiagnosisCacheMaxEntries+16; i++ { + cache.set(modelAvailabilityDiagnosisCacheKey{ + platform: PlatformOpenAI, + model: "model-" + strconv.Itoa(i), + }, ModelAvailabilityDiagnosis{HasAccountsInPool: true}, now) + } + + cache.mu.Lock() + defer cache.mu.Unlock() + require.Len(t, cache.entries, modelAvailabilityDiagnosisCacheMaxEntries, + "attacker-controlled model names must not grow the diagnosis cache without bound") +} + +func TestGatewayDiagnoseModelAvailabilityCachesAndSeparatesContexts(t *testing.T) { + repo, groupID := newCountingModelAvailabilityRepo() + svc := &GatewayService{accountRepo: repo, cfg: testConfig()} + ctx := context.Background() + + svc.DiagnoseModelAvailabilityForPlatform(ctx, &groupID, "gpt-5.1-codex-mini", PlatformOpenAI) + svc.DiagnoseModelAvailabilityForPlatform(ctx, &groupID, "gpt-5.1-codex-mini", PlatformOpenAI) + require.Equal(t, int64(1), repo.calls.Load(), "generic gateway diagnoses must be cached too") + + // The generic support check reads request-scoped inputs; a different + // thinking setting must not reuse the entry. + withThinking := WithThinkingEnabled(ctx, true, false) + svc.DiagnoseModelAvailabilityForPlatform(withThinking, &groupID, "gpt-5.1-codex-mini", PlatformOpenAI) + require.Equal(t, int64(2), repo.calls.Load()) +} diff --git a/backend/internal/service/openai_account_scheduler_test.go b/backend/internal/service/openai_account_scheduler_test.go index 6a31e46cc5..aa02e8c090 100644 --- a/backend/internal/service/openai_account_scheduler_test.go +++ b/backend/internal/service/openai_account_scheduler_test.go @@ -1725,7 +1725,11 @@ func TestOpenAIGatewayService_SelectAccountWithScheduler_SkipsQuarantinedSharedP maxEntries: 16, }), } - svc.openaiProxyStreamCircuit.recordFailure(proxyA, time.Now()) + // Both accounts on proxyA are quarantined: the healthy proxyB account must + // win. Quarantining only one account is covered by the dedicated peer test + // below (#5010). + svc.openaiProxyStreamCircuit.recordFailure(circuitTestKey(469801, proxyA), time.Now()) + svc.openaiProxyStreamCircuit.recordFailure(circuitTestKey(469802, proxyA), time.Now()) selection, _, err := svc.SelectAccountWithScheduler( context.Background(), nil, "", "", "gpt-5.6-sol", nil, OpenAIUpstreamTransportAny, false, @@ -1736,6 +1740,41 @@ func TestOpenAIGatewayService_SelectAccountWithScheduler_SkipsQuarantinedSharedP require.Equal(t, int64(469803), selection.Account.ID) } +func TestOpenAIGatewayService_SelectAccountWithScheduler_QuarantinedAccountKeepsPeerOnSharedProxy(t *testing.T) { + resetOpenAIAdvancedSchedulerSettingCacheForTest() + + proxyA := int64(5010) + proxyB := int64(5011) + accounts := []Account{ + {ID: 501001, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, Concurrency: 1, Priority: 0, ProxyID: &proxyA}, + {ID: 501002, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, Concurrency: 1, Priority: 0, ProxyID: &proxyA}, + {ID: 501003, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, Concurrency: 1, Priority: 5, ProxyID: &proxyB}, + } + cfg := &config.Config{} + cfg.Gateway.Scheduling.LoadBatchEnabled = false + svc := &OpenAIGatewayService{ + accountRepo: schedulerTestOpenAIAccountRepo{accounts: accounts}, + cfg: cfg, + concurrencyService: NewConcurrencyService(schedulerTestConcurrencyCache{}), + openaiProxyStreamCircuit: newOpenAIProxyStreamCircuit(openAIProxyStreamCircuitSettings{ + failureThreshold: 1, + failureWindow: time.Minute, + quarantineTTL: 10 * time.Minute, + maxEntries: 16, + }), + } + svc.openaiProxyStreamCircuit.recordFailure(circuitTestKey(501001, proxyA), time.Now()) + + selection, _, err := svc.SelectAccountWithScheduler( + context.Background(), nil, "", "", "gpt-5.6-sol", nil, OpenAIUpstreamTransportAny, false, + ) + require.NoError(t, err) + require.NotNil(t, selection) + require.NotNil(t, selection.Account) + require.Equal(t, int64(501002), selection.Account.ID, + "one failing account must not quarantine its peer on the same proxy (#5010)") +} + func TestOpenAIGatewayService_SelectAccountWithScheduler_FailsOpenWhenAllProxiesQuarantined(t *testing.T) { resetOpenAIAdvancedSchedulerSettingCacheForTest() @@ -1759,7 +1798,9 @@ func TestOpenAIGatewayService_SelectAccountWithScheduler_FailsOpenWhenAllProxies maxEntries: 16, }), } - tripped, _ := svc.openaiProxyStreamCircuit.recordFailure(proxyA, time.Now()) + tripped, _ := svc.openaiProxyStreamCircuit.recordFailure(circuitTestKey(505601, proxyA), time.Now()) + require.True(t, tripped) + tripped, _ = svc.openaiProxyStreamCircuit.recordFailure(circuitTestKey(505602, proxyA), time.Now()) require.True(t, tripped) selection, _, err := svc.SelectAccountWithScheduler( @@ -1770,8 +1811,9 @@ func TestOpenAIGatewayService_SelectAccountWithScheduler_FailsOpenWhenAllProxies require.NotNil(t, selection.Account) require.NotNil(t, selection.Account.ProxyID) require.Equal(t, proxyA, *selection.Account.ProxyID) - require.True(t, svc.openaiProxyStreamCircuit.isBlocked(proxyA, time.Now()), + require.True(t, svc.openaiProxyStreamCircuit.isBlocked(circuitTestKey(505601, proxyA), time.Now()), "fail-open must not clear the quarantine; only a completed stream or TTL expiry does") + require.True(t, svc.openaiProxyStreamCircuit.isBlocked(circuitTestKey(505602, proxyA), time.Now())) } func TestOpenAIGatewayService_SelectAccountWithScheduler_SessionStickyRateLimitedAccountFallsBackToFreshCandidate(t *testing.T) { diff --git a/backend/internal/service/openai_gateway_model_availability.go b/backend/internal/service/openai_gateway_model_availability.go index eec311d4af..f7caa88b45 100644 --- a/backend/internal/service/openai_gateway_model_availability.go +++ b/backend/internal/service/openai_gateway_model_availability.go @@ -42,47 +42,60 @@ func (s *OpenAIGatewayService) DiagnoseModelAvailabilityForPlatform( queryGroupID = nil includeGrouped = true } - accounts, err := s.accountRepo.ListModelAvailabilityCandidates( - ctx, - queryGroupID, - []string{platform}, - includeGrouped, - ) - if err != nil { - // Conservative fallback so the caller keeps returning 503; we do not - // want a transient lookup failure to flip into 404 model_not_found. - return ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true} + key := modelAvailabilityDiagnosisCacheKey{ + platform: platform, + model: requestedModel, + noGroup: queryGroupID == nil, + grouped: includeGrouped, } - - diag := ModelAvailabilityDiagnosis{} - var earliestRecovery time.Duration - // A supporting account with no persisted cooldown is waiting on a runtime - // filter (quota, RPM, window cost, ...) whose recovery time is unknown, so - // the pool-level hint must be omitted rather than inflated by a cooling peer. - hasUncooledCandidate := false - for i := range accounts { - diag.HasAccountsInPool = true - if isRetiredOpenAISubscriptionModel(&accounts[i], resolveOpenAIAccountUpstreamModelForRequest(&accounts[i], requestedModel, false)) { - diag.HasRetiredSubscriptionModel = true + if queryGroupID != nil { + key.groupID = *queryGroupID + } + return s.modelAvailabilityDiagCache.getOrLoad(key, func() (ModelAvailabilityDiagnosis, bool) { + accounts, err := s.accountRepo.ListModelAvailabilityCandidates( + ctx, + queryGroupID, + []string{platform}, + includeGrouped, + ) + if err != nil { + // Conservative fallback so the caller keeps returning 503; we do + // not want a transient lookup failure to flip into 404 + // model_not_found. Do not cache the failure: the next request + // retries. + return ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true}, false } - // Mirrors the per-candidate filter used during account selection - // (openai_account_scheduler.isAccountRequestCompatible): empty - // model_mapping accepts everything; otherwise the explicit / wildcard - // mapping must match. - if accounts[i].IsModelSupported(requestedModel) { - diag.HasModelSupport = true - if remaining := accountCooldownRemaining(ctx, &accounts[i], requestedModel); remaining > 0 { - if earliestRecovery == 0 || remaining < earliestRecovery { - earliestRecovery = remaining + + diag := ModelAvailabilityDiagnosis{} + var earliestRecovery time.Duration + // A supporting account with no persisted cooldown is waiting on a runtime + // filter (quota, RPM, window cost, ...) whose recovery time is unknown, so + // the pool-level hint must be omitted rather than inflated by a cooling peer. + hasUncooledCandidate := false + for i := range accounts { + diag.HasAccountsInPool = true + if isRetiredOpenAISubscriptionModel(&accounts[i], resolveOpenAIAccountUpstreamModelForRequest(&accounts[i], requestedModel, false)) { + diag.HasRetiredSubscriptionModel = true + } + // Mirrors the per-candidate filter used during account selection + // (openai_account_scheduler.isAccountRequestCompatible): empty + // model_mapping accepts everything; otherwise the explicit / wildcard + // mapping must match. + if accounts[i].IsModelSupported(requestedModel) { + diag.HasModelSupport = true + if remaining := accountCooldownRemaining(ctx, &accounts[i], requestedModel); remaining > 0 { + if earliestRecovery == 0 || remaining < earliestRecovery { + earliestRecovery = remaining + } + } else { + hasUncooledCandidate = true } - } else { - hasUncooledCandidate = true } } - } - if hasUncooledCandidate { - earliestRecovery = 0 - } - diag.RetryAfterSeconds = ceilRetryAfterSeconds(earliestRecovery, DownstreamRetryAfterMaxSeconds(s.cfg)) - return diag + if hasUncooledCandidate { + earliestRecovery = 0 + } + diag.RetryAfterSeconds = ceilRetryAfterSeconds(earliestRecovery, DownstreamRetryAfterMaxSeconds(s.cfg)) + return diag, true + }) } diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go index 4884ed802d..91faebaf73 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -509,6 +509,7 @@ type OpenAIGatewayService struct { openaiWSRetryMetrics openAIWSRetryMetrics responseHeaderFilter *responseheaders.CompiledHeaderFilter codexSnapshotThrottle *accountWriteThrottle + modelAvailabilityDiagCache modelAvailabilityDiagnosisCache openAIModelsCache openAIModelsCache openaiCompatSessionResponses sessionMemoryCache openaiCompatAnthropicDigestSessions sessionMemoryCache diff --git a/backend/internal/service/openai_image_size_routing_test.go b/backend/internal/service/openai_image_size_routing_test.go index aef39c1429..5973275c85 100644 --- a/backend/internal/service/openai_image_size_routing_test.go +++ b/backend/internal/service/openai_image_size_routing_test.go @@ -393,7 +393,7 @@ func TestSelectAccountWithSchedulerForImages_UnspecifiedSizePrefersHealthyProxyO quarantineTTL: 10 * time.Minute, maxEntries: 16, }) - svc.openaiProxyStreamCircuit.recordFailure(quarantinedProxy, time.Now()) + svc.openaiProxyStreamCircuit.recordFailure(circuitTestKey(unrestricted.ID, quarantinedProxy), time.Now()) selection, err := selectOpenAIImageSizeTestAccount(t, svc, 93010, "", "") require.NoError(t, err) diff --git a/backend/internal/service/openai_legacy_scheduler_decision_test.go b/backend/internal/service/openai_legacy_scheduler_decision_test.go index 2e1ac52176..3b3b32f4ef 100644 --- a/backend/internal/service/openai_legacy_scheduler_decision_test.go +++ b/backend/internal/service/openai_legacy_scheduler_decision_test.go @@ -216,7 +216,7 @@ func TestLegacySchedulerDecision_PreviousResponseRouting(t *testing.T) { quarantineTTL: 10 * time.Minute, maxEntries: 16, }) - tripped, _ := svc.openaiProxyStreamCircuit.recordFailure(quarantinedProxy, time.Now()) + tripped, _ := svc.openaiProxyStreamCircuit.recordFailure(circuitTestKey(38102, quarantinedProxy), time.Now()) require.True(t, tripped) require.NoError(t, svc.getOpenAIWSStateStore().BindResponseAccount(ctx, groupID, responseID, 38102, time.Hour)) @@ -246,7 +246,9 @@ func TestLegacySchedulerDecision_PreviousResponseRouting(t *testing.T) { quarantineTTL: 10 * time.Minute, maxEntries: 16, }) - tripped, _ := svc.openaiProxyStreamCircuit.recordFailure(proxy, time.Now()) + tripped, _ := svc.openaiProxyStreamCircuit.recordFailure(circuitTestKey(38101, proxy), time.Now()) + require.True(t, tripped) + tripped, _ = svc.openaiProxyStreamCircuit.recordFailure(circuitTestKey(38102, proxy), time.Now()) require.True(t, tripped) require.NoError(t, svc.getOpenAIWSStateStore().BindResponseAccount(ctx, groupID, responseID, 38102, time.Hour)) diff --git a/backend/internal/service/openai_proxy_stream_circuit.go b/backend/internal/service/openai_proxy_stream_circuit.go index 575fc134bb..761eac39fe 100644 --- a/backend/internal/service/openai_proxy_stream_circuit.go +++ b/backend/internal/service/openai_proxy_stream_circuit.go @@ -43,13 +43,22 @@ type openAIProxyStreamCircuitEntry struct { lastTouched time.Time } -// openAIProxyStreamCircuit is an in-process, proxy-ID keyed circuit. It is -// intentionally bounded and ephemeral: a restart clears observations, while a -// tripped entry expires automatically after its TTL. +// openAIProxyStreamCircuitKey scopes a circuit entry to one account on one +// proxy. The fault domain must stay per account: a single account whose +// streams disconnect repeatedly cannot be trusted, but other accounts sharing +// the same egress proxy are still healthy and must remain schedulable (#5010). +type openAIProxyStreamCircuitKey struct { + accountID int64 + proxyID int64 +} + +// openAIProxyStreamCircuit is an in-process, account+proxy keyed circuit. It +// is intentionally bounded and ephemeral: a restart clears observations, +// while a tripped entry expires automatically after its TTL. type openAIProxyStreamCircuit struct { mu sync.Mutex settings openAIProxyStreamCircuitSettings - entries map[int64]openAIProxyStreamCircuitEntry + entries map[openAIProxyStreamCircuitKey]openAIProxyStreamCircuitEntry } func resolveOpenAIProxyStreamCircuitSettings(s *OpenAIGatewayService) openAIProxyStreamCircuitSettings { @@ -95,7 +104,7 @@ func newOpenAIProxyStreamCircuit(settings openAIProxyStreamCircuitSettings) *ope } return &openAIProxyStreamCircuit{ settings: settings, - entries: make(map[int64]openAIProxyStreamCircuitEntry), + entries: make(map[openAIProxyStreamCircuitKey]openAIProxyStreamCircuitEntry), } } @@ -111,17 +120,17 @@ func (s *OpenAIGatewayService) getOpenAIProxyStreamCircuit() *openAIProxyStreamC return s.openaiProxyStreamCircuit } -func (c *openAIProxyStreamCircuit) recordFailure(proxyID int64, now time.Time) (bool, time.Time) { - if c == nil || c.settings.disabled || proxyID <= 0 { +func (c *openAIProxyStreamCircuit) recordFailure(key openAIProxyStreamCircuitKey, now time.Time) (bool, time.Time) { + if c == nil || c.settings.disabled || key.accountID <= 0 || key.proxyID <= 0 { return false, time.Time{} } c.mu.Lock() defer c.mu.Unlock() - entry, exists := c.entries[proxyID] + entry, exists := c.entries[key] if exists && now.Before(entry.blockedUntil) { entry.lastTouched = now - c.entries[proxyID] = entry + c.entries[key] = entry return false, entry.blockedUntil } if !exists { @@ -138,7 +147,7 @@ func (c *openAIProxyStreamCircuit) recordFailure(proxyID int64, now time.Time) ( if c.settings.collapseInterval > 0 && !entry.lastFailureAt.IsZero() && now.Sub(entry.lastFailureAt) >= 0 && now.Sub(entry.lastFailureAt) < c.settings.collapseInterval { entry.lastTouched = now - c.entries[proxyID] = entry + c.entries[key] = entry return false, time.Time{} } entry.failureCount++ @@ -148,44 +157,44 @@ func (c *openAIProxyStreamCircuit) recordFailure(proxyID int64, now time.Time) ( if tripped { entry.blockedUntil = now.Add(c.settings.quarantineTTL) } - c.entries[proxyID] = entry + c.entries[key] = entry return tripped, entry.blockedUntil } -func (c *openAIProxyStreamCircuit) recordSuccess(proxyID int64) bool { - if c == nil || proxyID <= 0 { +func (c *openAIProxyStreamCircuit) recordSuccess(key openAIProxyStreamCircuitKey) bool { + if c == nil || key.accountID <= 0 || key.proxyID <= 0 { return false } c.mu.Lock() defer c.mu.Unlock() - if _, ok := c.entries[proxyID]; !ok { + if _, ok := c.entries[key]; !ok { return false } - delete(c.entries, proxyID) + delete(c.entries, key) return true } -func (c *openAIProxyStreamCircuit) isBlocked(proxyID int64, now time.Time) bool { - if c == nil || c.settings.disabled || proxyID <= 0 { +func (c *openAIProxyStreamCircuit) isBlocked(key openAIProxyStreamCircuitKey, now time.Time) bool { + if c == nil || c.settings.disabled || key.accountID <= 0 || key.proxyID <= 0 { return false } c.mu.Lock() defer c.mu.Unlock() - entry, ok := c.entries[proxyID] + entry, ok := c.entries[key] if !ok || entry.blockedUntil.IsZero() { return false } if !now.Before(entry.blockedUntil) { - delete(c.entries, proxyID) + delete(c.entries, key) return false } return true } -// activeBlockCount reports how many proxies are currently quarantined. It -// gates the fail-open retry: a "no available accounts" selection result only -// warrants a second, quarantine-blind pass when the circuit is actually -// withholding capacity. +// activeBlockCount reports how many account+proxy pairs are currently +// quarantined. It gates the fail-open retry: a "no available accounts" +// selection result only warrants a second, quarantine-blind pass when the +// circuit is actually withholding capacity. func (c *openAIProxyStreamCircuit) activeBlockCount(now time.Time) int { if c == nil || c.settings.disabled { return 0 @@ -205,50 +214,56 @@ func (c *openAIProxyStreamCircuit) ensureCapacityLocked(now time.Time) { if len(c.entries) < c.settings.maxEntries { return } - for proxyID, entry := range c.entries { + for key, entry := range c.entries { staleObservation := entry.blockedUntil.IsZero() && now.Sub(entry.lastTouched) > c.settings.failureWindow expiredQuarantine := !entry.blockedUntil.IsZero() && !now.Before(entry.blockedUntil) if staleObservation || expiredQuarantine { - delete(c.entries, proxyID) + delete(c.entries, key) } } if len(c.entries) < c.settings.maxEntries { return } - var oldestProxyID int64 + var oldestKey openAIProxyStreamCircuitKey var oldest time.Time - for proxyID, entry := range c.entries { - if oldestProxyID == 0 || entry.lastTouched.Before(oldest) { - oldestProxyID = proxyID + found := false + for key, entry := range c.entries { + if !found || entry.lastTouched.Before(oldest) { + oldestKey = key oldest = entry.lastTouched + found = true } } - if oldestProxyID > 0 { - delete(c.entries, oldestProxyID) + if found { + delete(c.entries, oldestKey) } } -func openAIProxyStreamCircuitProxyID(account *Account) (int64, bool) { - if account == nil || account.Platform != PlatformOpenAI || account.ProxyID == nil || *account.ProxyID <= 0 { - return 0, false +// openAIProxyStreamCircuitKeyForAccount derives the circuit key from the +// account that owned the failed stream. Accounts without a static proxy keep +// bypassing the circuit, matching the previous proxy-only behaviour. +func openAIProxyStreamCircuitKeyForAccount(account *Account) (openAIProxyStreamCircuitKey, bool) { + if account == nil || account.Platform != PlatformOpenAI || account.ID <= 0 || + account.ProxyID == nil || *account.ProxyID <= 0 { + return openAIProxyStreamCircuitKey{}, false } - return *account.ProxyID, true + return openAIProxyStreamCircuitKey{accountID: account.ID, proxyID: *account.ProxyID}, true } func (s *OpenAIGatewayService) recordOpenAIProxyStreamDisconnect(account *Account, streamErr error, upstreamRequestID string) { - proxyID, ok := openAIProxyStreamCircuitProxyID(account) + key, ok := openAIProxyStreamCircuitKeyForAccount(account) if !ok || streamErr == nil || errors.Is(streamErr, context.Canceled) || errors.Is(streamErr, context.DeadlineExceeded) { return } circuit := s.getOpenAIProxyStreamCircuit() - tripped, until := circuit.recordFailure(proxyID, time.Now()) + tripped, until := circuit.recordFailure(key, time.Now()) if !tripped { return } logger.L().With(zap.String("component", "service.openai_gateway")).Warn( "openai.proxy_quarantined_stream_disconnect", - zap.Int64("proxy_id", proxyID), - zap.Int64("account_id", account.ID), + zap.Int64("proxy_id", key.proxyID), + zap.Int64("account_id", key.accountID), zap.Time("until", until), zap.String("upstream_request_id", upstreamRequestID), zap.String("error", sanitizeUpstreamErrorMessage(streamErr.Error())), @@ -256,12 +271,12 @@ func (s *OpenAIGatewayService) recordOpenAIProxyStreamDisconnect(account *Accoun } func (s *OpenAIGatewayService) clearOpenAIProxyStreamDisconnect(account *Account) { - proxyID, ok := openAIProxyStreamCircuitProxyID(account) + key, ok := openAIProxyStreamCircuitKeyForAccount(account) if !ok { return } if circuit := s.getOpenAIProxyStreamCircuit(); circuit != nil { - circuit.recordSuccess(proxyID) + circuit.recordSuccess(key) } } @@ -284,7 +299,7 @@ func openAIProxyStreamQuarantineBypassed(ctx context.Context) bool { } func (s *OpenAIGatewayService) isOpenAIProxyStreamQuarantined(ctx context.Context, account *Account) bool { - proxyID, ok := openAIProxyStreamCircuitProxyID(account) + key, ok := openAIProxyStreamCircuitKeyForAccount(account) if !ok { return false } @@ -292,7 +307,7 @@ func (s *OpenAIGatewayService) isOpenAIProxyStreamQuarantined(ctx context.Contex return false } circuit := s.getOpenAIProxyStreamCircuit() - return circuit != nil && circuit.isBlocked(proxyID, time.Now()) + return circuit != nil && circuit.isBlocked(key, time.Now()) } // logOpenAIProxyStreamQuarantineFailOpen emits a rate-limited warning when a diff --git a/backend/internal/service/openai_proxy_stream_circuit_test.go b/backend/internal/service/openai_proxy_stream_circuit_test.go index 76a07f9eae..fdcbc85227 100644 --- a/backend/internal/service/openai_proxy_stream_circuit_test.go +++ b/backend/internal/service/openai_proxy_stream_circuit_test.go @@ -8,6 +8,10 @@ import ( "github.com/stretchr/testify/require" ) +func circuitTestKey(accountID, proxyID int64) openAIProxyStreamCircuitKey { + return openAIProxyStreamCircuitKey{accountID: accountID, proxyID: proxyID} +} + func TestOpenAIProxyStreamCircuitThresholdTTLAndSuccessReset(t *testing.T) { base := time.Unix(1_800_000_000, 0) circuit := newOpenAIProxyStreamCircuit(openAIProxyStreamCircuitSettings{ @@ -16,23 +20,25 @@ func TestOpenAIProxyStreamCircuitThresholdTTLAndSuccessReset(t *testing.T) { quarantineTTL: 10 * time.Minute, maxEntries: 16, }) + key := circuitTestKey(1, 1) - tripped, _ := circuit.recordFailure(1, base) + tripped, _ := circuit.recordFailure(key, base) require.False(t, tripped) - require.False(t, circuit.isBlocked(1, base)) - require.True(t, circuit.recordSuccess(1)) + require.False(t, circuit.isBlocked(key, base)) + require.True(t, circuit.recordSuccess(key)) - tripped, _ = circuit.recordFailure(1, base.Add(10*time.Second)) + tripped, _ = circuit.recordFailure(key, base.Add(10*time.Second)) require.False(t, tripped, "success must clear the previous failure observation") - tripped, until := circuit.recordFailure(1, base.Add(20*time.Second)) + tripped, until := circuit.recordFailure(key, base.Add(20*time.Second)) require.True(t, tripped) require.Equal(t, base.Add(20*time.Second+10*time.Minute), until) - require.True(t, circuit.isBlocked(1, until.Add(-time.Nanosecond))) - require.False(t, circuit.isBlocked(1, until), "TTL expiry must re-admit the proxy") + require.True(t, circuit.isBlocked(key, until.Add(-time.Nanosecond))) + require.False(t, circuit.isBlocked(key, until), "TTL expiry must re-admit the account+proxy pair") - tripped, _ = circuit.recordFailure(2, base) + other := circuitTestKey(2, 1) + tripped, _ = circuit.recordFailure(other, base) require.False(t, tripped) - tripped, _ = circuit.recordFailure(2, base.Add(2*time.Minute)) + tripped, _ = circuit.recordFailure(other, base.Add(2*time.Minute)) require.False(t, tripped, "failures outside the window must not accumulate") } @@ -45,21 +51,22 @@ func TestOpenAIProxyStreamCircuitCollapsesBurstFailures(t *testing.T) { collapseInterval: 3 * time.Second, maxEntries: 16, }) + key := circuitTestKey(1, 1) // One HTTP/2 connection loss kills several multiplexed streams at once: // the near-simultaneous reports must count as a single failure event. - tripped, _ := circuit.recordFailure(1, base) + tripped, _ := circuit.recordFailure(key, base) require.False(t, tripped) - tripped, _ = circuit.recordFailure(1, base.Add(time.Second)) + tripped, _ = circuit.recordFailure(key, base.Add(time.Second)) require.False(t, tripped, "burst failures inside the collapse interval must merge") - tripped, _ = circuit.recordFailure(1, base.Add(2*time.Second)) + tripped, _ = circuit.recordFailure(key, base.Add(2*time.Second)) require.False(t, tripped, "burst failures inside the collapse interval must merge") - require.False(t, circuit.isBlocked(1, base.Add(2*time.Second))) + require.False(t, circuit.isBlocked(key, base.Add(2*time.Second))) // A second, distinct incident past the collapse interval still trips. - tripped, _ = circuit.recordFailure(1, base.Add(5*time.Second)) + tripped, _ = circuit.recordFailure(key, base.Add(5*time.Second)) require.True(t, tripped) - require.True(t, circuit.isBlocked(1, base.Add(5*time.Second))) + require.True(t, circuit.isBlocked(key, base.Add(5*time.Second))) } func TestOpenAIProxyStreamCircuitDisabled(t *testing.T) { @@ -71,10 +78,11 @@ func TestOpenAIProxyStreamCircuitDisabled(t *testing.T) { quarantineTTL: 10 * time.Minute, maxEntries: 16, }) + key := circuitTestKey(1, 1) - tripped, _ := circuit.recordFailure(1, base) + tripped, _ := circuit.recordFailure(key, base) require.False(t, tripped) - require.False(t, circuit.isBlocked(1, base)) + require.False(t, circuit.isBlocked(key, base)) require.Equal(t, 0, circuit.activeBlockCount(base)) } @@ -88,13 +96,42 @@ func TestOpenAIProxyStreamCircuitActiveBlockCount(t *testing.T) { }) require.Equal(t, 0, circuit.activeBlockCount(base)) - tripped, until := circuit.recordFailure(1, base) + tripped, until := circuit.recordFailure(circuitTestKey(1, 1), base) require.True(t, tripped) - circuit.recordFailure(2, base) // second proxy also tripped (threshold 1) + circuit.recordFailure(circuitTestKey(2, 1), base) // second account on the same proxy also tripped (threshold 1) require.Equal(t, 2, circuit.activeBlockCount(base.Add(time.Second))) require.Equal(t, 0, circuit.activeBlockCount(until), "expired quarantines must not count") } +func TestOpenAIProxyStreamCircuitIsolatesAccountsSharingProxy(t *testing.T) { + base := time.Unix(1_800_000_000, 0) + circuit := newOpenAIProxyStreamCircuit(openAIProxyStreamCircuitSettings{ + failureThreshold: 2, + failureWindow: time.Minute, + quarantineTTL: 10 * time.Minute, + maxEntries: 16, + }) + + failing := circuitTestKey(1, 7) + healthy := circuitTestKey(2, 7) + tripped, _ := circuit.recordFailure(failing, base) + require.False(t, tripped) + tripped, _ = circuit.recordFailure(failing, base.Add(time.Second)) + require.True(t, tripped) + require.True(t, circuit.isBlocked(failing, base.Add(time.Second))) + require.False(t, circuit.isBlocked(healthy, base.Add(time.Second)), + "another account on the same proxy must stay schedulable (#5010)") + + // Success on the healthy account must not clear the failing account's + // quarantine, and clearing the failing account must not clear a third one. + tripped, _ = circuit.recordFailure(healthy, base.Add(2*time.Second)) + require.False(t, tripped) + require.True(t, circuit.recordSuccess(healthy)) + require.True(t, circuit.isBlocked(failing, base.Add(2*time.Second))) + require.True(t, circuit.recordSuccess(failing)) + require.False(t, circuit.isBlocked(failing, base.Add(2*time.Second))) +} + func TestOpenAIProxyStreamQuarantineBypassContext(t *testing.T) { proxyID := int64(7) account := &Account{ID: 1, Platform: PlatformOpenAI, ProxyID: &proxyID} @@ -105,7 +142,7 @@ func TestOpenAIProxyStreamQuarantineBypassContext(t *testing.T) { quarantineTTL: 10 * time.Minute, maxEntries: 16, }) - svc.openaiProxyStreamCircuit.recordFailure(proxyID, time.Now()) + svc.openaiProxyStreamCircuit.recordFailure(circuitTestKey(account.ID, proxyID), time.Now()) ctx := context.Background() require.True(t, svc.isOpenAIProxyStreamQuarantined(ctx, account)) @@ -121,13 +158,13 @@ func TestOpenAIProxyStreamCircuitBoundsEntries(t *testing.T) { maxEntries: 2, }) - circuit.recordFailure(1, base) - circuit.recordFailure(2, base.Add(time.Second)) - circuit.recordFailure(3, base.Add(2*time.Second)) + circuit.recordFailure(circuitTestKey(1, 1), base) + circuit.recordFailure(circuitTestKey(2, 1), base.Add(time.Second)) + circuit.recordFailure(circuitTestKey(3, 1), base.Add(2*time.Second)) circuit.mu.Lock() defer circuit.mu.Unlock() require.Len(t, circuit.entries, 2) - _, oldestRetained := circuit.entries[1] + _, oldestRetained := circuit.entries[circuitTestKey(1, 1)] require.False(t, oldestRetained, "the oldest entry must be evicted at the bound") }