Files
sub2api/backend/internal/service/gateway_model_availability.go

195 lines
7.4 KiB
Go

package service
import (
"context"
"strings"
"time"
)
// ModelAvailabilityDiagnosis describes whether the requested model can be
// served by any persistently eligible account in the group (active with its
// schedulable setting enabled), ignoring transient state such as rate limits,
// overload, temporary unschedulability, and runtime blocks. Handlers use this
// on the "no available accounts" error path to distinguish 404
// model_not_found from 503 service_unavailable.
type ModelAvailabilityDiagnosis struct {
// HasAccountsInPool is true if the group has at least one persistently
// eligible account on the queried platform (or, for Anthropic/Gemini, on
// the platform plus mixed-scheduled Antigravity accounts).
HasAccountsInPool bool
// HasModelSupport is true if at least one account's model mapping admits
// the requested model.
HasModelSupport bool
// HasRetiredSubscriptionModel records a ChatGPT upstream blocked by model
// retirement, so an unsupported request can include migration guidance.
HasRetiredSubscriptionModel bool
// RetryAfterSeconds is the shortest known cooldown among model-capable
// accounts, rounded up and capped by gateway.retry_after_max_seconds. Zero
// means no recovery time could be determined, in which case handlers must
// omit the Retry-After header rather than guess.
RetryAfterSeconds int
}
// ModelAvailabilityDiagnoser is implemented by gateway services that can
// report whether the requested model is configured to be served by any
// account. Both *GatewayService and *OpenAIGatewayService implement this so
// handlers in either package can share a single classifier.
type ModelAvailabilityDiagnoser interface {
DiagnoseModelAvailabilityForPlatform(
ctx context.Context,
groupID *int64,
requestedModel string,
platform string,
) ModelAvailabilityDiagnosis
}
// DiagnoseModelAvailabilityForPlatform inspects accounts enabled for scheduling
// by persistent configuration and returns whether the requested model is
// configured to be served by any of them. The dedicated repository query
// bypasses scheduler snapshots and deliberately ignores transient rate-limit,
// overload, temporary-unschedulable, expiry, quota, and runtime-block state when
// deciding persistent eligibility; those transient cooldowns are instead
// reported as the earliest recovery time callers can turn into Retry-After.
//
// Safe to call on the error path: returns {true,true} on any internal failure
// or when the inputs preclude meaningful diagnosis (empty model, etc.), so
// callers stay on the 503 fallback branch.
func (s *GatewayService) DiagnoseModelAvailabilityForPlatform(
ctx context.Context,
groupID *int64,
requestedModel string,
platform string,
) ModelAvailabilityDiagnosis {
if s == nil {
return ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true}
}
requestedModel = strings.TrimSpace(requestedModel)
if requestedModel == "" {
// No model specified — cannot decide model_not_found. Caller falls back to 503.
return ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true}
}
poolActive := GenericCompositePoolActive(ctx)
if !poolActive && strings.TrimSpace(platform) == "" {
// Without a platform we cannot scope the lookup; bail out to the
// 503 branch rather than make an unscoped scan.
return ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true}
}
if s.accountRepo == nil {
return ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true}
}
useMixed := false
var platforms []string
cachePlatform := platform
if poolActive {
platforms = activeCompositePoolPlatformsForDiagnosis(ctx)
if len(platforms) == 0 {
return ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true}
}
cachePlatform = "pool:" + strings.Join(platforms, ",")
} else {
useMixed = platform == PlatformAnthropic || platform == PlatformGemini
platforms = []string{platform}
if useMixed {
platforms = append(platforms, PlatformAntigravity)
}
}
queryGroupID := groupID
includeGrouped := false
if useMixed {
// Preserve the generic scheduler's scope rules: an explicit group wins
// for mixed scheduling, while group-less simple mode scans all accounts.
if groupID == nil && s.cfg.UsesSharedSimpleModePool() {
includeGrouped = true
}
} else if s.cfg.UsesSharedSimpleModePool() {
queryGroupID = nil
includeGrouped = true
}
key := modelAvailabilityDiagnosisCacheKey{
platform: cachePlatform,
model: requestedModel,
noGroup: queryGroupID == nil,
grouped: includeGrouped,
contextKey: modelAvailabilityDiagnosisContextKey(ctx),
}
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 := 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 poolActive && !genericCompositePoolAccountServable(&accounts[i]) {
continue
}
diag.HasAccountsInPool = true
supported := false
if poolActive {
supported = s.gatewaySchedulingModelSupported(ctx, &accounts[i], requestedModel)
} else {
supported = s.isModelSupportedByAccountWithContext(ctx, &accounts[i], requestedModel)
}
if supported {
diag.HasModelSupport = true
if remaining := accountCooldownRemaining(ctx, &accounts[i], requestedModel); remaining > 0 {
if earliestRecovery == 0 || remaining < earliestRecovery {
earliestRecovery = remaining
}
} else {
hasUncooledCandidate = true
}
}
}
if hasUncooledCandidate {
earliestRecovery = 0
}
diag.RetryAfterSeconds = ceilRetryAfterSeconds(earliestRecovery, DownstreamRetryAfterMaxSeconds(s.cfg))
return diag, true
})
}
// accountCooldownRemaining reports how long an account stays unschedulable
// because of persisted cooldown state: account-level rate limit, overload, or
// temporary unschedulability windows plus per-model rate limits. Returns 0 when
// the account is not cooling down. When several windows overlap, the latest
// end wins because the account becomes schedulable only after all of them.
func accountCooldownRemaining(ctx context.Context, account *Account, requestedModel string) time.Duration {
if account == nil {
return 0
}
remaining := account.GetModelRateLimitRemainingTimeWithContext(ctx, requestedModel)
now := time.Now()
for _, until := range []*time.Time{
account.RateLimitResetAt,
account.OverloadUntil,
account.TempUnschedulableUntil,
} {
if until == nil {
continue
}
if wait := until.Sub(now); wait > remaining {
remaining = wait
}
}
return remaining
}