feat(scheduling): suspend exhausted legacy ollama cloud accounts

增量 4a(③ 组 A6+C25+E9 + ⑤ 组 A2 + F4,同批落地):

- A2: 新增 AccountModeOllamaLegacy/OllamaCredits 常量与
  Account.GetOllamaCloudAccountMode 解析器(非 ollama_cloud/非 apikey
  返回空串;未设置或值不认识默认 legacy,存量账号保持受阈值保护)
- A6: AllowedSchedulingThresholdPlatforms 纳入 ollama_cloud(4 个消费点
  同步生效:评估器门禁、设置校验、存储解析、设置审计 diff)
- C25: 评估器新增 ollama 分支 + ollamaCloudThresholdCandidates,仅 legacy
  产生 5h/weekly 停调候选(credits 型月度信用池候选恒空);快照缺失/
  status!=ok/无窗口数据不停调;取最晚 reset(与 openai/anthropic 同类)
- E9: 前端 SchedulingThresholdPlatformType union 与
  SCHEDULING_THRESHOLD_PLATFORMS 数组加 ollama_cloud(与后端白名单两侧同步)
- F4: 评估器表驱动用例(legacy 停/credits 不停/默认 legacy/坏快照不停)、
  ApplyAccountSchedulingThreshold 端到端(temp_unschedulable 落库断言)、
  mode 解析器用例、设置校验 ollama_cloud 往返用例

无迁移、无 DTO 变更(account_mode 为自由 JSONB,无 CHECK 约束)。
This commit is contained in:
alfadb committed 2026-09-13 10:38:55 +08:00
1 parent d36c935255
commit 59ea2290e6
9 files changed
+409 -1

No files matched your search

