fix(anthropic): scope Fable scheduling threshold to Fable models

让 Fable 7d_oi 调度阈值仅限制 Fable 模型族,不暂停整个 Anthropic 账号。
This commit is contained in:
m11y authored and GitHub committed 2026-08-29 17:30:18 +08:00
1 parent 32ac921f24
commit ea4291a92c
5 files changed
+203

No files matched your search

@@ -78,6 +78,32 @@ func EvaluateAccountSchedulingThreshold(account *Account, thresholds map[string]
return decision
}
func evaluateAnthropicFableSchedulingThreshold(account *Account, thresholds map[string]int, now time.Time) AccountSchedulingThresholdDecision {
decision := AccountSchedulingThresholdDecision{}
if account == nil || !strings.EqualFold(strings.TrimSpace(account.Platform), PlatformAnthropic) {
return decision
}
decision.Platform = PlatformAnthropic
threshold, ok := resolveEffectiveAccountSchedulingThreshold(account, thresholds, PlatformAnthropic)
decision.ThresholdPercent = threshold
if !ok || threshold >= 100 {
return decision
}
candidate := anthropicFableThresholdCandidate(account)
if !candidateMatchesThreshold(candidate, threshold, now) {
return decision
}
decision.ShouldPause = true
decision.Window = candidate.window
decision.Scope = candidate.scope
decision.UsedPercent = candidate.usedPercent
decision.Until = candidate.until
return decision
}
func isAllowedSchedulingThresholdPlatform(platform string) bool {
for _, allowed := range AllowedSchedulingThresholdPlatforms {
if platform == allowed {
@@ -280,6 +306,22 @@ func anthropicThresholdCandidates(account *Account) []*accountSchedulingThreshol
return candidates
}
func anthropicFableThresholdCandidate(account *Account) *accountSchedulingThresholdCandidate {
if account == nil {
return nil
}
usedPercent := utilizationAsPercent(account.Extra["passive_usage_7d_oi_utilization"])
if usedPercent <= 0 {
return nil
}
return &accountSchedulingThresholdCandidate{
window: "7d_oi",
scope: anthropicFableRateLimitKey,
usedPercent: usedPercent,
until: parseSchedulingResetAt(account.Extra["passive_usage_7d_oi_reset"]),
}
}
// NOTE: Gemini / Kiro / Antigravity are intentionally NOT threshold-pausing
// platforms (see AllowedSchedulingThresholdPlatforms and the evaluator switch,
// asserted by TestEvaluateAccountSchedulingThreshold_UnsupportedPlatformsDoNotPause).
@@ -96,6 +96,43 @@ func TestEvaluateAccountSchedulingThreshold_AnthropicIgnoresExpiredFiveHourWindo
require.True(t, wantUntil.Equal(*decision.Until))
}
func TestEvaluateAnthropicFableSchedulingThreshold_UsesAccountOverrideWithoutPausingAccount(t *testing.T) {
t.Parallel()
now := time.Date(2026, 8, 29, 1, 0, 0, 0, time.UTC)
wantUntil := now.Add(4 * 24 * time.Hour)
account := &Account{
Platform: PlatformAnthropic,
Credentials: map[string]any{
"account_scheduling_threshold": 60,
},
Extra: map[string]any{
"passive_usage_7d_utilization": 0.40,
"passive_usage_7d_reset": float64(now.Add(3 * 24 * time.Hour).Unix()),
"passive_usage_7d_oi_utilization": 0.61,
"passive_usage_7d_oi_reset": float64(wantUntil.Unix()),
},
}
thresholds := map[string]int{
PlatformAnthropic: 100,
}
accountDecision := EvaluateAccountSchedulingThreshold(account, thresholds, now)
require.False(t, accountDecision.ShouldPause)
decision := evaluateAnthropicFableSchedulingThreshold(account, thresholds, now)
require.True(t, decision.ShouldPause)
require.Equal(t, PlatformAnthropic, decision.Platform)
require.Equal(t, "7d_oi", decision.Window)
require.Equal(t, anthropicFableRateLimitKey, decision.Scope)
require.Equal(t, 60, decision.ThresholdPercent)
require.Equal(t, 61.0, decision.UsedPercent)
require.NotNil(t, decision.Until)
require.True(t, wantUntil.Equal(*decision.Until))
}
func TestEvaluateAccountSchedulingThreshold_OpenAIPreservesPercentageSemantics(t *testing.T) {
t.Parallel()
@@ -188,3 +188,25 @@ func (a *Account) modelRateLimitResetAt(scope string) *time.Time {
}
return &resetAt
}
func setAccountModelRateLimitSnapshot(account *Account, scope string, resetAt time.Time, reason string, now time.Time) {
if account == nil || strings.TrimSpace(scope) == "" {
return
}
if account.Extra == nil {
account.Extra = make(map[string]any)
}
limits, ok := account.Extra[modelRateLimitsKey].(map[string]any)
if !ok {
limits = make(map[string]any)
account.Extra[modelRateLimitsKey] = limits
}
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
}
limits[scope] = payload
}
@@ -169,6 +169,7 @@ func (s *RateLimitService) ApplyAccountSchedulingThreshold(ctx context.Context,
thresholds := s.settingService.GetAccountSchedulingThresholds(ctx)
decision := EvaluateAccountSchedulingThreshold(account, thresholds, now)
if !decision.ShouldPause || decision.Until == nil || !decision.Until.After(now) {
s.applyAnthropicFableSchedulingThreshold(ctx, account, thresholds, now)
return false
}
@@ -222,6 +223,43 @@ func (s *RateLimitService) ApplyAccountSchedulingThreshold(ctx context.Context,
return true
}
func (s *RateLimitService) applyAnthropicFableSchedulingThreshold(ctx context.Context, account *Account, thresholds map[string]int, now time.Time) {
decision := evaluateAnthropicFableSchedulingThreshold(account, thresholds, now)
if !decision.ShouldPause || decision.Until == nil || !decision.Until.After(now) {
return
}
if account.isRateLimitActiveForKey(anthropicFableRateLimitKey) {
return
}
reason := BuildDetailedAccountSchedulingThresholdReason(AccountSchedulingThresholdReasonInput{
Platform: decision.Platform,
Window: decision.Window,
Scope: decision.Scope,
ThresholdPercent: decision.ThresholdPercent,
UsedPercent: decision.UsedPercent,
Until: *decision.Until,
Now: now,
})
setAccountModelRateLimitSnapshot(account, anthropicFableRateLimitKey, *decision.Until, reason, now)
if err := s.accountRepo.SetModelRateLimit(ctx, account.ID, anthropicFableRateLimitKey, *decision.Until, reason); err != nil {
slog.Warn("anthropic_fable_scheduling_threshold_set_model_limit_failed",
"account_id", account.ID,
"threshold_percent", decision.ThresholdPercent,
"used_percent", decision.UsedPercent,
"until", decision.Until.UTC(),
"error", err)
return
}
slog.Info("anthropic_fable_scheduling_threshold_model_limited",
"account_id", account.ID,
"scope", anthropicFableRateLimitKey,
"threshold_percent", decision.ThresholdPercent,
"used_percent", decision.UsedPercent,
"until", decision.Until.UTC())
}
func accountHasSameSchedulingThresholdPause(account *Account, until time.Time, reason string) bool {
if account == nil || account.TempUnschedulableUntil == nil {
return false
@@ -90,6 +90,70 @@ func TestRateLimitService_ApplyAccountSchedulingThreshold_UsesAccountOverrideInR
require.Contains(t, payload["error_message"], "85.5% used >= 80%")
}
type fableSchedulingThresholdRepoStub struct {
rateLimitAccountRepoStub
modelCalls int
lastModelScope string
lastModelReset time.Time
lastModelReason string
}
func (r *fableSchedulingThresholdRepoStub) SetModelRateLimit(_ context.Context, _ int64, scope string, resetAt time.Time, reason ...string) error {
r.modelCalls++
r.lastModelScope = scope
r.lastModelReset = resetAt
if len(reason) > 0 {
r.lastModelReason = reason[0]
}
return nil
}
func TestRateLimitService_ApplyAccountSchedulingThreshold_FableOnlyLimitsFableModels(t *testing.T) {
accountSchedulingThresholdsSF.Forget(SettingKeyAccountSchedulingThresholds)
accountSchedulingThresholdsCache.Store(&cachedAccountSchedulingThresholds{})
settingsRepo := newMockSettingRepo()
settingsRepo.data[SettingKeyAccountSchedulingThresholds] = `{"anthropic":100}`
accountRepo := &fableSchedulingThresholdRepoStub{}
rl := NewRateLimitService(accountRepo, nil, &config.Config{}, nil, nil)
rl.SetSettingService(NewSettingService(settingsRepo, &config.Config{}))
until := time.Now().UTC().Add(4 * 24 * time.Hour).Truncate(time.Second)
account := &Account{
ID: 1004,
Platform: PlatformAnthropic,
Status: StatusActive,
Schedulable: true,
Credentials: map[string]any{
"account_scheduling_threshold": 60,
},
Extra: map[string]any{
"passive_usage_7d_utilization": 0.40,
"passive_usage_7d_reset": float64(time.Now().UTC().Add(3 * 24 * time.Hour).Unix()),
"passive_usage_7d_oi_utilization": 0.61,
"passive_usage_7d_oi_reset": float64(until.Unix()),
},
}
blocked := rl.ApplyAccountSchedulingThreshold(context.Background(), account)
require.False(t, blocked, "the Fable-only window must not pause the whole account")
require.Zero(t, accountRepo.tempCalls)
require.Equal(t, 1, accountRepo.modelCalls)
require.Equal(t, anthropicFableRateLimitKey, accountRepo.lastModelScope)
require.WithinDuration(t, until, accountRepo.lastModelReset, time.Second)
require.True(t, IsAccountSchedulingThresholdReason(accountRepo.lastModelReason))
require.False(t, account.IsSchedulableForModel("claude-fable-5"))
require.False(t, account.IsSchedulableForModel("claude-fable-5[1m]"))
require.True(t, account.IsSchedulableForModel("claude-opus-4-8"))
require.True(t, account.IsSchedulableForModel("claude-sonnet-4-6"))
blocked = rl.ApplyAccountSchedulingThreshold(context.Background(), account)
require.False(t, blocked)
require.Equal(t, 1, accountRepo.modelCalls, "an active model limit should not be persisted twice")
}
func TestRateLimitService_ApplyAccountSchedulingThreshold_SkipsDuplicateTempUnschedulable(t *testing.T) {
accountSchedulingThresholdsSF.Forget(SettingKeyAccountSchedulingThresholds)
accountSchedulingThresholdsCache.Store(&cachedAccountSchedulingThresholds{})