mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
fix(composite): generic Messages 池补齐 messages 调度开关、推理强度与配额自动暂停
- allow_messages_dispatch 关闭时整平台屏蔽 openai,与 OpenAI handler 同语义; - 选中 anthropic 账号时按单目标 anthropic 语义应用分组推理强度策略; - 池成员门纳入策略 deny 与 openai/grok 配额自动暂停(注入全局默认阈值), sticky、负载感知与 legacy 取号统一经此门; - 测试调度快照按桶平台返回,与生产单平台桶一致。
This commit is contained in:
1 parent
fbd50da3f1
commit
68de872287
7 files changed
+168
-1
No files matched your search
@@ -137,6 +137,22 @@ type compositePoolMessagesHarness struct {
|
||||
usageRepo *compositePoolUsageLogRepo
|
||||
}
|
||||
|
||||
// platformScopedSchedulerCache 按桶平台返回快照,与生产调度快照的单平台桶语义一致
|
||||
// (池按候选平台逐桶取号,被 deny 的平台整桶跳过)。
|
||||
type platformScopedSchedulerCache struct {
|
||||
fakeSchedulerCache
|
||||
}
|
||||
|
||||
func (f *platformScopedSchedulerCache) GetSnapshot(_ context.Context, bucket service.SchedulerBucket) ([]*service.Account, bool, error) {
|
||||
out := make([]*service.Account, 0, len(f.accounts))
|
||||
for _, account := range f.accounts {
|
||||
if account != nil && account.Platform == bucket.Platform {
|
||||
out = append(out, account)
|
||||
}
|
||||
}
|
||||
return out, true, nil
|
||||
}
|
||||
|
||||
func newCompositePoolMessagesHarness(t *testing.T, accounts []*service.Account) *compositePoolMessagesHarness {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
@@ -151,7 +167,7 @@ func newCompositePoolMessagesHarness(t *testing.T, accounts []*service.Account)
|
||||
openAIUpstream := &compositePoolFakeUpstream{}
|
||||
gwUpstream := &compositePoolFakeUpstream{}
|
||||
|
||||
schedulerCache := &fakeSchedulerCache{accounts: accounts}
|
||||
schedulerCache := &platformScopedSchedulerCache{fakeSchedulerCache{accounts: accounts}}
|
||||
schedulerSnapshot := service.NewSchedulerSnapshotService(schedulerCache, nil, nil, nil, nil)
|
||||
billingService := service.NewBillingService(cfg, nil)
|
||||
|
||||
@@ -488,3 +504,37 @@ func TestCompositePoolMessagesDelegatedUsageExcludesCachedInputTokens(t *testing
|
||||
require.Equal(t, 80, logs[0].CacheReadTokens)
|
||||
require.Equal(t, 7, logs[0].OutputTokens)
|
||||
}
|
||||
|
||||
// 跨族 Messages 池与 OpenAI handler 同语义:分组关闭 allow_messages_dispatch 时 openai
|
||||
// 账号整平台屏蔽、由其余平台承接;开启时 openai 账号可被委派。
|
||||
func TestCompositePoolMessagesRespectsAllowMessagesDispatch(t *testing.T) {
|
||||
t.Run("disabled masks openai", func(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{
|
||||
poolOpenAIAccount(41301, 41011, 0),
|
||||
poolAnthropicAccount(41302, 41011, 10),
|
||||
})
|
||||
h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return anthropicMessagesOKResponse()
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/messages", poolMessagesBody(), service.PlatformAnthropic, service.PlatformOpenAI)
|
||||
h.handler.Messages(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Empty(t, h.openAIUpstream.snapshot(), "开关关闭时 openai 账号不得承接 /v1/messages")
|
||||
require.Len(t, h.gwUpstream.snapshot(), 1)
|
||||
})
|
||||
|
||||
t.Run("enabled delegates openai", func(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolOpenAIAccount(41304, 41011, 0)})
|
||||
h.group.AllowMessagesDispatch = true
|
||||
|
||||
c, _ := h.newRequest(t, "/v1/messages", poolMessagesBody(), service.PlatformAnthropic, service.PlatformOpenAI)
|
||||
h.handler.Messages(c)
|
||||
|
||||
calls := h.openAIUpstream.snapshot()
|
||||
require.NotEmpty(t, calls)
|
||||
require.Contains(t, calls[0].Authorization, "openai-key")
|
||||
require.Empty(t, h.gwUpstream.snapshot())
|
||||
})
|
||||
}
|
||||
@@ -256,6 +256,18 @@ func releaseCompositePoolSelection(selection *service.AccountSelectionResult) {
|
||||
}
|
||||
}
|
||||
|
||||
// applyCompositePoolAnthropicReasoningEffortPolicy 为 composite 账号池 /v1/messages
|
||||
// 选中 anthropic 账号的 attempt 补齐分组推理强度策略:池请求准入期有效平台为
|
||||
// composite,applyAnthropicReasoningEffortPolicyForRequest 不生效;选中 anthropic
|
||||
// 账号时与单目标 anthropic 同语义,其余平台由各自转发链处理。
|
||||
func applyCompositePoolAnthropicReasoningEffortPolicy(apiKey *service.APIKey, account *service.Account, body []byte) ([]byte, bool, error) {
|
||||
if apiKey == nil || apiKey.Group == nil || account == nil || account.Platform != service.PlatformAnthropic {
|
||||
return body, false, nil
|
||||
}
|
||||
maxEffort, mappings := anthropicCompatibleReasoningEffortPolicy(apiKey.Group.MaxReasoningEffort, apiKey.Group.ReasoningEffortMappings)
|
||||
return service.ApplyReasoningEffortPolicy(body, maxEffort, mappings, apiKey.Group.MaxReasoningEffortOverLimit)
|
||||
}
|
||||
|
||||
// applyCompositePoolReasoningEffortPolicyForSelectedAccount 在账号选定后为
|
||||
// composite 账号池请求补齐组 reasoning-effort 策略(CC/Responses 直转路径:
|
||||
// 服务侧 forward 不再应用组策略)。池请求准入期没有单一目标平台,无法预判
|
||||
|
||||
@@ -89,6 +89,7 @@ func TestCompositeCrossFamilyPoolAppliesReasoningEffortCap(t *testing.T) {
|
||||
func TestCompositeCrossFamilyPoolMessagesAppliesReasoningEffortCap(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolOpenAIAccount(44201, 41011, 0)})
|
||||
h.group.MaxReasoningEffort = "medium"
|
||||
h.group.AllowMessagesDispatch = true
|
||||
h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return openAIResponsesSSEOKResponse("gpt-5.4")
|
||||
}
|
||||
@@ -103,3 +104,23 @@ func TestCompositeCrossFamilyPoolMessagesAppliesReasoningEffortCap(t *testing.T)
|
||||
require.Len(t, calls, 1)
|
||||
require.Equal(t, "medium", gjson.GetBytes(calls[0].Body, "reasoning.effort").String(), "upstream body=%s", calls[0].Body)
|
||||
}
|
||||
|
||||
// 跨族 Messages 池选中 anthropic 账号:准入期有效平台为 composite,组推理强度上限须在
|
||||
// attempt 级补齐,与单目标 anthropic 同语义。
|
||||
func TestCompositeCrossFamilyPoolMessagesAppliesReasoningEffortCapToAnthropic(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolAnthropicAccount(44202, 41011, 0)})
|
||||
h.group.MaxReasoningEffort = "medium"
|
||||
h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return anthropicMessagesOKResponse()
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/messages",
|
||||
`{"model":"my-model","max_tokens":64,"stream":false,"messages":[{"role":"user","content":"hello"}],"output_config":{"effort":"max"}}`,
|
||||
service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.Messages(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
calls := h.gwUpstream.snapshot()
|
||||
require.Len(t, calls, 1)
|
||||
require.Equal(t, "medium", gjson.GetBytes(calls[0].Body, "output_config.effort").String(), "upstream body=%s", calls[0].Body)
|
||||
}
|
||||
@@ -647,6 +647,15 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
// poolDenials 恒为空、attempt 策略不生效,整条路径零变化。
|
||||
isPoolRequest := service.GenericCompositePoolActive(c.Request.Context())
|
||||
poolDenials := newCompositePoolPlatformDenials()
|
||||
if isPoolRequest && !apiKey.Group.AllowMessagesDispatch {
|
||||
// 与 OpenAI handler 的 allowOpenAICompatibleMessagesDispatch 同语义:openai 账号承接
|
||||
// /v1/messages 受分组开关控制(grok / 多协议供应商豁免),关闭时整平台屏蔽 openai。
|
||||
poolDenials.deny(service.PlatformOpenAI)
|
||||
if _, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials); !ok {
|
||||
h.errorResponse(c, http.StatusForbidden, "permission_error", "This group does not allow /v1/messages dispatch")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 单账号分组提前设置 SingleAccountRetry 标记,让 Service 层首次 503 就不设模型限流标记。
|
||||
// 避免单账号分组收到 503 (MODEL_CAPACITY_EXHAUSTED) 时设 29s 限流,导致后续请求连续快速失败。
|
||||
@@ -785,6 +794,24 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
// 账号池选中 anthropic 账号:按单目标 anthropic 语义补齐分组推理强度策略(放在槽位获取前)。
|
||||
if isPoolRequest {
|
||||
cappedBody, changed, policyErr := applyCompositePoolAnthropicReasoningEffortPolicy(apiKey, account, attemptParsedReq.Body.Bytes())
|
||||
if policyErr != nil {
|
||||
releaseCompositePoolSelection(selection)
|
||||
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey)
|
||||
respondOpenAIReasoningEffortPolicyError(c, policyErr, h.errorResponse)
|
||||
return
|
||||
}
|
||||
if changed {
|
||||
if err := attemptParsedReq.ReplaceBody(cappedBody); err != nil {
|
||||
releaseCompositePoolSelection(selection)
|
||||
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey)
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to apply reasoning effort policy")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 检查请求拦截(预热请求、SUGGESTION MODE等)
|
||||
if account.IsInterceptWarmupEnabled() {
|
||||
|
||||
@@ -35,6 +35,18 @@ func genericCompositePoolAllowsAccount(ctx context.Context, account *Account) bo
|
||||
if account == nil || !genericCompositePoolAccountServable(account) {
|
||||
return false
|
||||
}
|
||||
// 本次请求被策略 deny 的平台整平台排除(与 OpenAI 族调度门同语义),覆盖
|
||||
// 不经 listSchedulableAccountsForCompositePool 取号的 sticky / 路由 / legacy 路径。
|
||||
if compositePoolPlatformDenied(ctx, account.Platform) {
|
||||
return false
|
||||
}
|
||||
// 委派 OpenAI 网关链的 openai / grok 账号不经 OpenAI 调度资格门,沿用其配额自动暂停。
|
||||
if paused, _ := shouldAutoPauseOpenAIAccountByQuota(ctx, account); paused {
|
||||
return false
|
||||
}
|
||||
if paused, _ := shouldAutoPauseGrokAccountByQuota(account); paused {
|
||||
return false
|
||||
}
|
||||
for _, platform := range CompositeCandidatePlatformsFromContext(ctx) {
|
||||
if platform == account.Platform {
|
||||
return true
|
||||
@@ -43,6 +55,15 @@ func genericCompositePoolAllowsAccount(ctx context.Context, account *Account) bo
|
||||
return false
|
||||
}
|
||||
|
||||
// withCompositePoolQuotaAutoPauseContext 为 generic 账号池选号注入 OpenAI 配额自动暂停
|
||||
// 的全局默认阈值(与 OpenAI 调度器同源,SettingService 内存缓存,不读库)。
|
||||
func (s *GatewayService) withCompositePoolQuotaAutoPauseContext(ctx context.Context) context.Context {
|
||||
if s == nil || s.settingService == nil || !GenericCompositePoolActive(ctx) {
|
||||
return ctx
|
||||
}
|
||||
return withOpenAIQuotaAutoPauseSettings(ctx, s.settingService.GetOpenAIQuotaAutoPauseSettings(ctx))
|
||||
}
|
||||
|
||||
// genericCompositePoolAccountServable 报告账号能否被 generic messages 路径服务。
|
||||
// 纯能力判定,不依赖候选池:
|
||||
// - PlatformAnthropic:generic 网关原生账号(OAuth/APIKey/ServiceAccount);
|
||||
|
||||
@@ -379,6 +379,33 @@ func TestGenericCompositePool_LoadAwareSelectsAcrossPlatforms(t *testing.T) {
|
||||
require.EqualValues(t, 44402, selection.Account.ID)
|
||||
}
|
||||
|
||||
// ---- e1. 委派 OpenAI 链的账号沿用配额自动暂停 ----
|
||||
|
||||
func TestGenericCompositePool_SkipsQuotaAutoPausedOpenAIAccount(t *testing.T) {
|
||||
groupID := int64(41007)
|
||||
group := newGenericPoolTestGroup(groupID)
|
||||
model := "my-model"
|
||||
ctx := genericPoolTestContext([]string{PlatformAnthropic, PlatformOpenAI})
|
||||
|
||||
build := func(usedPercent float64) *GatewayService {
|
||||
openai := genericPoolTestAccount(44601, PlatformOpenAI, groupID, 0,
|
||||
map[string]any{"model_mapping": map[string]any{"my-model": "gpt-5.4"}},
|
||||
map[string]any{"codex_5h_used_percent": usedPercent, "auto_pause_5h_threshold": 0.95})
|
||||
anthropic := genericPoolTestAccount(44602, PlatformAnthropic, groupID, 5,
|
||||
map[string]any{"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}}, nil)
|
||||
svc, _ := newGenericPoolTestService([]Account{openai, anthropic}, group, &compositePoolTestCache{}, nil)
|
||||
return svc
|
||||
}
|
||||
|
||||
selected, err := build(50).SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 44601, selected.ID, "未达阈值时 openai 按 priority 获胜")
|
||||
|
||||
selected, err = build(95).SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 44602, selected.ID, "达到自动暂停阈值的 openai 账号不得被池选中")
|
||||
}
|
||||
|
||||
// ---- e2. 显式 resolved 平台 pin 优先于池(单平台旧行为保持) ----
|
||||
|
||||
func TestGenericCompositePool_ResolvedPlatformPinBeatsPool(t *testing.T) {
|
||||
@@ -438,6 +465,9 @@ func TestCompositeGenericPoolPredicates(t *testing.T) {
|
||||
require.True(t, genericCompositePoolAllowsAccount(poolCtx, &openai))
|
||||
require.False(t, genericCompositePoolAllowsAccount(poolCtx, &gemini), "gemini 不在候选池")
|
||||
require.False(t, genericCompositePoolAllowsAccount(context.Background(), &kimiAdaptive), "无池恒 false")
|
||||
deniedCtx := WithCompositePoolDeniedPlatforms(poolCtx, []string{PlatformOpenAI})
|
||||
require.False(t, genericCompositePoolAllowsAccount(deniedCtx, &openai), "被 deny 的平台整平台排除(含 sticky 复检)")
|
||||
require.True(t, genericCompositePoolAllowsAccount(deniedCtx, &anthropicNative))
|
||||
|
||||
// countable:anthropic 原生 / anthropic-协议 / adaptive / gemini / antigravity
|
||||
// 可计数;纯 OpenAI 族(chat_completions 国产 / openai)不算。
|
||||
|
||||
@@ -74,6 +74,7 @@ func (s *GatewayService) SelectAccountForModelWithExclusions(ctx context.Context
|
||||
platform = PlatformAnthropic
|
||||
}
|
||||
ctx = s.withGatewayProfitControlGate(ctx, groupID)
|
||||
ctx = s.withCompositePoolQuotaAutoPauseContext(ctx)
|
||||
|
||||
// Claude Code 限制可能已将 groupID 解析为 fallback group,
|
||||
// 渠道限制预检查必须使用解析后的分组。
|
||||
@@ -127,6 +128,7 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro
|
||||
}
|
||||
ctx = s.withGroupContext(ctx, group)
|
||||
ctx = s.withGatewayProfitControlGate(ctx, groupID)
|
||||
ctx = s.withCompositePoolQuotaAutoPauseContext(ctx)
|
||||
|
||||
// Claude Code 限制可能已将 groupID 解析为 fallback group,
|
||||
// 渠道限制预检查必须使用解析后的分组。
|
||||
@@ -1162,6 +1164,10 @@ func (s *GatewayService) listSchedulableAccountsForCompositePool(ctx context.Con
|
||||
if _, duplicate := seen[bucket[i].ID]; duplicate {
|
||||
continue
|
||||
}
|
||||
// 与 sticky / 负载感知路径同一池成员门;legacy 选号循环不逐账号复检池成员资格,在取号时统一过滤。
|
||||
if !genericCompositePoolAllowsAccount(ctx, &bucket[i]) {
|
||||
continue
|
||||
}
|
||||
seen[bucket[i].ID] = struct{}{}
|
||||
merged = append(merged, bucket[i])
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user