+6
View File
@@ -38,11 +38,17 @@ const (
// Account mode constants 区分国产供应商的「按量付费(余额)」与「Coding Plan」两种接入方式。
// 存储于 credentials["account_mode"],决定 base_url 预设与额度监控方式。
// ollama_cloud 的两代额度语义同存于此键:legacy 是 5h/7d 滚动窗口(与 Go 订阅同类,
// 受阈值停调保护);credits 是 2026-08-31 新定价后的月度美元信用池(无滚动窗口,
// 用完不硬停,不走阈值停调)。
const (
AccountModePayG = "payg" // 按量付费:消耗余额,做余额检测冷却
AccountModeCoding = "coding" // Coding Plan:滚动用量窗口冷却(5h / weekly)
AccountModeZen = "zen" // OpenCode Zen:按量付费,https://opencode.ai/zen/v1
AccountModeGo = "go" // OpenCode Go:订阅额度窗口,https://opencode.ai/zen/go/v1
AccountModeOllamaLegacy = "ollama_legacy" // Ollama Cloud legacy:5h / 7d 滚动窗口
AccountModeOllamaCredits = "ollama_credits" // Ollama Cloud 月度美元信用池
)
// API protocol constants 国产供应商的上游 API 协议维度。存储于
+15
View File
@@ -299,6 +299,21 @@ func (a *Account) IsOllamaCloud() bool {
return a != nil && IsOllamaCloud(a.Platform)
}
// GetOllamaCloudAccountMode 返回 Ollama Cloud 账号的额度模式
// (AccountModeOllamaLegacy / AccountModeOllamaCredits)。非 ollama_cloud 平台
// 或非 apikey 类型返回空串;credentials 未设置或值不认识时默认 legacy
// (保守:legacy 有 5h/7d 滚动窗口 → 受阈值停调保护,默认 credits 会让存量
// legacy 账号失去保护)。与 GetAccountMode(国产 payg/coding 白名单)互不影响。
func (a *Account) GetOllamaCloudAccountMode() string {
if a == nil || !a.IsOllamaCloud() || a.Type != AccountTypeAPIKey {
return ""
}
if strings.TrimSpace(a.GetCredential("account_mode")) == AccountModeOllamaCredits {
return AccountModeOllamaCredits
}
return AccountModeOllamaLegacy
}
// IsOpenAICompatible 报告账号是否走 OpenAI 网关(OpenAI 协议族)。
// openai/grok 原生走 OpenAI 网关;国产供应商同为 OpenAI Chat Completions
// 兼容上游,也经 OpenAI 网关转发。OpenCode 与 Ollama Cloud 同样经 OpenAI
@@ -0,0 +1,92 @@
//go:build unit
package service
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestGetOllamaCloudAccountMode(t *testing.T) {
t.Parallel()
cases := []struct {
name string
platform string
accountType string
credentials map[string]any
want string
}{
{
name: "defaults to legacy when unset",
platform: PlatformOllamaCloud,
accountType: AccountTypeAPIKey,
credentials: nil,
want: AccountModeOllamaLegacy,
},
{
name: "explicit legacy",
platform: PlatformOllamaCloud,
accountType: AccountTypeAPIKey,
credentials: map[string]any{"account_mode": AccountModeOllamaLegacy},
want: AccountModeOllamaLegacy,
},
{
name: "explicit credits",
platform: PlatformOllamaCloud,
accountType: AccountTypeAPIKey,
credentials: map[string]any{"account_mode": AccountModeOllamaCredits},
want: AccountModeOllamaCredits,
},
{
name: "unknown value falls back to legacy",
platform: PlatformOllamaCloud,
accountType: AccountTypeAPIKey,
credentials: map[string]any{"account_mode": "bogus"},
want: AccountModeOllamaLegacy,
},
{
name: "oauth account returns empty",
platform: PlatformOllamaCloud,
accountType: AccountTypeOAuth,
credentials: map[string]any{"account_mode": AccountModeOllamaCredits},
want: "",
},
{
name: "non ollama platform returns empty",
platform: PlatformOpenAI,
accountType: AccountTypeAPIKey,
credentials: map[string]any{"account_mode": AccountModeOllamaCredits},
want: "",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
account := &Account{
Platform: tc.platform,
Type: tc.accountType,
Credentials: tc.credentials,
}
require.Equal(t, tc.want, account.GetOllamaCloudAccountMode())
})
}
}
func TestGetAccountMode_IgnoresOllamaCloudModes(t *testing.T) {
t.Parallel()
// 防回归:GetAccountMode 是国产 payg/coding 的白名单解析器,
// 不得被 ollama_cloud 的新 mode 值污染。
for _, mode := range []string{AccountModeOllamaLegacy, AccountModeOllamaCredits} {
account := &Account{
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Credentials: map[string]any{"account_mode": mode},
}
require.Empty(t, account.GetAccountMode())
}
}
@@ -60,6 +60,8 @@ func EvaluateAccountSchedulingThreshold(account *Account, thresholds map[string]
winner = pickLatestResetSchedulingCandidate(grokThresholdCandidates(account), threshold, now)
case PlatformKimi, PlatformZhipu, PlatformMiniMax, PlatformOpenCodeGo:
winner = pickLatestResetSchedulingCandidate(cnProviderThresholdCandidates(account, decision.Platform), threshold, now)
case PlatformOllamaCloud:
winner = pickLatestResetSchedulingCandidate(ollamaCloudThresholdCandidates(account), threshold, now)
default:
return decision
}
@@ -393,6 +395,40 @@ func cnThresholdCandidate(extra map[string]any, provider, window string) *accoun
}
}
// ollamaCloudThresholdCandidates 读取 ollama_cloud 账号 5h / 7d 滚动窗口的用量快照
// (由 OllamaCloudUsageService 写入 account.Extra,经 decodeOllamaCloudUsageSnapshot
// 解出嵌套 struct —— 与 CN 的扁平 extra 键不同构,不复用 cnThresholdCandidate)。
//
// 仅 legacy 账号有滚动窗口;credits 型是月度美元信用池、没有窗口 reset 可等,
// 候选恒空(credits 赗欠告警走余额告警通道,不写 TempUnschedulableUntil)。
// 快照缺失 / status != ok / 无窗口数据时同样返回 nil —— 宁可不停调也不基于
// 坏快照误停。窗口语义与 openai/anthropic/kimi 同类:取最晚 reset。
func ollamaCloudThresholdCandidates(account *Account) []*accountSchedulingThresholdCandidate {
if account == nil || account.GetOllamaCloudAccountMode() != AccountModeOllamaLegacy {
return nil
}
snapshot := decodeOllamaCloudUsageSnapshot(account.Extra)
if snapshot == nil || snapshot.Status != OllamaCloudUsageStatusOK || snapshot.Data == nil {
return nil
}
return []*accountSchedulingThresholdCandidate{
ollamaCloudThresholdCandidate(snapshot.Data.FiveHour, "5h"),
ollamaCloudThresholdCandidate(snapshot.Data.SevenDay, "weekly"),
}
}
func ollamaCloudThresholdCandidate(window *OllamaCloudUsageWindow, label string) *accountSchedulingThresholdCandidate {
if window == nil {
return nil
}
return &accountSchedulingThresholdCandidate{
window: label,
scope: PlatformOllamaCloud,
usedPercent: window.UsedPercent,
until: cloneTimePtr(window.ResetAt),
}
}
func pickLatestResetSchedulingCandidate(candidates []*accountSchedulingThresholdCandidate, threshold int, now time.Time) *accountSchedulingThresholdCandidate {
var winner *accountSchedulingThresholdCandidate
for _, candidate := range candidates {
@@ -471,3 +471,147 @@ func TestEvaluateAccountSchedulingThreshold_GrokUsesOnlyHeaderQuotaWindow(t *tes
require.NotNil(t, decision.Until)
require.True(t, headerUntil.Equal(*decision.Until))
}
// ollamaCloudSnapshotExtra 构造 account.Extra 里 ollama_cloud 用量快照的测试夹具,
// 形状与 DB JSONB 反序列化后的嵌套 map 一致(decodeOllamaCloudUsageSnapshot 走
// marshal/unmarshal 往返,map 形式即生产读取路径)。
func ollamaCloudSnapshotExtra(status string, data map[string]any) map[string]any {
snapshot := map[string]any{"status": status}
if data != nil {
snapshot["data"] = data
}
return map[string]any{OllamaCloudUsageSnapshotExtraKey: snapshot}
}
func ollamaCloudUsageWindowFixture(usedPercent float64, resetAt time.Time) map[string]any {
return map[string]any{
"used_percent": usedPercent,
"reset_at": resetAt.Format(time.RFC3339),
}
}
func TestEvaluateAccountSchedulingThreshold_OllamaCloud(t *testing.T) {
t.Parallel()
now := time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC)
fiveHourReset := now.Add(2 * time.Hour)
sevenDayReset := now.Add(5 * 24 * time.Hour)
newSnapshotAccount := func(mode string, extra map[string]any) *Account {
account := &Account{
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Extra: extra,
}
if mode != "" {
account.Credentials = map[string]any{"account_mode": mode}
}
return account
}
okExtra := ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{
"five_hour": ollamaCloudUsageWindowFixture(95, fiveHourReset),
"seven_day": ollamaCloudUsageWindowFixture(40, sevenDayReset),
})
cases := []struct {
name string
account *Account
shouldPause bool
wantWindow string
wantUntil time.Time
}{
{
name: "legacy pauses at exhausted five hour window",
account: newSnapshotAccount("ollama_legacy", okExtra),
shouldPause: true,
wantWindow: "5h",
wantUntil: fiveHourReset,
},
{
name: "mode unset defaults to legacy and pauses",
account: newSnapshotAccount("", okExtra),
shouldPause: true,
wantWindow: "5h",
wantUntil: fiveHourReset,
},
{
name: "unknown mode value falls back to legacy and pauses",
account: newSnapshotAccount("bogus", okExtra),
shouldPause: true,
wantWindow: "5h",
wantUntil: fiveHourReset,
},
{
// 防回归护栏:credits 型是月度美元信用池、没有滚动窗口 reset,
// 即使快照里解析出 5h/7d 数据也绝不停调。
name: "credits never pauses despite fully populated snapshot",
account: newSnapshotAccount("ollama_credits", okExtra),
shouldPause: false,
},
{
name: "failed snapshot does not pause",
account: newSnapshotAccount("ollama_legacy", ollamaCloudSnapshotExtra(OllamaCloudUsageStatusFailed, nil)),
shouldPause: false,
},
{
name: "ok snapshot without window data does not pause",
account: newSnapshotAccount("ollama_legacy", ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{})),
shouldPause: false,
},
{
// 防回归护栏:A6 纳入白名单后,无快照的账号同样不得停调。
name: "missing snapshot does not pause",
account: newSnapshotAccount("ollama_legacy", map[string]any{}),
shouldPause: false,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
decision := EvaluateAccountSchedulingThreshold(tc.account, map[string]int{
PlatformOllamaCloud: 80,
}, now)
require.Equal(t, tc.shouldPause, decision.ShouldPause)
if !tc.shouldPause {
return
}
require.Equal(t, PlatformOllamaCloud, decision.Platform)
require.Equal(t, tc.wantWindow, decision.Window)
require.Equal(t, PlatformOllamaCloud, decision.Scope)
require.NotNil(t, decision.Until)
require.True(t, tc.wantUntil.Equal(*decision.Until))
})
}
}
func TestEvaluateAccountSchedulingThreshold_OllamaCloudPicksLatestResetWindow(t *testing.T) {
t.Parallel()
// 与 openai/anthropic/kimi 同类取最晚 reset(不是 CN 供应商的最早 reset)。
now := time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC)
fiveHourReset := now.Add(2 * time.Hour)
sevenDayReset := now.Add(5 * 24 * time.Hour)
account := &Account{
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Credentials: map[string]any{
"account_mode": "ollama_legacy",
},
Extra: ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{
"five_hour": ollamaCloudUsageWindowFixture(95, fiveHourReset),
"seven_day": ollamaCloudUsageWindowFixture(90, sevenDayReset),
}),
}
decision := EvaluateAccountSchedulingThreshold(account, map[string]int{
PlatformOllamaCloud: 80,
}, now)
require.True(t, decision.ShouldPause)
require.Equal(t, "weekly", decision.Window)
require.Equal(t, PlatformOllamaCloud, decision.Scope)
require.NotNil(t, decision.Until)
require.True(t, sevenDayReset.Equal(*decision.Until))
}
@@ -63,6 +63,9 @@ const (
AccountModeCoding = domain.AccountModeCoding
AccountModeZen = domain.AccountModeZen
AccountModeGo = domain.AccountModeGo
AccountModeOllamaLegacy = domain.AccountModeOllamaLegacy // Ollama Cloud legacy:5h / 7d 滚动窗口
AccountModeOllamaCredits = domain.AccountModeOllamaCredits // Ollama Cloud 月度美元信用池
)
// 上游 API 协议(国产供应商):决定转发端点与格式,与接入模式正交。
@@ -152,6 +155,8 @@ var AllowedQuotaPlatforms = []string{
// AllowedSchedulingThresholdPlatforms 是允许设置账号自动停调阈值的平台列表。
// openai/anthropic/grok 有原生用量窗口;kimi/zhipu/minimax 的 Coding Plan 同样暴露
// 5h/weekly 滚动窗口,纳入阈值评估。deepseek 为余额型,走余额检测而非阈值。
// ollama_cloud 仅 legacy 账号有 5h/7d 滚动窗口可等 reset;credits 型是月度美元
// 信用池、没有窗口 reset,评估器候选恒空(见 ollamaCloudThresholdCandidates)。
var AllowedSchedulingThresholdPlatforms = []string{
PlatformOpenAI,
PlatformAnthropic,
@@ -160,6 +165,7 @@ var AllowedSchedulingThresholdPlatforms = []string{
PlatformZhipu,
PlatformMiniMax,
PlatformOpenCodeGo,
PlatformOllamaCloud,
}
// IsAllowedQuotaPlatform 报告 s 是否为合法的 quota platform 标识。
@@ -228,3 +228,81 @@ func TestRateLimitService_ApplyAccountSchedulingThreshold_UnsupportedPlatformDoe
require.Nil(t, account.TempUnschedulableUntil)
require.Empty(t, account.TempUnschedulableReason)
}
func TestRateLimitService_ApplyAccountSchedulingThreshold_OllamaCloudLegacySetsTempUnschedulable(t *testing.T) {
accountSchedulingThresholdsSF.Forget(SettingKeyAccountSchedulingThresholds)
accountSchedulingThresholdsCache.Store(&cachedAccountSchedulingThresholds{})
settingsRepo := newMockSettingRepo()
settingsRepo.data[SettingKeyAccountSchedulingThresholds] = `{"ollama_cloud":80}`
accountRepo := &rateLimitAccountRepoStub{}
rl := NewRateLimitService(accountRepo, nil, &config.Config{}, nil, nil)
rl.SetSettingService(NewSettingService(settingsRepo, &config.Config{}))
until := time.Now().UTC().Add(2 * time.Hour)
account := &Account{
ID: 3001,
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Status: StatusActive,
Schedulable: true,
Credentials: map[string]any{
"account_mode": "ollama_legacy",
},
Extra: ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{
"five_hour": ollamaCloudUsageWindowFixture(95, until),
"seven_day": ollamaCloudUsageWindowFixture(40, until.Add(5*24*time.Hour)),
}),
}
blocked := rl.ApplyAccountSchedulingThreshold(context.Background(), account)
require.True(t, blocked)
require.Equal(t, 1, accountRepo.tempCalls)
require.NotNil(t, account.TempUnschedulableUntil)
require.WithinDuration(t, until, *account.TempUnschedulableUntil, time.Second)
require.True(t, IsAccountSchedulingThresholdReason(accountRepo.lastTempReason))
var payload map[string]any
require.NoError(t, json.Unmarshal([]byte(accountRepo.lastTempReason), &payload))
require.Equal(t, PlatformOllamaCloud, payload["platform"])
require.Equal(t, "5h", payload["window"])
require.Equal(t, float64(80), payload["threshold_percent"])
require.Equal(t, float64(95), payload["used_percent"])
}
func TestRateLimitService_ApplyAccountSchedulingThreshold_OllamaCloudCreditsDoesNotBlock(t *testing.T) {
accountSchedulingThresholdsSF.Forget(SettingKeyAccountSchedulingThresholds)
accountSchedulingThresholdsCache.Store(&cachedAccountSchedulingThresholds{})
settingsRepo := newMockSettingRepo()
settingsRepo.data[SettingKeyAccountSchedulingThresholds] = `{"ollama_cloud":80}`
accountRepo := &rateLimitAccountRepoStub{}
rl := NewRateLimitService(accountRepo, nil, &config.Config{}, nil, nil)
rl.SetSettingService(NewSettingService(settingsRepo, &config.Config{}))
until := time.Now().UTC().Add(2 * time.Hour)
account := &Account{
ID: 3002,
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Status: StatusActive,
Schedulable: true,
Credentials: map[string]any{
"account_mode": "ollama_credits",
},
Extra: ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{
"five_hour": ollamaCloudUsageWindowFixture(100, until),
"seven_day": ollamaCloudUsageWindowFixture(100, until.Add(5*24*time.Hour)),
}),
}
blocked := rl.ApplyAccountSchedulingThreshold(context.Background(), account)
require.False(t, blocked)
require.Equal(t, 0, accountRepo.tempCalls)
require.Nil(t, account.TempUnschedulableUntil)
require.Empty(t, account.TempUnschedulableReason)
}
@@ -169,3 +169,31 @@ func TestGetAccountSchedulingThresholds_NilRepoReturnsDefaults(t *testing.T) {
PlatformGrok: 100,
}, got)
}
func TestValidateAndNormalizeAccountSchedulingThresholds_AcceptsOllamaCloud(t *testing.T) {
normalized, err := validateAndNormalizeAccountSchedulingThresholds(map[string]int{
PlatformOllamaCloud: 80,
})
require.NoError(t, err)
require.Equal(t, 80, normalized[PlatformOllamaCloud])
}
func TestAccountSchedulingThresholds_OllamaCloudRoundTrip(t *testing.T) {
svc := newSettingServiceForPlatformThresholdTest(nil)
// A6 验收的服务层等价路径:PUT account_scheduling_thresholds {"ollama_cloud":80}
// 必须被接受并回读 —— 白名单未纳入 ollama_cloud 时这里被
// validateAndNormalizeAccountSchedulingThresholds 拒为 unknown platform(400)。
err := svc.UpdateSettings(context.Background(), &SystemSettings{
AccountSchedulingThresholds: map[string]int{
PlatformOllamaCloud: 80,
},
})
require.NoError(t, err)
stored := svc.settingRepo.(*mockSettingRepo).data[SettingKeyAccountSchedulingThresholds]
require.Contains(t, stored, `"ollama_cloud":80`)
cached := svc.GetAccountSchedulingThresholds(context.Background())
require.Equal(t, 80, cached[PlatformOllamaCloud])
}
+4 -1
View File
@@ -40,11 +40,13 @@ export type SchedulingThresholdPlatformType =
| "zhipu"
| "minimax"
| "opencode_go"
| "ollama_cloud"
export type AccountSchedulingThresholdsMap = Record<SchedulingThresholdPlatformType, number>
// 与后端 AllowedSchedulingThresholdPlatforms 保持一致(deepseek 为余额型,
// 走余额检测而非用量阈值;minimax Coding/Token Plan 与 OpenCode GO 有滚动窗口)。
// 走余额检测而非用量阈值;minimax Coding/Token Plan 与 OpenCode GO 有滚动窗口;
// ollama_cloud 仅 legacy 账号有 5h/7d 滚动窗口,credits 型月度信用池无窗口不停调)。
export const SCHEDULING_THRESHOLD_PLATFORMS: SchedulingThresholdPlatformType[] = [
"openai",
"anthropic",
@@ -53,6 +55,7 @@ export const SCHEDULING_THRESHOLD_PLATFORMS: SchedulingThresholdPlatformType[] =
"zhipu",
"minimax",
"opencode_go",
"ollama_cloud",
]
export function normalizeAccountSchedulingThresholdsMap(