Files
sub2api/backend/internal/handler/failover_loop_profit_veto_test.go
T
shaw dec47e8fae fix(profit-control): stop leaking profit policy, close veto livelock, restore passthrough turn pricing
审计修复,逐条如下。

H1 利润策略泄露给所有普通用户
  profit_control_enabled / profit_min_margin / profit_safety_buffer 从
  dto.Group 移到 dto.AdminGroup(后者内嵌前者),赋值相应从
  groupFromServiceBase 移到 GroupFromServiceAdmin;前端 TS 同步从 Group 移到
  AdminGroup。dto.Group 是 GET /api/v1/groups/available 的响应体,该响应本就带
  rate_multiplier,相乘即可反推运营方上游采购成本上限。
  api_contract_test.go 的 /groups/available golden JSON 回滚这三个字段,并把
  fixture 改成非零值(require.JSONEq 是精确比对,缺字段即失败)。
  新增 dto 层边界测试:普通用户 DTO 不含三字段、管理员 DTO 仍含。

M1 利润终检 continue 与 failover 503 退避互动产生活锁
  FailoverState 新增 profitVetoedAccountIDs / profitVetoCount 与
  RecordProfitVeto():加入排除集 + 计数,达 maxProfitVetoAttempts(10) 返回
  FailoverExhausted。HandleSelectionExhausted 的 503 清空分支改为清空后把利润
  否决的账号放回排除集;若排除集已全部由利润否决贡献,清空不会带来任何新候选,
  直接判定耗尽(否则 SwitchCount 永不前进、退避条件永远成立,每 2s 空转一轮)。
  五个 handler 否决点(gateway_handler ×2 / responses / chat_completions /
  gemini_v1beta)改为经 RecordProfitVeto 决策,耗尽时按无可用账号终止。
  回归测试钉死:503 之后持续利润否决必须有限步终止且不 spin;未启用利润控制的
  请求退避语义完全不变。

M2 排队等槽后才终检,延迟可放大到 N × WaitPlan.Timeout
  OpenAI 侧选号循环(自有 failedAccountIDs map,非 FailoverState)新增
  recordOpenAIProfitVeto + handleOpenAIProfitVetoExhausted,共用同一上限语义。
  覆盖 responses / messages-dispatch / chat_completions / alpha_search /
  embeddings / images / grok_media 七处,以及 WS 两处否决分支。

M4 ws_v2 透传 ingress 绕过 per-turn 重定价(选方案 B:最小止血)
  透传 relay 只回调 AfterTurn、没有任何 turn 起始回调,hooks.BeforeTurn 永远
  不触发,而 handler 把 turnPricingAt 初始化成建连时刻 ⇒ 透传连接全部 turn 按
  建连时刻的高峰因子结算,客户端峰前建连保活即可全程谷价——正是本 PR 想堵的
  漏洞。改为 openAIWSTurnPricing 零值起步、只由 BeforeTurn 冻结;透传路径保持
  零值,RecordUsage 回退记录时刻,与引入利润控制前的基线一致。
  未选方案 A(给透传补 turn 起始回调):passthrough_relay.go 是 #5167 刚修过的
  取消传播/close frame 时序敏感区;且 BeforeTurn 还承担 turn>1 的并发槽位抢占,
  接进去等于给透传连接引入 per-turn 抢槽,风险远超本次修复范围。透传仍有建连时
  的准入门,只是没有 turn 级复核,已在两处注释写明。
  测试:service 层钉死透传 ingress 不触发 BeforeTurn(含失败时的复核指引),
  handler 层钉死零值语义与逐 turn 覆盖。

M5 装门读分组走了带账号计数聚合的 GetByID
  SchedulerSnapshotService 新增 GetGroupByIDLite,openai/gateway 两处装门改用
  之。门只需要平台/倍率/利润/高峰字段,且该查询发生在「是否启用利润控制」判定
  之前,未启用的分组同样付代价。两个测试 stub 的 GetByID 改成 panic 守卫。

