Merge pull request #8763 from wc4440222/fix/kimi-monthly-quota

fix(kimi): 解析新套餐月度额度并清理缺席窗口快照
This commit is contained in:
Wesley Liddick authored and GitHub committed 2026-11-16 16:32:59 +08:00
commit 56848016c5
3 files changed
+344 -39

No files matched your search

@@ -375,9 +375,15 @@ func cnProviderThresholdCandidates(account *Account, provider string) []*account
return candidates
}
// cnQuotaHasMonthlyWindow 报告供应商的额度快照是否含月度窗口(OpenCode Go、Command Code)。
// cnQuotaHasMonthlyWindow 报告供应商的额度快照是否含月度窗口(OpenCode Go、
// Command Code 与 Kimi 新套餐)。
func cnQuotaHasMonthlyWindow(provider string) bool {
return provider == PlatformOpenCodeGo || provider == PlatformCommandCode
switch provider {
case PlatformOpenCodeGo, PlatformCommandCode, PlatformKimi:
return true
default:
return false
}
}
func cnThresholdCandidate(extra map[string]any, provider, window string) *accountSchedulingThresholdCandidate {
@@ -6,6 +6,7 @@ import (
"fmt"
"io"
"log/slog"
"math"
"net/http"
"sort"
"strconv"
@@ -268,10 +269,27 @@ func (s *CNProviderQuotaService) queryUsageForAccount(ctx context.Context, accou
result.PlanLevel = strings.TrimSpace(gjson.GetBytes(bodyBytes, "current_subscribe_title").String())
}
result.Tiers = tiers
// 2xx 但一个可用窗口都解析不出来,通常意味着上游报文改版/字段改名,而不是
// 「额度无限」。必须按失败处理:保留旧快照、不写成功时间;否则下面的缺席
// 清理会把 5h/weekly/monthly 全写 nil,调度层看到「没有窗口」就会解除预停调,
// 让仍处于耗尽的账号回池撞 429。
if len(tiers) == 0 {
result.Error = fmt.Sprintf(
"quota response for %s contains no recognized usage window (upstream schema may have changed); keeping the previous snapshot",
provider)
slog.Warn("cn_quota_no_recognized_window",
"account_id", account.ID, "provider", provider, "http_status", resp.StatusCode)
return result, nil
}
result.Success = true
result.CredentialValid = true
updates := cnQuotaExtraUpdates(provider, tiers, now)
// 只对 5h/weekly/monthly 三档通吃的供应商清理缺席窗口;Command Code 与
// Cline 走各自的取舍(抓取失败时保留月度),不在这里处理。
if provider == PlatformKimi || provider == PlatformZhipu || provider == PlatformMiniMax || provider == PlatformOpenCodeGo {
clearAbsentCNQuotaWindows(provider, tiers, updates)
}
if err := s.accountRepo.UpdateExtra(ctx, account.ID, updates); err != nil {
slog.Warn("cn_quota_persist_failed", "account_id", account.ID, "provider", provider, "error", err)
} else {
@@ -379,59 +397,119 @@ func zhipuQuotaHost(baseURL string) string {
// parseKimiUsageTiers 解析 Kimi For Coding 的 /usages 响应。
//
// - limits[].detail.{limit,remaining,resetTime} → 5h 窗口(取首个 detail)
// - usage.{limit,remaining,resetTime} → 周窗口
// Kimi 目前并存两种套餐形态:
//
// utilization = (limit-remaining)/limit*100。
// - 老套餐(5h + 7d):limits[].detail.{limit,remaining,resetTime} → 5h
// (取首个 detail),顶层 usage.{limit,remaining,resetTime} → 周窗口,
// utilization = (limit-remaining)/limit*100。
// - 新套餐(5h + 月度):不再有顶层 usage,改由 usages.limit_5h /
// usages.limit_7d / usages.limit_month_total / usages.limit_month_code
// 以 used_ratio(0-1)+ reset_time 上报。月度 total 与 code 任一耗尽都会
// 限流,因此 monthly 取两者较大用量、较早重置时间。
//
// 两者同时出现时 used_ratio 优先(比 counts 更贴近官方口径),顶层 usage 仅兜底;
// usages.limit_5h 只在 limits[] 没有 detail 时补位,避免重复产出 5h 档。
func parseKimiUsageTiers(body []byte) []CNQuotaTier {
var tiers []CNQuotaTier
hasFiveHour := false
if limits := gjson.GetBytes(body, "limits"); limits.IsArray() {
limits.ForEach(func(_, item gjson.Result) bool {
detail := item.Get("detail")
if !detail.Exists() {
return true
}
limit, _ := cnParseF64(detail.Get("limit").Value())
remaining, _ := cnParseF64(detail.Get("remaining").Value())
used := limit - remaining
if used < 0 {
used = 0
}
var util float64
if limit > 0 {
util = used / limit * 100
// 字段节点存在不等于数值可信:limit/remaining 必须可解析、limit>0、
// remaining 落在 [0, limit],否则跳过该条(`{"detail":{}}` 或 limit=0
// 不能产出一个「已用 0%」的伪窗口,那会掩盖真实的额度耗尽状态)。
limit, okLimit := cnParseF64(detail.Get("limit").Value())
remaining, okRemaining := cnParseF64(detail.Get("remaining").Value())
if !okLimit || !okRemaining || limit <= 0 || remaining < 0 || remaining > limit {
return true
}
util := (limit - remaining) / limit * 100
tiers = append(tiers, CNQuotaTier{
Window: "5h",
UsedPercent: util,
ResetAt: cnNormalizeResetTime(detail.Get("resetTime").Value()),
})
return false // 取首个 detail 作为 5h 窗口
hasFiveHour = true
return false // 取首个有效 detail 作为 5h 窗口
})
}
if !hasFiveHour {
if tier, ok := kimiUsedRatioTier(body, "limit_5h", "5h"); ok {
tiers = append(tiers, tier)
hasFiveHour = true
}
}
if usage := gjson.GetBytes(body, "usage"); usage.Exists() {
limit, _ := cnParseF64(usage.Get("limit").Value())
remaining, _ := cnParseF64(usage.Get("remaining").Value())
used := limit - remaining
if used < 0 {
used = 0
// 周窗口:usages.limit_7d 优先,顶层 usage(老套餐单数)兜底。
if tier, ok := kimiUsedRatioTier(body, "limit_7d", "weekly"); ok {
tiers = append(tiers, tier)
} else if usage := gjson.GetBytes(body, "usage"); usage.Exists() {
limit, okLimit := cnParseF64(usage.Get("limit").Value())
remaining, okRemaining := cnParseF64(usage.Get("remaining").Value())
if okLimit && okRemaining && limit > 0 && remaining >= 0 && remaining <= limit {
tiers = append(tiers, CNQuotaTier{
Window: "weekly",
UsedPercent: (limit - remaining) / limit * 100,
ResetAt: cnNormalizeResetTime(usage.Get("resetTime").Value()),
})
}
var util float64
if limit > 0 {
util = used / limit * 100
}
// 月度限额(新套餐):total 与 code 是两个**独立**的限流窗口,任一耗尽都会限流。
// 用量取两者较大值;重置时间取**较晚**者——取较早会在另一个窗口仍耗尽时提前
// 解除预停调(例如 total 到 11-26 才恢复、code 到 11-20 恢复)。宁可晚回池,
// 不可提前撞 429。
total, hasTotal := kimiUsedRatioTier(body, "limit_month_total", "monthly")
code, hasCode := kimiUsedRatioTier(body, "limit_month_code", "monthly")
if hasTotal || hasCode {
monthly := total
if !hasTotal {
monthly = code
} else if hasCode {
if code.UsedPercent > monthly.UsedPercent {
monthly.UsedPercent = code.UsedPercent
}
if code.ResetAt != "" && (monthly.ResetAt == "" || code.ResetAt > monthly.ResetAt) {
monthly.ResetAt = code.ResetAt
}
}
tiers = append(tiers, CNQuotaTier{
Window: "weekly",
UsedPercent: util,
ResetAt: cnNormalizeResetTime(usage.Get("resetTime").Value()),
})
tiers = append(tiers, monthly)
}
return tiers
}
// kimiUsedRatioTier 解析 usages.<key>.{used_ratio,reset_time} 为窗口档位。
// used_ratio 是 0-1 比例,输出换算为百分比;键缺失、不可解析或越界返回 false。
func kimiUsedRatioTier(body []byte, key, window string) (CNQuotaTier, bool) {
node := gjson.GetBytes(body, "usages."+key)
if !node.Exists() {
return CNQuotaTier{}, false
}
ratioNode := node.Get("used_ratio")
if !ratioNode.Exists() {
return CNQuotaTier{}, false
}
ratio, ok := cnParseF64(ratioNode.Value())
if !ok {
return CNQuotaTier{}, false
}
// 必须落在上游声明区间 [0,1]:越界值(例如把百分数 65 直接塞进 used_ratio)
// 会算出 6500%,NaN/Inf 同理不可信。
if ratio < 0 || ratio > 1 {
return CNQuotaTier{}, false
}
return CNQuotaTier{
Window: window,
UsedPercent: ratio * 100,
ResetAt: cnNormalizeResetTime(node.Get("reset_time").Value()),
}, true
}
// parseMiniMaxUsageTiers 解析 MiniMax Token Plan / Coding Plan remains 响应。
//
// 只取 model_name == "general"(编程套餐),跳过 video。字段是剩余百分比,
@@ -574,9 +652,11 @@ func parseZhipuTokenTiers(data gjson.Result) []CNQuotaTier {
if limitType != "TOKENS_LIMIT" && limitType != "CREDIT_LIMIT" {
return true
}
percentage := 0.0
if p, ok := cnParseF64(item.Get("percentage").Value()); ok {
percentage = p
// percentage 缺失/非数字/NaN/越界时不能默认 0:那会产出一个「已用 0%」的
// 合法窗口,既掩盖真实耗尽状态,也会被缺席清理当成有效快照落库。
percentage, okPercentage := cnParseF64(item.Get("percentage").Value())
if !okPercentage || percentage < 0 || percentage > 100 {
return true
}
var (
resetMs int64
@@ -671,6 +751,35 @@ func cnQuotaExtraUpdates(provider string, tiers []CNQuotaTier, now time.Time) ma
return updates
}
// clearAbsentCNQuotaWindows 把本次探测缺席的窗口显式写 nil(JSONB 合并语义下等于
// 移除按键):账号 extra 的更新走 `extra || $1`,只"不写"会保留旧值。上游改套餐
// (Kimi 老套餐 7d → 新套餐月度)后旧窗口不再上报,不清理就会把切换前的用量永久
// 冻结在快照里(生产实测冻结 13 天,列表一直显示过期的 7D 用量)。
//
// 仅供 5h/weekly/monthly 三档通吃的供应商调用;Command Code / Cline 有自己的
// 取舍(周期端点抓取失败时保留月度值),不在此列。
func clearAbsentCNQuotaWindows(provider string, tiers []CNQuotaTier, updates map[string]any) {
present := make(map[string]CNQuotaTier, len(tiers))
for _, tier := range tiers {
present[tier.Window] = tier
}
for _, window := range []struct{ name, used, reset string }{
{"5h", cnExtraSuffix5hUsed, cnExtraSuffix5hReset},
{"weekly", cnExtraSuffixWeeklyUsed, cnExtraSuffixWeeklyReset},
{"monthly", cnExtraSuffixMonthlyUsed, cnExtraSuffixMonthlyReset},
} {
tier, ok := present[window.name]
if !ok {
updates[cnExtraKey(provider, window.used)] = nil
updates[cnExtraKey(provider, window.reset)] = nil
continue
}
if tier.ResetAt == "" {
updates[cnExtraKey(provider, window.reset)] = nil
}
}
}
// parseOpenCodeGoUsageTiers 解析 OpenCode Go GET /usage 响应。
//
// 结构对齐 cc-switch extractor:
@@ -718,24 +827,37 @@ func parseOpenCodeGoUsageTiers(body []byte) []CNQuotaTier {
// cnParseF64 把 JSON 数值或字符串解析为 float64(兼容 "100" 与 100)。
func cnParseF64(raw any) (float64, bool) {
var value float64
switch v := raw.(type) {
case float64:
return v, true
value = v
case float32:
return float64(v), true
value = float64(v)
case int:
return float64(v), true
value = float64(v)
case int64:
return float64(v), true
value = float64(v)
case json.Number:
f, err := v.Float64()
return f, err == nil
if err != nil {
return 0, false
}
value = f
case string:
f, err := strconv.ParseFloat(strings.TrimSpace(v), 64)
return f, err == nil
if err != nil {
return 0, false
}
value = f
default:
return 0, false
}
// strconv.ParseFloat 接受 "NaN"/"Inf",JSON 的 1e999 也会得到 +Inf;
// 这类值参与百分比与阈值比较会让停调判定失效,一律视为不可解析。
if math.IsNaN(value) || math.IsInf(value, 0) {
return 0, false
}
return value, true
}
// cnNormalizeResetTime 把上游重置时间(ISO8601 字符串 / 秒级 / 毫秒级数字)归一化为
+178 -1
View File
@@ -103,8 +103,84 @@ func TestParseKimiUsageTiers_LimitZero(t *testing.T) {
t.Parallel()
body := []byte(`{"limits":[{"detail":{"limit":0,"remaining":0,"resetTime":"2026-08-14T15:00:00Z"}}]}`)
tiers := parseKimiUsageTiers(body)
// limit=0 无法计算利用率:不能产出「已用 0%」的伪窗口(那会把额度耗尽
// 显示成完全没用),该条目应被跳过。
require.Len(t, tiers, 0)
}
// TestParseKimiUsageTiers_MonthlyPlan 新套餐形态(5h + 月度限额):不再有顶层
// usage,改由 usages.limit_5h / limit_month_total / limit_month_code 以
// used_ratio(0-1)+ reset_time 上报。monthly 取两条月度键的较大用量 + 较早重置。
func TestParseKimiUsageTiers_MonthlyPlan(t *testing.T) {
t.Parallel()
body := []byte(`{
"limits": [{
"window": {"duration": 300, "timeUnit": "TIME_UNIT_MINUTE"},
"detail": {"limit": "100", "used": "10", "remaining": "90", "resetTime": "2026-11-13T16:10:29.523075Z"}
}],
"usages": {
"limit_5h": {"used_ratio": 0.0982, "reset_time": "2026-11-13T16:10:28Z"},
"limit_month_total": {"used_ratio": 0.6564, "reset_time": "2026-11-26T00:00:00Z"},
"limit_month_code": {"used_ratio": 0.6252, "reset_time": "2026-11-26T00:00:00Z"}
}
}`)
tiers := parseKimiUsageTiers(body)
require.Len(t, tiers, 2, "新套餐应为 5h + monthly,且不得产出已废弃的 weekly")
require.Equal(t, "5h", tiers[0].Window)
require.InDelta(t, 10.0, tiers[0].UsedPercent, 1e-9, "5h 用 limits[].detail 的绝对计数")
require.Equal(t, "2026-11-13T16:10:29Z", tiers[0].ResetAt)
require.Equal(t, "monthly", tiers[1].Window)
require.InDelta(t, 65.64, tiers[1].UsedPercent, 1e-9, "used_ratio 0-1 换算为百分比")
require.Equal(t, "2026-11-26T00:00:00Z", tiers[1].ResetAt)
}
// TestParseKimiUsageTiers_MonthlyPicksMaxUsage total/code 任一耗尽都会限流:
// monthly 取较大用量;重置时间取较早者(先恢复额度,避免过度停调)。
func TestParseKimiUsageTiers_MonthlyPicksMaxUsage(t *testing.T) {
t.Parallel()
body := []byte(`{"usages":{
"limit_month_total":{"used_ratio":0.4,"reset_time":"2026-11-26T00:00:00Z"},
"limit_month_code":{"used_ratio":0.9,"reset_time":"2026-11-20T00:00:00Z"}}}`)
tiers := parseKimiUsageTiers(body)
require.Len(t, tiers, 1)
require.InDelta(t, 0.0, tiers[0].UsedPercent, 1e-9)
require.Equal(t, "monthly", tiers[0].Window)
require.InDelta(t, 90.0, tiers[0].UsedPercent, 1e-9)
// total 与 code 是两个独立限流窗口:reset 必须取较晚者,否则 code 先到期的
// 11-20 会让仍处于 40% 的 total 窗口提前放行。
require.Equal(t, "2026-11-26T00:00:00Z", tiers[0].ResetAt)
// 两窗口同为 100% 时也不得取更早的 reset。
bothFull := parseKimiUsageTiers([]byte(`{"usages":{
"limit_month_total":{"used_ratio":1,"reset_time":"2026-11-26T00:00:00Z"},
"limit_month_code":{"used_ratio":1,"reset_time":"2026-11-20T00:00:00Z"}}}`))
require.Len(t, bothFull, 1)
require.Equal(t, "2026-11-26T00:00:00Z", bothFull[0].ResetAt)
onlyCode := parseKimiUsageTiers([]byte(`{"usages":{"limit_month_code":{"used_ratio":0.5,"reset_time":"2026-11-20T00:00:00Z"}}}`))
require.Len(t, onlyCode, 1)
require.Equal(t, "monthly", onlyCode[0].Window)
require.InDelta(t, 50.0, onlyCode[0].UsedPercent, 1e-9)
}
// TestParseKimiUsageTiers_LegacyWithUsedRatio 老套餐(顶层 usage)同时携带
// usages.limit_7d 时,weekly 以 used_ratio 为准、不重复产出 weekly 档。
func TestParseKimiUsageTiers_LegacyWithUsedRatio(t *testing.T) {
t.Parallel()
body := []byte(`{
"usage": {"limit": "100", "remaining": "80", "resetTime": "2026-10-07T05:04:39.713183Z"},
"usages": {
"limit_5h": {"used_ratio": 0, "reset_time": "2026-10-04T11:04:38Z"},
"limit_7d": {"used_ratio": 0.203912, "reset_time": "2026-10-07T05:04:38Z"}
}
}`)
tiers := parseKimiUsageTiers(body)
require.Len(t, tiers, 2)
require.Equal(t, "5h", tiers[0].Window)
require.Equal(t, "weekly", tiers[1].Window)
require.InDelta(t, 20.3912, tiers[1].UsedPercent, 1e-9)
require.Equal(t, "2026-10-07T05:04:38Z", tiers[1].ResetAt)
}
// TestParseZhipuTokenTiers_UnitClassification 显式 unit(3=5h / 6=weekly)优先分类,
@@ -231,6 +307,107 @@ func TestCNQuotaExtraUpdates(t *testing.T) {
require.Equal(t, now.Format(time.RFC3339), updates["kimi_usage_updated_at"])
}
// 缺席窗口必须显式写 nil:extra 走 JSONB 合并(`extra || $1`),只"不写"会保留
// 旧值。Kimi 老套餐 → 新套餐(月度)切换后 weekly 不再上报,不清理就会把切换前
// 的用量永久冻结在快照里(生产实测冻结 13 天)。
func TestCNQuotaExtraUpdatesClearsAbsentWindows(t *testing.T) {
t.Parallel()
now := time.Date(2026, 11, 13, 0, 0, 0, 0, time.UTC)
tiers := []CNQuotaTier{
{Window: "5h", UsedPercent: 10, ResetAt: "2026-11-13T16:10:29Z"},
{Window: "monthly", UsedPercent: 65.64, ResetAt: "2026-11-26T00:00:00Z"},
}
updates := cnQuotaExtraUpdates(PlatformKimi, tiers, now)
clearAbsentCNQuotaWindows(PlatformKimi, tiers, updates)
value, present := updates["kimi_weekly_used_percent"]
require.True(t, present, "缺席的 weekly 必须显式出现在更新里")
require.Nil(t, value)
_, resetPresent := updates["kimi_weekly_reset_at"]
require.True(t, resetPresent)
require.Equal(t, 10.0, updates["kimi_5h_used_percent"])
require.Equal(t, 65.64, updates["kimi_monthly_used_percent"])
require.Equal(t, "2026-11-26T00:00:00Z", updates["kimi_monthly_reset_at"])
}
// TestParseKimiUsageTiers_RejectsMalformedWindows 受损/改版结构不得产出伪窗口。
// 这类窗口一旦被当成有效快照落库,缺席清理会把其他窗口写成 nil,
// 调度层看到「没有窗口」就会解除预停调。
func TestParseKimiUsageTiers_RejectsMalformedWindows(t *testing.T) {
t.Parallel()
cases := map[string]struct {
body []byte
}{
"empty object": {[]byte(`{}`)},
"empty detail": {[]byte(`{"limits":[{"detail":{}}]}`)},
"limit zero": {[]byte(`{"limits":[{"detail":{"limit":0,"remaining":0}}]}`)},
"remaining exceeds": {[]byte(`{"limits":[{"detail":{"limit":100,"remaining":200}}]}`)},
"limit not a number": {[]byte(`{"limits":[{"detail":{"limit":"abc","remaining":"1"}}]}`)},
"empty usage": {[]byte(`{"usage":{}}`)},
"ratio out of range": {[]byte(`{"usages":{"limit_5h":{"used_ratio":65}}}`)},
"ratio NaN": {[]byte(`{"usages":{"limit_5h":{"used_ratio":"NaN"}}}`)},
"ratio negative": {[]byte(`{"usages":{"limit_5h":{"used_ratio":-0.2}}}`)},
"renamed top level key": {[]byte(`{"limits_v2":[{"detail":{"limit":100,"remaining":50}}]}`)},
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
tiers := parseKimiUsageTiers(tc.body)
require.Empty(t, tiers, "受损结构不得产出窗口:%s", string(tc.body))
})
}
}
// TestParseKimiUsageTiers_KeepsLegalEdgeValues 合法边界(0%、满额、单窗口、整数)不得被误伤。
func TestParseKimiUsageTiers_KeepsLegalEdgeValues(t *testing.T) {
t.Parallel()
// remaining == limit → 合法的 0%。
tiers := parseKimiUsageTiers([]byte(`{"limits":[{"detail":{"limit":100,"remaining":100}}]}`))
require.Len(t, tiers, 1)
require.InDelta(t, 0.0, tiers[0].UsedPercent, 1e-9)
// remaining == 0 → 100%。
tiers = parseKimiUsageTiers([]byte(`{"limits":[{"detail":{"limit":100,"remaining":0}}]}`))
require.Len(t, tiers, 1)
require.InDelta(t, 100.0, tiers[0].UsedPercent, 1e-9)
// used_ratio == 0 / 1 同样合法。
tiers = parseKimiUsageTiers([]byte(`{"usages":{"limit_5h":{"used_ratio":0}}}`))
require.Len(t, tiers, 1)
require.InDelta(t, 0.0, tiers[0].UsedPercent, 1e-9)
tiers = parseKimiUsageTiers([]byte(`{"usages":{"limit_5h":{"used_ratio":1}}}`))
require.Len(t, tiers, 1)
require.InDelta(t, 100.0, tiers[0].UsedPercent, 1e-9)
// 首个 detail 坏、后续合法 → 采用首个有效条目。
tiers = parseKimiUsageTiers([]byte(`{"limits":[{"detail":{}},{"detail":{"limit":100,"remaining":60}}]}`))
require.Len(t, tiers, 1)
require.InDelta(t, 40.0, tiers[0].UsedPercent, 1e-9)
}
// TestParseZhipuTokenTiers_SkipsMissingPercentage percentage 缺失/非法不得伪造 0% 窗口。
func TestParseZhipuTokenTiers_SkipsMissingPercentage(t *testing.T) {
t.Parallel()
cases := map[string]struct {
body string
wantTiers int
}{
"missing percentage": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3}]}`, 0},
"non numeric": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":"abc"}]}`, 0},
"negative": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":-5}]}`, 0},
"over 100": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":120}]}`, 0},
"legal zero": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":0}]}`, 1},
"legal five hour": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":42}]}`, 1},
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
tiers := parseZhipuTokenTiers(gjson.Parse(tc.body))
require.Len(t, tiers, tc.wantTiers, "输入:%s", tc.body)
})
}
}
func TestParseOpenCodeGoUsageTiers(t *testing.T) {
t.Parallel()
body := []byte(`{