mirror of
https://github.com/Wei-Shaw/sub2api
synced 2026-12-06 01:12:31 +00:00
Merge pull request #9231 from debug-zhang/fix/6182-selection-failure-diagnostics
fix(observability): attribute selection model cooldown failures by reason
This commit is contained in:
8 files changed
+438
-15
No files matched your search
@@ -380,3 +380,26 @@ func TestClassifyNoAccountError_ModelNotFoundOmitsRetryAfter(t *testing.T) {
|
||||
require.Empty(t, c.Writer.Header().Get("Retry-After"),
|
||||
"a permanent model configuration error has no recovery time")
|
||||
}
|
||||
|
||||
// The scheduler now appends a model-cooldown reason breakdown to the legacy
|
||||
// summary. The 429 upgrade must keep parsing the aggregate model_rate_limited
|
||||
// count, and the breakdown keys must not be mistaken for it.
|
||||
func TestClassifySelectionFailureError_NewReasonBreakdownStillUpgrades(t *testing.T) {
|
||||
fallback := noAccountErrorClassification{
|
||||
Status: http.StatusServiceUnavailable,
|
||||
ErrType: "api_error",
|
||||
Message: "Service temporarily unavailable",
|
||||
}
|
||||
|
||||
got := classifySelectionFailureError(
|
||||
fmt.Errorf("no available accounts supporting model: gpt-5.6-sol "+
|
||||
"(total=37 eligible=0 excluded=0 unschedulable=0 platform_filtered=0 model_unsupported=0 "+
|
||||
"model_rate_limited=36 model_rate_limited_reasons=other:2,upstream_404_model_not_found:34 profit_threshold=0 "+
|
||||
"profit_invalid_account_rate=0)"),
|
||||
fallback,
|
||||
)
|
||||
|
||||
require.Equal(t, http.StatusTooManyRequests, got.Status)
|
||||
require.Equal(t, "rate_limit_error", got.ErrType)
|
||||
require.False(t, got.ModelNotFound)
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"log/slog"
|
||||
mathrand "math/rand"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -2415,23 +2416,30 @@ func (s *GatewayService) selectAccountWithMixedScheduling(ctx context.Context, g
|
||||
}
|
||||
|
||||
type selectionFailureStats struct {
|
||||
Total int
|
||||
Eligible int
|
||||
Excluded int
|
||||
Unschedulable int
|
||||
PlatformFiltered int
|
||||
ModelUnsupported int
|
||||
ModelRateLimited int
|
||||
ProfitThreshold int
|
||||
ProfitInvalidRate int
|
||||
SamplePlatformIDs []int64
|
||||
SampleMappingIDs []int64
|
||||
SampleRateLimitIDs []string
|
||||
Total int
|
||||
Eligible int
|
||||
Excluded int
|
||||
Unschedulable int
|
||||
PlatformFiltered int
|
||||
ModelUnsupported int
|
||||
ModelRateLimited int
|
||||
ProfitThreshold int
|
||||
ProfitInvalidRate int
|
||||
// ModelRateLimitedReasons breaks ModelRateLimited down by the persisted
|
||||
// model-level cooldown reason (e.g. upstream_404_model_not_found). Empty or
|
||||
// unrecognized reasons are bucketed as "other" so the key set stays bounded.
|
||||
ModelRateLimitedReasons map[string]int
|
||||
SamplePlatformIDs []int64
|
||||
SampleMappingIDs []int64
|
||||
SampleRateLimitIDs []string
|
||||
}
|
||||
|
||||
type selectionFailureDiagnosis struct {
|
||||
Category string
|
||||
Detail string
|
||||
// Reason carries the persisted cooldown reason for model_rate_limited. It is
|
||||
// diagnostics-only and never feeds back into scheduling decisions.
|
||||
Reason string
|
||||
}
|
||||
|
||||
func (s *GatewayService) logDetailedSelectionFailure(
|
||||
@@ -2445,9 +2453,14 @@ func (s *GatewayService) logDetailedSelectionFailure(
|
||||
allowMixedScheduling bool,
|
||||
) selectionFailureStats {
|
||||
stats := s.collectSelectionFailureStats(ctx, accounts, requestedModel, platform, excludedIDs, allowMixedScheduling)
|
||||
reasonCounts := formatSelectionFailureReasonCounts(stats.ModelRateLimitedReasons)
|
||||
if reasonCounts == "" {
|
||||
reasonCounts = "-"
|
||||
}
|
||||
logger.LegacyPrintf(
|
||||
"service.gateway",
|
||||
"[SelectAccountDetailed] group_id=%v model=%s platform=%s session=%s total=%d eligible=%d excluded=%d unschedulable=%d platform_filtered=%d model_unsupported=%d model_rate_limited=%d profit_threshold=%d profit_invalid_account_rate=%d sample_platform_filtered=%v sample_model_unsupported=%v sample_model_rate_limited=%v",
|
||||
"[SelectAccountDetailed] request_id=%s group_id=%v model=%s platform=%s session=%s total=%d eligible=%d excluded=%d unschedulable=%d platform_filtered=%d model_unsupported=%d model_rate_limited=%d model_rate_limited_reasons=%s profit_threshold=%d profit_invalid_account_rate=%d sample_platform_filtered=%v sample_model_unsupported=%v sample_model_rate_limited=%v",
|
||||
selectionFailureRequestID(ctx),
|
||||
derefGroupID(groupID),
|
||||
requestedModel,
|
||||
platform,
|
||||
@@ -2459,6 +2472,7 @@ func (s *GatewayService) logDetailedSelectionFailure(
|
||||
stats.PlatformFiltered,
|
||||
stats.ModelUnsupported,
|
||||
stats.ModelRateLimited,
|
||||
reasonCounts,
|
||||
stats.ProfitThreshold,
|
||||
stats.ProfitInvalidRate,
|
||||
stats.SamplePlatformIDs,
|
||||
@@ -2468,6 +2482,17 @@ func (s *GatewayService) logDetailedSelectionFailure(
|
||||
return stats
|
||||
}
|
||||
|
||||
// selectionFailureRequestID extracts the request-scoped ID used by the request
|
||||
// logger so the selection-failure log line can be joined with the final error
|
||||
// and upstream events for the same request.
|
||||
func selectionFailureRequestID(ctx context.Context) string {
|
||||
if ctx == nil {
|
||||
return ""
|
||||
}
|
||||
requestID, _ := ctx.Value(ctxkey.RequestID).(string)
|
||||
return strings.TrimSpace(requestID)
|
||||
}
|
||||
|
||||
func (s *GatewayService) collectSelectionFailureStats(
|
||||
ctx context.Context,
|
||||
accounts []Account,
|
||||
@@ -2496,6 +2521,14 @@ func (s *GatewayService) collectSelectionFailureStats(
|
||||
stats.SampleMappingIDs = appendSelectionFailureSampleID(stats.SampleMappingIDs, acc.ID)
|
||||
case "model_rate_limited":
|
||||
stats.ModelRateLimited++
|
||||
reason := strings.TrimSpace(diagnosis.Reason)
|
||||
if reason == "" {
|
||||
reason = modelRateLimitDiagnosticOtherReason
|
||||
}
|
||||
if stats.ModelRateLimitedReasons == nil {
|
||||
stats.ModelRateLimitedReasons = make(map[string]int, 4)
|
||||
}
|
||||
stats.ModelRateLimitedReasons[reason]++
|
||||
remaining := acc.GetRateLimitRemainingTimeWithContext(ctx, requestedModel).Truncate(time.Second)
|
||||
stats.SampleRateLimitIDs = appendSelectionFailureRateSample(stats.SampleRateLimitIDs, acc.ID, remaining)
|
||||
case openAIProfitFilterReasonThreshold:
|
||||
@@ -2541,9 +2574,15 @@ func (s *GatewayService) diagnoseSelectionFailure(
|
||||
}
|
||||
if !s.isAccountSchedulableForModelSelection(ctx, acc, requestedModel) {
|
||||
remaining := acc.GetRateLimitRemainingTimeWithContext(ctx, requestedModel).Truncate(time.Second)
|
||||
reason := modelRateLimitDiagnosticOtherReason
|
||||
if diagnostic, ok := acc.activeModelRateLimitDiagnostic(ctx, requestedModel); ok {
|
||||
remaining = diagnostic.Remaining.Truncate(time.Second)
|
||||
reason = diagnostic.Reason
|
||||
}
|
||||
return selectionFailureDiagnosis{
|
||||
Category: "model_rate_limited",
|
||||
Detail: fmt.Sprintf("remaining=%s", remaining),
|
||||
Detail: fmt.Sprintf("remaining=%s reason=%s", remaining, reason),
|
||||
Reason: reason,
|
||||
}
|
||||
}
|
||||
if vetoed, reason := openAIProfitControlVetoReason(ctx, acc); vetoed {
|
||||
@@ -2585,7 +2624,7 @@ func appendSelectionFailureRateSample(samples []string, accountID int64, remaini
|
||||
}
|
||||
|
||||
func summarizeSelectionFailureStats(stats selectionFailureStats) string {
|
||||
return fmt.Sprintf(
|
||||
summary := fmt.Sprintf(
|
||||
"total=%d eligible=%d excluded=%d unschedulable=%d platform_filtered=%d model_unsupported=%d model_rate_limited=%d profit_threshold=%d profit_invalid_account_rate=%d",
|
||||
stats.Total,
|
||||
stats.Eligible,
|
||||
@@ -2597,6 +2636,36 @@ func summarizeSelectionFailureStats(stats selectionFailureStats) string {
|
||||
stats.ProfitThreshold,
|
||||
stats.ProfitInvalidRate,
|
||||
)
|
||||
// Keep the legacy summary prefix verbatim: handlers parse
|
||||
// model_rate_limited=<n> to classify the failure. The breakdown is appended
|
||||
// only when present and never reuses the "<name>=<n>" form of that key.
|
||||
if reasons := formatSelectionFailureReasonCounts(stats.ModelRateLimitedReasons); reasons != "" {
|
||||
summary += " model_rate_limited_reasons=" + reasons
|
||||
}
|
||||
return summary
|
||||
}
|
||||
|
||||
// formatSelectionFailureReasonCounts renders reason counts deterministically
|
||||
// (sorted by reason, comma separated) for both the error summary and logs.
|
||||
func formatSelectionFailureReasonCounts(counts map[string]int) string {
|
||||
if len(counts) == 0 {
|
||||
return ""
|
||||
}
|
||||
reasons := make([]string, 0, len(counts))
|
||||
for reason := range counts {
|
||||
reasons = append(reasons, reason)
|
||||
}
|
||||
sort.Strings(reasons)
|
||||
var b strings.Builder
|
||||
for i, reason := range reasons {
|
||||
if i > 0 {
|
||||
_ = b.WriteByte(',')
|
||||
}
|
||||
_, _ = b.WriteString(reason)
|
||||
_ = b.WriteByte(':')
|
||||
_, _ = b.WriteString(strconv.Itoa(counts[reason]))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// isModelSupportedByAccountWithContext 根据账户平台检查模型支持(带 context)
|
||||
|
||||
@@ -139,3 +139,146 @@ func TestDiagnoseSelectionFailure_ModelRateLimitedDetail(t *testing.T) {
|
||||
t.Fatalf("detail=%s want contains remaining=", diagnosis.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
func modelRateLimitExtra(model, resetAt, reason string) map[string]any {
|
||||
limit := map[string]any{
|
||||
"rate_limit_reset_at": resetAt,
|
||||
}
|
||||
if reason != "" {
|
||||
limit["reason"] = reason
|
||||
}
|
||||
return map[string]any{
|
||||
"model_rate_limits": map[string]any{
|
||||
model: limit,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Model-level cooldowns used to be aggregated into a single
|
||||
// model_rate_limited counter. The breakdown must attribute each account to the
|
||||
// reason persisted by the cooldown writer, without changing the primary bucket.
|
||||
func TestCollectSelectionFailureStats_ModelRateLimitReasons(t *testing.T) {
|
||||
svc := &GatewayService{}
|
||||
model := "gpt-5.4"
|
||||
resetAt := time.Now().Add(2 * time.Minute).UTC().Format(time.RFC3339)
|
||||
|
||||
accounts := []Account{
|
||||
{
|
||||
ID: 21,
|
||||
Platform: PlatformOpenAI,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Extra: modelRateLimitExtra(model, resetAt, upstreamModelNotFoundReason),
|
||||
},
|
||||
{
|
||||
ID: 22,
|
||||
Platform: PlatformOpenAI,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Extra: modelRateLimitExtra(model, resetAt, openAIImageRateLimitReason),
|
||||
},
|
||||
{
|
||||
ID: 23,
|
||||
Platform: PlatformOpenAI,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Extra: modelRateLimitExtra(model, resetAt, ""),
|
||||
},
|
||||
{
|
||||
ID: 24,
|
||||
Platform: PlatformOpenAI,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Extra: modelRateLimitExtra(model, resetAt, BuildAccountSchedulingThresholdReason("weekly cap")),
|
||||
},
|
||||
{
|
||||
ID: 25,
|
||||
Platform: PlatformOpenAI,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Extra: modelRateLimitExtra(model, resetAt, BuildTempUnschedReasonPayload("custom_rule", "temporary block")),
|
||||
},
|
||||
}
|
||||
|
||||
stats := svc.collectSelectionFailureStats(context.Background(), accounts, model, PlatformOpenAI, map[int64]struct{}{}, false)
|
||||
|
||||
if stats.ModelRateLimited != 5 {
|
||||
t.Fatalf("model_rate_limited=%d want=5", stats.ModelRateLimited)
|
||||
}
|
||||
want := map[string]int{
|
||||
upstreamModelNotFoundReason: 1,
|
||||
openAIImageRateLimitReason: 1,
|
||||
modelRateLimitDiagnosticOtherReason: 1,
|
||||
modelRateLimitDiagnosticThresholdReason: 1,
|
||||
modelRateLimitDiagnosticTempUnschedReason: 1,
|
||||
}
|
||||
if len(stats.ModelRateLimitedReasons) != len(want) {
|
||||
t.Fatalf("reasons=%v want=%v", stats.ModelRateLimitedReasons, want)
|
||||
}
|
||||
for reason, count := range want {
|
||||
if got := stats.ModelRateLimitedReasons[reason]; got != count {
|
||||
t.Fatalf("reason %s=%d want=%d (all=%v)", reason, got, count, stats.ModelRateLimitedReasons)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeModelRateLimitDiagnosticReason(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
want string
|
||||
}{
|
||||
{name: "empty", raw: "", want: modelRateLimitDiagnosticOtherReason},
|
||||
{name: "known", raw: upstreamModelNotFoundReason, want: upstreamModelNotFoundReason},
|
||||
{name: "known suffix", raw: clinePassLimitReason + ": 7d window used up", want: clinePassLimitReason},
|
||||
{name: "threshold json", raw: BuildAccountSchedulingThresholdReason("cap"), want: modelRateLimitDiagnosticThresholdReason},
|
||||
{name: "temp unsched json", raw: BuildTempUnschedReasonPayload("custom", "blocked"), want: modelRateLimitDiagnosticTempUnschedReason},
|
||||
{name: "unknown", raw: "legacy-free-text", want: modelRateLimitDiagnosticOtherReason},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := normalizeModelRateLimitDiagnosticReason(tc.raw); got != tc.want {
|
||||
t.Fatalf("normalize(%q)=%q want=%q", tc.raw, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSummarizeSelectionFailureStats_LegacyFormatIsPreserved(t *testing.T) {
|
||||
stats := selectionFailureStats{
|
||||
Total: 3,
|
||||
ModelRateLimited: 3,
|
||||
}
|
||||
|
||||
got := summarizeSelectionFailureStats(stats)
|
||||
want := "total=3 eligible=0 excluded=0 unschedulable=0 platform_filtered=0 model_unsupported=0 model_rate_limited=3 profit_threshold=0 profit_invalid_account_rate=0"
|
||||
if got != want {
|
||||
t.Fatalf("summary=%q want=%q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSummarizeSelectionFailureStats_ReasonBreakdownIsAppended(t *testing.T) {
|
||||
stats := selectionFailureStats{
|
||||
Total: 3,
|
||||
ModelRateLimited: 3,
|
||||
ModelRateLimitedReasons: map[string]int{
|
||||
upstreamModelNotFoundReason: 2,
|
||||
modelRateLimitDiagnosticOtherReason: 1,
|
||||
},
|
||||
}
|
||||
|
||||
got := summarizeSelectionFailureStats(stats)
|
||||
wantPrefix := "total=3 eligible=0 excluded=0 unschedulable=0 platform_filtered=0 model_unsupported=0 model_rate_limited=3 profit_threshold=0 profit_invalid_account_rate=0"
|
||||
if !strings.HasPrefix(got, wantPrefix) {
|
||||
t.Fatalf("summary=%q want prefix=%q", got, wantPrefix)
|
||||
}
|
||||
// Deterministic, sorted breakdown appended after the legacy fields.
|
||||
wantSuffix := " model_rate_limited_reasons=" + modelRateLimitDiagnosticOtherReason + ":1," + upstreamModelNotFoundReason + ":2"
|
||||
if !strings.HasSuffix(got, wantSuffix) {
|
||||
t.Fatalf("summary=%q want suffix=%q", got, wantSuffix)
|
||||
}
|
||||
// The legacy aggregate token is still present for the handler regex.
|
||||
if !strings.Contains(got, "model_rate_limited=3") {
|
||||
t.Fatalf("summary=%q must keep model_rate_limited=3", got)
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,94 @@ func (a *Account) GetModelRateLimitRemainingTimeWithContext(ctx context.Context,
|
||||
return remaining
|
||||
}
|
||||
|
||||
const (
|
||||
// modelRateLimitDiagnosticOtherReason 汇总历史空 reason 与无法识别的状态,
|
||||
// 保证诊断输出基数有界。
|
||||
modelRateLimitDiagnosticOtherReason = "other"
|
||||
// modelRateLimitDiagnosticTempUnschedReason 是模型级临时停调规则写入的结构化
|
||||
// reason;规则匹配到的上游文案不进入诊断。
|
||||
modelRateLimitDiagnosticTempUnschedReason = "temp_unschedulable"
|
||||
// modelRateLimitDiagnosticThresholdReason 是账号调度阈值自动暂停写入的 JSON reason。
|
||||
modelRateLimitDiagnosticThresholdReason = "account_scheduling_threshold"
|
||||
)
|
||||
|
||||
// modelRateLimitDiagnostic 描述当前生效的模型级冷却来源,仅用于选号失败诊断,
|
||||
// 不参与调度判定。
|
||||
type modelRateLimitDiagnostic struct {
|
||||
Scope string
|
||||
Reason string
|
||||
Remaining time.Duration
|
||||
}
|
||||
|
||||
// activeModelRateLimitDiagnostic 返回剩余时间最长的生效模型级冷却及其持久化
|
||||
// reason。它只读取 model_rate_limits 快照,不改变 IsSchedulableForModelWithContext
|
||||
// 的判定结果。
|
||||
func (a *Account) activeModelRateLimitDiagnostic(ctx context.Context, requestedModel string) (modelRateLimitDiagnostic, bool) {
|
||||
if a == nil {
|
||||
return modelRateLimitDiagnostic{}, false
|
||||
}
|
||||
best := modelRateLimitDiagnostic{}
|
||||
found := false
|
||||
for _, key := range a.modelRateLimitKeysForRequest(ctx, requestedModel) {
|
||||
remaining := a.getRateLimitRemainingForKey(key)
|
||||
if remaining <= 0 {
|
||||
continue
|
||||
}
|
||||
if !found || remaining > best.Remaining {
|
||||
best = modelRateLimitDiagnostic{
|
||||
Scope: key,
|
||||
Reason: normalizeModelRateLimitDiagnosticReason(a.modelRateLimitReason(key)),
|
||||
Remaining: remaining,
|
||||
}
|
||||
found = true
|
||||
}
|
||||
}
|
||||
return best, found
|
||||
}
|
||||
|
||||
// modelRateLimitDiagnosticReasonPrefixes 列出会写入模型级冷却的既有 reason。
|
||||
// 诊断只透传这些受控值(必要时截掉后缀),避免把上游响应文案带进日志。
|
||||
var modelRateLimitDiagnosticReasonPrefixes = []string{
|
||||
upstreamModelNotFoundReason,
|
||||
upstreamModelNotFound401Reason,
|
||||
upstreamCodexPlanGatedModelReason,
|
||||
openAICodexSparkRateLimitReason,
|
||||
openAIImageRateLimitReason,
|
||||
openAIImageCapabilityLossReason,
|
||||
openAIImagesBalanceRateLimitReason,
|
||||
anthropicFableWindowReason,
|
||||
anthropicFableCreditsRequiredReason,
|
||||
clinePassLimitReason,
|
||||
clinePassUnavailableReason,
|
||||
clineSpendLimitReason,
|
||||
clineInferenceCapReason,
|
||||
clineFreeModelLimitReason,
|
||||
clineCreditsReason,
|
||||
commandCodeSpendLimitReason,
|
||||
bedrockThrottlingReason,
|
||||
}
|
||||
|
||||
// normalizeModelRateLimitDiagnosticReason 把持久化 reason 收敛到受控集合:
|
||||
// 已知 reason 原样保留,结构化规则原因归类,其余(含历史空值)归为 other。
|
||||
func normalizeModelRateLimitDiagnosticReason(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return modelRateLimitDiagnosticOtherReason
|
||||
}
|
||||
for _, known := range modelRateLimitDiagnosticReasonPrefixes {
|
||||
if raw == known || strings.HasPrefix(raw, known+":") || strings.HasPrefix(raw, known+" ") {
|
||||
return known
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(raw, "{") {
|
||||
if IsAccountSchedulingThresholdReason(raw) {
|
||||
return modelRateLimitDiagnosticThresholdReason
|
||||
}
|
||||
return modelRateLimitDiagnosticTempUnschedReason
|
||||
}
|
||||
return modelRateLimitDiagnosticOtherReason
|
||||
}
|
||||
|
||||
func (a *Account) modelRateLimitKeysForRequest(ctx context.Context, requestedModel string) []string {
|
||||
if a == nil {
|
||||
return nil
|
||||
|
||||
@@ -1342,6 +1342,9 @@ func (s *defaultOpenAIAccountScheduler) tryFallbackToWeightedSticky(
|
||||
type openAISelectionFilterStats struct {
|
||||
pool int
|
||||
reasons map[string]int
|
||||
// modelRateLimitReasons breaks the aggregated model_rate_limited count down
|
||||
// by the persisted model-cooldown reason. It is diagnostics-only.
|
||||
modelRateLimitReasons map[string]int
|
||||
}
|
||||
|
||||
func (s *openAISelectionFilterStats) exclude(reason string) {
|
||||
@@ -1351,6 +1354,22 @@ func (s *openAISelectionFilterStats) exclude(reason string) {
|
||||
s.reasons[reason]++
|
||||
}
|
||||
|
||||
// excludeModelRateLimited attributes an account excluded as model_rate_limited
|
||||
// to the reason persisted with its (account, model) cooldown. nil accounts and
|
||||
// unknown/legacy reasons fall back to "other" so keys stay bounded.
|
||||
func (s *openAISelectionFilterStats) excludeModelRateLimited(ctx context.Context, account *Account, requestedModel string) {
|
||||
reason := modelRateLimitDiagnosticOtherReason
|
||||
if account != nil {
|
||||
if diagnostic, ok := account.activeModelRateLimitDiagnostic(ctx, requestedModel); ok {
|
||||
reason = diagnostic.Reason
|
||||
}
|
||||
}
|
||||
if s.modelRateLimitReasons == nil {
|
||||
s.modelRateLimitReasons = make(map[string]int, 4)
|
||||
}
|
||||
s.modelRateLimitReasons[reason]++
|
||||
}
|
||||
|
||||
// summary renders deterministic exclusion statistics for scheduling error
|
||||
// messages, e.g. "pool=3, filtered: model_not_supported=2 quota_auto_pause_7d=1".
|
||||
// Reasons are sorted lexicographically so the output is stable for tests and
|
||||
@@ -1373,6 +1392,12 @@ func (s openAISelectionFilterStats) summary(extra string) string {
|
||||
_, _ = b.WriteString(strconv.Itoa(s.reasons[reason]))
|
||||
}
|
||||
}
|
||||
// Keep the aggregate model_rate_limited=<n> token intact for the handler
|
||||
// regex; the breakdown only adds attributed detail.
|
||||
if reasons := formatSelectionFailureReasonCounts(s.modelRateLimitReasons); reasons != "" {
|
||||
_, _ = b.WriteString(", model_rate_limited_reasons=")
|
||||
_, _ = b.WriteString(reasons)
|
||||
}
|
||||
if extra != "" {
|
||||
_, _ = b.WriteString(", ")
|
||||
_, _ = b.WriteString(extra)
|
||||
|
||||
@@ -4053,3 +4053,48 @@ func TestOpenAIGatewayService_SelectAccountWithScheduler_LegacyAccountModelRoute
|
||||
selection.ReleaseFunc()
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAISelectionFilterStats_ModelRateLimitReasonBreakdown(t *testing.T) {
|
||||
model := "gpt-5.4"
|
||||
resetAt := time.Now().Add(2 * time.Minute).UTC().Format(time.RFC3339)
|
||||
accounts := []Account{
|
||||
{
|
||||
ID: 41001,
|
||||
Platform: PlatformOpenAI,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Extra: modelRateLimitExtra(model, resetAt, upstreamModelNotFoundReason),
|
||||
},
|
||||
{
|
||||
ID: 41002,
|
||||
Platform: PlatformOpenAI,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Extra: modelRateLimitExtra(model, resetAt, ""),
|
||||
},
|
||||
}
|
||||
|
||||
filterStats := openAISelectionFilterStats{pool: len(accounts)}
|
||||
for i := range accounts {
|
||||
filterStats.exclude("model_rate_limited")
|
||||
filterStats.excludeModelRateLimited(context.Background(), &accounts[i], model)
|
||||
}
|
||||
|
||||
summary := filterStats.summary("")
|
||||
require.Contains(t, summary, "pool=2, filtered: model_rate_limited=2",
|
||||
"the aggregate token must stay byte-compatible for the handler regex")
|
||||
require.Contains(t, summary, "model_rate_limited_reasons=other:1,upstream_404_model_not_found:1",
|
||||
"the breakdown must attribute each cooldown to its persisted reason")
|
||||
}
|
||||
|
||||
func TestOpenAISelectionFilterStats_SummaryWithoutBreakdownIsUnchanged(t *testing.T) {
|
||||
stats := openAISelectionFilterStats{
|
||||
pool: 3,
|
||||
reasons: map[string]int{"model_rate_limited": 2, "runtime_blocked": 1},
|
||||
}
|
||||
require.Equal(t, "pool=3, filtered: model_rate_limited=2 runtime_blocked=1", stats.summary(""))
|
||||
|
||||
withExtra := stats.summary("selection_order_empty")
|
||||
require.Equal(t, "pool=3, filtered: model_rate_limited=2 runtime_blocked=1, selection_order_empty", withExtra,
|
||||
"the trailing stage marker must stay last when no breakdown exists")
|
||||
}
|
||||
@@ -1289,6 +1289,9 @@ func (s *OpenAIGatewayService) selectAccountWithLoadAwareness(ctx context.Contex
|
||||
// are not selected again before the bucket is rebuilt.
|
||||
if reason := openAICompatibleAccountEligibilityFailureReason(ctx, acc, platform, requestedModel, false, requiredCapability); reason != "" {
|
||||
filterStats.exclude(reason)
|
||||
if reason == "model_rate_limited" {
|
||||
filterStats.excludeModelRateLimited(ctx, acc, requestedModel)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !parentHealthyForShadow(acc, parentLookupL2) {
|
||||
|
||||
@@ -906,6 +906,33 @@ func TestOpenAISelectAccountWithLoadAwareness_ImageRateLimitSkipsOnlyImageReques
|
||||
}
|
||||
}
|
||||
|
||||
// When the load-aware initial filter drops every candidate because of a
|
||||
// model-level cooldown, the error must attribute the aggregate
|
||||
// model_rate_limited count to the persisted cooldown reason.
|
||||
func TestOpenAISelectAccountWithLoadAwareness_NoAvailableErrorReportsModelCooldownReason(t *testing.T) {
|
||||
groupID := int64(1)
|
||||
limited := Account{
|
||||
ID: 1,
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 1,
|
||||
Extra: modelRateLimitExtra("gpt-5.4", time.Now().Add(10*time.Minute).UTC().Format(time.RFC3339), openAIImageRateLimitReason),
|
||||
}
|
||||
svc := &OpenAIGatewayService{
|
||||
accountRepo: stubOpenAIAccountRepo{accounts: []Account{limited}},
|
||||
concurrencyService: NewConcurrencyService(stubConcurrencyCache{}),
|
||||
}
|
||||
|
||||
selection, err := svc.SelectAccountWithLoadAwareness(WithOpenAIImageGenerationIntent(context.Background()), &groupID, "", "gpt-5.4", nil)
|
||||
require.Error(t, err)
|
||||
require.ErrorIs(t, err, ErrNoAvailableAccounts)
|
||||
require.Nil(t, selection)
|
||||
require.Contains(t, err.Error(), "pool=1, filtered: model_rate_limited=1")
|
||||
require.Contains(t, err.Error(), "model_rate_limited_reasons=openai_image_rate_limited:1")
|
||||
}
|
||||
|
||||
func TestOpenAISelectAccountWithLoadAwareness_FiltersUnschedulableWhenNoConcurrencyService(t *testing.T) {
|
||||
now := time.Now()
|
||||
resetAt := now.Add(10 * time.Minute)
|
||||
|
||||
Reference in new issue
Block a user