Files
sub2api/backend/internal/service/model_rate_limit.go
T
lishuangqiang 4114fedd18 fix(ratelimit): lift Anthropic Fable model limit when the 7d_oi window recovers
7d_oi 窗口耗尽时 persistAnthropicFableWindowLimit 会给账号写入
model_rate_limits["claude-fable-5"],冷却到窗口重置时间(最长 7 天)。
写入之后没有任何路径会撤销它:

- samplePassiveUsageFromHeaders / syncActiveToPassive 只更新
  passive_usage_7d_oi_utilization,不与 model_rate_limits 联动;
- applyAnthropicFableSchedulingThreshold 只设不清;
- UpdateSessionWindow 的自动清除只看账号级 RateLimitResetAt,
  而窗口耗尽分支刻意不设它(账号对其他模型仍然可调度)。

于是用户用重置卡让上游额度提前归零后,本地仍按旧的 rate_limit_reset_at 返回
503 No available accounts supporting model,只能人工删 extra 或点“清除限流”。

修复:

- 上游明确回报 7d_oi utilization 低于阈值(重置卡生效/窗口滚动)、且该窗口未处于
  rejected/exceeded 时,撤销窗口耗尽写入的限流;缺失数据一律不动,缺失不等于 0;
- 只清 claude-fable-5 这一个 scope(新增 AccountRepository.ClearModelRateLimit,
  jsonb 单键删除),不影响其他模型与并发新写入的限流;
- 只清 reason 为 anthropic_7d_oi_window_exhausted 的记录:credits required 与
  管理端阈值来源语义不同,不能被窗口用量顺手清掉;
- 写库成功后才同步本实例的账号快照;写库失败保持原样,避免本实例放行而调度快照仍拦截。

两个观测点都接上:请求响应头的被动采样,以及管理端主动刷新额度。
2026-11-14 17:50:14 +08:00

