Files
sub2api/backend/internal/service/model_availability_diagnosis_cache.go
debug-zhang ff06dab68d 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.
2026-12-02 19:30:02 +08:00

175 lines
5.5 KiB
Go

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()
}