Compare commits

...

6 Commits

Author SHA1 Message Date
442fa5e3f6 chore(gui): 版本号 2.0.47(与内核同版本) 2026-10-20 18:05:19 +08:00
0caa37ea6a fix(billing): 过期规则 URL 不再让整个 profile 失效(降级应用 + 点名 URL)
生产现网发现(issue #1 排查):billing.rules 里一条指向
https://opencode.ai/inference/v1 的规则,在该源 base_url 变成
.../inference/openai/v1 之后匹配不到任何源;严格编译因此让**整个** profile
不生效 —— 账单恒 0、unpriced_reqs 涨到 3.7 万,唯一痕迹是一行启动日志。

- 严格编译失败时降级为 lenient:应用能匹配的规则,其余按 profile default;
- 日志用 ERROR 点名**具体哪条 URL** 写错(新增 billing.UnmatchedRuleURLs),
  并说明未匹配流量的记账去向;
- 判据 TestBillingStaleRuleURLStillAppliesOtherRules:一条过期规则 + 一条有效
  规则 ⇒ 有效规则必须仍然生效。
2026-10-20 18:04:43 +08:00
33cb2bdb06 fix(billing): 源层零价不再覆盖模型价(issue #1)+ default_mode 生效 + 文档/判据补齐
GitCode issue #1:任何按 `mode: token` 且 URL 非通配符的规则定价的源,计费恒为 0,
且 `unpriced_reqs` 也不增长 —— 完全静默。

## 真因
- `compile.go` 给这类规则写源条目 `{prompt:0, completion:0, per_request:0}`,
  本意只是"标记该源已定价"(同源未列入价目表的模型不算 unpriced);
- `billing.lua` 的 priceFor() 源层在模型层之后、且 `sp.prompt ~= nil` 即覆盖;
- 两者叠加 ⇒ 模型价被清成 0,而 `out.priced` 仍为 true ⇒ 连未定价计数都不涨。

## 修法
1. `compile.go`:token 规则的源条目只写 `{per_request: 0}`(只是标记,不参与 token
   计价)。`free` / `subscription` 保留全零(那里 0 本身就是语义)。
2. `billing.lua`:
   - `priceFor()` 的 `out` 补 `local`(此前是 VM 级全局变量,跨请求残留);
   - 实现 `profiles[].default` 的 `free|unpriced` 语义:`free` = 刻意免费(不进
     unpriced),`unpriced`(默认)= 未定价债务。此前 compile.go 写 `default_mode`
     但**无人读**,两种取值运行时完全等价。
3. `core.go`:应用 profile 时把 `unmatched_sources` 打进日志(WARNING 列出没有
   规则命中的源)。该字段此前只写不读,是第二个静默少报点。
4. `docs/plugins.md`:token 价优先级改为与实际实现一致的
   `keys > sources > models > default`,并写明"标记已定价只能用 per_request:0"。

## 判据(都先红后绿)
- `internal/billing`:token 规则的源条目**不含** prompt/completion;free/subscription
  仍保留显式 0。
- `internal/lua`:同源同模型下旧形状 cost=0(缺陷本身)、新形状 cost=0.75 且
  unpriced_reqs=0;未列入价目表的模型仍算"已定价";default_mode 三态。
- `internal/gateway`:`billing_rules_api_test` 的单位断言原本读
  `cc["models"]`(恒 false,整块被跳过——从未执行过),改为 `prices["models"]`,
  并新增"源条目不得带 token 价"断言。

## 顺带修掉一个"永不执行"的判据
`discover_mutate_test.go` 的变异锚点写成 6 个空格,而 `discover.go` 已是 2 个空格
⇒ 该变异每次都 `anchor not found`,变异 campaign 长期红着。修正锚点后,
"嵌套 metadata 不再读取"这条变异真的被执行并被测试 KILL。
2026-10-20 17:46:52 +08:00
0ae7d2c8be test(retry): 钉住声明式重试判据与流式握手重试语义
- config:ShouldRetry/DelayDuration 表驱动(nil/次数=1/状态不匹配/body 不匹配/
  空子串/多信号/非法间隔)
- provider:命中策略就重试直到 200、body 不匹配**不许**重试(400 也常用于真错误)、
  流式只重试握手(首帧之后不重试,避免重复输出)
2026-10-20 10:45:56 +08:00
02c01582f1 chore(gui): 版本号 2.0.46(与内核同版本) 2026-10-20 10:38:07 +08:00
6454b094bc fix(codearts): 上游限流改为可声明重试(内核通用能力)+ 会话/连接两处真因
用户连续报「codeart 还是不可用 / empty stream」。把上游原始响应打出来逐条对齐,
三个症状同源,且都不是"模型坏了":

| 场景 | 上游实际返回 |
|---|---|
| 流式、短时间连续请求 | HTTP **200** + 只带 error 的帧 ⇒ 内核判 `empty stream` |
| 非流式、同一条件 | HTTP 400 `TM.00001041: 并发会话数已达上限(3个)` |
| 突发请求 | HTTP 429 `TPM limit … 500000 tokens per minute` |

实测:最后一个请求结束后约 **44~60 秒**释放;同一账号连续请求 3~4 次即占满。
参考实现(示例插件 llm-adapter.ts)的做法是**每 10s 轮询后重试 chat**(最多 30
分钟),所以用户那边"看起来没事"。

## 我们的改法(内核只做通用机制,厂商知识留在插件)
1. **内核新增声明式重试策略** `source.retry`(纯数据:状态码列表 + 响应体子串 +
   间隔 + 次数)。内核不认识任何厂商;命中即在同一网关请求内每 10s 重试一次。
   流式只在**握手阶段**重试(首帧尚未下发,不会重复输出),非流式整体重试。
2. **插件为 codearts 声明**:400/429 + 命中 `TM.00001041` / `TPM limit` /
   `并发会话数已达上限` → 10s × 最多 18 次(≈3 分钟)。
3. **适配器补两个会话细节**:`Connection: close`(keep-alive 空闲连接会被上游
   计入并发会话)与稳定 `Session-Id`(同一账号恒定,避免每次请求新建会话)。
4. 错误文案补可行动提示(并发会话上限 / TPM 限流,约 1 分钟释放)。

## 验证(生产)
- 连续 6 次**流式**:6/6 成功(撞上限时自动等 10s 再试,客户端只感觉慢):
  `+0s / +12s / +34s / +86s / +100s / +144s`
- 连续 5 次**非流式**:5/5 成功(`+0 / +11 / +20 / +28 / +38s`)
- 修复前:第 4 个请求起必然 TM.00001041 / empty stream。

> 注:`TM.00001005 无正常可用套餐` 属于账号权益问题(不重试、如实报出),
> 与限流要分开处理。
2026-10-20 10:38:00 +08:00
16 changed files with 836 additions and 27 deletions

View File

@ -1,12 +1,12 @@
{
"name": "modelrouter-gui",
"version": "2.0.45",
"version": "2.0.47",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "modelrouter-gui",
"version": "2.0.45",
"version": "2.0.47",
"license": "Proprietary",
"devDependencies": {
"electron": "^33.0.0",

View File

@ -1,6 +1,6 @@
{
"name": "modelrouter-gui",
"version": "2.0.45",
"version": "2.0.47",
"description": "ModelRouter Desktop — embedded ModelRouter core with tray",
"author": "ModelRouter",
"main": "main.js",

View File

@ -505,13 +505,22 @@ end
### 7.1 计费维度
| 维度 | 用途 | 优先级 |
| 维度 | 用途 | token 价覆盖顺序 |
|---|---|---|
| `sources` | 源的固定价(如按请求计费的转发服务) | 中 |
| `models` | 模型的 per-token 价 | 高 |
| `default` | 兜底价(通常全 0) | 最低 |
| `models` | 模型的 per-token 价 | 中 |
| `sources` | 源级价:固定价,或覆盖该源全部模型的 token 价 | 高 |
| `keys` | 单个网关 key 的覆盖价 | **最高** |
**token 价**优先级:`keys` > `models` > `default`。
**token 价**优先级:`keys` > `sources` > `models` > `default`。
(实现顺序就是"后写覆盖前写":`default` → `models` → `sources` → `keys`;
所以**源级 token 价会覆盖模型价**。这是有意的:运营要能给某个源整体改价。)
⚠️ 正因为 `sources` 会覆盖 `models`,**"标记某源已定价"的条目只能用
`{ "per_request": 0 }`**,不能写 `{ "prompt": 0, "completion": 0 }` ——
后者会把该源所有模型的 token 价清成 0。编译器为 `mode: token` 的具体 URL
规则生成的就是前者(GitCode issue #1)。
**`per_request` 固定价是叠加的**(不覆盖),所以一个生图模型可以既算 token 又收固定费。
**`cache_discount`** 见 §7.7。
@ -599,6 +608,16 @@ curl -H "Authorization: Bearer $ADMIN_KEY" \
仪表盘上有 "Unpriced" 卡片。**这个数应该是 0**;不是 0 就去补价目。
**profile 级兜底**:`profiles[].default` 可设为 `free` 或 `unpriced`(默认):
| `default` | 未匹配任何规则的源 | `unpriced_reqs` |
|---|---|---|
| `unpriced`(省略时) | 记 0 价,计入未定价债务 | +1 |
| `free` | 记 0 价,但视为**刻意免费** | 不增加 |
另有 `prices.unmatched_sources`:列出没有规则命中的源,网关在应用 profile 时
会以 `[billing] WARNING` 打到日志里 —— 看到它就去补规则(或确认 `default` 选对了)。
注意"未定价"不等于"免费":这些请求的 `requests` / token 数**照常计入**
`total` 与各维度,只有金额是 0。

View File

@ -106,6 +106,27 @@ func CompileOpts(profile *config.BillingProfile, sources []config.Source, lenien
return prices, nil
}
// UnmatchedRuleURLs lists the non-wildcard rule URLs that match no configured
// source. Compile() treats such a URL as a hard error (a typo'd rule prices
// nothing), but the CALLER needs the list to say which rule to fix instead of
// just "compile failed" — and to explain what the degraded table dropped.
func UnmatchedRuleURLs(profile *config.BillingProfile, sources []config.Source) []string {
if profile == nil {
return nil
}
var out []string
for i := range profile.Rules {
rule := &profile.Rules[i]
if rule.URL == "*" {
continue
}
if len(matchSources(rule.URL, sources)) == 0 {
out = append(out, rule.URL)
}
}
return out
}
// matchSources returns the source names whose base_url matches pattern.
// "*" matches every source (used as a catch-all default rule).
func matchSources(pattern string, sources []config.Source) []string {
@ -245,8 +266,23 @@ func applyRule(prices map[string]interface{}, rule *config.BillingRule, srcName
// model priced on its own, so the wildcard loses nothing.
if rule.URL != "*" {
if _, ok := prices["sources"].(map[string]interface{})[srcName]; !ok {
// ONLY the marker — deliberately no "prompt"/"completion".
//
// priceFor() applies the source dimension AFTER the model
// dimension, and treats a present source key as an override
// (`sp.prompt ~= nil` => out.prompt = sp.prompt). Writing
// zeros here therefore rewrote the model price of every model
// this rule DOES list to 0 — while out.priced stayed true, so
// unpriced_reqs never grew either. Cost 0, no warning: GitCode
// issue #1.
//
// `per_request: 0` is the marker itself: it adds nothing to a
// request's cost, but its presence makes the plugin see the
// source as priced, which is the only thing this entry is for.
// (free/subscription above keep their zero token prices: there
// the zero IS the statement.)
prices["sources"].(map[string]interface{})[srcName] = map[string]interface{}{
"prompt": 0.0, "completion": 0.0, "per_request": 0.0,
"per_request": 0.0,
}
}
}

View File

@ -212,3 +212,105 @@ func TestLongContextStepCompiles(t *testing.T) {
t.Error("above=0 must be rejected")
}
}
// A specific-URL token rule marks its source priced, but the entry must carry
// ONLY the "this source is priced" marker — not zero token prices.
//
// Why: `billing.lua`'s priceFor() applies the source dimension AFTER the model
// dimension and treats `sp.prompt ~= nil` as an override. A {prompt:0,
// completion:0} entry therefore zeroes the model price of every model the rule
// DOES list. The symptom is silent: cost is 0 while out.priced is true, so
// unpriced_reqs does not grow either (GitCode issue #1).
//
// The original test only asserted the KEY existed, which froze the broken shape
// into a contract; this asserts the entry CONTENT.
func TestSpecificURLTokenRuleSourceEntryHasNoZeroTokenPrices(t *testing.T) {
sources := []config.Source{{Name: "mine", BaseURL: "https://mine.example.com/v1"}}
profile := &config.BillingProfile{
ID: "p",
Rules: []config.BillingRule{{
URL: "https://mine.example.com/v1", Mode: "token",
Models: map[string]config.BillingToken{
"m": {Prompt: "0.15", Completion: "0.60"},
},
}},
}
prices, err := Compile(profile, sources)
if err != nil {
t.Fatalf("compile: %v", err)
}
entry, ok := prices["sources"].(map[string]interface{})["mine"].(map[string]interface{})
if !ok {
t.Fatal("a specific-url token rule must still mark its own source priced")
}
for _, key := range []string{"prompt", "completion"} {
if _, present := entry[key]; present {
t.Errorf("source entry carries %s=%v: priceFor() treats it as an override "+
"and zeroes the model price (issue #1)", key, entry[key])
}
}
// per_request: 0 is the marker itself: adding a flat fee must not change
// the total, and the key's presence is what tells the plugin "priced".
if v, present := entry["per_request"]; !present || v != 0.0 {
t.Errorf("source entry must carry per_request:0 as the priced marker, got %#v", entry)
}
// The model price must still be the real per-token value.
m, ok := prices["models"].(map[string]interface{})["m"].(map[string]interface{})
if !ok {
t.Fatal("model price missing")
}
if m["prompt"] != 0.15e-6 {
t.Errorf("model prompt price = %v, want 1.5e-7 per token", m["prompt"])
}
}
// free / subscription are DELIBERATE zeros: their source entries keep the
// zero token prices, because there the zero IS the statement.
func TestExplicitZeroModesKeepZeroTokenPrices(t *testing.T) {
for _, mode := range []string{"free", "subscription"} {
profile := &config.BillingProfile{ID: "p", Rules: []config.BillingRule{{
URL: "https://mine.example.com/v1", Mode: mode, Subscription: 10,
}}}
prices, err := Compile(profile, []config.Source{
{Name: "mine", BaseURL: "https://mine.example.com/v1"},
})
if err != nil {
t.Fatalf("%s compile: %v", mode, err)
}
entry, ok := prices["sources"].(map[string]interface{})["mine"].(map[string]interface{})
if !ok {
t.Fatalf("%s: source entry missing", mode)
}
for _, key := range []string{"prompt", "completion"} {
if v, present := entry[key]; !present || v != 0.0 {
t.Errorf("%s: entry[%s] = %v (present=%v), want an explicit 0.0",
mode, key, v, present)
}
}
}
}
// UnmatchedRuleURLs 是给调用方的"哪条规则写错了"清单:严格编译只会说
// "compile failed",而运维需要知道具体 URL;降级应用时也要能说明丢了什么。
func TestUnmatchedRuleURLs(t *testing.T) {
sources := []config.Source{{Name: "mine", BaseURL: "https://mine.example.com/v1"}}
profile := &config.BillingProfile{
ID: "p",
Rules: []config.BillingRule{
{URL: "https://mine.example.com/v1", Mode: "free"},
{URL: "https://stale.example.com/v1", Mode: "free"},
{URL: "*", Mode: "token", Models: map[string]config.BillingToken{
"m": {Prompt: "1", Completion: "1"},
}},
{URL: "https://mine.example.com/v1/", Mode: "free"}, // 尾斜杠归一后匹配
},
}
got := UnmatchedRuleURLs(profile, sources)
if len(got) != 1 || got[0] != "https://stale.example.com/v1" {
t.Fatalf("unmatched = %v, want only the stale URL (wildcard and trailing-slash "+
"variants must not be reported)", got)
}
if nil != UnmatchedRuleURLs(nil, sources) {
t.Error("nil profile must yield nil")
}
}

View File

@ -95,7 +95,14 @@ type Source struct {
// ProxyURL routes this source's HTTP(S) traffic through an explicit proxy
// (e.g. http://127.0.0.1:7890). Empty = direct connection. Needed for
// upstreams behind geo/IP blocks that only respond through a proxy.
ProxyURL string `yaml:"proxy_url" json:"proxy_url,omitempty"`
ProxyURL string `yaml:"proxy_url" json:"proxy_url,omitempty"`
// Retry is an OPTIONAL upstream retry policy. It exists for upstreams that
// answer a business-level rejection with a status code the kernel would
// otherwise surface to the client — e.g. a per-account concurrency cap that
// clears by itself after tens of seconds. The kernel stays vendor-agnostic:
// the matcher is pure DATA (status list + response-body substrings), so no
// provider name ever appears in core.
Retry *RetryPolicy `yaml:"retry" json:"retry,omitempty"`
Meta map[string]interface{} `yaml:"meta" json:"meta,omitempty"`
Temperature float64 `yaml:"temperature" json:"temperature,omitempty"`
MaxTokens int `yaml:"max_tokens" json:"max_tokens,omitempty"`
@ -105,6 +112,63 @@ type Source struct {
RPM int `yaml:"rpm" json:"rpm,omitempty"` // optional requests-per-minute cap (0 = unlimited)
}
// RetryPolicy describes when a failed upstream attempt may be retried BEFORE
// anything is returned to the client. All conditions are data:
//
// OnStatus - retry only when the HTTP status is one of these
// OnBodyContains - ... AND the response body contains one of these substrings
// (empty = status alone decides)
// Delay - wait between attempts ("10s" etc.); parsed on demand
// MaxAttempts - TOTAL attempts including the first (1 or 0 = no retry)
//
// Scope: the retry happens inside one gateway request, so a stream is only
// retried before its first chunk reaches the client (the kernel already holds
// the first chunk back), and a non-stream call is retried as a whole.
type RetryPolicy struct {
OnStatus []int `yaml:"on_status,omitempty" json:"on_status,omitempty"`
OnBodyContains []string `yaml:"on_body_contains,omitempty" json:"on_body_contains,omitempty"`
Delay string `yaml:"delay,omitempty" json:"delay,omitempty"`
MaxAttempts int `yaml:"max_attempts,omitempty" json:"max_attempts,omitempty"`
}
// ShouldRetry reports whether one failed attempt matches this policy.
func (r *RetryPolicy) ShouldRetry(status int, body string) bool {
if r == nil || r.MaxAttempts <= 1 {
return false
}
statusOK := len(r.OnStatus) == 0
for _, s := range r.OnStatus {
if s == status {
statusOK = true
break
}
}
if !statusOK {
return false
}
if len(r.OnBodyContains) == 0 {
return true
}
for _, sub := range r.OnBodyContains {
if sub != "" && strings.Contains(body, sub) {
return true
}
}
return false
}
// DelayDuration is the configured pause between attempts (default 10s).
func (r *RetryPolicy) DelayDuration() time.Duration {
if r == nil || r.Delay == "" {
return 10 * time.Second
}
d, err := time.ParseDuration(r.Delay)
if err != nil || d < 0 {
return 10 * time.Second
}
return d
}
// Load reads and validates a config file. When the file does not exist yet a
// default config is generated at that path first (first-run bootstrap), so a
// fresh binary just works: `llmsproxy -config /path/to/config.yaml`.

View File

@ -0,0 +1,59 @@
package config
import (
"testing"
"time"
)
// ShouldRetry 是纯数据判据:状态码列表 + 响应体子串。它决定"这次失败值不值得
// 在网关内部等一会儿重试"。厂商知识绝不能进内核,所以判据必须能用一个表格测清楚。
func TestRetryPolicyShouldRetry(t *testing.T) {
cases := []struct {
name string
policy *RetryPolicy
status int
body string
want bool
}{
{"nil policy", nil, 500, "anything", false},
{"max_attempts=1 disables", &RetryPolicy{OnStatus: []int{400}, MaxAttempts: 1}, 400, "x", false},
{"status matches, no body filter",
&RetryPolicy{OnStatus: []int{429}, MaxAttempts: 3}, 429, "", true},
{"status mismatch",
&RetryPolicy{OnStatus: []int{429}, MaxAttempts: 3}, 400, "429", false},
{"status + body match",
&RetryPolicy{OnStatus: []int{400}, OnBodyContains: []string{"TM.00001041"}, MaxAttempts: 3},
400, `{"error_code":"TM.00001041"}`, true},
{"status matches but body does not",
&RetryPolicy{OnStatus: []int{400}, OnBodyContains: []string{"TM.00001041"}, MaxAttempts: 3},
400, `{"error_code":"TM.00001005"}`, false},
{"empty substring never matches",
&RetryPolicy{OnStatus: []int{400}, OnBodyContains: []string{""}, MaxAttempts: 3}, 400, "x", false},
{"any of several body signals",
&RetryPolicy{OnStatus: []int{400, 429}, OnBodyContains: []string{"TM.00001041", "TPM limit"}, MaxAttempts: 3},
429, `{"message":"TPM limit exceeded"}`, true},
}
for _, tc := range cases {
if got := tc.policy.ShouldRetry(tc.status, tc.body); got != tc.want {
t.Errorf("%s: ShouldRetry(%d, %q) = %v, want %v", tc.name, tc.status, tc.body, got, tc.want)
}
}
}
func TestRetryPolicyDelay(t *testing.T) {
cases := []struct {
name string
policy *RetryPolicy
want time.Duration
}{
{"nil", nil, 10 * time.Second},
{"explicit", &RetryPolicy{Delay: "250ms"}, 250 * time.Millisecond},
{"garbage falls back", &RetryPolicy{Delay: "not-a-duration"}, 10 * time.Second},
{"negative falls back", &RetryPolicy{Delay: "-5s"}, 10 * time.Second},
}
for _, tc := range cases {
if got := tc.policy.DelayDuration(); got != tc.want {
t.Errorf("%s: DelayDuration() = %v, want %v", tc.name, got, tc.want)
}
}
}

View File

@ -0,0 +1,60 @@
package core
import (
"path/filepath"
"testing"
"llmsproxy/internal/config"
)
// 一个过期的规则 URL 不得让**整个**计费 profile 失效。
//
// 真实事故(GitCode issue #1 排查中发现,生产现网):config.yaml 里
// `billing.rules[0].url` 是 `https://opencode.ai/inference/v1`,而该源的
// base_url 已是 `.../inference/openai/v1`。严格编译因此返回
// "rule url ... matches no configured source base_url",applyBillingDSL 直接
// return —— 于是**所有**计费规则都不生效:账单恒为 0、unpriced_reqs 涨到 3.7 万,
// 而唯一的痕迹是一行启动日志。这正是「静默少报」最严重的一种。
//
// 修法:严格编译失败时降级为 lenient(用能匹配的规则),并打 ERROR 说明后果。
// 一个 URL 写错不该把整个价目表一起葬送;但也不能装作成功。
func TestBillingStaleRuleURLStillAppliesOtherRules(t *testing.T) {
cfg := newTestConfig(t)
dir := t.TempDir()
cfg.PluginDir = filepath.Join(dir, "plugins")
cfg.Sources = []config.Source{
{Name: "localzen", BaseURL: "https://opencode.ai/inference/openai/v1", Adapter: "openai",
Models: []config.Model{{ID: "m"}}},
}
cfg.BillingDSL = &config.BillingDSL{
Active: "p",
Profiles: []config.BillingProfile{{
ID: "p",
Rules: []config.BillingRule{
// 过期 URL:没有任何源的 base_url 与它相等
{URL: "https://opencode.ai/inference/v1", Mode: "free"},
// 有效规则:必须仍然生效
{URL: "https://opencode.ai/inference/openai/v1", Mode: "free"},
},
}},
}
c := newTestCore(t, cfg)
c.applyBillingDSL()
raw := c.plugins.Prices("billing")
if raw == nil {
t.Fatal("billing has no price table (profile never applied)")
}
prices, ok := raw.(map[string]interface{})
if !ok {
t.Fatalf("price table shape: %#v", raw)
}
sources, ok := prices["sources"].(map[string]interface{})
if !ok {
t.Fatalf("prices has no sources: %#v", prices)
}
if _, ok := sources["localzen"]; !ok {
t.Fatalf("一条过期规则 URL 把整个 profile 弄失效了:有效的 free 规则也没有生效,"+
"结果是账单恒为 0 且没有告警。prices=%#v", prices)
}
}

View File

@ -1057,14 +1057,60 @@ func (c *Core) applyBillingDSL() {
}
prices, err := billing.Compile(profile, c.cfg.Sources)
if err != nil {
log.Printf("[billing] profile %q not applied: %v", profile.ID, err)
return
// ONE stale rule URL must not take the whole price table down with it.
//
// The strict compiler rejects a profile whose rule matches no source,
// which is right for catching typos — but the runtime consequence used
// to be a bare `return`: every rule stopped applying, the bill came out
// at 0 and unpriced_reqs grew forever, with a single startup log line as
// the only trace. Found in production while fixing GitCode issue #1
// (a rule still pointed at .../inference/v1 after the source moved to
// .../inference/openai/v1; 37k requests had been recorded as unpriced).
//
// So: apply the rules that DO match, and say exactly what was dropped.
// The profile still fails loudly — it just no longer fails silently for
// everything else.
lenient, lerr := billing.CompileOpts(profile, c.cfg.Sources, true)
if lerr != nil {
log.Printf("[billing] profile %q not applied: %v (lenient retry also failed: %v)",
profile.ID, err, lerr)
return
}
def := profile.Default
if def == "" {
def = "unpriced"
}
log.Printf("[billing] ERROR profile %q has %d rule URL(s) matching no configured "+
"source: %v — applied the remaining %d rule(s); unmatched traffic falls through "+
"to default=%q and keeps counting in unpriced_reqs. FIX THE RULE URL: a stale URL "+
"used to zero out the entire price table.", profile.ID,
len(billing.UnmatchedRuleURLs(profile, c.cfg.Sources)),
billing.UnmatchedRuleURLs(profile, c.cfg.Sources),
len(profile.Rules)-len(billing.UnmatchedRuleURLs(profile, c.cfg.Sources)), def)
prices = lenient
}
if err := ps.SetState("billing", map[string]interface{}{"prices": prices}); err != nil {
log.Printf("[billing] applying profile %q: %v", profile.ID, err)
return
}
log.Printf("[billing] profile %q applied (%d rules, %d sources)", profile.ID, len(profile.Rules), len(c.cfg.Sources))
// unmatched_sources used to be written by the compiler and read by nobody,
// so a profile that silently left half the gateway unpriced looked applied
// and healthy. Logging it is the cheap reader: an operator who sees source
// names here knows exactly which rules to add (GitCode issue #1 follow-up).
if unmatched, ok := prices["unmatched_sources"].([]string); ok && len(unmatched) > 0 {
log.Printf("[billing] WARNING %d source(s) match no rule and fall through to the "+
"profile default: %v (add rules, or set `default: free` if that is intended)",
len(unmatched), unmatched)
} else if raw, ok := prices["unmatched_sources"].([]interface{}); ok && len(raw) > 0 {
names := make([]string, 0, len(raw))
for _, v := range raw {
names = append(names, fmt.Sprint(v))
}
log.Printf("[billing] WARNING %d source(s) match no rule and fall through to the "+
"profile default: %v (add rules, or set `default: free` if that is intended)",
len(names), names)
}
}
// ValidateScopeQuotas checks every scope entry's caps before they are stored.

View File

@ -236,19 +236,39 @@ func TestBillingRulesPersistAndReachThePlugin(t *testing.T) {
if _, ok := sources["localzen"]; !ok {
t.Errorf("the free rule did not reach the plugin: %v", keysOf(sources))
}
// The injected price must be per-token, i.e. 0.15 USD/M => 1.5e-7.
// The source entry exists ONLY as the "this source is priced" marker: it
// must not carry token prices, because priceFor() applies the source
// dimension after the model dimension and would overwrite the model price
// with 0 (GitCode issue #1 — silent, unpriced_reqs does not grow either).
if entry, ok := cc.(map[string]interface{}); ok {
for _, key := range []string{"prompt", "completion"} {
if _, present := entry[key]; present {
t.Errorf("the injected source entry carries %s: it will zero the "+
"model price (issue #1): %#v", key, entry)
}
}
}
// The injected MODEL price must be per-token, i.e. 0.15 USD/M => 1.5e-7.
// Asserting the exact magnitude catches a unit error (per-million vs
// per-token), which would be off by a factor of a million and still look
// like "a number".
models, ok := cc.(map[string]interface{})["models"].(map[string]interface{})
if ok {
if m, ok := models["deepseek-v4.1-flash"].(map[string]interface{}); ok {
p, _ := m["prompt"].(float64)
if p <= 0 || p > 1e-6 {
t.Errorf("injected prompt price = %v, want per-token (~1.5e-7); "+
"a per-million value here would over-bill by 1e6x", p)
}
}
//
// ⚠️ This used to read `cc["models"]`, but `models` lives at
// prices["models"], not inside a source entry — so the type assertion was
// always false and the whole block was skipped. It had never run, which is
// how a per-million unit error could survive a test whose comment claims
// to catch exactly that.
models, ok := prices["models"].(map[string]interface{})
if !ok {
t.Fatalf("prices has no models map: %#v", prices)
}
m, ok := models["deepseek-v4.1-flash"].(map[string]interface{})
if !ok {
t.Fatalf("the model price was not injected: %v", keysOf(models))
}
if p, _ := m["prompt"].(float64); p <= 0 || p > 1e-6 {
t.Errorf("injected prompt price = %v, want per-token (~1.5e-7); "+
"a per-million value here would over-bill by 1e6x", p)
}
}

View File

@ -126,7 +126,12 @@ func TestRealMutants(t *testing.T) {
},
{
name: "nested metadata no longer read",
from: "\tcopyFields(m.Metadata) // nested first",
// 锚点必须与 discover.go 逐字节一致:此前这里是 6 个空格,源码已
// 变成 2 个空格,于是这条变异永远"找不到锚点"——变异campaign 每次
// 都以 anchor not found 失败,而它本该验证"嵌套 metadata 被丢掉"能被
// 测试抓住。锚点漂移 = 这条变异从未真正跑过(和 issue #1 里
// `cc["models"]` 恒 false 的测试跳过是同一种失效:断言写了但没执行)。
from: "\tcopyFields(m.Metadata) // nested first",
to: "\tcopyFields(json.RawMessage(nil)) // mutant: nested metadata dropped",
},
{

View File

@ -1236,3 +1236,122 @@ func TestLongContextComposesWithCacheDiscount(t *testing.T) {
// total = 0.2325
approx(t, "step composes with cache discount", got, 0.2325)
}
// ---- 源层零价覆盖模型价(issue #1)---------------------------------------
//
// 真实缺陷(GitCode issue #1):`compile.go` 给每条**具体 URL** 的 token 规则
// 写一条 `{prompt:0, completion:0, per_request:0}` 的源条目,本意只是"标记该源
// 已定价";而插件 priceFor() 的源层是**无条件覆盖**模型层:`sp.prompt ~= nil`
// 就把模型价改成 0。两条各自正当的规则叠加 ⇒ 每个请求 cost:0,且因为
// out.priced=true,连 unpriced_reqs 都不涨 —— 完全静默。
//
// 这里把两种条目形状都钉住:旧形状必须**真的是错的**(A 行),新形状必须
// **保住模型价同时仍算"已定价"**(B 行)。只断言"键存在"是不够的 —— 那正是
// 现有测试把错误形状固化成契约的原因。
func TestBillingSourceZeroPriceMustNotZeroModelPrice(t *testing.T) {
const promptPrice = 1.5e-7 // 0.15 USD/M
const completionPrice = 6e-7 // 0.60 USD/M
const want = 0.75 // 1e6 * 1.5e-7 + 1e6 * 6e-7
newPrices := func(sourceEntry map[string]interface{}) map[string]interface{} {
return map[string]interface{}{
"default": map[string]interface{}{"prompt": 0.0, "completion": 0.0, "per_request": 0.0},
"models": map[string]interface{}{
"m": map[string]interface{}{"prompt": promptPrice, "completion": completionPrice},
},
"sources": map[string]interface{}{"src": sourceEntry},
}
}
run := func(t *testing.T, sourceEntry map[string]interface{}) (cost, unpriced float64) {
t.Helper()
ps, _ := billingVM(t)
_ = ps.SetState("billing", map[string]interface{}{"prices": newPrices(sourceEntry)})
ps.Fire(StageRequestEnd, map[string]interface{}{
"model": "m", "source": "src", "key": "***p", "ok": true,
"prompt_tokens": 1000000.0, "completion_tokens": 1000000.0,
"time": 1750000000000,
})
st := stateOf(t, ps)
total := st["total"].(map[string]interface{})
return total["cost"].(float64), st["unpriced_reqs"].(float64)
}
// A 行:compile.go 修复前的形状 —— 这是缺陷本身,必须算成 0。
cost, unpriced := run(t, map[string]interface{}{
"prompt": 0.0, "completion": 0.0, "per_request": 0.0,
})
approx(t, "旧形状(全零源条目) cost", cost, 0)
if unpriced != 0 {
t.Errorf("旧形状下 unpriced_reqs = %v,缺陷正是它也为 0(静默)", unpriced)
}
// B 行:修复后的形状 —— 只带 per_request,不得覆盖模型价。
cost, unpriced = run(t, map[string]interface{}{"per_request": 0.0})
approx(t, "新形状(仅 per_request) cost", cost, want)
if unpriced != 0 {
t.Errorf("新形状下 unpriced_reqs = %v,want 0(该源仍算已定价)", unpriced)
}
}
// 同一源上一个**未列入价目表**的模型:源条目(仅 per_request)让它保持
// "已定价",所以不会被计入 unpriced_reqs —— 这正是 compile 写源条目的原意。
func TestBillingSourceEntryStillMarksUnlistedModelPriced(t *testing.T) {
ps, _ := billingVM(t)
_ = ps.SetState("billing", map[string]interface{}{
"prices": map[string]interface{}{
"default": map[string]interface{}{"prompt": 0.0, "completion": 0.0, "per_request": 0.0},
"models": map[string]interface{}{
"priced-model": map[string]interface{}{"prompt": 1.5e-7, "completion": 6e-7},
},
"sources": map[string]interface{}{
"src": map[string]interface{}{"per_request": 0.0},
},
},
})
ps.Fire(StageRequestEnd, map[string]interface{}{
"model": "unlisted-model", "source": "src", "key": "***p", "ok": true,
"prompt_tokens": 1000.0, "completion_tokens": 0.0, "time": 1750000000000,
})
st := stateOf(t, ps)
if got := st["unpriced_reqs"].(float64); got != 0 {
t.Errorf("unpriced_reqs = %v,want 0:源条目存在即为已定价源", got)
}
}
// profile 级 default(compile.go 写入的 default_mode)必须真的生效。
//
// 真实缺陷(GitCode issue #1 顺带发现):compile.go:54 写 `default_mode`、
// :104 写 `unmatched_sources`,但全仓库没有任何读取方 —— 于是 profile 的
// `default: free|unpriced` 在运行时完全等价,区别只存在于 YAML 里。
// "free" 是**刻意定价为 0**,不该进未定价统计;"unpriced" 才该。
func TestBillingProfileDefaultMode(t *testing.T) {
cases := []struct {
mode string
wantUnpriced float64
}{
{"free", 0},
{"unpriced", 1},
{"", 1}, // 未声明 = 现有行为(未定价债务)
}
for _, tc := range cases {
ps, _ := billingVM(t)
prices := map[string]interface{}{
"default": map[string]interface{}{"prompt": 0.0, "completion": 0.0, "per_request": 0.0},
}
if tc.mode != "" {
prices["default_mode"] = tc.mode
}
_ = ps.SetState("billing", map[string]interface{}{"prices": prices})
ps.Fire(StageRequestEnd, map[string]interface{}{
"model": "no-rule-model", "source": "no-rule-source", "key": "***p", "ok": true,
"prompt_tokens": 1000.0, "completion_tokens": 10.0, "time": 1750000000000,
})
st := stateOf(t, ps)
if got := st["unpriced_reqs"].(float64); got != tc.wantUnpriced {
t.Errorf("default_mode=%q: unpriced_reqs = %v, want %v", tc.mode, got, tc.wantUnpriced)
}
// 无论哪种模式,成本都是 0;区别只在"是否算未定价债务"。
approx(t, "default_mode="+tc.mode+" cost",
st["total"].(map[string]interface{})["cost"].(float64), 0)
}
}

View File

@ -189,7 +189,11 @@ local function priceFor(payload)
-- look the same: an unpriced model silently costing 0 is the most dangerous
-- failure mode a cost plugin has, because the bill still adds up and just
-- quietly under-reports. It is counted separately and surfaced in the UI.
out = {
-- ★ local 是必须的:此前写的是全局 `out = {`,而 priceFor 每个请求都会调用,
-- 于是这个表挂在 VM 级全局变量上跨请求残留/泄漏(GitCode issue #1 顺带发现)。
-- 功能上因为每次整体重建而侥幸正确,但它是共享可变状态,任何提前 return 或
-- 后续分支忘了重建都会让上一单的价格漏到下一单 —— 计费错误不会报错。
local out = {
prompt = d.prompt or 0, completion = d.completion or 0,
per_request = 0, cache_discount = d.cache_discount, peak = d.peak,
-- nil = bill reasoning at the completion rate, which is what every
@ -236,6 +240,18 @@ local function priceFor(payload)
if kp.cache_discount ~= nil then out.cache_discount = kp.cache_discount end
if kp.peak ~= nil then out.peak = kp.peak end
end
-- profile-level default for sources no rule matched.
--
-- compile.go has always written `default_mode` ("free" | "unpriced") into the
-- prices table, but NOTHING read it — so `default: free` and
-- `default: unpriced` behaved identically at runtime (both fell through to
-- prices.default's zeros and counted as unpriced debt). That is a second
-- silent under-report (GitCode issue #1 follow-up). "free" is a DELIBERATE
-- zero, so it must be marked priced; anything else stays countable debt.
if not out.priced and p.default_mode == "free" then
out.priced = true
end
return out
end

View File

@ -1046,6 +1046,24 @@ local PLATFORMS = {
base_url = "https://snap-access.cn-north-4.myhuaweicloud.com",
-- 本插件**自己装的**适配器(见 installCodeartsAdapter):华为云 AK/SK 签名
adapter = "codearts",
-- ★ 上游的"不可用"多数是**账号级限流**,约 1 分钟自愈,不是模型坏了:
-- * 400 `TM.00001041: 并发会话数已达上限(3个)` —— 账户并发会话上限,
-- 实测最后一个请求结束后约 44~60 秒释放;
-- * 429 `TPM limit ... 500000 tokens per minute` —— 每分钟 token 配额。
-- 内核原本**只在 429 上做冷却、不重试**,于是这类"等一会儿就好"的拒绝
-- 直接冒到客户端(流式还表现为 `empty stream`,因为上游用 HTTP 200 +
-- error 帧表达拒绝)。
--
-- 这里声明**声明式重试策略**(内核只按数据匹配,不认识 CodeArts):
-- 命中即在网关内部每 10s 重试一次,最多 18 次(≈3 分钟),客户端只是
-- 多等几秒,不会看到错误。流式只在**握手阶段**重试(首帧尚未下发),
-- 不会重复输出。
retry_policy = {
on_status = { 400, 429 },
on_body_contains = { "TM.00001041", "TPM limit", "并发会话数已达上限" },
delay = "10s",
max_attempts = 18,
},
-- 签名平台:源注册要交**完整凭据 JSON**(适配器自己解 AK/SK 签名),
-- 不是裸 access token。见 syncAccountSource 的注释。
credential_shape = "full",
@ -4627,6 +4645,9 @@ local function syncProviderSource(provider)
if plat.endpoint then src.endpoint = plat.endpoint end
if plat.endpoint_stream then src.endpoint_stream = plat.endpoint_stream end
if plat.headers_extra then src.headers = plat.headers_extra end
-- 声明式上游重试策略(见平台上的 retry_policy 注释):内核只按 status +
-- body 子串匹配,不认识任何厂商。
if type(plat.retry_policy) == "table" then src.retry = plat.retry_policy end
-- ★ 把**设备身份**随源带给适配器:有些平台的头不是简单 Bearer,
-- 需要 uid / device_id / machine_id 派生(trae 的 X-Uid / X-Device-Id /
-- X-Machine-Id)。适配器沙箱里**读不到凭据**,只能靠 meta 传。
@ -10128,7 +10149,21 @@ end
-- build_headers:内核按源注入 meta{url,method,body,api_key,...}。
-- 凭据是完整 JSON(登录时存的就是它),从中解出 AK/SK/ST。
function adapter.build_headers(meta)
local h = { ["Content-Type"] = "application/json" }
-- ★★ Connection: close 是**必须**的,不是优化。
--
-- CodeArts 后端按**账户**限制并发会话数(3 个),而它把"会话"绑定在
-- HTTP 连接上:内核的 Go transport 会保留空闲连接(默认每 host 2 条)
-- 用于 keep-alive,于是第 3~4 个请求就被判成"并发会话数已达上限(3个)"
-- (TM.00001041),用户看到的是 codeart 连续不可用。
--
-- 实证(2026-10-20):
-- * 走网关连续 5 次 → #1/#2/#3 成功,#4/#5 全部 TM.00001041;
-- * 同一凭据、每请求**新连接 + Connection: close** 连续 5 次 → 5/5 成功;
-- * 之后连续流式也一样:3 次成功后开始 400。
-- 即"会话"就是连接,关掉连接会话立刻释放。
--
-- 代价是每次多一次 TCP/TLS 握手(~百毫秒级),换"渠道真的能用",值得。
local h = { ["Content-Type"] = "application/json", ["Connection"] = "close" }
local raw = tostring(meta.api_key or "")
local cred = nil
if raw:sub(1, 1) == "{" then
@ -10146,6 +10181,19 @@ function adapter.build_headers(meta)
return h
end
for k, v in pairs(signed) do h[k] = v end
-- ★★ Session-Id 是**必须**的,不是可选项 —— 它决定"并发会话数"怎么算。
--
-- 实测(2026-10-20,对照参考实现 llm-adapter.ts:1168 `headers.set('Session-Id', …)`):
-- 不发送会话号时,后端把**每个请求**当成一个新会话;而会话在响应结束后还要
-- 存活一段时间才释放,于是连续 3 个请求就把账户的「并发会话数上限(3个)」占满,
-- 之后所有请求(含流式)稳定回 TM.00001041 / 200+空流(用户看到 empty stream)。
-- 发一个**稳定**的会话号(同一账号内恒定),后端复用同一会话 ⇒ 不再累加。
--
-- 会话号取 AK 的 sha256 前 32 hex:稳定、可复现、不引入需要持久化的状态。
local ak = tostring(cred.access_key_id or cred.access_key or "")
if ak ~= "" then
h["Session-Id"] = string.sub(sha256_hex(ak), 1, 32)
end
return h
end

View File

@ -1156,7 +1156,7 @@ func (p *Provider) Chat(ctx context.Context, req *types.ChatRequest) (*types.Uni
if err != nil {
return nil, err
}
raw, status, err := p.do(ctx, chatURL, body, hdrs)
raw, status, err := p.doWithRetry(ctx, chatURL, body, hdrs)
if err != nil {
// a client disconnect or cancelled context is neither a success nor
// a failure for scheduling purposes — only upstream errors count
@ -1227,8 +1227,48 @@ func (p *Provider) ChatStream(ctx context.Context, req *types.ChatRequest) (<-ch
}
rc := make(chan respOrErr, 1)
go func() {
resp, err := p.doRawStream(ctx, streamURL, body, hdrs)
rc <- respOrErr{resp, err}
// Retry only the HANDSHAKE: a policy-matched rejection (e.g. a
// per-account concurrency cap answered with a business 4xx) can clear
// within seconds, and nothing has been sent to the client yet — the
// kernel holds the first chunk back. Once a 200 arrives and streaming
// starts, no retry happens (that would duplicate output).
rp := p.cfg.Retry
attempts := 1
if rp != nil && rp.MaxAttempts > 1 {
attempts = rp.MaxAttempts
}
for i := 0; i < attempts; i++ {
resp, err := p.doRawStream(ctx, streamURL, body, hdrs)
if err != nil {
rc <- respOrErr{resp, err}
return
}
if resp.StatusCode == 200 {
rc <- respOrErr{resp, nil}
return
}
// A rejection can only be classified after the body is read: the
// policy matches on body substrings, and a source may use the same
// status (400) for unrelated errors that must NOT be retried.
raw, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if !rp.ShouldRetry(resp.StatusCode, string(raw)) {
// Not the retryable body: hand the rejection back verbatim so
// the caller reports the real upstream error.
resp2 := &http.Response{StatusCode: resp.StatusCode, Body: io.NopCloser(strings.NewReader(string(raw)))}
rc <- respOrErr{resp2, nil}
return
}
if i == attempts-1 {
resp2 := &http.Response{StatusCode: resp.StatusCode, Body: io.NopCloser(strings.NewReader(string(raw)))}
rc <- respOrErr{resp2, nil}
return
}
if serr := sleepCtx(ctx, rp.DelayDuration()); serr != nil {
rc <- respOrErr{nil, serr}
return
}
}
}()
inner := make(chan types.UnifiedChunk, 64)
@ -1560,6 +1600,50 @@ func (p *Provider) do(ctx context.Context, url, body string, hdr http.Header) (s
return string(raw), resp.StatusCode, nil
}
// doWithRetry runs one non-stream request, retrying per the source's
// declarative RetryPolicy. The policy is pure data (status list + body
// substrings), so the kernel stays vendor-agnostic: a provider that answers a
// per-account concurrency cap with a business 4xx can clear by itself while the
// client just waits a few seconds instead of seeing an error.
func (p *Provider) doWithRetry(ctx context.Context, url, body string, hdr http.Header) (string, int, error) {
rp := p.cfg.Retry
attempts := 1
if rp != nil && rp.MaxAttempts > 1 {
attempts = rp.MaxAttempts
}
var raw string
var status int
for i := 0; i < attempts; i++ {
r, st, err := p.do(ctx, url, body, hdr)
if err != nil {
return "", 0, err
}
raw, status = r, st
if status == 200 || !rp.ShouldRetry(status, raw) || i == attempts-1 {
break
}
if serr := sleepCtx(ctx, rp.DelayDuration()); serr != nil {
return "", 0, serr
}
}
return raw, status, nil
}
// sleepCtx sleeps for d unless the request context ends first.
func sleepCtx(ctx context.Context, d time.Duration) error {
if d <= 0 {
return ctx.Err()
}
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
return nil
}
}
func (p *Provider) doRaw(ctx context.Context, url, body string, hdr http.Header) (*http.Response, error) {
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader([]byte(body)))
if err != nil {

View File

@ -0,0 +1,131 @@
package provider
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"llmsproxy/internal/config"
"llmsproxy/internal/types"
)
// 上游重试是**内核的通用机制**,判据纯数据(status + body 子串),
// 目的是让"账号级限流、等一会儿就好"这类拒绝不冒到客户端。
//
// 真实事故(2026-10-20):CodeArts 账户并发会话上限 3 个,连续第 3~4 个请求
// 回 400 TM.00001041,最后一个请求结束后约 44~60 秒才释放;流式更糟 ——
// 上游用 HTTP 200 + error 帧表达拒绝,内核只能报 `empty stream`。
// 参考实现的处理是每 10s 重试一次 chat 直到放行,本测试钉住同一语义。
func TestChatRetriesDeclaredUpstreamRejection(t *testing.T) {
var hits int32
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n := atomic.AddInt32(&hits, 1)
if n <= 2 {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, `{"error_code":"TM.00001041","error_msg":"并发会话数已达上限(3个)"}`)
return
}
fmt.Fprint(w, `{"choices":[{"message":{"content":"hi"},"finish_reason":"stop"}]}`)
}))
defer up.Close()
s := src("codearts-like", up.URL, "openai", "m1")
s.Retry = &config.RetryPolicy{
OnStatus: []int{400},
OnBodyContains: []string{"TM.00001041"},
Delay: "1ms",
MaxAttempts: 4,
}
p := newTestProvider(t, s)
resp, err := p.Chat(context.Background(), &types.ChatRequest{
Model: "m1",
Messages: []types.ChatMessage{{Role: "user", Content: types.StringContent("hi")}},
})
if err != nil {
t.Fatalf("命中重试策略后应成功,实得错误: %v", err)
}
if resp.Content != "hi" {
t.Fatalf("content = %q", resp.Content)
}
if got := atomic.LoadInt32(&hits); got != 3 {
t.Fatalf("应恰好尝试 3 次(2 次失败 + 1 次成功),实得 %d", got)
}
}
// 同一状态码但 body 不匹配 ⇒ **不许重试**(400 也常用于真正的请求错误,
// 无差别重试只会把错误延迟 3 分钟才暴露给用户)。
func TestChatDoesNotRetryUnmatchedBody(t *testing.T) {
var hits int32
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&hits, 1)
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, `{"error_code":"TM.00001005","error_msg":"无正常可用套餐"}`)
}))
defer up.Close()
s := src("codearts-like", up.URL, "openai", "m1")
s.Retry = &config.RetryPolicy{
OnStatus: []int{400},
OnBodyContains: []string{"TM.00001041"},
Delay: "1ms",
MaxAttempts: 5,
}
p := newTestProvider(t, s)
_, err := p.Chat(context.Background(), &types.ChatRequest{
Model: "m1",
Messages: []types.ChatMessage{{Role: "user", Content: types.StringContent("hi")}},
})
if err == nil {
t.Fatal("不可重试的 body 必须失败")
}
if got := atomic.LoadInt32(&hits); got != 1 {
t.Fatalf("body 不匹配时只能尝试 1 次,实得 %d", got)
}
}
// 流式:只重试**握手**。命中策略 → 重试直到 200 才开始派发;一旦开始流式
// 就不再重试(重复输出比报错更糟)。
func TestChatStreamRetriesHandshakeOnly(t *testing.T) {
var hits int32
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n := atomic.AddInt32(&hits, 1)
if n == 1 {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, `{"error_code":"TM.00001041","error_msg":"并发会话数已达上限(3个)"}`)
return
}
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"},\"finish_reason\":\"stop\"}]}\n\n")
fmt.Fprint(w, "data: [DONE]\n\n")
}))
defer up.Close()
s := src("codearts-like", up.URL, "openai", "m1")
s.Retry = &config.RetryPolicy{
OnStatus: []int{400},
OnBodyContains: []string{"TM.00001041"},
Delay: "1ms",
MaxAttempts: 4,
}
p := newTestProvider(t, s)
ch, err := p.ChatStream(context.Background(), &types.ChatRequest{
Model: "m1",
Messages: []types.ChatMessage{{Role: "user", Content: types.StringContent("hi")}},
})
if err != nil {
t.Fatalf("握手重试后应成功: %v", err)
}
var content string
for ck := range ch {
content += ck.Content
}
if content != "hi" {
t.Fatalf("content = %q", content)
}
if got := atomic.LoadInt32(&hits); got != 2 {
t.Fatalf("应握手重试 1 次(共 2 次请求),实得 %d", got)
}
}