271 lines
8.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package service
import (
"context"
"maps"
"strings"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/antigravity"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
)
const (
modelRateLimitsKey = "model_rate_limits"
antigravityGeminiModelRateLimitKey = "antigravity:gemini"
antigravityArgonModelRateLimitKey = "antigravity:gemini:argon"
openAIImageGenerationRateLimitKey = "openai:image_generation"
openAICodexSparkRateLimitReason = "openai_codex_spark_rate_limit"
// anthropicFableRateLimitKey 是 Anthropic 7d_oi(Fable 专属 7d 窗口)限流的
// 家族级 scope:命中后所有 Fable 变体(含 [1m] 等后缀)都不再调度到该账号。
anthropicFableRateLimitKey = "claude-fable-5"
)
// isRateLimitActiveForKey 检查指定 key 的限流是否生效
func (a *Account) isRateLimitActiveForKey(key string) bool {
resetAt := a.modelRateLimitResetAt(key)
return resetAt != nil && time.Now().Before(*resetAt)
}
// getRateLimitRemainingForKey 获取指定 key 的限流剩余时间,0 表示未限流或已过期
func (a *Account) getRateLimitRemainingForKey(key string) time.Duration {
resetAt := a.modelRateLimitResetAt(key)
if resetAt == nil {
return 0
}
remaining := time.Until(*resetAt)
if remaining > 0 {
return remaining
}
return 0
}
func (a *Account) isModelRateLimitedWithContext(ctx context.Context, requestedModel string) bool {
for _, key := range a.modelRateLimitKeysForRequest(ctx, requestedModel) {
if a.isRateLimitActiveForKey(key) {
return true
}
}
return false
}
// GetModelRateLimitRemainingTime 获取模型限流剩余时间
// 返回 0 表示未限流或已过期
func (a *Account) GetModelRateLimitRemainingTime(requestedModel string) time.Duration {
return a.GetModelRateLimitRemainingTimeWithContext(context.Background(), requestedModel)
}
func (a *Account) GetModelRateLimitRemainingTimeWithContext(ctx context.Context, requestedModel string) time.Duration {
remaining := time.Duration(0)
for _, key := range a.modelRateLimitKeysForRequest(ctx, requestedModel) {
if keyRemaining := a.getRateLimitRemainingForKey(key); keyRemaining > remaining {
remaining = keyRemaining
}
}
return remaining
}
func (a *Account) modelRateLimitKeysForRequest(ctx context.Context, requestedModel string) []string {
if a == nil {
return nil
}
modelKey := a.GetMappedModel(requestedModel)
if a.Platform == PlatformAntigravity {
modelKey = resolveFinalAntigravityModelKey(ctx, a, requestedModel)
}
modelKey = strings.TrimSpace(modelKey)
if modelKey == "" {
return nil
}
keys := []string{modelKey}
switch a.Platform {
case PlatformAntigravity:
return antigravityModelRateLimitKeys(a, modelKey)
case PlatformOpenAI:
if openAIImageGenerationRateLimitApplies(ctx, requestedModel, modelKey) && modelKey != openAIImageGenerationRateLimitKey {
keys = append(keys, openAIImageGenerationRateLimitKey)
}
case PlatformAnthropic:
if isAnthropicFableModel(modelKey) && modelKey != anthropicFableRateLimitKey {
keys = append(keys, anthropicFableRateLimitKey)
}
case PlatformCline:
if walletKey := clineWalletRateLimitKey(modelKey); walletKey != "" {
keys = append(keys, walletKey)
}
}
return keys
}
// isAnthropicFableModel 判断是否为 Fable 模型家族(claude-fable-5、claude-fable-5[1m] 等变体)
func isAnthropicFableModel(model string) bool {
return strings.Contains(strings.ToLower(model), "fable")
}
func openAIImageGenerationRateLimitApplies(ctx context.Context, requestedModel, modelKey string) bool {
if isOpenAIImageGenerationModel(requestedModel) || isOpenAIImageGenerationModel(modelKey) {
return true
}
return OpenAIImageGenerationIntentFromContext(ctx)
}
func WithOpenAIImageGenerationIntent(ctx context.Context) context.Context {
if ctx == nil {
ctx = context.Background()
}
return context.WithValue(ctx, ctxkey.OpenAIImageGenerationIntent, true)
}
func OpenAIImageGenerationIntentFromContext(ctx context.Context) bool {
if ctx == nil {
return false
}
enabled, ok := ctx.Value(ctxkey.OpenAIImageGenerationIntent).(bool)
return ok && enabled
}
// WithOpenAIImagesEndpoint 标记请求从 /v1/images/* 专用生图端点入站。
func WithOpenAIImagesEndpoint(ctx context.Context) context.Context {
if ctx == nil {
ctx = context.Background()
}
return context.WithValue(ctx, ctxkey.OpenAIImagesEndpoint, true)
}
// OpenAIImagesEndpointFromContext 报告请求是否来自 /v1/images/*。
func OpenAIImagesEndpointFromContext(ctx context.Context) bool {
if ctx == nil {
return false
}
enabled, ok := ctx.Value(ctxkey.OpenAIImagesEndpoint).(bool)
return ok && enabled
}
func resolveFinalAntigravityModelKey(ctx context.Context, account *Account, requestedModel string) string {
modelKey := mapAntigravityModel(account, requestedModel)
if modelKey == "" {
return ""
}
// thinking 会影响 Antigravity 最终模型名(例如 claude-sonnet-4-5 -> claude-sonnet-4-5-thinking)
if enabled, ok := ThinkingEnabledFromContext(ctx); ok {
modelKey = applyThinkingModelSuffix(modelKey, enabled)
}
return modelKey
}
func isAntigravityGeminiModel(model string) bool {
return strings.HasPrefix(normalizeAntigravityModelName(model), "gemini-")
}
func antigravityModelRateLimitKeys(account *Account, model string) []string {
model = strings.TrimSpace(model)
if model == "" {
return nil
}
keys := []string{model}
if isAntigravityGeminiModel(model) && !isAntigravityGeminiImageModel(model) && model != antigravityGeminiModelRateLimitKey {
familyKey := antigravityGeminiModelRateLimitKey
// Pro has a separate Argon quota pool. Ultra and unknown plans retain
// the shared Gemini scope; Argon variants still cool down together.
if account != nil && strings.EqualFold(strings.TrimSpace(antigravity.TierIDToPlanType(account.GetCredential("plan_type"))), "Pro") {
normalized := normalizeAntigravityModelName(model)
if normalized == "gemini-4-argon" || strings.HasPrefix(normalized, "gemini-4-argon-") {
familyKey = antigravityArgonModelRateLimitKey
}
}
keys = append(keys, familyKey)
}
return keys
}
func isAntigravityGeminiImageModel(model string) bool {
normalized := normalizeAntigravityModelName(model)
return strings.HasPrefix(normalized, "gemini-") && strings.Contains(normalized, "-image")
}
func (a *Account) modelRateLimitResetAt(scope string) *time.Time {
if a == nil || a.Extra == nil || scope == "" {
return nil
}
rawLimits, ok := a.Extra[modelRateLimitsKey].(map[string]any)
if !ok {
return nil
}
rawLimit, ok := rawLimits[scope].(map[string]any)
if !ok {
return nil
}
resetAtRaw, ok := rawLimit["rate_limit_reset_at"].(string)
if !ok || strings.TrimSpace(resetAtRaw) == "" {
return nil
}
resetAt, err := time.Parse(time.RFC3339, resetAtRaw)
if err != nil {
return nil
}
return &resetAt
}
// modelRateLimitReason 返回指定 scope 冷却记录中的原因;没有记录时为空。
func (a *Account) modelRateLimitReason(scope string) string {
if a == nil || a.Extra == nil {
return ""
}
rawLimits, _ := a.Extra[modelRateLimitsKey].(map[string]any)
rawLimit, _ := rawLimits[scope].(map[string]any)
reason, _ := rawLimit["reason"].(string)
return reason
}
// setAccountModelRateLimitSnapshot 把模型级限流写进本账号对象的 Extra 快照。
// 写时复制:Extra 与其中的 model_rate_limits 可能与调度快照母本及其它副本共享,
// 这里只读取旧 map,写入新复制的 map 后替换 account.Extra,不修改任何已有 map。
func setAccountModelRateLimitSnapshot(account *Account, scope string, resetAt time.Time, reason string, now time.Time) {
if account == nil || strings.TrimSpace(scope) == "" {
return
}
payload := map[string]any{
"rate_limited_at": now.UTC().Format(time.RFC3339),
"rate_limit_reset_at": resetAt.UTC().Format(time.RFC3339),
}
if reason = strings.TrimSpace(reason); reason != "" {
payload["reason"] = reason
}
oldLimits, _ := account.Extra[modelRateLimitsKey].(map[string]any)
limits := make(map[string]any, len(oldLimits)+1)
maps.Copy(limits, oldLimits)
limits[scope] = payload
extra := make(map[string]any, len(account.Extra)+1)
maps.Copy(extra, account.Extra)
extra[modelRateLimitsKey] = limits
account.Extra = extra
}
// clearAccountModelRateLimitSnapshot 从本账号对象的 Extra 快照中删除指定 scope,
// 让当前实例立刻停止跳过该模型,而不必等下一次快照重建。
// 与 setAccountModelRateLimitSnapshot 一样写时复制,不修改可能共享的旧 map。
func clearAccountModelRateLimitSnapshot(account *Account, scope string) {
if account == nil || strings.TrimSpace(scope) == "" {
return
}
oldLimits, ok := account.Extra[modelRateLimitsKey].(map[string]any)
if !ok {
return
}
if _, exists := oldLimits[scope]; !exists {
return
}
limits := make(map[string]any, len(oldLimits))
maps.Copy(limits, oldLimits)
delete(limits, scope)
extra := make(map[string]any, len(account.Extra))
maps.Copy(extra, account.Extra)
extra[modelRateLimitsKey] = limits
account.Extra = extra
}