From bf3951a59e23974f6efecfe62e835c701e73fa25 Mon Sep 17 00:00:00 2001 From: shaw Date: Mon, 16 Nov 2026 19:25:39 +0800 Subject: [PATCH] fix(monitor): don't flip channel monitor to error on OpenAI quota refresh failure quota_refresh_failed only means the active probe could not refresh the quota and the values come from an earlier observation. The probe is throttled by openAIProbeCacheTTL, so only the read that triggered it carries the code; treating it as a failure made the quota monitor flap between error and operational roughly every 10 minutes. Exempt it like grok's quota_unknown, so monitor status is derived from the cached observation as before. Adds an end-to-end no-flap test. --- .../internal/service/account_usage_service.go | 6 +++- .../service/channel_monitor_quota_fetcher.go | 7 +++- .../channel_monitor_quota_fetcher_test.go | 36 +++++++++++++++++++ 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/account_usage_service.go b/backend/internal/service/account_usage_service.go index f911753aa7..6999daa2a0 100644 --- a/backend/internal/service/account_usage_service.go +++ b/backend/internal/service/account_usage_service.go @@ -831,7 +831,7 @@ func (s *AccountUsageService) getOpenAIUsage(ctx context.Context, account *Accou if usage.Source != "active" { // Keep the last observation available, but never turn a failed probe // (or a response without quota data) into a fresh successful read. - usage.ErrorCode = "quota_refresh_failed" + usage.ErrorCode = errorCodeQuotaRefreshFailed usage.Error = "Unable to refresh OpenAI quota; displayed values may be from an earlier observation" } } @@ -1071,6 +1071,10 @@ func applyExtraToUsage(usage *UsageInfo, extra map[string]any, now time.Time) { } } +// errorCodeQuotaRefreshFailed 标记 OpenAI OAuth 额度主动刷新失败:返回值仍是上次 +// 观测(或未知),只说明额度数据可能陈旧,不代表账号不可用。 +const errorCodeQuotaRefreshFailed = "quota_refresh_failed" + func hasOpenAIQuotaObservation(updates map[string]any) bool { _, has5h := updates["codex_5h_used_percent"] _, has7d := updates["codex_7d_used_percent"] diff --git a/backend/internal/service/channel_monitor_quota_fetcher.go b/backend/internal/service/channel_monitor_quota_fetcher.go index 8e2700137f..8a3659f01f 100644 --- a/backend/internal/service/channel_monitor_quota_fetcher.go +++ b/backend/internal/service/channel_monitor_quota_fetcher.go @@ -484,11 +484,16 @@ func isCredentialErrorMessage(msg string) bool { // // grok 的 ErrorCode=quota_unknown 是「尚未观测到计费快照/限流头」的已知未知态, // 不是失败(严格按 ErrorCode 判会把健康 grok 账号永久判 error),显式豁免。 +// +// OpenAI OAuth 的 quota_refresh_failed 同理豁免:它只说明本次主动刷新没拿到新额度、 +// 返回的是上次观测,账号本身未必不可用;且探测受 openAIProbeCacheTTL 节流,只有真正 +// 发起探测的那次读取会带该码,若判 error,监控会在 error/operational 间周期性跳动。 +// 状态按缓存观测(未知窗口已在 appendProgressTier 跳过)推导。 func usageFailureInfo(usage *UsageInfo) (failed, credentialInvalid bool, msg string) { if usage == nil { return false, false, "" } - if usage.ErrorCode == "quota_unknown" { + if usage.ErrorCode == "quota_unknown" || usage.ErrorCode == errorCodeQuotaRefreshFailed { return false, false, "" } failed = usage.Error != "" || usage.NeedsReauth || usage.IsBanned || diff --git a/backend/internal/service/channel_monitor_quota_fetcher_test.go b/backend/internal/service/channel_monitor_quota_fetcher_test.go index e37127bc63..0f6223d3ac 100644 --- a/backend/internal/service/channel_monitor_quota_fetcher_test.go +++ b/backend/internal/service/channel_monitor_quota_fetcher_test.go @@ -348,6 +348,7 @@ func TestUsageFailureInfo_ClassificationMatrix(t *testing.T) { {name: "error code rate limited", usage: &UsageInfo{ErrorCode: errorCodeRateLimited}, failed: true, msg: errorCodeRateLimited}, {name: "error code network error", usage: &UsageInfo{ErrorCode: errorCodeNetworkError}, failed: true, msg: errorCodeNetworkError}, {name: "grok quota unknown exempted", usage: &UsageInfo{ErrorCode: "quota_unknown", Error: "Grok quota is unknown until billing is probed"}}, + {name: "openai quota refresh failed exempted", usage: &UsageInfo{ErrorCode: errorCodeQuotaRefreshFailed, Error: "Unable to refresh OpenAI quota"}}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -748,3 +749,38 @@ func TestDeriveQuotaCheckResult_StatusMatrix(t *testing.T) { res = deriveQuotaCheckResult(nil, "quota", now) require.Equal(t, MonitorStatusError, res.Status) } + +// OpenAI OAuth 额度刷新失败(探测被 10 分钟节流)不能让配额监控在 error 与 +// operational 间来回跳:失败只出现在真正发起探测的那一次读取上,节流窗口内的 +// 后续读取不带错误。刷新失败只说明额度数据可能陈旧,不代表账号不可用, +// 监控须与 #8747 之前一致按缓存观测推导状态。 +func TestQuotaFetcher_OpenAIQuotaRefreshFailureDoesNotFlap(t *testing.T) { + observedAt := time.Now().Add(-time.Hour).UTC().Truncate(time.Second) + account := &Account{ + ID: 77, + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Status: StatusActive, + // 只有 7d 窗口 → shouldRefreshOpenAICodexSnapshot 恒为 true;无 access token → 探测必失败。 + Extra: map[string]any{ + "codex_7d_used_percent": 95.0, + "codex_usage_updated_at": observedAt.Format(time.RFC3339), + }, + } + fetcher := &ChannelMonitorQuotaFetcher{ + usage: &AccountUsageService{cache: NewUsageCache()}, + accounts: &stubMonitorAccountSource{accounts: map[int64]*Account{77: account}}, + balanceThreshold: monitorBalanceThreshold(nil), + cache: make(map[int64]monitorQuotaCacheEntry), + } + + var statuses []string + for i := 0; i < 3; i++ { + snapshot := fetcher.fetchUncached(context.Background(), 77, time.Now()) + res := deriveQuotaCheckResult(snapshot, "quota", time.Now()) + statuses = append(statuses, res.Status) + require.True(t, snapshot.Success, "round %d: refresh failure must not be a failed snapshot: %s", i, snapshot.Error) + require.Len(t, snapshot.Tiers, 1, "round %d: cached 7d observation stays visible", i) + } + require.Equal(t, []string{MonitorStatusDegraded, MonitorStatusDegraded, MonitorStatusDegraded}, statuses) +}