Skip to content

fix(kimi): 解析新套餐月度额度并清理缺席窗口快照 - #8763

Merged
Wei-Shaw merged 2 commits into
Wei-Shaw:mainfrom
wc4440222:fix/kimi-monthly-quota
Nov 16, 2026
Merged

Wei-Shaw merged 2 commits into
Wei-Shaw:mainfrom
wc4440222:fix/kimi-monthly-quota

Conversation

@wc4440222

@wc4440222 wc4440222 commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

背景

Fixes #8762。

Kimi For Coding 现在并存两种 /coding/v1/usages 响应形态:

  • 老套餐:limits[].detail(5h 计数)+ 顶层 usage(周池)
  • 新套餐(Go/Plus/Pro):没有顶层 usage,改由 usages.limit_5h / usages.limit_7d / usages.limit_month_total / usages.limit_month_code 以 used_ratio(0–1)+ reset_time 上报

当前实现只认老套餐,导致两个可见问题:

  1. 月度额度完全不显示 —— usages.* 没解析,kimi_monthly_used_percent 从不写入;cnQuotaHasMonthlyWindow() 也不含 kimi。
  2. 过期 7D 永久冻结 —— 账号 extra 更新是 JSONB 合并(extra = COALESCE(extra,'{}') || $1),cnQuotaExtraUpdates 只写本次出现的档位,缺席档位既不写 nil 也不删键。老套餐时代的 kimi_weekly_used_percent 就永久留在快照里(实测冻结 13 天,reset 已过期)。

改动

parseKimiUsageTiers

  • 新增 usages.* 解析(used_ratio × 100,reset_time 归一化为 RFC3339):
    • limit_5h → 5h(仅当 limits[] 没有 detail 时补位,避免重复)
    • limit_7d → weekly(优先于老套餐顶层 usage,不重复产出)
    • limit_month_total / limit_month_code → monthly:取两者较大用量(任一耗尽都会限流)、较晚重置时间
      (total 与 code 是两个独立限流窗口,取较早会在另一个窗口仍耗尽时提前解除预停调)
  • 顶层 usage 保留为兜底,老套餐正常路径行为不变。

缺席窗口清理

新增 clearAbsentCNQuotaWindows,在 kimi / zhipu / minimax / opencode_go 的探测落库前对 5h/weekly/monthly 三档做「缺席显式写 nil、有档位但无重置时间则清 reset 键」。

  • Command Code / Cline 不在其中:它们有自己的取舍(周期端点抓取失败时保留月度值),保持原逻辑。

解析健壮性(防止误解除预停调)

「缺席写 nil」只有在响应结构可信时才安全,因此同批补了三处校验:

  • 2xx 但解析出 0 个窗口 → 按失败处理:保留旧快照、不写成功时间。否则清理逻辑会把三档全写 nil,
    调度层读到「没有窗口」= 无额度限制,会解除预停调,让仍耗尽的账号回池撞上游 429。
  • limits[].detail / 顶层 usage 数值校验:要求 limit > 0 且 remaining ∈ [0, limit];
    {"detail":{}} 或 limit=0 过去会产出一个「已用 0%」的伪窗口,掩盖真实耗尽状态。
  • used_ratio 必须是 [0,1] 内的有限值:越界(例如上游改成百分数口径)会算出 6500%,
    ParseFloat 还会接受 NaN/Inf;cnParseF64 现在统一拒绝非有限值。

阈值与冷却

cnQuotaHasMonthlyWindow 纳入 kimi,使月度窗口参与阈值预停调与 429 冷却快照重置点选择。

Zhipu 顺带收紧

parseZhipuTokenTiers 的 percentage 缺失/非数字/越界不再默认 0 —— 缺席清理现在也覆盖 zhipu,
同样的伪窗口问题必须一并关掉(合法的 percentage: 0 仍然有效)。

测试

-tags unit ./internal/service:

  • TestParseKimiUsageTiers_MonthlyPlan:新套餐形态(真实响应),断言 5h + monthly、不产出 weekly
  • TestParseKimiUsageTiers_MonthlyPicksMaxUsage:total/code 取较大用量 + 较晚重置;双窗口同 100% 不同 reset;只有 code 键时也产出 monthly
  • TestParseKimiUsageTiers_LegacyWithUsedRatio:老套餐 + limit_7d 并存时以 ratio 为准且只产出一次 weekly
  • TestParseKimiUsageTiers_RejectsMalformedWindows:空对象 / detail:{} / limit=0 / remaining 越界 / 非数字 / usage:{} / ratio 越界 / NaN / 顶层键改名 全部不产出窗口
  • TestParseKimiUsageTiers_KeepsLegalEdgeValues:0%、满额、单窗口、整数 JSON、首个 detail 坏后续合法
  • TestParseZhipuTokenTiers_SkipsMissingPercentage:缺失/非数字/负数/>100 跳过,合法的 0% 保留
  • TestCNQuotaExtraUpdatesClearsAbsentWindows:缺席 weekly 显式写 nil,存在的档位不被覆盖
  • 既有 TestParseKimiUsageTiers / TestCNQuotaExtraUpdates 等保持通过(_LimitZero 语义按上修:limit=0 不再产出档位)