M6 认证快照注释与真实读取路径相反
  门解析优先取 ctxkey.Group,而它就是本快照物化出来的对象,直连流量走的正是这
  条路。改正注释,与 api_key_repo.go 投影处的说明对齐,避免后人照旧注释删列。

M3 rate_multiplier 为 nil 时利润门 fail-closed(不改行为,加护栏)
  保留 fail-closed。补 repository 层测试钉死账号调度快照的 full/metadata 两份
  payload 都必须保留 RateMultiplier(含 0 值),漏列在 CI 就红。

L1 迁移号注释 191 / 191-192 改为实际的 192/193。
L2 admin group Create 的利润配置预校验改用与 CreateGroup 一致的归一化平台
   (新增 service.NormalizeGroupPlatform,两边共用)。保留预校验而非删除:
   service 层返回的是无类型 error,经 ErrorFrom 会变成 500,删掉会把合法的
   400 降级成 500。
L3 前端利润校验的上界改为判定换算后的小数(后端按小数校验 [0,1)),
   99.999% 会四舍五入进位成 1.0 而被后端 400;i18n en/zh 同步改为 0-99.99。
L4 clampProfitControlThreshold / profitControlOverThreshold 抽为共用函数,
   线上装门/否决点与 profit-preview 不再各自实现,附边界语义测试。
L5 profit-preview 补「默认 D 有账号但最低有效 D 归零」的告警(两档都为 0 由
   既有告警覆盖,不重复)。
2026-08-01 22:39:33 +08:00

