fix(billing-probe): govern the automatic account rate write-back

- 自动写回值域治理与留痕:上游声明值必须 > 0 且 <= 100 才写回。0 会让
  accountCost 恒为 0(账号总额/日/周配额与成本告警全部静默失效),极大值可
  一次打爆配额并污染成本报表;越界时保持原倍率、记 WARN,探测快照照常记 ok。
  写回成功时记结构化 slog(account_id / 旧值 / 新值 / source),并在快照中
  新增 synced_rate_multiplier 记录本次写回值——后台任务裸 SQL 不产生
  audit_logs,这两处是唯一可追溯来源。管理员手工设 0 不受影响。
- 写回改用 resolved_rate_multiplier(不含高峰的基准倍率):effective 含探测
  那一刻的高峰系数,写回会把一个探测周期的峰值/谷值冻结进静态列,而展示与
  调度用 upstreamBillingRateAt 按当前时间重算高峰,两者会持续不一致。
- 倍率解析失败不再污染公共探测路径:账号级值域/精度只在该账号已开启同步、
  真要写回时才有影响;未开同步的账号照常记 ok 快照,不累计 failure_count、
  不进入指数退避。
- 单账号编辑补 service 层守卫:同步开启时拒绝手工倍率(新增
  UPSTREAM_BILLING_RATE_SYNC_CONFLICT,与批量路径同族),此前只有前端
  disabled 挡人,直接 PUT /admin/accounts/{id} 可写入并活到下次成功探测。
  判断的是本次请求生效后的状态,"关同步 + 改倍率"同请求仍然放行。
- 修正开关反推方向:不再由 rate_sync=true 推出 probe=true,否则一条"同步开、
  探测键缺失"的僵尸记录会在任意一次无关编辑时静默打开周期性外呼;改为探测
  关闭/缺失一律把同步归零。
- 删除死代码 UpdateWithUpstreamBillingProbeEnabled(PR 删接口后生产已无调用
  方),其回滚测试改为直接覆盖生产路径 UpdateWithAccountBillingSettings。
  upstreamBillingRateSyncEnabled 不再是只服务测试的假门控,现为写回前置过滤,
  SQL CAS 仍是权威门控,两侧均加注释说明分工。
- en/zh 文案补充:同步的是不含高峰的基准倍率;开启同步会连带打开自动探测。
This commit is contained in:
shaw committed 2026-08-01 22:11:10 +08:00
1 parent b0f5007f04
commit 0b6b4ea956
9 files changed
+421 -45

No files matched your search

