Files
sub2api/backend/internal/service/profit_preview.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

212 lines
8.1 KiB
Go

package service
// 分组利润控制离线预演:使用生产只读导出的分组配置、账号倍率、探测状态、
// 用户覆盖倍率与主力模型清单,复用线上 U/D/epsilon 语义推演准入。
// 探测状态仅用于解释账号倍率来源是否健康,不影响准入结论。
import (
"math"
"sort"
"time"
)
const (
ProfitPreviewRateSourceManual = "manual"
ProfitPreviewRateSourceUpstreamProbe = "upstream_probe_sync"
ProfitPreviewWarningProbeMissing = "probe_snapshot_missing"
ProfitPreviewWarningProbeStale = "probe_snapshot_stale"
ProfitPreviewWarningProbeFailed = "probe_failed"
ProfitPreviewWarningProbeUnsupported = "probe_unsupported"
ProfitPreviewWarningManualRateOne = "manual_rate_1_suspected_unmaintained"
)
// ProfitPreviewGroupInput 是一个分组的预演输入。
type ProfitPreviewGroupInput struct {
Group *Group
// Accounts 为该分组绑定且状态可调度的账号,允许 Anthropic/Gemini 分组中
// 参与 mixed scheduling 的 Antigravity 账号。
Accounts []*Account
// UserOverrides 为该分组所有用户覆盖倍率(user_id → 倍率)。
UserOverrides map[int64]float64
// Models 为该分组近期主力模型清单。
Models []string
// AssumeEnabled 在分组当前关闭时仍按其保存配置启用利润门,供部署前执行
// “先关组、预演、逐组重开”。
AssumeEnabled bool
}
// 预演账号分类与线上否决原因一一对应。
const (
ProfitPreviewClassAdmitted = "admitted"
ProfitPreviewClassRejectedThreshold = "rejected_threshold"
ProfitPreviewClassRejectedInvalidRate = "rejected_invalid_account_rate"
)
// ProfitPreviewAccountVerdict 是单账号的预演结论。
type ProfitPreviewAccountVerdict struct {
AccountID int64 `json:"account_id"`
Name string `json:"name"`
Platform string `json:"platform"`
Class string `json:"class"`
AccountRate *float64 `json:"account_rate,omitempty"`
RateSource string `json:"rate_source"`
Warnings []string `json:"warnings,omitempty"`
// RejectedUnderMinD 表示账号在最低有效 D(用户覆盖最坏口径)下会被排除。
RejectedUnderMinD bool `json:"rejected_under_min_d,omitempty"`
// SupportedModels 为该账号支持的主力模型子集。
SupportedModels []string `json:"supported_models,omitempty"`
}
// ProfitPreviewGroupReport 是单分组的预演报告。
type ProfitPreviewGroupReport struct {
GroupID int64 `json:"group_id"`
GroupName string `json:"group_name"`
Platform string `json:"platform"`
EffectiveGate bool `json:"effective_gate"`
AssumedEnabled bool `json:"assumed_enabled,omitempty"`
// DefaultD / MinEffectiveD:分组默认 D 与最低有效 D(含 evalAt 高峰因子;
// MinEffectiveD = min(分组默认, 全部非空用户覆盖) × 高峰因子)。
DefaultD float64 `json:"default_d"`
MinEffectiveD float64 `json:"min_effective_d"`
// ThresholdDefault / ThresholdMinD:两档 D 对应的准入阈值。
ThresholdDefault float64 `json:"threshold_default"`
ThresholdMinD float64 `json:"threshold_min_d"`
// RemainingByModel 仅表示利润门准入账号数,不模拟健康、冷却、限流或槽位。
RemainingByModel map[string]int `json:"profit_admitted_by_model"`
RemainingByModelMinD map[string]int `json:"profit_admitted_by_model_min_d"`
Verdicts []ProfitPreviewAccountVerdict `json:"verdicts"`
}
// PreviewProfitAdmission 对五大平台分组推演利润门准入结果。未启用的分组仅在
// AssumeEnabled=true 时按保存配置执行门;Composite 分组始终不直接安装利润门。
func PreviewProfitAdmission(inputs []ProfitPreviewGroupInput, evalAt time.Time) []ProfitPreviewGroupReport {
reports := make([]ProfitPreviewGroupReport, 0, len(inputs))
for _, in := range inputs {
if in.Group == nil {
continue
}
group := in.Group
effectiveGate := (group.ProfitControlEnabled || in.AssumeEnabled) && profitControlPlatformSupported(group.Platform)
report := ProfitPreviewGroupReport{
GroupID: group.ID,
GroupName: group.Name,
Platform: group.Platform,
EffectiveGate: effectiveGate,
AssumedEnabled: in.AssumeEnabled && !group.ProfitControlEnabled && effectiveGate,
RemainingByModel: make(map[string]int, len(in.Models)),
RemainingByModelMinD: make(map[string]int, len(in.Models)),
}
for _, model := range in.Models {
report.RemainingByModel[model] = 0
report.RemainingByModelMinD[model] = 0
}
peak := group.PeakMultiplierAt(evalAt)
defaultD := group.RateMultiplier * peak
minRate := group.RateMultiplier
for _, override := range in.UserOverrides {
if math.IsNaN(override) || math.IsInf(override, 0) || override < 0 {
continue
}
if override < minRate {
minRate = override
}
}
minD := minRate * peak
deduction := group.ProfitMinMargin + group.ProfitSafetyBuffer
thresholdDefault := clampProfitControlThreshold(defaultD * (1 - deduction))
thresholdMinD := clampProfitControlThreshold(minD * (1 - deduction))
report.DefaultD = defaultD
report.MinEffectiveD = minD
report.ThresholdDefault = thresholdDefault
report.ThresholdMinD = thresholdMinD
for _, account := range in.Accounts {
if account == nil {
continue
}
verdict := previewAccountProfitAdmission(account, effectiveGate, thresholdDefault, thresholdMinD, evalAt)
admittedDefault := verdict.Class == ProfitPreviewClassAdmitted
admittedMinD := admittedDefault && !verdict.RejectedUnderMinD
for _, model := range in.Models {
if !account.IsModelSupported(model) {
continue
}
verdict.SupportedModels = append(verdict.SupportedModels, model)
if admittedDefault {
report.RemainingByModel[model]++
}
if admittedMinD {
report.RemainingByModelMinD[model]++
}
}
sort.Strings(verdict.SupportedModels)
report.Verdicts = append(report.Verdicts, verdict)
}
sort.Slice(report.Verdicts, func(i, j int) bool { return report.Verdicts[i].AccountID < report.Verdicts[j].AccountID })
reports = append(reports, report)
}
return reports
}
func previewAccountProfitAdmission(
account *Account,
effectiveGate bool,
thresholdDefault float64,
thresholdMinD float64,
evalAt time.Time,
) ProfitPreviewAccountVerdict {
verdict := ProfitPreviewAccountVerdict{
AccountID: account.ID,
Name: account.Name,
Platform: account.Platform,
RateSource: ProfitPreviewRateSourceManual,
}
if enabled, _ := account.Extra[UpstreamBillingRateSyncEnabledExtraKey].(bool); enabled {
verdict.RateSource = ProfitPreviewRateSourceUpstreamProbe
verdict.Warnings = append(verdict.Warnings, profitPreviewProbeWarnings(account, evalAt)...)
} else if account.RateMultiplier != nil && *account.RateMultiplier == 1 {
verdict.Warnings = append(verdict.Warnings, ProfitPreviewWarningManualRateOne)
}
validRate := account.RateMultiplier != nil &&
!math.IsNaN(*account.RateMultiplier) &&
!math.IsInf(*account.RateMultiplier, 0) &&
*account.RateMultiplier >= 0
if validRate {
rate := *account.RateMultiplier
verdict.AccountRate = &rate
}
switch {
case !effectiveGate:
verdict.Class = ProfitPreviewClassAdmitted
case !validRate:
verdict.Class = ProfitPreviewClassRejectedInvalidRate
case profitControlOverThreshold(*account.RateMultiplier, thresholdDefault):
verdict.Class = ProfitPreviewClassRejectedThreshold
default:
verdict.Class = ProfitPreviewClassAdmitted
verdict.RejectedUnderMinD = profitControlOverThreshold(*account.RateMultiplier, thresholdMinD)
}
return verdict
}
func profitPreviewProbeWarnings(account *Account, evalAt time.Time) []string {
snapshot := decodeUpstreamBillingProbeSnapshot(account.Extra)
if snapshot == nil {
return []string{ProfitPreviewWarningProbeMissing}
}
switch snapshot.Status {
case UpstreamBillingProbeStatusFailed:
return []string{ProfitPreviewWarningProbeFailed}
case UpstreamBillingProbeStatusUnsupported:
return []string{ProfitPreviewWarningProbeUnsupported}
case UpstreamBillingProbeStatusOK:
if snapshot.FreshUntil == nil || !evalAt.Before(*snapshot.FreshUntil) {
return []string{ProfitPreviewWarningProbeStale}
}
}
return nil
}