140 lines
5.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package handler
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
)
// profitVetoLoopResult 记录一次模拟选号循环的终止方式与步数。
type profitVetoLoopResult struct {
outcome string // "forwarded" | "exhausted" | "budget_exceeded"
forwardedID int64
iterations int
backoffRetries int
}
// runProfitVetoLoop 模拟 handler 的「选号 → 利润终检 → 重选」循环,只保留与
// 活锁相关的状态机(FailoverState + 排除列表 + HandleSelectionExhausted),
// 不涉及真实调度器与上游转发。
//
// pool 按顺序给出候选账号;vetoed 中的账号每次终检都被利润门否决——这对应
// 「候选池快照与 per-account 快照短暂不一致」时门的确定性判定。
// maxIterations 是测试自身的预算:循环超过它即视为活锁。
func runProfitVetoLoop(t *testing.T, fs *FailoverState, pool []int64, vetoed map[int64]bool, maxIterations int) profitVetoLoopResult {
t.Helper()
res := profitVetoLoopResult{}
for res.iterations = 1; res.iterations <= maxIterations; res.iterations++ {
// 选号:返回第一个不在排除列表中的账号。
var picked int64
for _, id := range pool {
if _, excluded := fs.FailedAccountIDs[id]; !excluded {
picked = id
break
}
}
if picked == 0 {
// 选号耗尽,交给退避决策。
switch fs.HandleSelectionExhausted(context.Background()) {
case FailoverContinue:
res.backoffRetries++
continue
default:
res.outcome = "exhausted"
return res
}
}
if vetoed[picked] {
if fs.RecordProfitVeto(picked) == FailoverExhausted {
res.outcome = "exhausted"
return res
}
continue
}
res.outcome = "forwarded"
res.forwardedID = picked
return res
}
res.outcome = "budget_exceeded"
return res
}
// TestProfitVetoAfter503DoesNotLivelock 钉死 #4925 引入的活锁回归:
// 一次真实 503 之后,若调度器持续返回会被利润门否决的账号,
// 「选号 → 否决 → 排除 → 选号耗尽 → 清空排除 → 睡 2s → 选号」会无限循环,
// 因为利润否决不推进 SwitchCount,退避条件永远成立。
func TestProfitVetoAfter503DoesNotLivelock(t *testing.T) {
fs := NewFailoverState(10, false)
// 已经历一次真实 503(Antigravity 单账号分组 MODEL_CAPACITY_EXHAUSTED 是设计内路径)。
fs.LastFailoverErr = newTestFailoverErr(503, false, false)
fs.SwitchCount = 1
fs.FailedAccountIDs[1] = struct{}{}
start := time.Now()
res := runProfitVetoLoop(t, fs, []int64{1}, map[int64]bool{1: true}, 50)
elapsed := time.Since(start)
require.Equal(t, "exhausted", res.outcome, "整池被利润门否决时必须有限步终止")
require.LessOrEqual(t, res.backoffRetries, 1, "被否决的账号不得被退避分支复活并反复重选")
require.Less(t, elapsed, 10*time.Second, "不得每 2s 空转一轮")
}
// TestProfitVetoKeepsBackoffUsefulForHealthyAccount 钉死修复没有削弱既有的
// 503 退避语义:排除列表里仍有非利润否决的账号时,退避照常清空并重试,
// 只是被利润门否决的账号不再复活。
func TestProfitVetoKeepsBackoffUsefulForHealthyAccount(t *testing.T) {
fs := NewFailoverState(10, false)
fs.LastFailoverErr = newTestFailoverErr(503, false, false)
fs.SwitchCount = 1
// 账号 1 因真实 503 被排除;账号 2 会被利润门否决。
fs.FailedAccountIDs[1] = struct{}{}
res := runProfitVetoLoop(t, fs, []int64{2, 1}, map[int64]bool{2: true}, 50)
require.Equal(t, "forwarded", res.outcome)
require.Equal(t, int64(1), res.forwardedID, "退避清空后应重新可选账号 1")
require.Equal(t, 1, res.backoffRetries, "应发生且只发生一次退避重试")
require.Contains(t, fs.FailedAccountIDs, int64(2), "利润否决的账号在退避清空后必须被放回排除集")
}
// TestProfitVetoAttemptsCapped 钉死没有 503 参与时,大分组整池越线也会在
// 常数步内终止,而不是把整池逐个选一遍。
func TestProfitVetoAttemptsCapped(t *testing.T) {
fs := NewFailoverState(10, false)
pool := make([]int64, 0, 64)
vetoed := make(map[int64]bool, 64)
for id := int64(1); id <= 64; id++ {
pool = append(pool, id)
vetoed[id] = true
}
res := runProfitVetoLoop(t, fs, pool, vetoed, 200)
require.Equal(t, "exhausted", res.outcome)
require.Equal(t, maxProfitVetoAttempts, fs.ProfitVetoCount())
require.Equal(t, maxProfitVetoAttempts, res.iterations, "达到上限即终止,不应继续遍历候选池")
}
// TestRecordProfitVetoExcludesAccount 钉死 RecordProfitVeto 仍然把账号加入
// 调度排除列表(选号入参用的就是 FailedAccountIDs)。
func TestRecordProfitVetoExcludesAccount(t *testing.T) {
fs := NewFailoverState(10, false)
require.Equal(t, FailoverContinue, fs.RecordProfitVeto(42))
require.Contains(t, fs.FailedAccountIDs, int64(42))
require.Equal(t, 1, fs.ProfitVetoCount())
}
// TestHandleSelectionExhaustedUnaffectedWithoutProfitVeto 钉死未启用利润控制的
// 请求(无任何利润否决)走的仍是原有退避语义:清空排除列表并重试。
func TestHandleSelectionExhaustedUnaffectedWithoutProfitVeto(t *testing.T) {
fs := NewFailoverState(3, false)
fs.LastFailoverErr = newTestFailoverErr(503, false, false)
fs.SwitchCount = 1
fs.FailedAccountIDs[100] = struct{}{}
require.Equal(t, FailoverContinue, fs.HandleSelectionExhausted(context.Background()))
require.Empty(t, fs.FailedAccountIDs, "无利润否决时排除列表应被完全清空")
}