@@ -324,8 +324,12 @@ func TestUpstreamBillingProbeSuccessPersistsSanitizedSnapshot(t *testing.T) {
require.Equal(t, fixedNow.Add(time.Hour), *snapshot.FreshUntil)
require.False(t, snapshot.NextProbeAt.Before(fixedNow.Add(24*time.Minute)))
require.False(t, snapshot.NextProbeAt.After(fixedNow.Add(36*time.Minute)))
// 写回的是不含高峰因子的 resolved 倍率(0.6),不是探测那一刻含高峰的
// effective 倍率(0.9)——否则一个探测周期的峰值会被冻结进静态列。
require.NotNil(t, account.RateMultiplier)
require.Equal(t, 0.9, *account.RateMultiplier)
require.Equal(t, 0.6, *account.RateMultiplier)
require.NotNil(t, snapshot.SyncedRateMultiplier)
require.Equal(t, 0.6, *snapshot.SyncedRateMultiplier)
require.Equal(t, "https://upstream.example/v1/sub2api/billing", upstream.lastReq.URL.String())
require.Equal(t, http.MethodGet, upstream.lastReq.Method)
require.Equal(t, "Bearer sk-sensitive", upstream.lastReq.Header.Get("Authorization"))
@@ -336,7 +340,7 @@ func TestUpstreamBillingProbeSuccessPersistsSanitizedSnapshot(t *testing.T) {
require.Equal(t, snapshot.Status, persisted.Status)
}
func TestUpstreamBillingProbeSyncsEffectiveRateForAllAPIKeyPlatforms(t *testing.T) {
func TestUpstreamBillingProbeSyncsResolvedRateForAllAPIKeyPlatforms(t *testing.T) {
for _, platform := range []string{
PlatformOpenAI,
PlatformAnthropic,
@@ -402,24 +406,27 @@ func TestUpstreamBillingProbeOnlyDoesNotChangeAccountRate(t *testing.T) {
require.Contains(t, account.Extra, UpstreamBillingProbeExtraKey)
}
func TestUpstreamBillingProbeAccountRateMatchesDatabasePrecision(t *testing.T) {
func TestUpstreamBillingProbeSyncRateRangeAndPrecision(t *testing.T) {
tests := []struct {
name string
value float64
want float64
ok bool
}{
{name: "zero", value: 0, want: 0, ok: true},
{name: "round to four decimals", value: 0.07654, want: 0.0765, ok: true},
{name: "maximum", value: upstreamBillingProbeAccountRateMax, want: upstreamBillingProbeAccountRateMax, ok: true},
{name: "positive below database precision", value: 0.00001, ok: false},
{name: "overflow before rounding", value: 999999.99991, ok: false},
{name: "overflow after rounding", value: 999999.99996, ok: false},
{name: "maximum", value: upstreamBillingRateSyncMaxMultiplier, want: upstreamBillingRateSyncMaxMultiplier, ok: true},
// 0 会让 accountCost 恒为 0,账号配额与成本告警全部静默失效,
// 自动写回一律拒绝(管理员手工设 0 仍然允许)。
{name: "zero is rejected", value: 0, ok: false},
{name: "positive below database precision rounds to zero", value: 0.00001, ok: false},
{name: "just above the write-back ceiling", value: 100.0001, ok: false},
{name: "column ceiling is far above the write-back ceiling", value: 999999.9999, ok: false},
{name: "negative", value: -1, ok: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, ok := upstreamBillingProbeAccountRate(map[string]any{"effective_rate_multiplier": tt.value})
got, ok := upstreamBillingProbeSyncRate(map[string]any{"resolved_rate_multiplier": tt.value})
require.Equal(t, tt.ok, ok)
if tt.ok {
require.Equal(t, tt.want, got)
@@ -428,6 +435,122 @@ func TestUpstreamBillingProbeAccountRateMatchesDatabasePrecision(t *testing.T) {
}
}
// 只读取 resolved(时间无关的基准倍率):effective 含探测那一刻的高峰系数,
// 写回它会把一个探测周期的峰值/谷值冻结进静态列。
func TestUpstreamBillingProbeSyncRateIgnoresEffectiveRate(t *testing.T) {
got, ok := upstreamBillingProbeSyncRate(map[string]any{
"resolved_rate_multiplier": 0.6,
"effective_rate_multiplier": 0.9,
})
require.True(t, ok)
require.Equal(t, 0.6, got)
_, ok = upstreamBillingProbeSyncRate(map[string]any{"effective_rate_multiplier": 0.9})
require.False(t, ok)
}
// 上游声明超出自动写回值域时保持原倍率,但探测本身是成功的:
// 快照照常记 ok,不累计 failure_count、不进入退避。
func TestUpstreamBillingProbeKeepsRateWhenDeclarationOutOfSyncRange(t *testing.T) {
for _, tt := range []struct {
name string
declared string
}{
{name: "zero", declared: "0"},
{name: "above ceiling", declared: "1000"},
} {
t.Run(tt.name, func(t *testing.T) {
initialRate := 0.25
account := &Account{
ID: 21,
Platform: PlatformOpenAI,
Type: AccountTypeAPIKey,
Status: StatusActive,
Concurrency: 1,
RateMultiplier: &initialRate,
Credentials: map[string]any{
"api_key": "sk-sensitive",
"base_url": "https://upstream.example",
},
Extra: map[string]any{
UpstreamBillingProbeEnabledExtraKey: true,
UpstreamBillingRateSyncEnabledExtraKey: true,
},
}
repo := &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{account.ID: account}}
upstream := &httpUpstreamRecorder{resp: &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(fmt.Sprintf(`{
"object":"sub2api.key_billing",
"schema_version":1,
"billing_scope":"token",
"group_rate_multiplier":%[1]s,
"resolved_rate_multiplier":%[1]s,
"peak_rate_enabled":false,
"effective_rate_multiplier":%[1]s,
"observed_at":"2026-07-13T01:00:00Z"
}`, tt.declared))),
}}
svc := newUpstreamBillingProbeTestService(repo, upstream, &upstreamBillingProbeSettingRepo{})
snapshot, err := svc.ProbeAccount(context.Background(), account.ID)
require.NoError(t, err)
require.Equal(t, UpstreamBillingProbeStatusOK, snapshot.Status)
require.Zero(t, snapshot.FailureCount)
require.Nil(t, snapshot.SyncedRateMultiplier)
require.NotNil(t, account.RateMultiplier)
require.Equal(t, initialRate, *account.RateMultiplier)
// 原始声明仍进快照供展示。
require.Equal(t, snapshot.Data["resolved_rate_multiplier"], snapshot.Data["effective_rate_multiplier"])
})
}
}
// 未开启同步的账号只观察上游声明:声明值不适配 accounts.rate_multiplier
// 不得被记成探测失败(否则会累计 failure_count 并进入指数退避)。
func TestUpstreamBillingProbeWithoutSyncIgnoresUnusableDeclaredRate(t *testing.T) {
account := &Account{
ID: 22,
Platform: PlatformOpenAI,
Type: AccountTypeAPIKey,
Status: StatusActive,
Concurrency: 1,
Credentials: map[string]any{
"api_key": "sk-sensitive",
"base_url": "https://upstream.example",
},
Extra: map[string]any{UpstreamBillingProbeEnabledExtraKey: true},
}
repo := &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{account.ID: account}}
upstream := &httpUpstreamRecorder{resp: &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{
"object":"sub2api.key_billing",
"schema_version":1,
"billing_scope":"token",
"group_rate_multiplier":0,
"resolved_rate_multiplier":0,
"peak_rate_enabled":false,
"effective_rate_multiplier":0,
"observed_at":"2026-07-13T01:00:00Z"
}`)),
}}
svc := newUpstreamBillingProbeTestService(repo, upstream, &upstreamBillingProbeSettingRepo{})
snapshot, err := svc.ProbeAccount(context.Background(), account.ID)
require.NoError(t, err)
require.Equal(t, UpstreamBillingProbeStatusOK, snapshot.Status)
require.Zero(t, snapshot.FailureCount)
require.Empty(t, snapshot.LastError)
require.Nil(t, snapshot.SyncedRateMultiplier)
require.Equal(t, float64(0), snapshot.Data["resolved_rate_multiplier"])
require.Nil(t, account.RateMultiplier)
}
func TestUpstreamBillingProbeRejectsMissingRequiredMultiplier(t *testing.T) {
_, err := parseUpstreamBillingProbeResponse([]byte(`{
"object":"sub2api.key_billing",