fix(gateway, composite): 修复跨组降级凭据隔离、input_tokens/compact 池收窄与连接测试中转基址

This commit is contained in:
shaw committed 2026-12-05 17:26:44 +08:00
1 parent e9481fb0cb
commit 319ee85330
31 files changed
+1046 -50

No files matched your search

@@ -2976,6 +2976,19 @@ func (h *AccountHandler) respondAvailableModels(c *gin.Context, account *service
return
}
if account.IsOllamaCloud() && len(account.GetModelMapping()) == 0 {
allowed := account.GetOllamaCloudOutboundModels()
if len(allowed) == 0 {
allowed = service.DefaultOllamaCloudModelIDs()
}
models := make([]claude.Model, 0, len(allowed))
for _, id := range allowed {
models = append(models, claude.Model{ID: id, Type: "model", DisplayName: id})
}
response.Success(c, models)
return
}
// Handle Claude/Anthropic accounts
// For OAuth and Setup-Token accounts: return default models
if account.IsOAuth() {
@@ -56,6 +56,52 @@ func compositePoolAttemptContext(base context.Context, account *service.Account)
return service.WithResolvedTargetPlatform(base, account.Platform)
}
// syncSelectionEffectiveGroup 在选号发生 ClaudeCodeOnly 跨分组降级切换时,同步当前
// 调度分组、请求上下文、渠道映射与池状态(不改写最终计费归属 apiKey)。
func (h *GatewayHandler) syncSelectionEffectiveGroup(
c *gin.Context,
baseAPIKey *service.APIKey,
schedAPIKey *service.APIKey,
baseCtx context.Context,
channelMapping service.ChannelMappingResult,
reqModel string,
isPoolRequest bool,
poolDenials *compositePoolPlatformDenials,
selection *service.AccountSelectionResult,
) (*service.APIKey, context.Context, service.ChannelMappingResult, bool, *compositePoolPlatformDenials, bool) {
if selection == nil || selection.EffectiveGroup == nil || schedAPIKey == nil ||
selection.EffectiveGroup.ID == derefGroupID(schedAPIKey.GroupID) {
return schedAPIKey, baseCtx, channelMapping, isPoolRequest, poolDenials, false
}
nextKey := cloneAPIKeyWithGroup(baseAPIKey, selection.EffectiveGroup)
nextCtx := baseCtx
if selection.SelectionCtx != nil {
nextCtx = selection.SelectionCtx
}
if c != nil && c.Request != nil {
c.Request = c.Request.WithContext(nextCtx)
}
nextPool := service.GenericCompositePoolActive(nextCtx)
nextModel := reqModel
if !nextPool {
if upstreamModel, ok := service.ResolvedUpstreamModelFromContext(nextCtx); ok && upstreamModel != "" {
nextModel = upstreamModel
}
}
nextMapping := service.ChannelMappingResult{MappedModel: nextModel, Mapped: nextModel != reqModel}
if !nextPool && h != nil && h.gatewayService != nil {
resolvedMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(nextCtx, nextKey.GroupID, nextModel)
if resolvedMapping.Mapped {
nextMapping = resolvedMapping
}
}
return nextKey, nextCtx, nextMapping, nextPool, newCompositePoolPlatformDenials(), true
}
func compositeOrPoolDispatchActive(isPoolRequest bool, schedAPIKey *service.APIKey) bool {
return isPoolRequest || (schedAPIKey != nil && schedAPIKey.Group != nil && schedAPIKey.Group.Platform == service.PlatformComposite)
}
// compositePoolPlatformDenials 记录一次请求内被业务限制(配额/渠道限制)的平台,
// 供 failover 再选时做整平台 mask。每个请求一个实例,仅在 handler 的顺序 failover
// 循环里读写,无并发访问。
@@ -0,0 +1,322 @@
//go:build unit
package handler
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type multiGroupStubRepo struct {
fakeGroupRepo
byID map[int64]*service.Group
}
func (r *multiGroupStubRepo) GetByID(_ context.Context, id int64) (*service.Group, error) {
if g, ok := r.byID[id]; ok {
return g, nil
}
return nil, service.ErrGroupNotFound
}
func (r *multiGroupStubRepo) GetByIDLite(ctx context.Context, id int64) (*service.Group, error) {
return r.GetByID(ctx, id)
}
// C3 正向:anthropic 分组开启 ClaudeCodeOnly 并降级到 composite 池分组时,选中 OpenAI
// 账号必须经 OpenAI 兼容链转发,绝不能误入 GatewayService.Forward 把 API Key 发往 api.anthropic.com。
func TestClaudeCodeOnlyFallback_AnthropicToCompositePoolDelegatesOpenAIWithoutLeak(t *testing.T) {
gin.SetMode(gin.TestMode)
primaryID := int64(5101)
fallbackID := int64(5102)
primaryGroup := &service.Group{
ID: primaryID,
Name: "ant-cc-only",
Platform: service.PlatformAnthropic,
Status: service.StatusActive,
Hydrated: true,
ClaudeCodeOnly: true,
FallbackGroupID: &fallbackID,
AllowMessagesDispatch: true,
}
fallbackGroup := &service.Group{
ID: fallbackID,
Name: "comp-fallback-pool",
Platform: service.PlatformComposite,
Status: service.StatusActive,
Hydrated: true,
AllowMessagesDispatch: true,
}
openAIAcc := &service.Account{
ID: 8101,
Name: "oa-pool-member",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 2,
Priority: 1,
GroupIDs: []int64{fallbackID},
Credentials: map[string]any{
"api_key": "sk-openai-secret-never-send-to-anthropic",
"base_url": "https://openai-mock.example/v1",
"model_mapping": map[string]any{"shared-model": "gpt-5.4"},
},
Extra: map[string]any{
"openai_responses_mode": "force_chat_completions",
"openai_responses_supported": false,
},
}
antAcc := &service.Account{
ID: 8102,
Name: "ant-pool-member",
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 2,
Priority: 10,
GroupIDs: []int64{fallbackID},
Credentials: map[string]any{
"api_key": "sk-ant",
"base_url": "https://anthropic-mock.example",
"model_mapping": map[string]any{"shared-model": "claude-sonnet-4-5"},
},
}
accounts := []*service.Account{openAIAcc, antAcc}
cfg := &config.Config{RunMode: config.RunModeSimple}
cfg.Security = config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}
openAIUpstream := &compositePoolFakeUpstream{
respond: func(_ compositePoolUpstreamCall, _ int) *http.Response {
return chatCompletionsOKResponse("gpt-5.4", 10, 5)
},
}
gwUpstream := &compositePoolFakeUpstream{}
groupRepo := &multiGroupStubRepo{byID: map[int64]*service.Group{
primaryID: primaryGroup,
fallbackID: fallbackGroup,
}}
schedCache := &platformScopedSchedulerCache{fakeSchedulerCache{accounts: accounts}}
snap := service.NewSchedulerSnapshotService(schedCache, nil, nil, nil, nil)
bs := service.NewBillingService(cfg, nil)
usageRepo := &compositePoolUsageLogRepo{}
compositeResolver := service.NewCompositeRouteResolver(nil)
gwSvc := service.NewGatewayService(
nil, groupRepo, usageRepo, nil, nil, nil, nil, nil, cfg, snap, nil, bs, nil, nil, nil,
gwUpstream, nil, nil, nil, nil, nil, nil, nil, nil, nil, compositeResolver, nil, nil,
)
compositeResolver.SetModelOwnershipResolver(func(context.Context, int64, string) (service.CompositeModelOwnership, error) {
return service.CompositeModelOwnership{
Matched: true,
CandidatePlatforms: []string{service.PlatformAnthropic, service.PlatformOpenAI},
RequiredClaimStrength: service.CompositeClaimExplicit,
}, nil
})
oaSvc := service.NewOpenAIGatewayService(
nil, usageRepo, nil, nil, nil, nil, nil, cfg, nil, nil, bs, nil, nil,
openAIUpstream, service.NewDeferredService(nil, nil, 0), nil, nil, nil, nil, nil, nil, nil,
)
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCache.Stop)
h := &GatewayHandler{
gatewayService: gwSvc,
openAIGatewayService: oaSvc,
billingCacheService: billingCache,
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
maxAccountSwitches: 3,
cfg: cfg,
openAIHandler: &OpenAIGatewayHandler{gatewayService: oaSvc},
}
body := `{"model":"shared-model","max_tokens":32,"messages":[{"role":"user","content":"hi"}]}`
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body))
c.Request.Header.Set("Content-Type", "application/json")
c.Request.Header.Set("User-Agent", "curl/8.0") // 非 Claude Code 客户端,触发 FallbackGroupID
apiKey := &service.APIKey{
ID: 1, UserID: 1, GroupID: &primaryID, Group: primaryGroup,
User: &service.User{ID: 1, Concurrency: 5},
}
ctx := context.WithValue(c.Request.Context(), ctxkey.Group, primaryGroup)
c.Request = c.Request.WithContext(ctx)
c.Set(string(middleware2.ContextKeyAPIKey), apiKey)
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 1, Concurrency: 5})
h.Messages(c)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Empty(t, gwUpstream.snapshot(), "OpenAI APIKey must NEVER enter generic Anthropic HTTP upstream")
require.Len(t, openAIUpstream.snapshot(), 1, "OpenAI pool account must be delegated to OpenAIGatewayService")
}
// H8:通用池委派 OpenAI 链因组推理强度策略 deny 返回 403 JSON 时,不得在尾部追加 SSE 错误帧。
func TestCompositePoolDelegatedReasoningDeny_PureJSONWithoutTrailingSSE(t *testing.T) {
openAIAcc := &service.Account{
ID: 8201,
Name: "oa-deny",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 2,
Priority: 1,
GroupIDs: []int64{41011},
Credentials: map[string]any{
"api_key": "sk-oa",
"base_url": "https://openai-mock.example/v1",
"model_mapping": map[string]any{"shared-effort": "gpt-5.4"},
},
}
antAcc := &service.Account{
ID: 8202,
Name: "ant-peer",
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 2,
Priority: 10,
GroupIDs: []int64{41011},
Credentials: map[string]any{
"api_key": "sk-ant",
"model_mapping": map[string]any{"shared-effort": "claude-sonnet-4-5"},
},
}
harness := newCompositePoolMessagesHarness(t, []*service.Account{openAIAcc, antAcc})
harness.group.AllowMessagesDispatch = true
harness.group.MaxReasoningEffort = "medium"
harness.group.MaxReasoningEffortOverLimit = service.ReasoningEffortOverLimitDeny
c, rec := harness.newRequest(t, "/v1/messages",
`{"model":"shared-effort","max_tokens":64,"output_config":{"effort":"max"},"messages":[{"role":"user","content":"hi"}]}`,
service.PlatformAnthropic, service.PlatformOpenAI)
harness.handler.Messages(c)
require.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String())
require.NotContains(t, rec.Body.String(), "event: error", "403 JSON body must not be corrupted with trailing SSE frames")
var parsed map[string]any
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &parsed),
"response body must remain valid single JSON document: %s", rec.Body.String())
}
// C3 反向:composite 池分组开启 ClaudeCodeOnly(且未开启 AllowMessagesDispatch 或受原组策略限制)
// 降级到普通 anthropic 分组时,不得套用原分组的池策略把降级分组账号逐个踢进 502。
func TestClaudeCodeOnlyFallback_CompositePoolToAnthropicServesFallbackGroup(t *testing.T) {
gin.SetMode(gin.TestMode)
primaryID := int64(5201)
fallbackID := int64(5202)
primaryGroup := &service.Group{
ID: primaryID,
Name: "comp-cc-only",
Platform: service.PlatformComposite,
Status: service.StatusActive,
Hydrated: true,
ClaudeCodeOnly: true,
FallbackGroupID: &fallbackID,
}
fallbackGroup := &service.Group{
ID: fallbackID,
Name: "ant-fallback",
Platform: service.PlatformAnthropic,
Status: service.StatusActive,
Hydrated: true,
}
antAcc := &service.Account{
ID: 8301,
Name: "ant-fallback-acc",
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 2,
Priority: 1,
GroupIDs: []int64{fallbackID},
Credentials: map[string]any{
"api_key": "sk-ant-fallback",
"base_url": "https://anthropic-fallback.example",
},
}
cfg := &config.Config{RunMode: config.RunModeSimple}
cfg.Security = config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}
gwUpstream := &compositePoolFakeUpstream{
respond: func(_ compositePoolUpstreamCall, _ int) *http.Response {
return anthropicMessagesOKResponse()
},
}
groupRepo := &multiGroupStubRepo{byID: map[int64]*service.Group{
primaryID: primaryGroup,
fallbackID: fallbackGroup,
}}
schedCache := &platformScopedSchedulerCache{fakeSchedulerCache{accounts: []*service.Account{antAcc}}}
snap := service.NewSchedulerSnapshotService(schedCache, nil, nil, nil, nil)
bs := service.NewBillingService(cfg, nil)
usageRepo := &compositePoolUsageLogRepo{}
gwSvc := service.NewGatewayService(
nil, groupRepo, usageRepo, nil, nil, nil, nil, nil, cfg, snap, nil, bs, nil, nil, nil,
gwUpstream, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
)
oaSvc := service.NewOpenAIGatewayService(
nil, usageRepo, nil, nil, nil, nil, nil, cfg, nil, nil, bs, nil, nil,
&compositePoolFakeUpstream{}, service.NewDeferredService(nil, nil, 0), nil, nil, nil, nil, nil, nil, nil,
)
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCache.Stop)
h := &GatewayHandler{
gatewayService: gwSvc,
openAIGatewayService: oaSvc,
billingCacheService: billingCache,
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
maxAccountSwitches: 3,
cfg: cfg,
openAIHandler: &OpenAIGatewayHandler{gatewayService: oaSvc},
}
body := `{"model":"claude-sonnet-4-5","max_tokens":32,"messages":[{"role":"user","content":"hi"}]}`
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body))
c.Request.Header.Set("Content-Type", "application/json")
c.Request.Header.Set("User-Agent", "curl/8.0")
ctx := service.WithCompositeRouteDecision(c.Request.Context(), service.CompositeRouteDecision{
Matched: true,
Source: service.CompositeRouteSourceAccountPool,
GroupID: primaryID,
PublicModel: "claude-sonnet-4-5",
CandidatePlatforms: []string{service.PlatformDeepseek, service.PlatformOpenAI},
RequiredClaimStrength: service.CompositeClaimExplicit,
})
ctx = context.WithValue(ctx, ctxkey.Group, primaryGroup)
c.Request = c.Request.WithContext(ctx)
apiKey := &service.APIKey{
ID: 1, UserID: 1, GroupID: &primaryID, Group: primaryGroup,
User: &service.User{ID: 1, Concurrency: 5},
}
c.Set(string(middleware2.ContextKeyAPIKey), apiKey)
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 1, Concurrency: 5})
h.Messages(c)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Len(t, gwUpstream.snapshot(), 1)
}
+23 -8
View File
@@ -697,6 +697,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
for {
fs := NewFailoverState(h.maxAccountSwitches, hasBoundSession)
retryWithFallback := false
schedAPIKey := currentAPIKey
for {
attemptParsedReq, err := parsedReq.CloneForBody(body)
@@ -721,7 +722,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
selectCtx = maskedCtx
}
}
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, currentAPIKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, parsedReq.MetadataUserID, subject.UserID)
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, schedAPIKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, parsedReq.MetadataUserID, subject.UserID)
if err != nil {
if failoverClientGone(c) {
reqLog.Info("gateway.account_select_aborted_client_disconnected", zap.Error(err))
@@ -769,6 +770,15 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.anthropicSecurityAuditError) {
return
}
var switchedGroup bool
schedAPIKey, _, channelMapping, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup(
c, currentAPIKey, schedAPIKey, c.Request.Context(), channelMapping, reqModel, isPoolRequest, poolDenials, selection)
if switchedGroup && isPoolRequest {
bindOpenAIReasoningEffortPolicyForMessagesRequest(c, schedAPIKey, body)
if !schedAPIKey.Group.AllowMessagesDispatch {
poolDenials.deny(service.PlatformOpenAI)
}
}
setOpsSelectedAccount(c, account.ID, account.Platform)
// [DEBUG-STICKY] 打印账号选择结果
@@ -789,10 +799,13 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
// 候选全部被业务限制时按原语义终止,不误报 model unsupported。
attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMapping}
isPoolAttempt := false
if isPoolRequest && compositePoolAttemptPolicyApplies(c, currentAPIKey) {
if isPoolRequest && compositePoolAttemptPolicyApplies(c, schedAPIKey) {
attemptPolicy = evaluateCompositePoolAttemptPolicy(
c.Request.Context(), h.billingCacheService, h.openAIGatewayService, currentAPIKey, currentSubscription, account, reqModel, false)
c.Request.Context(), h.billingCacheService, h.openAIGatewayService, schedAPIKey, currentSubscription, account, reqModel, false)
isPoolAttempt = true
if isPoolRequest && !schedAPIKey.Group.AllowMessagesDispatch && account.Platform == service.PlatformOpenAI {
attemptPolicy.Failure.ChannelRestricted = true
}
if attemptPolicy.Failure.denied() {
releaseCompositePoolSelection(selection)
// 选号链可能已为该账号注册会话槽:排除前释放,镜像 profit-veto 分支。
@@ -817,7 +830,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
h.handleStreamingAwareError(cc, status, code, message, streamStarted)
}
cappedBody, changed, policyErr := applyCompositePoolAnthropicReasoningEffortPolicy(currentAPIKey, account, attemptParsedReq.Body.Bytes())
cappedBody, changed, policyErr := applyCompositePoolAnthropicReasoningEffortPolicy(schedAPIKey, account, attemptParsedReq.Body.Bytes())
if policyErr != nil {
releaseCompositePoolSelection(selection)
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey)
@@ -1035,11 +1048,12 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
if selection.ProfitGateActive() {
attemptedAccountIDs = append(attemptedAccountIDs, account.ID)
}
canCrossFamilyDispatch := compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey)
// 记录 Forward 前已写入字节数,Forward 后若增加则说明 SSE 内容已发,禁止 failover
writerSizeBeforeForward := c.Writer.Size()
if account.Platform == service.PlatformAntigravity && account.Type != service.AccountTypeAPIKey {
result, err = h.antigravityGatewayService.Forward(requestCtx, c, account, attemptBody, hasBoundSession)
} else if isPoolRequest && account.Platform == service.PlatformGemini {
} else if canCrossFamilyDispatch && account.Platform == service.PlatformGemini {
// Gemini 账号经 Gemini 兼容链转换(与非池 gemini 分支同一实现);generic
// Forward 只能发往 Anthropic 协议上游,会把 Google 凭据发错主机。
if h.geminiCompatService == nil {
@@ -1047,15 +1061,15 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
} else {
result, err = h.geminiCompatService.Forward(requestCtx, c, account, attemptBody)
}
} else if isPoolRequest && compositePoolAccountDelegatesToOpenAI(account) {
// 纯 OpenAI 族账号(无 Anthropic 协议能力)在池激活时委派 OpenAI 网关的
} else if canCrossFamilyDispatch && compositePoolAccountDelegatesToOpenAI(account) {
// 纯 OpenAI 族账号(无 Anthropic 协议能力)在池激活或跨组切入 composite 时委派 OpenAI 网关的
// /v1/messages 兼容链:Anthropic → Responses/CC 协议转换、响应写回与
// failover 错误信封都由该链完成,错误信封已是 Anthropic 风格,不再二次包装。
// promptCacheKey 传 ""(内部按 cache_control / metadata 会话种子兜底);
// defaultMappedModel 与 OpenAI handler Messages 路径同源。
openAIResult, delegateErr := h.openAIGatewayService.ForwardAsAnthropic(
requestCtx, c, account, attemptBody, "",
strings.TrimSpace(resolveOpenAIMessagesDispatchMappedModel(c, apiKey, reqModel)))
strings.TrimSpace(resolveOpenAIMessagesDispatchMappedModel(c, schedAPIKey, reqModel)))
delegated = true
delegatedResult = openAIResult
result = adaptOpenAIForwardResultToForwardResult(openAIResult)
@@ -1212,6 +1226,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
currentSubscription = nil
isPoolRequest = false
poolDenials = newCompositePoolPlatformDenials()
channelMapping, _ = h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), currentAPIKey.GroupID, reqModel)
fallbackUsed = true
retryWithFallback = true
// 原分组账号已确定性失败(prompt too long),先释放其会话注册再走兜底分组
@@ -211,6 +211,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
if groupPlatform == service.PlatformGemini {
fs = NewFailoverState(h.maxAccountSwitchesGemini, false)
}
schedAPIKey := apiKey
for {
if failoverClientGone(c) {
@@ -225,7 +226,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
selectCtx = maskedCtx
}
}
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, apiKey.GroupID, selectionSessionHash, reqModel, fs.FailedAccountIDs, "", int64(0))
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, schedAPIKey.GroupID, selectionSessionHash, reqModel, fs.FailedAccountIDs, "", int64(0))
if err != nil {
if failoverClientGone(c) {
reqLog.Info("gateway.cc.account_select_aborted_client_disconnected", zap.Error(err))
@@ -264,6 +265,12 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
return
}
var switchedGroup bool
schedAPIKey, _, channelMapping, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup(
c, apiKey, schedAPIKey, c.Request.Context(), channelMapping, reqModel, isPoolRequest, poolDenials, selection)
if switchedGroup && compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) && poolPromptCacheKey == "" && h.openAIGatewayService != nil {
poolPromptCacheKey = h.openAIGatewayService.ExtractSessionID(c, body)
}
setOpsSelectedAccount(c, account.ID, account.Platform)
// composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform
@@ -274,9 +281,9 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
// 候选全部被业务限制时按原语义终止,不误报 model unsupported。
attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMapping}
isPoolAttempt := false
if isPoolRequest && compositePoolAttemptPolicyApplies(c, apiKey) {
if isPoolRequest && compositePoolAttemptPolicyApplies(c, schedAPIKey) {
attemptPolicy = evaluateCompositePoolAttemptPolicy(
c.Request.Context(), h.billingCacheService, h.openAIGatewayService, apiKey, subscription, account, reqModel, false)
c.Request.Context(), h.billingCacheService, h.openAIGatewayService, schedAPIKey, subscription, account, reqModel, false)
isPoolAttempt = true
if attemptPolicy.Failure.denied() {
releaseCompositePoolSelection(selection)
@@ -371,7 +378,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
}
// 账号池按选中账号应用分组推理强度策略(与单目标同语义,覆盖 openai / anthropic 账号)。
if isPoolRequest {
cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody)
cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, schedAPIKey, account, forwardBody)
if policyErr != nil {
if accountReleaseFunc != nil {
accountReleaseFunc()
@@ -420,7 +427,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
}
setActualUpstreamEndpoint(c, EndpointAntigravityGenerateContent)
result, err = h.antigravityGatewayService.ForwardAsChatCompletions(attemptCtx, c, account, forwardBody, parsedReq)
} else if isPoolRequest && compositePoolAccountDelegatesChatCompletionsToOpenAI(account) {
} else if compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) && compositePoolAccountDelegatesChatCompletionsToOpenAI(account) {
// OpenAI 兼容族账号在池激活时委派 OpenAI 网关 CC 链:入站同族优先
//(零转换,adaptive 账号由该链直转供应商原生 CC 端点),响应写回与
// failover 错误信封都由该链完成,错误信封已是 OpenAI CC 风格,不再二次
@@ -224,6 +224,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
// 3. Account selection + failover loop
fs := NewFailoverState(h.maxAccountSwitches, false)
schedAPIKey := apiKey
for {
if failoverClientGone(c) {
@@ -238,7 +239,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
selectCtx = maskedCtx
}
}
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, apiKey.GroupID, sessionHash, reqModel, fs.FailedAccountIDs, "", int64(0))
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, schedAPIKey.GroupID, sessionHash, reqModel, fs.FailedAccountIDs, "", int64(0))
if err != nil {
if failoverClientGone(c) {
reqLog.Info("gateway.responses.account_select_aborted_client_disconnected", zap.Error(err))
@@ -277,26 +278,34 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.responsesSecurityAuditError) {
return
}
var switchedGroup bool
schedAPIKey, requestCtx, channelMapping, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup(
c, apiKey, schedAPIKey, requestCtx, channelMapping, reqModel, isPoolRequest, poolDenials, selection)
if switchedGroup && isPoolRequest {
service.SetOpenAIHTTPResponseOwner(c, subject.UserID, apiKey.ID)
}
setOpsSelectedAccount(c, account.ID, account.Platform)
// Gemini 账号没有 Responses 转换链(generic 链只能发往 Anthropic 协议上游,会把
// Google 凭据发错主机):池请求整平台屏蔽 gemini 后重选,候选只剩 gemini 时终止。
if isPoolRequest && account.Platform == service.PlatformGemini {
if compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) && account.Platform == service.PlatformGemini {
releaseCompositePoolSelection(selection)
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionHash)
poolDenials.deny(account.Platform)
fs.FailedAccountIDs[account.ID] = struct{}{}
if _, ok := compositePoolSelectionRetryContext(requestCtx, poolDenials); !ok {
if streamStarted {
h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error",
"Model is only available on Gemini accounts in this group, which do not support /v1/responses", true)
} else {
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error",
"Model is only available on Gemini accounts in this group, which do not support /v1/responses")
if isPoolRequest {
poolDenials.deny(account.Platform)
fs.FailedAccountIDs[account.ID] = struct{}{}
if _, ok := compositePoolSelectionRetryContext(requestCtx, poolDenials); ok {
continue
}
return
}
continue
if streamStarted {
h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error",
"Model is only available on Gemini accounts in this group, which do not support /v1/responses", true)
} else {
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error",
"Model is only available on Gemini accounts in this group, which do not support /v1/responses")
}
return
}
// composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform
@@ -308,9 +317,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
// unsupported。
attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: requestCtx, Mapping: channelMapping}
isPoolAttempt := false
if isPoolRequest && compositePoolAttemptPolicyApplies(c, apiKey) {
if isPoolRequest && compositePoolAttemptPolicyApplies(c, schedAPIKey) {
attemptPolicy = evaluateCompositePoolAttemptPolicy(
requestCtx, h.billingCacheService, h.openAIGatewayService, apiKey, subscription, account, reqModel, false)
requestCtx, h.billingCacheService, h.openAIGatewayService, schedAPIKey, subscription, account, reqModel, false)
isPoolAttempt = true
if attemptPolicy.Failure.denied() {
releaseCompositePoolSelection(selection)
@@ -398,7 +407,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
}
// 账号池按选中账号应用分组推理强度策略(与单目标同语义,覆盖 openai / anthropic 账号)。
if isPoolRequest {
cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody)
cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, schedAPIKey, account, forwardBody)
if policyErr != nil {
if accountReleaseFunc != nil {
accountReleaseFunc()
@@ -439,7 +448,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
}
setActualUpstreamEndpoint(c, EndpointAntigravityGenerateContent)
result, err = h.antigravityGatewayService.ForwardAsResponses(attemptCtx, c, account, forwardBody, parsedReq)
} else if isPoolRequest && compositePoolAccountDelegatesResponsesToOpenAI(account) {
} else if compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) && compositePoolAccountDelegatesResponsesToOpenAI(account) {
// 纯 OpenAI 族 / 原生 Responses 账号在池激活时委派 OpenAI 网关 Responses
// 链:入站同族优先(零或近零转换),响应写回与 failover 错误信封都由该
// 链完成,错误信封已是 OpenAI Responses 风格,不再二次包装。
+8 -1
View File
@@ -163,7 +163,11 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service.
defer userReleaseFunc()
}
if err := h.billingCacheService.CheckBillingEligibility(c.Request.Context(), apiKey.User, apiKey, apiKey.Group, subscription, service.QuotaPlatform(c.Request.Context(), apiKey)); err != nil {
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
if quotaPlatform == "" {
quotaPlatform = platform
}
if err := h.billingCacheService.CheckBillingEligibility(c.Request.Context(), apiKey.User, apiKey, apiKey.Group, subscription, quotaPlatform); err != nil {
reqLog.Info("grok_media.billing_eligibility_check_failed", zap.Error(err))
status, code, message, retryAfter := billingErrorDetails(err)
if retryAfter > 0 {
@@ -206,6 +210,9 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service.
// 范围内:显式豁免,防止 service 层防御性装门按文本 D 误过滤媒体请求,
// 也防止已计费的在途视频任务因绑定账号被门排除而查询返回伪 404。
requestCtx := service.WithOpenAIProfitControlSuppressed(c.Request.Context())
if apiKey.Group != nil && apiKey.Group.Platform == service.PlatformComposite {
requestCtx = service.WithResolvedTargetPlatform(service.WithoutCompositeRouteContext(requestCtx), platform)
}
profitVetoCount := 0
failedAccountIDs := make(map[int64]struct{})
sameAccountRetryCount := make(map[int64]int)
@@ -84,6 +84,9 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) {
}
channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel)
if compositePoolAttemptPolicyApplies(c, apiKey) {
channelMapping = service.ChannelMappingResult{MappedModel: reqModel}
}
routingModel := reqModel
forwardBody := body
if channelMapping.Mapped {
@@ -127,6 +130,13 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) {
return
}
setOpsSelectedAccount(c, account.ID, account.Platform)
if compositePoolAttemptPolicyApplies(c, apiKey) {
attemptMapping := h.gatewayService.CompositePoolAttemptChannelMapping(
compositePoolAttemptContext(c.Request.Context(), account), apiKey.GroupID, reqModel)
if attemptMapping.Mapped {
forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptMapping.MappedModel)
}
}
if err := h.gatewayService.ForwardResponsesInputTokens(c.Request.Context(), c, account, forwardBody); err != nil {
reqLog.Error("openai_input_tokens.forward_failed", zap.Int64("account_id", account.ID), zap.Error(err))
}
@@ -250,6 +260,9 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) {
setOpsEndpointContext(c, "", int16(service.RequestTypeFromLegacy(false, false)))
channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel)
if compositePoolAttemptPolicyApplies(c, apiKey) {
channelMapping = service.ChannelMappingResult{MappedModel: reqModel}
}
mappedBodyForMessages := newOpenAIModelMappedBodyCache(body, h.gatewayService.ReplaceModelInBody)
subscription, _ := middleware2.GetSubscriptionFromContext(c)
@@ -304,7 +317,12 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) {
return
}
setOpsSelectedAccount(c, account.ID, account.Platform)
forwardBody := mappedBodyForMessages(channelMapping.Mapped, channelMapping.MappedModel)
attemptMapping := channelMapping
if compositePoolAttemptPolicyApplies(c, apiKey) {
attemptMapping = h.gatewayService.CompositePoolAttemptChannelMapping(
compositePoolAttemptContext(c.Request.Context(), account), apiKey.GroupID, reqModel)
}
forwardBody := mappedBodyForMessages(attemptMapping.Mapped, attemptMapping.MappedModel)
defaultMappedModel := preferredMappedModel
if err := h.gatewayService.ForwardCountTokensAsAnthropic(c.Request.Context(), c, account, forwardBody, defaultMappedModel); err != nil {
@@ -280,7 +280,13 @@ func (r *accountRepository) updateOllamaCloudUsageGroup(
return nil
}
if dbent.TxFromContext(ctx) != nil {
return apply(ctx, clientFromContext(ctx, r.client))
if err := apply(ctx, clientFromContext(ctx, r.client)); err != nil {
return err
}
service.AfterAccountCommit(ctx, func(commitCtx context.Context) {
r.syncOllamaCloudUsageSchedulerState(commitCtx, syncedMemberIDs)
})
return nil
}
tx, err := r.client.Tx(ctx)
if errors.Is(err, dbent.ErrTxStarted) {
@@ -1754,6 +1754,7 @@ func filterSchedulerExtra(extra map[string]any) map[string]any {
service.UpstreamBillingProbeExtraKey,
service.GrokMediaEligibleExtraKey,
"grok_billing_snapshot",
"grok_usage_snapshot",
}
filtered := make(map[string]any)
for _, key := range keys {
@@ -105,4 +105,10 @@ func TestSchedulerMetadataAccount_KeepsOllamaCloudThresholdAndProtocolProjection
require.NoError(t, json.Unmarshal(creditsMeta, &projectedCredits))
require.Equal(t, service.AccountModeOllamaCredits, projectedCredits.GetOllamaCloudAccountMode())
require.False(t, service.EvaluateAccountSchedulingThreshold(&projectedCredits, nil, now).ShouldPause)
// H7: Grok OAuth 配额快照(grok_usage_snapshot)必须进入投影,保证跨族池自动暂停生效。
grokExtra := filterSchedulerExtra(map[string]any{
"grok_usage_snapshot": map[string]any{"remaining_queries": 0},
})
require.Contains(t, grokExtra, "grok_usage_snapshot")
}
+42 -7
View File
@@ -181,8 +181,18 @@ func RegisterGatewayRoutes(
})
return
}
if service.IsOpenAIResponsesInputTokensRequestPath(c) && isOpenAIResponsesCompatibleGatewayPlatform(c) {
h.OpenAIGateway.ResponsesInputTokens(c)
if service.IsOpenAIResponsesInputTokensRequestPath(c) {
if isOpenAIResponsesCompatibleGatewayPlatform(c) {
h.OpenAIGateway.ResponsesInputTokens(c)
return
}
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{
"error": gin.H{
"type": "not_found_error",
"message": "Responses input_tokens is not supported for this platform",
},
})
return
}
next(c)
@@ -711,14 +721,23 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver)
writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q has no OpenAI-compatible account in this composite group to continue previous_response_id; resend the full conversation without previous_response_id", model))
return
}
} else if isCompositePoolResponsesCompact(c, decision) {
// /responses/compact 仅由 OpenAI 网关链支持(含 compact 归一化、渠道限制与心跳):
// 跨族候选池收窄到 OpenAI 兼容族,避免落入通用网关按普通 Responses 误转协议。
} else if isCompositePoolResponsesCompact(c, decision, body) {
// /responses/compact(含裸 /responses 的 compaction_trigger v1/v2)仅由 OpenAI 网关链
// 支持(含 compact 归一化、渠道限制与心跳):跨族候选池收窄到 OpenAI 兼容族,
// 避免落入通用网关按普通 Responses 误转协议。
decision.CandidatePlatforms = openAICompatibleCandidatePlatforms(decision.CandidatePlatforms)
if len(decision.CandidatePlatforms) == 0 {
writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q has no OpenAI-compatible account in this composite group to support /responses/compact", model))
return
}
} else if isCompositePoolResponsesInputTokens(c, decision) {
// /responses/input_tokens 为免计费 token 预检端点,仅由 OpenAI 网关链支持:
// 跨族候选池收窄到 OpenAI 兼容族,防止落入通用网关触发真实推理并扣费。
decision.CandidatePlatforms = openAICompatibleCandidatePlatforms(decision.CandidatePlatforms)
if len(decision.CandidatePlatforms) == 0 {
writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q has no OpenAI-compatible account in this composite group to support /responses/input_tokens", model))
return
}
}
c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision))
if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) {
@@ -804,7 +823,7 @@ func isCompositePoolResponsesContinuation(c *gin.Context, decision service.Compo
return strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) != ""
}
func isCompositePoolResponsesCompact(c *gin.Context, decision service.CompositeRouteDecision) bool {
func isCompositePoolResponsesCompact(c *gin.Context, decision service.CompositeRouteDecision, body []byte) bool {
if c == nil || c.Request == nil || c.Request.URL == nil {
return false
}
@@ -812,7 +831,23 @@ func isCompositePoolResponsesCompact(c *gin.Context, decision service.CompositeR
return false
}
path := strings.TrimRight(c.Request.URL.Path, "/")
return strings.HasSuffix(path, "/responses/compact")
if strings.HasSuffix(path, "/responses/compact") {
return true
}
if path == "/v1/responses" || path == "/responses" || path == "/backend-api/codex/responses" {
return service.HasCompactionTriggerInInput(body)
}
return false
}
func isCompositePoolResponsesInputTokens(c *gin.Context, decision service.CompositeRouteDecision) bool {
if c == nil || c.Request == nil || c.Request.URL == nil {
return false
}
if strings.TrimSpace(decision.TargetPlatform) != "" || len(decision.CandidatePlatforms) == 0 {
return false
}
return service.IsOpenAIResponsesInputTokensRequestPath(c)
}
// openAICompatibleCandidatePlatforms 返回候选平台中经 OpenAI 网关转发的平台(保持顺序)。
@@ -628,3 +628,50 @@ func TestCompositePoolMessagesClaudeAliasUsesAccountMapping(t *testing.T) {
require.Equal(t, "deepseek-chat", gjson.GetBytes(captured[0].body, "model").String(),
"outbound model must come from the selected account's model_mapping, not the gpt-5.x dispatch default")
}
// C4:跨族候选池([anthropic, deepseek])调用免计费 /v1/responses/input_tokens 时,
// 必须收窄到 OpenAI 兼容族走 ResponsesInputTokens,绝不能跌落进 GatewayHandler.Responses
// 执行真实付费生成。
func TestCompositeCrossFamilyPool_ResponsesInputTokensNeverTriggersGeneration(t *testing.T) {
upstream := &captureUpstream{}
group := newPoolPolicyGroup(nil)
router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
group: group,
accounts: []service.Account{
newPoolPolicyAccountWithMapping(4301, service.PlatformAnthropic, 0, map[string]any{"shared-count": "claude-sonnet-4-6"}),
newPoolPolicyAccountWithMapping(4302, service.PlatformDeepseek, 5, map[string]any{"shared-count": "deepseek-chat"}),
},
upstream: upstream,
})
w := postPoolPolicyRequest(t, router, "/v1/responses/input_tokens",
`{"model":"shared-count","input":"hello world"}`)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
require.Equal(t, "response.input_tokens", gjson.GetBytes(w.Body.Bytes(), "object").String())
require.Greater(t, gjson.GetBytes(w.Body.Bytes(), "input_tokens").Int(), int64(0))
require.Empty(t, upstream.capturedSnapshot(), "token count must estimate locally on CN relay and never run Anthropic generation")
}
// H6:裸 /v1/responses 携带 compaction_trigger 时,跨族池必须收窄到 OpenAI 兼容族。
func TestCompositeCrossFamilyPool_BareResponsesCompactionTriggerNarrowsToOpenAIFamily(t *testing.T) {
upstream := &captureUpstream{}
group := newPoolPolicyGroup(nil)
ds := newPoolPolicyAccountWithMapping(4312, service.PlatformDeepseek, 5, map[string]any{"shared-compact": "deepseek-chat"})
ds.Credentials["api_protocol"] = service.APIProtocolResponses
router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
group: group,
accounts: []service.Account{
newPoolPolicyAccountWithMapping(4311, service.PlatformAnthropic, 0, map[string]any{"shared-compact": "claude-sonnet-4-6"}),
ds,
},
upstream: upstream,
})
w := postPoolPolicyRequest(t, router, "/v1/responses",
`{"model":"shared-compact","stream":false,"input":[{"type":"compaction_trigger"}]}`)
// 收窄到兼容族后绝不会发往 anthropic-pool-fake.test。
for _, rec := range upstream.capturedSnapshot() {
require.NotEqual(t, "anthropic-pool-fake.test", rec.host,
"compaction_trigger on bare /v1/responses must never route to generic Anthropic handler; resp=%s", w.Body.String())
}
}
+4
View File
@@ -1099,6 +1099,10 @@ func (a *Account) isModelMappingSupported(requestedModel string) bool {
}
return true // 无映射 = 允许所有
}
if a.IsOllamaCloud() {
mapped, matched := a.ResolveMappedModel(requestedModel)
return matched && strings.TrimSpace(mapped) != ""
}
if mappingSupportsRequestedModel(mapping, requestedModel) {
return true
}
@@ -113,6 +113,15 @@ func ollamaCloudSchedulableBySave(a *Account) bool {
return a != nil && a.IsActive() && a.Schedulable
}
// GetOllamaCloudOutboundModels 返回 ollama_cloud 账号配置的可出站模型列表(model_mapping
// 目标或 extra.allowed_models 白名单),供管理端账号可用模型与连接测试默认选项复用。
func (a *Account) GetOllamaCloudOutboundModels() []string {
if a == nil || !a.IsOllamaCloud() {
return nil
}
return ollamaCloudOutboundModelNames(a)
}
// ollamaCloudOutboundModelNames 收集 ollama_cloud 账号的可出站模型名集合
// (去重、去空)。空 mapping 且无有效清单时返回 nil。
//
@@ -258,6 +258,9 @@ func (s *AccountService) Create(ctx context.Context, req CreateAccountRequest) (
} else {
account.AutoPauseOnExpired = true
}
if req.Platform == PlatformOllamaCloud && req.Type != AccountTypeAPIKey {
return nil, errors.New("ollama_cloud accounts only support apikey credentials")
}
// B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil {
@@ -479,13 +479,14 @@ func (s *AccountTestService) testNativeResponsesConnection(c *gin.Context, accou
if authToken == "" {
return s.sendErrorAndEnd(c, "No API key available")
}
mappedModelID := account.GetMappedModel(testModelID)
c.Writer.Header().Set("Content-Type", "text/event-stream")
c.Writer.Header().Set("Cache-Control", "no-cache")
c.Writer.Header().Set("Connection", "keep-alive")
c.Writer.Header().Set("X-Accel-Buffering", "no")
c.Writer.Flush()
s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID})
return s.testCNProviderAdaptiveResponsesConnection(c, account, testModelID, authToken)
s.sendEvent(c, TestEvent{Type: "test_start", Model: mappedModelID})
return s.testCNProviderAdaptiveResponsesConnection(c, account, mappedModelID, authToken)
}
// testOllamaCloudAccountConnection probes an Ollama Cloud account's native
@@ -163,7 +163,11 @@ func (s *AccountTestService) processCNProviderAdaptiveAnthropicStream(c *gin.Con
func (s *AccountTestService) testCNProviderAdaptiveResponsesConnection(c *gin.Context, account *Account, testModelID string, authToken string) error {
ctx := c.Request.Context()
baseURL, err := s.validateUpstreamBaseURL(account.GetCNProtocolBaseURL(APIProtocolResponses))
rawBaseURL := account.GetOpenAIBaseURL()
if account.IsAdaptiveAPIProtocol() {
rawBaseURL = account.GetCNProtocolBaseURL(APIProtocolResponses)
}
baseURL, err := s.validateUpstreamBaseURL(rawBaseURL)
if err != nil {
return s.sendErrorAndEnd(c, fmt.Sprintf("Invalid adaptive Responses base URL: %s", err.Error()))
}
+31
View File
@@ -425,6 +425,9 @@ func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]an
if input.Platform == PlatformTypeSafe && input.Type != AccountTypeAPIKey {
return nil, errors.New("typesafe accounts only support apikey credentials")
}
if input.Platform == PlatformOllamaCloud && input.Type != AccountTypeAPIKey {
return nil, errors.New("ollama_cloud accounts only support apikey credentials")
}
// Probe/session state is system-managed. Only explicit account settings can enable it.
delete(accountExtra, UpstreamBillingProbeEnabledExtraKey)
delete(accountExtra, UpstreamBillingRateSyncEnabledExtraKey)
@@ -610,6 +613,9 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
if account.Platform == PlatformTypeSafe && input.Type != "" && input.Type != AccountTypeAPIKey {
return nil, errors.New("typesafe accounts only support apikey credentials")
}
if account.Platform == PlatformOllamaCloud && input.Type != "" && input.Type != AccountTypeAPIKey {
return nil, errors.New("ollama_cloud accounts only support apikey credentials")
}
// B2-③ 保存期无价门禁的触发判定快照:必须在应用本次请求的变更之前采集。
prevPlatform := account.Platform
prevOutboundSet := append([]string(nil), ollamaCloudOutboundModelNames(account)...)
@@ -1018,6 +1024,22 @@ func (s *adminServiceImpl) UpdateAccountExtra(ctx context.Context, id int64, upd
return err
}
}
if _, exists := updates[OllamaCloudAllowedModelsExtraKey]; exists {
account, err := s.accountRepo.GetByID(ctx, id)
if err != nil {
return err
}
if account != nil && account.IsOllamaCloud() {
next := *account
next.Extra = mergeMap(nil, account.Extra)
for key, value := range updates {
next.Extra[key] = value
}
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, &next); err != nil {
return err
}
}
}
if len(updates) == 0 {
return nil
}
@@ -1445,6 +1467,15 @@ func (s *adminServiceImpl) RefreshAccountCredentials(ctx context.Context, id int
}
func (s *adminServiceImpl) ClearAccountError(ctx context.Context, id int64) (*Account, error) {
current, err := s.accountRepo.GetByID(ctx, id)
if err != nil {
return nil, err
}
if current != nil && current.IsOllamaCloud() && current.Schedulable && !ollamaCloudSchedulableBySave(current) {
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, current); err != nil {
return nil, err
}
}
if err := s.accountRepo.ClearError(ctx, id); err != nil {
return nil, err
}
@@ -507,6 +507,9 @@ func (f *ChannelMonitorQuotaFetcher) fetchOllamaCloudQuota(account *Account, now
if balance, ok := parseOllamaCloudBalanceUSD(snapshot.Data.Balance); ok {
out.Balance = &balance
out.Currency = "USD"
if account.GetOllamaCloudAccountMode() == AccountModeOllamaCredits {
out.BalanceLow = balance <= 0 || (f.balanceThreshold > 0 && balance < f.balanceThreshold)
}
}
return out
}
@@ -0,0 +1,377 @@
//go:build unit
package service
import (
"context"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
"github.com/stretchr/testify/require"
)
// C1:composite 账号池不改写请求体 model 时,通用链与 OpenAI 链对未识别公开别名或
// LiteLLM $0 占位条目均必须按实际转发的具体模型计费,且通配倍率卡不得误留别名。
func TestCompositePoolPublicAliasBilling_BothChainsBillConcreteModel(t *testing.T) {
catalog := `{
"gemini-flash-experimental": {"input_cost_per_token": 0.0, "output_cost_per_token": 0.0, "litellm_provider": "gemini", "mode": "chat"},
"claude-opus-5": {"input_cost_per_token": 5e-06, "output_cost_per_token": 25e-06, "litellm_provider": "anthropic", "mode": "chat"},
"gpt-5.4": {"input_cost_per_token": 2.5e-06, "output_cost_per_token": 15e-06, "litellm_provider": "openai", "mode": "chat"}
}`
cfg := &config.Config{RunMode: config.RunModeStandard}
cfg.Default.RateMultiplier = 1
bs := NewBillingService(cfg, newStubPricingServiceFromJSON(t, catalog))
groupID := int64(601)
compGroup := &Group{ID: groupID, Platform: PlatformComposite, Status: StatusActive, Hydrated: true, RateMultiplier: 1}
apiKey := &APIKey{ID: 1, GroupID: &groupID, Group: compGroup, User: &User{ID: 1}}
t.Run("generic_chain_zero_placeholder_and_family_alias_bill_concrete_opus", func(t *testing.T) {
for _, publicAlias := range []string{"gemini-flash-experimental", "haiku-pro"} {
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
svc := newGatewayRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{})
svc.billingService = bs
svc.resolver = NewModelPricingResolver(nil, bs)
err := svc.RecordUsage(context.Background(), &RecordUsageInput{
Result: &ForwardResult{
RequestID: "comp_alias_" + publicAlias,
Model: publicAlias,
UpstreamModel: "claude-opus-5",
Usage: ClaudeUsage{InputTokens: 100_000, OutputTokens: 20_000},
Duration: time.Second,
},
QuotaPlatform: PlatformAnthropic,
APIKey: apiKey,
User: apiKey.User,
Account: &Account{ID: 11, Platform: PlatformAnthropic, Type: AccountTypeAPIKey},
})
require.NoError(t, err)
require.NotNil(t, usageRepo.lastLog)
// 100k * $5e-6 + 20k * $25e-6 = $1.00
require.InDelta(t, 1.0, usageRepo.lastLog.TotalCost, 1e-9, "alias=%s must bill concrete claude-opus-5", publicAlias)
}
})
t.Run("openai_chain_requested_source_falls_back_to_concrete_model_in_composite", func(t *testing.T) {
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
oaSvc := &OpenAIGatewayService{
cfg: cfg,
usageLogRepo: usageRepo,
userRepo: &openAIRecordUsageUserRepoStub{},
billingService: bs,
resolver: NewModelPricingResolver(nil, bs),
}
err := oaSvc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
Result: &OpenAIForwardResult{
RequestID: "oa_comp_req_source",
Model: "gemini-flash-experimental",
BillingModel: "qwen3.5:397b",
UpstreamModel: "qwen3.5:397b",
Usage: OpenAIUsage{InputTokens: 100_000, OutputTokens: 10_000},
},
APIKey: apiKey,
User: apiKey.User,
Account: &Account{ID: 12, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey},
QuotaPlatform: PlatformOllamaCloud,
ChannelUsageFields: ChannelUsageFields{
OriginalModel: "gemini-flash-experimental",
ChannelMappedModel: "gemini-flash-experimental",
BillingModelSource: BillingModelSourceRequested,
},
})
require.NoError(t, err)
require.NotNil(t, usageRepo.lastLog)
// qwen3.5:397b: 100k * $0.60e-6 + 10k * $3.60e-6 = $0.096 (绝非 $0)
require.InDelta(t, 0.096, usageRepo.lastLog.TotalCost, 1e-9)
})
t.Run("hosted_model_with_wildcard_multiplier_card_keeps_upstream_price", func(t *testing.T) {
chSvc := newChannelServiceWithPricings(groupID, []ChannelModelPricing{{
Platform: PlatformOllamaCloud,
Models: []string{"*"},
BillingMode: BillingModeToken,
ReasoningEffortMultipliers: map[string]float64{"high": 1.0},
}})
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
svc := newGatewayRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{})
svc.billingService = bs
svc.channelService = chSvc
svc.resolver = NewModelPricingResolver(chSvc, bs)
err := svc.RecordUsage(context.Background(), &RecordUsageInput{
Result: &ForwardResult{
RequestID: "ollama_wildcard_card",
Model: "gpt-5.4",
UpstreamModel: "qwen3.5:397b",
Usage: ClaudeUsage{InputTokens: 100_000, OutputTokens: 10_000},
Duration: time.Second,
},
QuotaPlatform: PlatformOllamaCloud,
APIKey: apiKey,
User: apiKey.User,
Account: &Account{ID: 13, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey},
ChannelUsageFields: ChannelUsageFields{
OriginalModel: "gpt-5.4",
ChannelMappedModel: "gpt-5.4",
BillingModelSource: BillingModelSourceChannelMapped,
},
})
require.NoError(t, err)
require.InDelta(t, 0.096, usageRepo.lastLog.TotalCost, 1e-9, "hosted ollama_cloud must bill qwen3.5:397b, not gpt-5.4")
})
}
// C2:仅配倍率的通配分组/渠道卡片不得把未定价模型伪装成 $0 已定价绕过 ollama_cloud 预检。
func TestOllamaCloudPricingPreflight_WildcardMultiplierCardDoesNotBypassUnpricedModel(t *testing.T) {
const groupID = int64(602)
bs := NewBillingService(nil, nil)
chSvc := newChannelServiceWithPricings(groupID, []ChannelModelPricing{{
Platform: PlatformOllamaCloud,
Models: []string{"*"},
BillingMode: BillingModeToken,
ReasoningEffortMultipliers: map[string]float64{"high": 1.5},
}})
resolver := NewModelPricingResolver(chSvc, bs)
group := &Group{ID: groupID, Platform: PlatformOllamaCloud, Status: StatusActive, Hydrated: true}
ctx := context.WithValue(context.Background(), ctxkey.Group, group)
require.True(t, ollamaCloudModelUnpricedForBilling(ctx, resolver, "qwen3.5:32b-unpriced"),
"multiplier-only wildcard card must not make unpriced ollama model pass preflight")
require.False(t, ollamaCloudModelUnpricedForBilling(ctx, resolver, "qwen3.5:397b"),
"base-priced ollama model must still pass preflight with wildcard multiplier card")
}
// H1:extractBaseName 仅剥 Bedrock 版本号(v1:0),非 Bedrock 的 :tag 模型不得跨型号碰撞。
func TestExtractBaseName_ColonTaggedModelsNeverCollideWithBaseOrFamily(t *testing.T) {
catalog := `{
"mistral-large": {"input_cost_per_token": 2e-06, "output_cost_per_token": 6e-06, "litellm_provider": "mistral", "mode": "chat"},
"gpt-oss:120b": {"input_cost_per_token": 0.15e-06, "output_cost_per_token": 0.60e-06, "litellm_provider": "ollama", "mode": "chat"},
"gpt-4o": {"input_cost_per_token": 2.5e-06, "output_cost_per_token": 10e-06, "litellm_provider": "openai", "mode": "chat"},
"gpt-4o-mini": {"input_cost_per_token": 0.15e-06, "output_cost_per_token": 0.60e-06, "litellm_provider": "openai", "mode": "chat"},
"claude-sonnet-4-5": {"input_cost_per_token": 3e-06, "output_cost_per_token": 15e-06, "litellm_provider": "anthropic", "mode": "chat"}
}`
bs := NewBillingService(&config.Config{}, newStubPricingServiceFromJSON(t, catalog))
// 1. mistral-large-3:675b 不得被目录里的 "mistral-large" 模糊匹配抢走,必须走内置 $0.50/$1.50。
pMistral, err := bs.getModelPricingAt("mistral-large-3:675b", ollamaPricingAt)
require.NoError(t, err)
require.InDelta(t, 0.50e-6, pMistral.InputPricePerToken, 1e-12)
require.InDelta(t, 1.50e-6, pMistral.OutputPricePerToken, 1e-12)
// 2. 目录含 "gpt-oss:120b"(旧代码基名为 "gpt")时,"gpt-oss:20b" 不得撞成 120b 价,
// 未定价的 "gpt-oss:999b" 也必须报缺价而非溜过 ollama 门禁。
p20b, err := bs.getModelPricingAt("gpt-oss:20b", ollamaPricingAt)
require.NoError(t, err)
require.InDelta(t, 0.07e-6, p20b.InputPricePerToken, 1e-12)
_, err = bs.getModelPricingAt("gpt-oss:999b", ollamaPricingAt)
require.ErrorIs(t, err, ErrModelPricingUnavailable)
// 3. "gpt-4o-mini:free" 经二级确定性剥 tag 命中 "gpt-4o-mini"($0.15),而非模糊撞上 "gpt-4o"($2.50)。
pMini, err := bs.getModelPricingAt("gpt-4o-mini:free", ollamaPricingAt)
require.NoError(t, err)
require.InDelta(t, 0.15e-6, pMini.InputPricePerToken, 1e-12)
// 4. Bedrock 版本后缀(-v1:0)继续正常剥离并识别。
require.NotNil(t, bs.pricingService.GetIdentifiedModelPricing("claude-sonnet-4-5-20250929-v1:0"))
}
// H2:固定 api_protocol=responses 且配置自定义中转 base_url 时,连接测试必须打中转地址并应用映射。
func TestAccountTestService_OllamaCloudPinnedResponsesHonorsCustomRelayBaseURL(t *testing.T) {
account := ollamaCloudTestAccount(603, map[string]any{
"api_protocol": APIProtocolResponses,
"base_url": "https://relay.example.com/v1",
"model_mapping": map[string]any{"public-alias": "qwen3.5:397b"},
})
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNResponsesTestResponse())
c, _ := newTestContext()
err := svc.TestAccountConnection(c, account.ID, "public-alias", "", AccountTestModeDefault)
require.NoError(t, err)
require.Len(t, upstream.requests, 1)
require.Equal(t, "https://relay.example.com/v1/responses", upstream.requests[0].URL.String(),
"custom relay base_url must not leak credentials to official ollama.com")
require.Contains(t, string(upstream.lastBody), `"model":"qwen3.5:397b"`)
}
// H3:ollama_cloud 映射目标为空串时,调度判不支持且请求期预检显式拦截。
func TestOllamaCloudBlankMappingTarget_DeniedInSchedulingAndPreflight(t *testing.T) {
acc := &Account{
ID: 604,
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Credentials: map[string]any{
"api_key": "sk-ol",
"model_mapping": map[string]any{"*": "gpt-oss:120b", "blocked-model": " "},
},
}
require.False(t, acc.IsModelSupported("blocked-model"))
require.True(t, acc.IsModelSupported("allowed-any"))
upstream := &httpUpstreamRecorder{}
svc := newPricingPreflightTestService(upstream, 0, nil)
body := []byte(`{"model":" ","input":"hi","stream":false}`)
c, rec, ctx := pricingPreflightContext("/v1/responses", body, nil)
err := svc.enforceOllamaCloudRequestPricingPreflight(ctx, c, acc, body)
require.Error(t, err)
require.Equal(t, 400, rec.Code)
}
// H4:composite 候选池在途预留按实际候选平台解析渠道映射,不被非池平台映射误导低估。
func TestEstimateInflightReservation_CompositePoolScopesChannelMappingPerCandidate(t *testing.T) {
cfg := &config.Config{RunMode: config.RunModeStandard}
cfg.Default.RateMultiplier = 1
cfg.Billing.InflightReservation.Enabled = true
cfg.Billing.InflightReservation.DefaultMaxTokens = 1000
cfg.Billing.InflightReservation.MaxInputTokens = 10000
cfg.Billing.InflightReservation.MaxOutputTokens = 10000
catalog := `{
"claude-3-haiku": {"input_cost_per_token": 0.25e-06, "output_cost_per_token": 1.25e-06, "litellm_provider": "anthropic", "mode": "chat"},
"gpt-5.5-pro": {"input_cost_per_token": 15e-06, "output_cost_per_token": 120e-06, "litellm_provider": "openai", "mode": "chat"}
}`
billing := NewBillingService(cfg, newStubPricingServiceFromJSON(t, catalog))
groupID := int64(605)
ch := Channel{
ID: 1,
Status: StatusActive,
GroupIDs: []int64{groupID},
BillingModelSource: BillingModelSourceChannelMapped,
ModelMapping: map[string]map[string]string{
// 非池内 anthropic 平台映射到廉价模型,不得遮蔽池内 openai 账号的昂贵映射。
PlatformAnthropic: {"pro-alias": "claude-3-haiku"},
},
}
chSvc := newTestChannelService(makeStandardRepo(ch, map[int64]string{groupID: PlatformComposite}))
resolver := NewModelPricingResolver(chSvc, billing)
snap := &inflightSnapshotCacheStub{byBucket: make(map[string][]Account)}
snap.set(groupID, PlatformOpenAI, []Account{{
ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true,
Credentials: map[string]any{"api_key": "sk-oa", "model_mapping": map[string]any{"pro-alias": "gpt-5.5-pro"}},
}})
snap.set(groupID, PlatformDeepseek, []Account{{
ID: 2, Platform: PlatformDeepseek, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true,
Credentials: map[string]any{"api_key": "sk-ds", "model_mapping": map[string]any{"pro-alias": "deepseek-v4-pro"}},
}})
repo := &inflightCountingAccountRepo{}
oaSvc := &OpenAIGatewayService{
cfg: cfg,
billingService: billing,
channelService: chSvc,
resolver: resolver,
accountRepo: repo,
schedulerSnapshot: NewSchedulerSnapshotService(snap, nil, repo, nil, cfg),
}
apiKey := &APIKey{
ID: 1, UserID: 1, GroupID: &groupID,
Group: &Group{ID: groupID, Platform: PlatformComposite, RateMultiplier: 1},
User: &User{ID: 1, Balance: 100},
}
poolCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformOpenAI})
cost, ok := oaSvc.EstimateInflightReservation(poolCtx, apiKey, InflightEstimateRequest{
Model: "pro-alias",
BodyBytes: 4000, // 1000 input tokens
MaxTokens: 1000,
})
require.True(t, ok)
// gpt-5.5-pro: 1000 * $15e-6 + 1000 * $120e-6 = $0.135(远高于 claude-3-haiku 的 $0.0015)
require.InDelta(t, 0.135, cost, 1e-9)
}
// M1 + M3a + M2 + M4 + M8 + C3 防护单元测试。
func TestAuditR6_OAuthGPTOSS_TagRestriction_AdminGates_MonitorAndCyber(t *testing.T) {
// M1: OpenAI OAuth 不冒领 gpt-oss:120b,但 DetectModelPlatform 保持原契约。
require.False(t, isOpenAIOAuthServableModel("gpt-oss:120b"))
require.False(t, isOpenAIOAuthServableModel("gpt-oss-120b"))
openAIOAuth := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth}
require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(openAIOAuth, "gpt-oss:120b"))
plat, ok := DetectModelPlatform("gpt-oss:120b")
require.True(t, ok)
require.Equal(t, PlatformOpenAI, plat)
// M3a: 渠道按基础名配价并开启 RestrictModels 时,带 :tag 的同款模型放行。
groupID := int64(606)
chSvc := newTestChannelService(makeStandardRepo(Channel{
ID: 2,
Status: StatusActive,
GroupIDs: []int64{groupID},
RestrictModels: true,
ModelPricing: []ChannelModelPricing{{
Platform: PlatformOllamaCloud,
Models: []string{"deepseek-v4-flash"},
}},
}, map[int64]string{groupID: PlatformComposite}))
ctx := WithResolvedTargetPlatform(context.Background(), PlatformOllamaCloud)
require.False(t, chSvc.IsModelRestricted(ctx, groupID, "deepseek-v4-flash:0731"))
require.True(t, chSvc.IsModelRestricted(ctx, groupID, "unlisted-model:0731"))
// M2: ClearAccountError 拒绝恢复未定价的 ollama_cloud 账号,且仅允许 apikey 类型。
repo := newOllamaGateAdminRepoStub()
adminSvc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)}
erroredUnpriced := seedOllamaGateAccount(t, repo, func(a *Account) {
a.Status = StatusError
a.Schedulable = true
})
_, err := adminSvc.ClearAccountError(context.Background(), erroredUnpriced.ID)
requireModelPricingMissing(t, err)
_, err = adminSvc.CreateAccount(context.Background(), &CreateAccountInput{
Name: "bad-oauth", Platform: PlatformOllamaCloud, Type: AccountTypeOAuth,
SkipDefaultGroupBind: true,
})
require.ErrorContains(t, err, "apikey")
// C3 纵深防护:非 anthropic 且无 base_url 的 APIKey 账号绝不默认发往 api.anthropic.com。
req, _, err := (&GatewayService{}).buildUpstreamRequest(
context.Background(), nil,
&Account{ID: 99, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "sk-live"}},
[]byte(`{"model":"gpt-5.4","messages":[]}`), "sk-live", "apikey", "gpt-5.4", false, false,
)
require.Error(t, err)
require.Nil(t, req)
// M8: ollama_credits 余额为 $0.00 或负数时置 BalanceLow=true。
now := time.Now().UTC()
fetcher := &ChannelMonitorQuotaFetcher{balanceThreshold: 5.0}
creditsAcc := &Account{
ID: 77, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey,
Credentials: map[string]any{"api_key": "sk", "base_url": "https://ollama.com/v1", "account_mode": AccountModeOllamaCredits},
Extra: map[string]any{
OllamaCloudUsageSnapshotExtraKey: &OllamaCloudUsageSnapshot{
Status: OllamaCloudUsageStatusOK,
FetchedAt: &now,
Data: &OllamaCloudUsageData{Balance: "$0.00"},
},
},
}
snap := fetcher.fetchOllamaCloudQuota(creditsAcc, now)
require.True(t, snap.Success)
require.True(t, snap.BalanceLow)
// M4: RecordCyberPolicyUsageLog 解析账号级映射模型计费,而非按未定价公开别名落 $0。
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
cyberCatalog := `{"gpt-5.5-pro": {"input_cost_per_token": 15e-06, "output_cost_per_token": 120e-06, "litellm_provider": "openai", "mode": "chat"}}`
cyberBS := NewBillingService(&config.Config{}, newStubPricingServiceFromJSON(t, cyberCatalog))
oaSvc := &OpenAIGatewayService{
cfg: &config.Config{RunMode: config.RunModeStandard},
usageLogRepo: usageRepo,
userRepo: &openAIRecordUsageUserRepoStub{},
billingService: cyberBS,
resolver: NewModelPricingResolver(nil, cyberBS),
}
compGroup := &Group{ID: groupID, Platform: PlatformComposite, RateMultiplier: 1}
oaSvc.RecordCyberPolicyUsageLog(context.Background(), CyberPolicyUsageInput{
APIKey: &APIKey{ID: 1, GroupID: &groupID, Group: compGroup, User: &User{ID: 1}},
Account: &Account{ID: 88, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{"model_mapping": map[string]any{"team/coder": "gpt-5.5-pro"}}},
RequestID: "req_cyber_alias",
Model: "team/coder",
InputTokens: 10_000,
OutputTokens: 1_000,
})
require.NotNil(t, usageRepo.lastLog)
require.InDelta(t, 0.27, usageRepo.lastLog.TotalCost, 1e-9)
}
@@ -312,6 +312,8 @@ func (s *GatewayService) buildUpstreamRequestAnthropicAPIKeyPassthrough(
}
if protocolTargetURL != "" {
targetURL = protocolTargetURL
} else if account.Platform != PlatformAnthropic {
return nil, nil, fmt.Errorf("account %d (%s) has no anthropic base url and cannot default to api.anthropic.com", account.ID, account.Platform)
}
}
+19 -6
View File
@@ -234,6 +234,11 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro
if err != nil {
return nil, err
}
if derefGroupID(groupID) != origGroupID {
if upstreamModel, ok := ResolvedUpstreamModelFromContext(ctx); ok && upstreamModel != "" {
requestedModel = upstreamModel
}
}
ctx = s.withCompositePoolQuotaAutoPauseContext(ctx)
preferOAuth := platform == PlatformGemini
if s.debugModelRoutingEnabled() && requestedModel != "" && modelRoutingAppliesToTargetPlatform(platform) {
@@ -1015,7 +1020,7 @@ func (s *GatewayService) resolvePlatform(ctx context.Context, groupID *int64, gr
// 池决策写回 ctx(immutable 候选池),平台保持 composite 哨兵用于日志。
return WithCompositeRouteDecision(ctx, decision), PlatformComposite, false, nil
}
return ctx, decision.TargetPlatform, false, nil
return WithCompositeRouteDecision(ctx, decision), decision.TargetPlatform, false, nil
}
return ctx, group.Platform, false, nil
}
@@ -1036,7 +1041,7 @@ func (s *GatewayService) resolvePlatform(ctx context.Context, groupID *int64, gr
// 池决策写回 ctx(immutable 候选池),平台保持 composite 哨兵用于日志。
return WithCompositeRouteDecision(ctx, decision), PlatformComposite, false, nil
}
return ctx, decision.TargetPlatform, false, nil
return WithCompositeRouteDecision(ctx, decision), decision.TargetPlatform, false, nil
}
return ctx, group.Platform, false, nil
}
@@ -1720,11 +1725,19 @@ func (s *GatewayService) newSelectionResult(ctx context.Context, groupID *int64,
}
return nil, err
}
var effectiveGroup *Group
if ctx != nil {
if g, ok := ctx.Value(ctxkey.Group).(*Group); ok && g != nil {
effectiveGroup = g
}
}
return attachSelectionProfitGate(ctx, &AccountSelectionResult{
Account: hydrated,
Acquired: acquired,
ReleaseFunc: release,
WaitPlan: waitPlan,
Account: hydrated,
Acquired: acquired,
ReleaseFunc: release,
WaitPlan: waitPlan,
EffectiveGroup: effectiveGroup,
SelectionCtx: ctx,
}), nil
}
@@ -659,6 +659,9 @@ type AccountSelectionResult struct {
// 局部 ctx 上,handler 必须经 ContextWithSelectionProfitGate 重放后才能在
// 调度栈之外做抢槽后终检与准入后粘性绑定。
profitGate *openAIProfitControlGate
// EffectiveGroup 与 SelectionCtx 携带 ClaudeCodeOnly 降级切换后实际生效的分组与选号上下文。
EffectiveGroup *Group
SelectionCtx context.Context
}
// ProfitGateActive 报告本次选号是否处于利润门之下。
@@ -75,6 +75,8 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex
}
if protocolTargetURL != "" {
targetURL = protocolTargetURL
} else if account.Platform != PlatformAnthropic {
return nil, nil, fmt.Errorf("account %d (%s) has no anthropic base url and cannot default to api.anthropic.com", account.ID, account.Platform)
}
} else if account.IsCustomBaseURLEnabled() {
customURL := account.GetCustomBaseURL()
@@ -1073,6 +1075,9 @@ func (s *GatewayService) anthropicUpstreamTargetURL(account *Account, path strin
}
return anthropicProtocolEndpointURL(account, validatedURL, path), nil
}
if account != nil && account.Platform != PlatformAnthropic && strings.TrimSpace(account.GetCredential("base_url")) == "" {
return "", fmt.Errorf("account %d (%s) has no anthropic base url and cannot default to api.anthropic.com", account.ID, account.Platform)
}
baseURL := account.GetBaseURL()
if baseURL == "" {
return "", nil
@@ -428,6 +428,7 @@ func (s *OpenAIGatewayService) readCCUpstreamJSONResponse(
// writeOpenAIResponsesFallbackError 以 /v1/responses 回退路径的既有错误格式回写
// (裸 error 对象;不调用 MarkResponseCommitted,与原内联写法保持一致)。
func writeOpenAIResponsesFallbackError(c *gin.Context, statusCode int, errType, message string) {
MarkResponseCommitted(c)
c.JSON(statusCode, gin.H{
"error": gin.H{
"type": errType,
@@ -150,7 +150,7 @@ func prepareNativeOpenAIInputTokensCountRequest(body []byte, account *Account) (
}
func shouldEstimateOpenAIInputTokensLocally(account *Account) bool {
if account == nil || account.IsGrok() || account.RoutesProtocolByInbound() || account.Type == AccountTypeUpstream {
if account == nil || account.IsGrok() || account.IsMultiProtocolAPIKey() || account.RoutesProtocolByInbound() || account.Type == AccountTypeUpstream {
return true
}
if account.Type != AccountTypeAPIKey {
@@ -1504,6 +1504,7 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse(
// body would be unreadable to the client's SSE parser, so the error is written
// as an SSE error event instead.
func writeAnthropicError(c *gin.Context, statusCode int, errType, message string) {
MarkResponseCommitted(c)
if c.Writer.Written() && strings.HasPrefix(c.Writer.Header().Get("Content-Type"), "text/event-stream") {
if _, err := fmt.Fprint(c.Writer, buildAnthropicStreamErrorSSE(errType, message)); err == nil {
c.Writer.Flush()
@@ -31,6 +31,8 @@ func resolveOpenAIForwardModel(account *Account, requestedModel, messagesDispatc
// ResolveThinkingProtocol(thinking_protocol.go)。
var openAIOAuthForeignModelPrefixes = []string{
"claude-",
"gpt-oss:",
"gpt-oss-",
"deepseek-",
"glm-",
"kimi-",
@@ -577,6 +577,10 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability(
}
}
account, err := s.getSchedulableAccount(ctx, accountID)
if errors.Is(err, ErrAccountNotFound) {
_ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID)
return 0, nil, "", nil
}
if err != nil || account == nil {
dropTransient()
return 0, nil, "", nil
+1
View File
@@ -84,6 +84,7 @@ func writeOpenCodeUnsupportedModelError(c *gin.Context, isAnthropic bool, model
if isAnthropic {
writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", msg)
} else {
MarkResponseCommitted(c)
c.JSON(http.StatusBadRequest, gin.H{
"error": gin.H{
"type": "invalid_request_error",