验证:go build ./... 通过;go test ./internal/service 全绿(146.9s)。

说明

与 PR #7856 的差异:那边做了 usages 解析与 monthly 候选,但没有处理缺席窗口清理(第 2 个问题的根因),
且当前处于 conflicting 状态;本 PR 一并覆盖两者,并补了解析健壮性守卫。

…hots

Kimi For Coding now ships two response shapes:

- Legacy plans: limits[].detail (5h counts) + top-level usage (weekly pool).
- New plans (Go/Plus/Pro): usages.limit_5h / limit_7d / limit_month_total /
  limit_month_code reported as used_ratio (0-1) with reset_time. There is no
  top-level usage block, so the monthly pool was never parsed and the monthly
  quota was invisible in the account list.

parseKimiUsageTiers now understands usages.* (used_ratio x100, monthly takes
the larger of total/code with the earlier reset), keeps the legacy usage block
as a fallback, and prefers usages.limit_7d over legacy weekly counts so weekly
is not emitted twice.

Snapshot writes also stopped clearing windows that disappear from the response:
extra updates are JSONB merges, so not writing a window keeps its previous
value forever. After a plan change the old weekly percentage froze (observed
13 days) and the account page kept showing an expired 7D window. Callers now
write explicit nils for absent 5h/weekly/monthly windows.

cnQuotaHasMonthlyWindow includes Kimi so threshold pre-pause and the 429
cooldown snapshot consider the monthly window too.
Follow-up hardening on the new-plan monthly quota support. All changes are
backward compatible with the legacy response shape.

1. Empty parse is not "unlimited"
   A 2xx response that yields zero recognized windows now counts as a failed
   probe: the previous snapshot is kept and no success timestamp is written.
   Without this, the absent-window cleanup would write 5h/weekly/monthly as
   nil, and the scheduler - which reads "no window" as "no quota limit" -
   would clear the pre-emptive pause and let an exhausted account back into
   rotation.

2. Reject malformed window values instead of fabricating 0%
   limits[].detail now requires limit > 0 and remaining in [0, limit]; the
   legacy top-level usage block gets the same check. `{"detail":{}}` or
   limit=0 used to produce a "0% used" tier, masking real exhaustion.

3. used_ratio must be a finite value in [0, 1]
   Out-of-range ratios (e.g. a provider switching to percent units) produced
   6500%-style values; NaN/Inf were accepted by ParseFloat. cnParseF64 now
   rejects non-finite results for every caller.

4. Monthly reset takes the later window
   total and code are two independent rate-limit windows. Taking the earlier
   reset (11-20) released the account while the other window was still
   exhausted (11-26). Use the later reset: better to stay parked slightly
   longer than to hit upstream 429.

5. Zhipu percentage is validated
   Missing/invalid/out-of-range percentage no longer defaults to 0, which had
   the same fabricated-window problem now that absent-window cleanup also
   covers zhipu.

Tests: added rejection matrices for malformed Kimi and Zhipu payloads, legal
edge-value cases (0%, full usage, single window, integer JSON), and the
dual-monthly-window reset assertions. Existing legacy-shape expectations are
unchanged except the limit=0 case, which must now yield no tier.
@wc4440222

Copy link
Copy Markdown
Contributor Author

CI 说明:backend-security 失败与本 PR 无关

backend-security 的 govulncheck 报的是标准库漏洞,不是本次改动的代码路径:

Vulnerability #1: GO-2026-6859
    HTTP/1 server crash due to MaxBytesReader header race in net/http
    Found in: net/http@go1.27.3
    Fixed in: net/http@go1.27.4

backend/go.mod 当前声明 go 1.27.3,GOTOOLCHAIN: local,因此该标准库版本被 govulncheck 标记;
升级路径在上游已有对应改动(分支 chore/bump-go-1.27.4 的 Security Scan 为 success)。

本 PR 只改 internal/service/cn_provider_quota_service.go 与 cn_providers_test.go
(配额报文解析与缺席窗口清理),不引入任何新依赖、不触碰 net/http 使用方式,
bump 之后该检查即转绿。

@Wei-Shaw
Wei-Shaw merged commit 5684801 into Wei-Shaw:main Nov 16, 2026
8 of 9 checks passed
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 16, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] kimi 平台新套餐(月度限额)用量不解析,且缺席窗口快照永久冻结

2 participants