fix(composite, billing): 修复跨平台账号池与 Ollama Cloud 合入后的计费、降级及路由回归

This commit is contained in:
shaw committed 2026-12-06 12:55:44 +08:00
1 parent 8cd45b9990
commit d0d143afad
23 files changed
+1141 -113

No files matched your search

@@ -57,21 +57,23 @@ func compositePoolAttemptContext(base context.Context, account *service.Account)
}
// syncSelectionEffectiveGroup 在选号发生 ClaudeCodeOnly 跨分组降级切换时,同步当前
// 调度分组、请求上下文、渠道映射与池状态(不改写最终计费归属 apiKey)。
// 调度分组、请求上下文、调度侧渠道映射、调度请求模型与池状态(不改写最终计费归属
// baseAPIKey 及其计费侧 channelMapping)。
func (h *GatewayHandler) syncSelectionEffectiveGroup(
c *gin.Context,
baseAPIKey *service.APIKey,
schedAPIKey *service.APIKey,
baseCtx context.Context,
channelMapping service.ChannelMappingResult,
schedChannelMapping service.ChannelMappingResult,
reqModel string,
schedReqModel string,
isPoolRequest bool,
poolDenials *compositePoolPlatformDenials,
selection *service.AccountSelectionResult,
) (*service.APIKey, context.Context, service.ChannelMappingResult, bool, *compositePoolPlatformDenials, bool) {
) (*service.APIKey, context.Context, service.ChannelMappingResult, string, bool, *compositePoolPlatformDenials, bool) {
if selection == nil || selection.EffectiveGroup == nil || schedAPIKey == nil ||
selection.EffectiveGroup.ID == derefGroupID(schedAPIKey.GroupID) {
return schedAPIKey, baseCtx, channelMapping, isPoolRequest, poolDenials, false
return schedAPIKey, baseCtx, schedChannelMapping, schedReqModel, isPoolRequest, poolDenials, false
}
nextKey := cloneAPIKeyWithGroup(baseAPIKey, selection.EffectiveGroup)
nextCtx := baseCtx
@@ -95,7 +97,24 @@ func (h *GatewayHandler) syncSelectionEffectiveGroup(
nextMapping = resolvedMapping
}
}
return nextKey, nextCtx, nextMapping, nextPool, newCompositePoolPlatformDenials(), true
return nextKey, nextCtx, nextMapping, nextModel, nextPool, newCompositePoolPlatformDenials(), true
}
// resolveBillingChannelMappingForAttempt 返回入账归因使用的渠道映射:
// 同分组请求沿用本次 attempt 的映射(含池平台作用域映射);ClaudeCodeOnly 跨组降级请求
// 计费始终归属 billingAPIKey(原认证分组),保持原分组的 ChannelID 与 BillingModelSource,
// 避免降级分组无渠道或绑定其它渠道时抹掉/污染计费分组的渠道归因。
func resolveBillingChannelMappingForAttempt(
billingAPIKey *service.APIKey,
schedAPIKey *service.APIKey,
billingMapping service.ChannelMappingResult,
attemptMapping service.ChannelMappingResult,
) service.ChannelMappingResult {
if billingAPIKey != nil && schedAPIKey != nil &&
derefGroupID(billingAPIKey.GroupID) != derefGroupID(schedAPIKey.GroupID) {
return billingMapping
}
return attemptMapping
}
func compositeOrPoolDispatchActive(isPoolRequest bool, schedAPIKey *service.APIKey) bool {
@@ -228,22 +247,41 @@ func evaluateCompositePoolAttemptPolicy(
requestedModel string,
requireCompact bool,
) compositePoolAttemptPolicy {
return evaluateCompositePoolAttemptPolicyForBillingGroup(
baseCtx, billing, gateway, apiKey, apiKey, subscription, account, requestedModel, requireCompact,
)
}
func evaluateCompositePoolAttemptPolicyForBillingGroup(
baseCtx context.Context,
billing *service.BillingCacheService,
gateway *service.OpenAIGatewayService,
billingAPIKey *service.APIKey,
schedAPIKey *service.APIKey,
subscription *service.UserSubscription,
account *service.Account,
requestedModel string,
requireCompact bool,
) compositePoolAttemptPolicy {
if schedAPIKey == nil {
schedAPIKey = billingAPIKey
}
result := compositePoolAttemptPolicy{AttemptCtx: baseCtx}
if baseCtx == nil || account == nil || account.Platform == "" {
return result
}
result.AttemptCtx = compositePoolAttemptContext(baseCtx, account)
result.Failure.QuotaErr = compositePoolAttemptQuotaError(billing, result.AttemptCtx, apiKey, subscription, account.Platform)
result.Failure.QuotaErr = compositePoolAttemptQuotaError(billing, result.AttemptCtx, billingAPIKey, subscription, account.Platform)
if result.Failure.QuotaErr != nil {
// 平台配额已耗尽:渠道映射仍按平台作用域解析,但请求不再外发。
if gateway != nil && apiKey != nil && apiKey.GroupID != nil {
result.Mapping = gateway.CompositePoolAttemptChannelMapping(result.AttemptCtx, apiKey.GroupID, requestedModel)
if gateway != nil && schedAPIKey != nil && schedAPIKey.GroupID != nil {
result.Mapping = gateway.CompositePoolAttemptChannelMapping(result.AttemptCtx, schedAPIKey.GroupID, requestedModel)
}
return result
}
if gateway != nil && apiKey != nil && apiKey.GroupID != nil {
result.Mapping = gateway.CompositePoolAttemptChannelMapping(result.AttemptCtx, apiKey.GroupID, requestedModel)
platformRestricted, accountRestricted := gateway.CompositePoolAttemptChannelRestriction(result.AttemptCtx, apiKey.GroupID, account, requestedModel, requireCompact)
if gateway != nil && schedAPIKey != nil && schedAPIKey.GroupID != nil {
result.Mapping = gateway.CompositePoolAttemptChannelMapping(result.AttemptCtx, schedAPIKey.GroupID, requestedModel)
platformRestricted, accountRestricted := gateway.CompositePoolAttemptChannelRestriction(result.AttemptCtx, schedAPIKey.GroupID, account, requestedModel, requireCompact)
result.Failure.ChannelRestricted = platformRestricted || accountRestricted
result.Failure.AccountChannelRestricted = accountRestricted && !platformRestricted
}
@@ -0,0 +1,295 @@
//go:build unit
package handler
import (
"context"
"io"
"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"
"github.com/tidwall/gjson"
)
// P0-2 回归(1):普通 anthropic → anthropic ClaudeCodeOnly 跨组降级时,
// 入账 UsageLog 必须保留原计费分组(G1)绑定的 ChannelID 与 BillingModelSource,
// 不得因兜底组 G2 未配置重命名映射而被擦除。
func TestClaudeCodeOnlyFallback_PreservesPrimaryGroupChannelAttribution(t *testing.T) {
gin.SetMode(gin.TestMode)
primaryID := int64(8301)
fallbackID := int64(8302)
primaryGroup := &service.Group{
ID: primaryID,
Name: "ant-primary-ch",
Platform: service.PlatformAnthropic,
Status: service.StatusActive,
Hydrated: true,
ClaudeCodeOnly: true,
FallbackGroupID: &fallbackID,
}
fallbackGroup := &service.Group{
ID: fallbackID,
Name: "ant-fallback-no-ch",
Platform: service.PlatformAnthropic,
Status: service.StatusActive,
Hydrated: true,
}
fallbackAcc := &service.Account{
ID: 8310,
Name: "ant-fb-acc",
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 2,
GroupIDs: []int64{fallbackID},
Credentials: map[string]any{
"api_key": "sk-ant-fb",
"base_url": "https://anthropic-fb.example",
"model_mapping": map[string]any{"claude-sonnet-4-5": "claude-haiku-4-5"},
},
}
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{fallbackAcc}}}
snap := service.NewSchedulerSnapshotService(schedCache, nil, nil, nil, nil)
bs := service.NewBillingService(cfg, nil)
usageRepo := &compositePoolUsageLogRepo{}
channelSvc := service.NewChannelService(&poolAttemptFakeChannelRepo{
channels: []service.Channel{{
ID: 991,
Status: service.StatusActive,
GroupIDs: []int64{primaryID},
BillingModelSource: service.BillingModelSourceRequested,
}},
platforms: map[int64]string{
primaryID: service.PlatformAnthropic,
fallbackID: service.PlatformAnthropic,
},
}, nil, nil, nil, nil)
resolver := service.NewModelPricingResolver(channelSvc, bs)
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, channelSvc, resolver, nil, nil, nil,
)
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCache.Stop)
h := &GatewayHandler{
gatewayService: gwSvc,
billingCacheService: billingCache,
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
maxAccountSwitches: 3,
cfg: cfg,
}
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")
apiKey := &service.APIKey{
ID: 1, UserID: 1, GroupID: &primaryID, Group: primaryGroup,
User: &service.User{ID: 1, Concurrency: 5},
}
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.Group, primaryGroup))
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())
logs := usageRepo.snapshot()
require.Len(t, logs, 1)
require.NotNil(t, logs[0].ChannelID, "primary billing group's ChannelID must not be wiped by fallback group")
require.EqualValues(t, 991, *logs[0].ChannelID)
require.Equal(t, "claude-sonnet-4-5", logs[0].Model, "primary group's BillingModelSource=requested must be preserved over fallback account mapping")
}
// P0-2 回归(2):ClaudeCodeOnly 降级到配置了显式 CompositeModelRoute(改写 UpstreamModel)
// 的 composite 分组时,首账号 429 后的第 2 轮选号必须按改写后的模型继续选中备号完成 failover。
func TestClaudeCodeOnlyFallback_ExplicitCompositeRouteSecondAttemptFailoverSucceeds(t *testing.T) {
gin.SetMode(gin.TestMode)
primaryID := int64(8401)
fallbackID := int64(8402)
primaryGroup := &service.Group{
ID: primaryID,
Name: "ant-primary",
Platform: service.PlatformAnthropic,
Status: service.StatusActive,
Hydrated: true,
ClaudeCodeOnly: true,
FallbackGroupID: &fallbackID,
}
fallbackGroup := &service.Group{
ID: fallbackID,
Name: "comp-explicit-route",
Platform: service.PlatformComposite,
Status: service.StatusActive,
Hydrated: true,
}
acc1 := &service.Account{
ID: 8411,
Name: "ant-acc-1-429",
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-1",
"base_url": "https://anthropic-1.example",
"model_mapping": map[string]any{"claude-haiku-4-5": "claude-haiku-4-5"},
},
}
acc2 := &service.Account{
ID: 8412,
Name: "ant-acc-2-ok",
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 2,
Priority: 2,
GroupIDs: []int64{fallbackID},
Credentials: map[string]any{
"api_key": "sk-ant-2",
"base_url": "https://anthropic-2.example",
"model_mapping": map[string]any{"claude-haiku-4-5": "claude-haiku-4-5"},
},
}
cfg := &config.Config{RunMode: config.RunModeSimple}
cfg.Security = config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}
gwUpstream := &compositePoolFakeUpstream{
respond: func(call compositePoolUpstreamCall, _ int) *http.Response {
if call.AccountID == acc1.ID {
return &http.Response{
StatusCode: http.StatusInternalServerError,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"type":"error","error":{"type":"api_error","message":"upstream 500"}}`)),
}
}
return anthropicMessagesOKResponse()
},
}
groupRepo := &multiGroupStubRepo{byID: map[int64]*service.Group{
primaryID: primaryGroup,
fallbackID: fallbackGroup,
}}
schedCache := &platformScopedSchedulerCache{fakeSchedulerCache{accounts: []*service.Account{acc1, acc2}}}
snap := service.NewSchedulerSnapshotService(schedCache, nil, nil, nil, nil)
bs := service.NewBillingService(cfg, nil)
usageRepo := &compositePoolUsageLogRepo{}
compositeResolver := service.NewCompositeRouteResolver(&compositeWSRouteRepo{routes: []service.CompositeModelRoute{{
ID: 1,
GroupID: fallbackID,
PublicModel: "claude-sonnet-4-5",
MatchType: service.CompositeRouteMatchExact,
TargetPlatform: service.PlatformAnthropic,
UpstreamModel: "claude-haiku-4-5",
Endpoint: service.CompositeRouteEndpointAny,
Enabled: true,
}}})
rateLimitSvc := service.NewRateLimitService(nil, nil, cfg, nil, nil)
gwSvc := service.NewGatewayService(
nil, groupRepo, usageRepo, nil, nil, nil, nil, nil, cfg, snap, nil, bs, rateLimitSvc, nil, nil,
gwUpstream, nil, nil, nil, nil, nil, nil, nil, nil, nil, compositeResolver, nil, nil,
)
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCache.Stop)
h := &GatewayHandler{
gatewayService: gwSvc,
billingCacheService: billingCache,
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
maxAccountSwitches: 3,
cfg: cfg,
}
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")
apiKey := &service.APIKey{
ID: 1, UserID: 1, GroupID: &primaryID, Group: primaryGroup,
User: &service.User{ID: 1, Concurrency: 5, Balance: 10},
}
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.Group, primaryGroup))
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())
calls := gwUpstream.snapshot()
require.Len(t, calls, 2, "must try acc1 (429) then fail over to acc2 using rewritten UpstreamModel")
require.Equal(t, acc1.ID, calls[0].AccountID)
require.Equal(t, acc2.ID, calls[1].AccountID)
}
// P1-5 回归:ResponsesWebSocket 在 composite 组模型解析为跨平台账号池(如 ["deepseek", "openai"]
// 或 ["grok", "openai"])时,收窄到支持 WS 的平台正常建连并保留公开模型名,不再误关 1008。
func TestOpenAIResponsesWebSocket_CompositePoolNarrowsAndConnects(t *testing.T) {
for _, candidates := range [][]string{
{service.PlatformDeepseek, service.PlatformOpenAI},
{service.PlatformGrok, service.PlatformOpenAI},
} {
t.Run(strings.Join(candidates, "+"), func(t *testing.T) {
resolver := service.NewCompositeRouteResolver(nil)
resolver.SetModelOwnershipResolver(func(context.Context, int64, string) (service.CompositeModelOwnership, error) {
return service.CompositeModelOwnership{
Matched: true,
CandidatePlatforms: candidates,
RequiredClaimStrength: service.CompositeClaimExplicit,
}, nil
})
got := runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","input":"hi"}`,
secondPayload: `{"type":"response.create","input":"again"}`,
group: compositeWSGroup("gpt-5.4"),
accountPlatform: service.PlatformOpenAI,
ingressMode: service.OpenAIWSIngressModePassthrough,
compositeResolver: resolver,
accountModelMapping: map[string]any{"gpt-5.4": "gpt-5.4"},
})
require.Len(t, got.upstreamPayloads, 2)
for i, payload := range got.upstreamPayloads {
require.Equal(t, "gpt-5.4", gjson.GetBytes(payload, "model").String())
require.Equal(t, "gpt-5.4", got.logs[i].RequestedModel)
}
})
}
}
+30 -11
View File
@@ -664,10 +664,12 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
// 与 OpenAI handler 的 allowOpenAICompatibleMessagesDispatch 同语义:openai 账号承接
// /v1/messages 受分组开关控制(grok / 多协议供应商豁免),关闭时整平台屏蔽 openai。
poolDenials.deny(service.PlatformOpenAI)
if _, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials); !ok {
maskedCtx, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials)
if !ok {
h.errorResponse(c, http.StatusForbidden, "permission_error", "This group does not allow /v1/messages dispatch")
return
}
c.Request = c.Request.WithContext(maskedCtx)
}
// 单账号分组首次 503 就不设模型限流标记,避免设 29s 限流导致后续请求连续快速失败;
@@ -699,6 +701,8 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
var lastPolicyFailure compositePoolAttemptPolicyFailure
retryWithFallback := false
schedAPIKey := currentAPIKey
schedChannelMapping := channelMapping
schedReqModel := reqModel
for {
attemptParsedReq, err := parsedReq.CloneForBody(body)
@@ -723,7 +727,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
selectCtx = maskedCtx
}
}
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, schedAPIKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, parsedReq.MetadataUserID, subject.UserID)
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, schedAPIKey.GroupID, sessionKey, schedReqModel, fs.FailedAccountIDs, parsedReq.MetadataUserID, subject.UserID)
if err != nil {
if failoverClientGone(c) {
reqLog.Info("gateway.account_select_aborted_client_disconnected", zap.Error(err))
@@ -776,9 +780,11 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.anthropicSecurityAuditError) {
return
}
prevQuotaPlatform := service.QuotaPlatform(c.Request.Context(), currentAPIKey)
var switchedGroup bool
schedAPIKey, _, channelMapping, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup(
c, currentAPIKey, schedAPIKey, c.Request.Context(), channelMapping, reqModel, isPoolRequest, poolDenials, selection)
var nextCtx context.Context
schedAPIKey, nextCtx, schedChannelMapping, schedReqModel, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup(
c, currentAPIKey, schedAPIKey, c.Request.Context(), schedChannelMapping, reqModel, schedReqModel, isPoolRequest, poolDenials, selection)
if switchedGroup && compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) {
bindOpenAIReasoningEffortPolicyForMessagesRequest(c, schedAPIKey, body)
if !schedAPIKey.Group.AllowMessagesDispatch {
@@ -793,6 +799,18 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
}
}
}
if switchedGroup && !isPoolRequest {
if nextQuotaPlatform := service.QuotaPlatform(nextCtx, currentAPIKey); nextQuotaPlatform != "" && nextQuotaPlatform != prevQuotaPlatform {
if quotaErr := compositePoolAttemptQuotaError(h.billingCacheService, nextCtx, currentAPIKey, currentSubscription, nextQuotaPlatform); quotaErr != nil {
releaseCompositePoolSelection(selection)
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey)
respondCompositePoolAttemptPolicyFailure(c, compositePoolAttemptPolicyFailure{QuotaErr: quotaErr}, func(cc *gin.Context, status int, code, message string) {
h.handleStreamingAwareError(cc, status, code, message, streamStarted)
})
return
}
}
}
setOpsSelectedAccount(c, account.ID, account.Platform)
// [DEBUG-STICKY] 打印账号选择结果
@@ -811,11 +829,11 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
// 放在槽位获取前:deny 不占并发槽。generic 循环无 previous_response_id,
// 无 pinned 分支;deny 记入 poolDenials 后按 masked 候选池整平台重选,
// 候选全部被业务限制时按原语义终止,不误报 model unsupported。
attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMapping}
attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: schedChannelMapping}
isPoolAttempt := false
if isPoolRequest && compositePoolAttemptPolicyApplies(c, schedAPIKey) {
attemptPolicy = evaluateCompositePoolAttemptPolicy(
c.Request.Context(), h.billingCacheService, h.openAIGatewayService, schedAPIKey, currentSubscription, account, reqModel, false)
attemptPolicy = evaluateCompositePoolAttemptPolicyForBillingGroup(
c.Request.Context(), h.billingCacheService, h.openAIGatewayService, currentAPIKey, schedAPIKey, currentSubscription, account, reqModel, false)
isPoolAttempt = true
if isPoolRequest && !schedAPIKey.Group.AllowMessagesDispatch && account.Platform == service.PlatformOpenAI {
attemptPolicy.Failure.MessagesDispatchForbidden = true
@@ -1018,10 +1036,11 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
// 渠道模型映射只作用于本次账号尝试,避免 failover 后污染原始 ParsedRequest。
// 池请求按选中平台的渠道映射(attempt 策略产出,platform-scoped)派生,
// 不用 composite 作用域的请求级映射(无 resolved 平台时跨平台行匹配不可靠)。
attemptChannelMapping := channelMapping
attemptChannelMapping := schedChannelMapping
if isPoolAttempt {
attemptChannelMapping = attemptPolicy.Mapping
}
billingChannelMapping := resolveBillingChannelMappingForAttempt(currentAPIKey, schedAPIKey, channelMapping, attemptChannelMapping)
if attemptChannelMapping.Mapped {
attemptParsedReq.Model = attemptChannelMapping.MappedModel
if err := attemptParsedReq.ReplaceBody(h.gatewayService.ReplaceModelInBody(attemptParsedReq.Body.Bytes(), attemptChannelMapping.MappedModel)); err != nil {
@@ -1104,7 +1123,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
accountReleaseFunc()
}
if delegated {
h.recordDelegatedCyberPolicyIfMarked(c, currentAPIKey, account, currentSubscription, reqModel, err != nil, attemptBody, clientRequestedUsageFields(c, attemptChannelMapping, reqModel, ""))
h.recordDelegatedCyberPolicyIfMarked(c, currentAPIKey, account, currentSubscription, reqModel, err != nil, attemptBody, clientRequestedUsageFields(c, billingChannelMapping, reqModel, ""))
}
// 提交 usage 记录。成功路径与"流中断但 Forward 已观测到 usage 的部分结果"
@@ -1123,7 +1142,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
QuotaPlatform: quotaPlatform,
PricingAt: pricingAt,
RequestPayloadHash: service.HashUsageRequestPayload(attemptBody),
ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, delegatedResult.UpstreamModel),
ChannelUsageFields: clientRequestedUsageFields(c, billingChannelMapping, reqModel, delegatedResult.UpstreamModel),
LogComponent: "handler.gateway.messages",
})
return
@@ -1159,7 +1178,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, currentAPIKey)
}
sessionID := service.ExtractClientSessionID(c)
channelUsageFields := clientRequestedUsageFields(c, attemptChannelMapping, reqModel, result.UpstreamModel)
channelUsageFields := clientRequestedUsageFields(c, billingChannelMapping, reqModel, result.UpstreamModel)
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
Result: result,
@@ -213,6 +213,8 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
}
var lastPolicyFailure compositePoolAttemptPolicyFailure
schedAPIKey := apiKey
schedChannelMapping := channelMapping
schedReqModel := reqModel
for {
if failoverClientGone(c) {
@@ -227,7 +229,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
selectCtx = maskedCtx
}
}
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, schedAPIKey.GroupID, selectionSessionHash, reqModel, fs.FailedAccountIDs, "", int64(0))
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, schedAPIKey.GroupID, selectionSessionHash, schedReqModel, fs.FailedAccountIDs, "", int64(0))
if err != nil {
if failoverClientGone(c) {
reqLog.Info("gateway.cc.account_select_aborted_client_disconnected", zap.Error(err))
@@ -277,12 +279,31 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
return
}
prevQuotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
var switchedGroup bool
schedAPIKey, _, channelMapping, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup(
c, apiKey, schedAPIKey, c.Request.Context(), channelMapping, reqModel, isPoolRequest, poolDenials, selection)
var nextCtx context.Context
schedAPIKey, nextCtx, schedChannelMapping, schedReqModel, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup(
c, apiKey, schedAPIKey, c.Request.Context(), schedChannelMapping, reqModel, schedReqModel, isPoolRequest, poolDenials, selection)
if switchedGroup && compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) && poolPromptCacheKey == "" && h.openAIGatewayService != nil {
poolPromptCacheKey = h.openAIGatewayService.ExtractSessionID(c, body)
}
if switchedGroup && !isPoolRequest {
if nextQuotaPlatform := service.QuotaPlatform(nextCtx, apiKey); nextQuotaPlatform != "" && nextQuotaPlatform != prevQuotaPlatform {
if quotaErr := compositePoolAttemptQuotaError(h.billingCacheService, nextCtx, apiKey, subscription, nextQuotaPlatform); quotaErr != nil {
releaseCompositePoolSelection(selection)
h.gatewayService.ReleaseAccountSession(context.Background(), account, selectionSessionHash)
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
if streamStarted {
h.handleStreamingAwareError(cc, status, code, message, true)
return
}
h.chatCompletionsErrorResponse(cc, status, code, message)
}
respondCompositePoolAttemptPolicyFailure(c, compositePoolAttemptPolicyFailure{QuotaErr: quotaErr}, streamAwareWrite)
return
}
}
}
setOpsSelectedAccount(c, account.ID, account.Platform)
// composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform
@@ -291,11 +312,11 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
// 放在槽位获取前:deny 不占并发槽。CC 循环无 previous_response_id 状态,
// 无 pinned 分支;deny 记入 poolDenials 后按 masked 候选池整平台重选,
// 候选全部被业务限制时按原语义终止,不误报 model unsupported。
attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMapping}
attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: schedChannelMapping}
isPoolAttempt := false
if isPoolRequest && compositePoolAttemptPolicyApplies(c, schedAPIKey) {
attemptPolicy = evaluateCompositePoolAttemptPolicy(
c.Request.Context(), h.billingCacheService, h.openAIGatewayService, schedAPIKey, subscription, account, reqModel, false)
attemptPolicy = evaluateCompositePoolAttemptPolicyForBillingGroup(
c.Request.Context(), h.billingCacheService, h.openAIGatewayService, apiKey, schedAPIKey, subscription, account, reqModel, false)
isPoolAttempt = true
if attemptPolicy.Failure.denied() {
releaseCompositePoolSelection(selection)
@@ -381,10 +402,11 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
writerSizeBeforeForward := c.Writer.Size()
// 渠道模型映射只作用于本次账号尝试:池请求按选中平台的渠道映射(attempt
// 策略产出,platform-scoped)派生,非池保持请求级映射语义不变。
attemptChannelMapping := channelMapping
attemptChannelMapping := schedChannelMapping
if isPoolAttempt {
attemptChannelMapping = attemptPolicy.Mapping
}
billingChannelMapping := resolveBillingChannelMappingForAttempt(apiKey, schedAPIKey, channelMapping, attemptChannelMapping)
forwardBody := body
if attemptChannelMapping.Mapped {
forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel)
@@ -396,6 +418,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
if accountReleaseFunc != nil {
accountReleaseFunc()
}
h.gatewayService.ReleaseAccountSession(context.Background(), account, selectionSessionHash)
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
if streamStarted {
h.handleStreamingAwareError(cc, status, code, message, true)
@@ -459,7 +482,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
accountReleaseFunc()
}
if delegated {
h.recordDelegatedCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, body, clientRequestedUsageFields(c, attemptChannelMapping, reqModel, ""))
h.recordDelegatedCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, body, clientRequestedUsageFields(c, billingChannelMapping, reqModel, ""))
}
// 池委派 OpenAI 网关链的结果按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。
@@ -476,7 +499,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
QuotaPlatform: quotaPlatform,
PricingAt: pricingAt,
RequestPayloadHash: service.HashUsageRequestPayload(body),
ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, delegatedResult.UpstreamModel),
ChannelUsageFields: clientRequestedUsageFields(c, billingChannelMapping, reqModel, delegatedResult.UpstreamModel),
LogComponent: "handler.gateway.chat_completions",
})
}
@@ -498,7 +521,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
}
sessionID := service.ExtractClientSessionID(c)
stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context()))
channelUsageFields := clientRequestedUsageFields(c, attemptChannelMapping, reqModel, result.UpstreamModel)
channelUsageFields := clientRequestedUsageFields(c, billingChannelMapping, reqModel, result.UpstreamModel)
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
Result: result,
@@ -226,6 +226,8 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
fs := NewFailoverState(h.maxAccountSwitches, false)
var lastPolicyFailure compositePoolAttemptPolicyFailure
schedAPIKey := apiKey
schedChannelMapping := channelMapping
schedReqModel := reqModel
for {
if failoverClientGone(c) {
@@ -240,7 +242,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
selectCtx = maskedCtx
}
}
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, schedAPIKey.GroupID, sessionHash, reqModel, fs.FailedAccountIDs, "", int64(0))
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, schedAPIKey.GroupID, sessionHash, schedReqModel, fs.FailedAccountIDs, "", int64(0))
if err != nil {
if failoverClientGone(c) {
reqLog.Info("gateway.responses.account_select_aborted_client_disconnected", zap.Error(err))
@@ -290,9 +292,10 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.responsesSecurityAuditError) {
return
}
prevQuotaPlatform := service.QuotaPlatform(requestCtx, apiKey)
var switchedGroup bool
schedAPIKey, requestCtx, channelMapping, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup(
c, apiKey, schedAPIKey, requestCtx, channelMapping, reqModel, isPoolRequest, poolDenials, selection)
schedAPIKey, requestCtx, schedChannelMapping, schedReqModel, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup(
c, apiKey, schedAPIKey, requestCtx, schedChannelMapping, reqModel, schedReqModel, isPoolRequest, poolDenials, selection)
if switchedGroup && compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) {
// 跨组降级进入 composite 组(单目标或账号池)前从未做过 previous_response_id 租户校验,
// 绝不允许把未校验的 previous_response_id 委派到共享 OpenAI 账号。
@@ -310,6 +313,23 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
}
service.SetOpenAIHTTPResponseOwner(c, subject.UserID, apiKey.ID)
}
if switchedGroup && !isPoolRequest {
if nextQuotaPlatform := service.QuotaPlatform(requestCtx, apiKey); nextQuotaPlatform != "" && nextQuotaPlatform != prevQuotaPlatform {
if quotaErr := compositePoolAttemptQuotaError(h.billingCacheService, requestCtx, apiKey, subscription, nextQuotaPlatform); quotaErr != nil {
releaseCompositePoolSelection(selection)
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionHash)
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
if streamStarted {
h.handleStreamingAwareError(cc, status, code, message, true)
return
}
h.responsesErrorResponse(cc, status, code, message)
}
respondCompositePoolAttemptPolicyFailure(c, compositePoolAttemptPolicyFailure{QuotaErr: quotaErr}, streamAwareWrite)
return
}
}
}
setOpsSelectedAccount(c, account.ID, account.Platform)
// Gemini 账号没有 Responses 转换链(generic 链只能发往 Anthropic 协议上游,会把
@@ -341,11 +361,11 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
// previous_response_id,无 pinned 分支;deny 记入 poolDenials 后按 masked
// 候选池整平台重选,候选全部被业务限制时按原语义终止,不误报 model
// unsupported。
attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: requestCtx, Mapping: channelMapping}
attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: requestCtx, Mapping: schedChannelMapping}
isPoolAttempt := false
if isPoolRequest && compositePoolAttemptPolicyApplies(c, schedAPIKey) {
attemptPolicy = evaluateCompositePoolAttemptPolicy(
requestCtx, h.billingCacheService, h.openAIGatewayService, schedAPIKey, subscription, account, reqModel, false)
attemptPolicy = evaluateCompositePoolAttemptPolicyForBillingGroup(
requestCtx, h.billingCacheService, h.openAIGatewayService, apiKey, schedAPIKey, subscription, account, reqModel, false)
isPoolAttempt = true
if attemptPolicy.Failure.denied() {
releaseCompositePoolSelection(selection)
@@ -424,10 +444,11 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
writerSizeBeforeForward := c.Writer.Size()
// 渠道模型映射只作用于本次账号尝试:池请求按选中平台的渠道映射(attempt
// 策略产出,platform-scoped)派生,非池保持请求级映射语义不变。
attemptChannelMapping := channelMapping
attemptChannelMapping := schedChannelMapping
if isPoolAttempt {
attemptChannelMapping = attemptPolicy.Mapping
}
billingChannelMapping := resolveBillingChannelMappingForAttempt(apiKey, schedAPIKey, channelMapping, attemptChannelMapping)
forwardBody := body
if attemptChannelMapping.Mapped {
forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel)
@@ -439,6 +460,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
if accountReleaseFunc != nil {
accountReleaseFunc()
}
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionHash)
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
if streamStarted {
h.handleStreamingAwareError(cc, status, code, message, true)
@@ -494,7 +516,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
accountReleaseFunc()
}
if delegated {
h.recordDelegatedCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, body, clientRequestedUsageFields(c, attemptChannelMapping, reqModel, ""))
h.recordDelegatedCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, body, clientRequestedUsageFields(c, billingChannelMapping, reqModel, ""))
}
// 池委派 OpenAI 网关链的结果按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。
@@ -511,7 +533,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
QuotaPlatform: quotaPlatform,
PricingAt: pricingAt,
RequestPayloadHash: service.HashUsageRequestPayload(body),
ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, delegatedResult.UpstreamModel),
ChannelUsageFields: clientRequestedUsageFields(c, billingChannelMapping, reqModel, delegatedResult.UpstreamModel),
LogComponent: "handler.gateway.responses",
})
}
@@ -533,7 +555,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
}
sessionID := service.ExtractClientSessionID(c)
stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context()))
channelUsageFields := clientRequestedUsageFields(c, attemptChannelMapping, reqModel, result.UpstreamModel)
channelUsageFields := clientRequestedUsageFields(c, billingChannelMapping, reqModel, result.UpstreamModel)
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
Result: result,
@@ -3066,16 +3066,41 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
return
}
if decision.Matched {
if strings.TrimSpace(decision.TargetPlatform) == "" && len(decision.CandidatePlatforms) > 0 {
wsCandidates := make([]string, 0, len(decision.CandidatePlatforms))
for _, candidate := range decision.CandidatePlatforms {
if isResponsesWebSocketCompositePlatform(candidate) {
wsCandidates = append(wsCandidates, candidate)
}
}
if len(wsCandidates) == 0 {
closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "Responses WebSocket API only supports OpenAI-compatible models for composite groups")
return
}
if len(wsCandidates) == 1 {
decision.Source = service.CompositeRouteSourceAccount
decision.TargetPlatform = wsCandidates[0]
decision.CandidatePlatforms = nil
if strings.TrimSpace(decision.UpstreamModel) == "" {
decision.UpstreamModel = decision.PublicModel
}
} else {
decision.CandidatePlatforms = wsCandidates
}
}
c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision))
wsRouteModel = decision.UpstreamModel
if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" {
wsRouteModel = upstreamModel
}
}
}
ctx = c.Request.Context()
if apiKey.Group != nil && apiKey.Group.Platform == service.PlatformComposite {
platform, ok := service.ResolvedTargetPlatformFromContext(ctx)
if !ok || !isResponsesWebSocketCompositePlatform(platform) {
closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "Responses WebSocket API only supports OpenAI-compatible models for composite groups")
return
if _, isPool := compositeAccountPoolCandidates(c); !isPool {
if platform, ok := service.ResolvedTargetPlatformFromContext(ctx); !ok || !isResponsesWebSocketCompositePlatform(platform) {
closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "Responses WebSocket API only supports OpenAI-compatible models for composite groups")
return
}
}
}
previousResponseID := strings.TrimSpace(gjson.GetBytes(firstMessage, "previous_response_id").String())
@@ -3134,6 +3159,9 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
// 解析渠道级模型映射
channelMappingWS, _ := h.gatewayService.ResolveChannelMappingAndRestrict(ctx, apiKey.GroupID, wsRouteModel)
if compositePoolAttemptPolicyApplies(c, apiKey) {
channelMappingWS = service.ChannelMappingResult{MappedModel: wsRouteModel}
}
wsForwardModel := openAIChannelForwardModel(channelMappingWS, wsRouteModel)
var currentUserRelease func()
@@ -3210,11 +3238,11 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
// after acquiring turn slots, including the first account-selection wait.
// Restrict this extra check to the opt-in mode so standard-mode RPM checks
// are not charged a second time for the same request.
checkSimpleModeTurnBilling := func() error {
checkSimpleModeTurnBilling := func(turnBillingCtx context.Context) error {
if h.cfg == nil || h.cfg.RunMode != config.RunModeSimple || !h.cfg.SimpleModeKeyRateLimitEnabled {
return nil
}
if err := h.billingCacheService.CheckBillingEligibility(ctx, apiKey.User, apiKey, apiKey.Group, subscription, service.QuotaPlatform(ctx, apiKey)); err != nil {
if err := h.billingCacheService.CheckBillingEligibility(turnBillingCtx, apiKey.User, apiKey, apiKey.Group, subscription, service.QuotaPlatform(turnBillingCtx, apiKey)); err != nil {
return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "billing check failed", err)
}
return nil
@@ -3308,6 +3336,8 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
// 建连时刻只用于选号/准入,不作为任何 turn 的计费定价时刻。
wsPricingCtx, _ := h.gatewayService.WithOpenAIRequestPricingContext(ctx, apiKey.GroupID)
ctx = wsPricingCtx
wsPoolDenials := newCompositePoolPlatformDenials()
wsSelectionCtx := ctx
for {
if ctx.Err() != nil {
@@ -3320,7 +3350,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
schedulePreviousResponseCanMove := previousResponseCanMove && !strictPreviousResponseAffinity
reqLog.Debug("openai.websocket_account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs)))
selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability(
ctx,
wsSelectionCtx,
apiKey.GroupID,
previousResponseID,
sessionHash,
@@ -3355,6 +3385,30 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
}
account := selection.Account
wsAttemptCtx := ctx
if compositePoolAttemptPolicyApplies(c, apiKey) {
attemptPolicyWS := evaluateCompositePoolAttemptPolicy(
ctx, h.billingCacheService, h.gatewayService, apiKey, subscription, account, wsRouteModel, false)
wsAttemptCtx = attemptPolicyWS.AttemptCtx
if attemptPolicyWS.Failure.denied() {
releaseCompositePoolSelection(selection)
if attemptPolicyWS.Failure.deniesPlatform() {
wsPoolDenials.deny(account.Platform)
}
failedAccountIDs[account.ID] = struct{}{}
retryCtx, ok := compositePoolSelectionRetryContext(ctx, wsPoolDenials)
if !ok {
if attemptPolicyWS.Failure.QuotaErr != nil {
closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "billing check failed")
} else {
closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "no available account")
}
return
}
wsSelectionCtx = retryCtx
continue
}
}
if strictPreviousResponseAffinity && !scheduleDecision.StickyPreviousHit {
if selection.ReleaseFunc != nil {
selection.ReleaseFunc()
@@ -3504,7 +3558,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
// 已打开的连接生效。
var turnBillingAPIKeys openAIWSTurnBillingAPIKeys
// Passthrough ingress does not invoke BeforeTurn for the first frame.
if err := checkSimpleModeTurnBilling(); err != nil {
if err := checkSimpleModeTurnBilling(wsAttemptCtx); err != nil {
closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "billing check failed")
return
}
@@ -3578,7 +3632,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
}
routeModel = wsRouteModel
}
mapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(ctx, apiKey.GroupID, routeModel)
mapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(wsAttemptCtx, apiKey.GroupID, routeModel)
mappedModelUnchanged := false
if previous := turnChannelMapping.Load(); previous != nil && previous.turn < turn {
mappedModelUnchanged = strings.TrimSpace(previous.mapping.MappedModel) == strings.TrimSpace(mapping.MappedModel)
@@ -3597,7 +3651,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
// 长连接跨峰谷/倍率刷新防护:每个 turn 按当前时刻重装门并复核
// 当前账号,越线即要求客户端重连重选(连接绑定单一上游账号,
// 无法中途换号)。本 turn 的准入与计费共用同一 pricingAt。
turnBillingCtx := turnBillingAPIKeys.begin(ctx, h.apiKeyService, turn, apiKey)
turnBillingCtx := turnBillingAPIKeys.begin(wsAttemptCtx, h.apiKeyService, turn, apiKey)
turnCtx, turnAt := h.gatewayService.WithOpenAITurnPricingContext(turnBillingCtx, apiKey.GroupID)
if _, vetoed, reason := h.gatewayService.ProfitControlVetoLatest(turnCtx, account); vetoed {
reqLog.Info("openai.websocket_turn_profit_vetoed",
@@ -3635,7 +3689,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
}
currentUserRelease = wrapReleaseOnDone(ctx, userReleaseFunc)
currentAccountRelease = wrapReleaseOnDone(ctx, accountReleaseFunc)
return checkSimpleModeTurnBilling()
return checkSimpleModeTurnBilling(wsAttemptCtx)
},
AfterTurn: func(turn int, result *service.OpenAIForwardResult, turnErr error) {
turnStart := getTurnStart(turn)
@@ -3711,7 +3765,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
h.gatewayService.ReportOpenAIAccountScheduleResult(account, scheduleModel, openAIForwardSucceededForScheduling(result), result.FirstTokenMs)
inboundEndpoint := GetInboundEndpoint(c)
upstreamEndpoint := resolveOpenAIUpstreamEndpoint(c, account, result)
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
quotaPlatform := service.QuotaPlatform(wsAttemptCtx, apiKey)
sessionID := service.ExtractClientSessionID(c)
turnRecordPricingAt := turnPricing.currentOr(turnStart)
turnBillingAPIKey := turnBillingAPIKeys.forTurn(turn, apiKey)
@@ -3749,13 +3803,13 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
// WebSocket 首包可能很大,hash 必须在 hooks 外算成字符串,避免 AfterTurn 闭包保活请求体。
requestPayloadHash = service.HashUsageRequestPayload(wsFirstMessage)
if preemptCtx, cleanupPreempt, armed := h.gatewayService.BeginOpenAIWSIngressSessionPreemptionWithClient(ctx, c, account, wsFirstMessage, wsConn); armed {
ctx = preemptCtx
if preemptCtx, cleanupPreempt, armed := h.gatewayService.BeginOpenAIWSIngressSessionPreemptionWithClient(wsAttemptCtx, c, account, wsFirstMessage, wsConn); armed {
wsAttemptCtx = preemptCtx
defer cleanupPreempt()
}
for {
err := h.gatewayService.ProxyResponsesWebSocketFromClient(ctx, c, wsConn, account, token, wsFirstMessage, hooks)
err := h.gatewayService.ProxyResponsesWebSocketFromClient(wsAttemptCtx, c, wsConn, account, token, wsFirstMessage, hooks)
if err == nil {
reqLog.Info("openai.websocket_ingress_closed", zap.Int64("account_id", account.ID))
return
+11 -3
View File
@@ -3239,7 +3239,15 @@ func (r *accountRepository) BulkUpdate(ctx context.Context, ids []int64, updates
return 0, err
}
credentialPlaceholder = "$" + itoa(idx)
setClauses = append(setClauses, "credentials = COALESCE(credentials, '{}'::jsonb) || "+credentialPlaceholder+"::jsonb")
credExpr := "COALESCE(credentials, '{}'::jsonb) || " + credentialPlaceholder + "::jsonb"
if rawBase, hasBase := updates.Credentials["base_url"].(string); hasBase && strings.TrimSpace(rawBase) != "" {
if _, hasAPIBaseURLs := updates.Credentials["api_base_urls"]; !hasAPIBaseURLs {
baseExpr := "btrim(" + credentialPlaceholder + "::jsonb ->> 'base_url')"
anthropicBaseExpr := "COALESCE(NULLIF(regexp_replace(" + baseExpr + ", '/v1/?$', ''), ''), " + baseExpr + ")"
credExpr = "CASE WHEN platform = 'ollama_cloud' AND jsonb_typeof(credentials -> 'api_base_urls') = 'object' THEN (" + credExpr + ") || jsonb_build_object('api_base_urls', jsonb_build_object('chat_completions', " + baseExpr + ", 'responses', " + baseExpr + ", 'anthropic', " + anthropicBaseExpr + ")) ELSE " + credExpr + " END"
}
}
setClauses = append(setClauses, "credentials = "+credExpr)
args = append(args, payload)
idx++
}
@@ -3250,8 +3258,8 @@ func (r *accountRepository) BulkUpdate(ctx context.Context, ids []int64, updates
}
if _, ok := updates.Credentials["base_url"]; ok {
ollamaGroupIdentityChanges = append(ollamaGroupIdentityChanges,
"NOT ("+ollamaCloudBaseURLMatchesSQL("credentials ->> 'base_url'")+
" AND "+ollamaCloudBaseURLMatchesSQL(credentialPlaceholder+"::jsonb ->> 'base_url'")+")")
"COALESCE(NOT ("+ollamaCloudBaseURLMatchesSQL("credentials ->> 'base_url'")+
" AND "+ollamaCloudBaseURLMatchesSQL(credentialPlaceholder+"::jsonb ->> 'base_url'")+"), true)")
}
// OpenCode Go 身份清理与 Ollama 同范式但更精确:仅当旧行按新谓词属于 OpenCode
@@ -348,6 +348,36 @@ func TestOllamaCloudUsagePlatformWhitelistMatchesServicePredicate(t *testing.T)
}
}
func TestBulkUpdateOllamaBaseURLNullSafeAndSyncsAPIBaseURLs(t *testing.T) {
t.Run("null_base_url_uses_coalesce_null_safe_cleanup", func(t *testing.T) {
exec := &recordingSQLExecutor{result: rowsAffectedResult(1)}
repo := newAccountRepositoryWithSQL(nil, exec, nil)
_, err := repo.BulkUpdate(context.Background(), []int64{17}, service.AccountBulkUpdate{
Credentials: map[string]any{"base_url": nil},
})
require.NoError(t, err)
require.NotEmpty(t, exec.execQueries)
query := normalizeSQLWhitespace(exec.execQueries[0])
require.Contains(t, query, "COALESCE(NOT ("+ollamaCloudBaseURLMatchesSQL("credentials ->> 'base_url'"))
require.Contains(t, query, "), true)")
})
t.Run("non_empty_base_url_syncs_existing_ollama_cloud_api_base_urls_per_row", func(t *testing.T) {
exec := &recordingSQLExecutor{result: rowsAffectedResult(2)}
repo := newAccountRepositoryWithSQL(nil, exec, nil)
_, err := repo.BulkUpdate(context.Background(), []int64{17, 18}, service.AccountBulkUpdate{
Credentials: map[string]any{"base_url": "https://relay.example.com/v1"},
})
require.NoError(t, err)
require.NotEmpty(t, exec.execQueries)
query := normalizeSQLWhitespace(exec.execQueries[0])
require.Contains(t, query, "WHEN platform = 'ollama_cloud' AND jsonb_typeof(credentials -> 'api_base_urls') = 'object'")
require.Contains(t, query, "jsonb_build_object('api_base_urls'")
})
}
// TestOllamaCloudUsagePlatformsMirror 锁定 SQL 平台白名单由 service 权威列表
// (OllamaCloudUsagePlatforms,含 ollama_cloud 本体)派生这一事实:字面量可
// 完整解析、成员一致、eligible 拼接结果包含全部平台项。若有人把派生改回手工
@@ -427,6 +427,60 @@ func TestCompositeLiveRouteDispatchesBySessionModelNotTopLevelAlias(t *testing.T
require.Equal(t, http.StatusNoContent, w.Code)
}
func TestCompositeGeminiTargetPlatformMiddlewareIgnoresForeignWildcardAndNarrowsAntigravityPool(t *testing.T) {
gin.SetMode(gin.TestMode)
runCase := func(t *testing.T, ownership service.CompositeModelOwnership, wantPlatform string) {
t.Helper()
resolver := service.NewCompositeRouteResolver(nil)
resolver.SetModelOwnershipResolver(func(context.Context, int64, string) (service.CompositeModelOwnership, error) {
return ownership, nil
})
router := gin.New()
router.Use(gin.HandlerFunc(servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) {
groupID := int64(1)
c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{
GroupID: &groupID,
Group: &service.Group{ID: groupID, Platform: service.PlatformComposite},
})
c.Next()
})))
router.Use(compositeGeminiTargetPlatformMiddleware(resolver))
router.POST("/v1beta/models/*modelAction", func(c *gin.Context) {
platform, ok := service.ResolvedTargetPlatformFromContext(c.Request.Context())
require.True(t, ok)
require.Equal(t, wantPlatform, platform)
if source, hasSource := service.CompositeRouteSourceFromContext(c.Request.Context()); hasSource {
require.Equal(t, service.CompositeRouteSourceAccount, source,
"pool narrowed to single target must downgrade source to account_model so claim tier stays enforced")
}
c.Status(http.StatusNoContent)
})
req := httptest.NewRequest(http.MethodPost, "/v1beta/models/gemini-2.5-pro:generateContent", strings.NewReader(`{"contents":[]}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
require.Equal(t, http.StatusNoContent, w.Code)
}
t.Run("foreign_wildcard_does_not_override_gemini_v1beta_default", func(t *testing.T) {
runCase(t, service.CompositeModelOwnership{
Matched: true,
TargetPlatform: service.PlatformDeepseek,
RequiredClaimStrength: service.CompositeClaimWildcard,
}, service.PlatformGemini)
})
t.Run("antigravity_plus_openai_pool_narrows_to_antigravity", func(t *testing.T) {
runCase(t, service.CompositeModelOwnership{
Matched: true,
CandidatePlatforms: []string{service.PlatformAntigravity, service.PlatformOpenAI},
RequiredClaimStrength: service.CompositeClaimExplicit,
}, service.PlatformAntigravity)
})
}
// A route that rewrites the model to a Claude 5.5 model also rewrites a
// thinking mode that model rejects into the nearest one it accepts; a route
// that keeps the client's model leaves thinking as the client sent it.
+42 -1
View File
@@ -767,7 +767,9 @@ func compositeGeminiTargetPlatformMiddleware(resolver *service.CompositeRouteRes
return
}
if decision.Matched {
c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision))
if narrowed, ok := narrowCompositeDecisionForGeminiEndpoint(decision); ok {
c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), narrowed))
}
}
}
if _, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context()); !resolved {
@@ -778,6 +780,45 @@ func compositeGeminiTargetPlatformMiddleware(resolver *service.CompositeRouteRes
}
}
// narrowCompositeDecisionForGeminiEndpoint 约束 /v1beta/* 上的非显式路由归属决策:
// 显式路由与内置 detector 原样保留;账号映射/账号池仅保留可承接 Gemini v1beta 的平台
// (gemini / antigravity),避免外平台 "*" 通配把 /v1beta 钉死到不兼容平台报 400,
// 也使 ["antigravity", "openai"] 池收窄到 antigravity 单目标继续服务。
func narrowCompositeDecisionForGeminiEndpoint(decision service.CompositeRouteDecision) (service.CompositeRouteDecision, bool) {
if decision.Source != service.CompositeRouteSourceAccount && decision.Source != service.CompositeRouteSourceAccountPool {
return decision, true
}
isGeminiCapable := func(platform string) bool {
return platform == service.PlatformGemini || platform == service.PlatformAntigravity
}
if target := strings.TrimSpace(decision.TargetPlatform); target != "" {
if !isGeminiCapable(target) {
return service.CompositeRouteDecision{}, false
}
return decision, true
}
narrowed := make([]string, 0, len(decision.CandidatePlatforms))
for _, p := range decision.CandidatePlatforms {
if isGeminiCapable(p) {
narrowed = append(narrowed, p)
}
}
if len(narrowed) == 0 {
return service.CompositeRouteDecision{}, false
}
decision.Source = service.CompositeRouteSourceAccount
if len(narrowed) == 1 {
decision.TargetPlatform = narrowed[0]
} else {
decision.TargetPlatform = service.PlatformGemini
}
decision.CandidatePlatforms = nil
if strings.TrimSpace(decision.UpstreamModel) == "" {
decision.UpstreamModel = decision.PublicModel
}
return decision, true
}
// grokCustomVoiceEndpoint derives the upstream Voice endpoint for the
// /custom-voices/:voice_id[/audio] routes.
//
+17 -6
View File
@@ -1677,16 +1677,27 @@ func (s *BillingService) CacheStoragePricePerTokenHour(model string) float64 {
// 兜底:剥掉 tag 的名字(如 gpt-oss:latest → gpt-oss)会被家族/OpenAI 末端
// catch-all 猜成无关模型的价格,并让计费门禁误判为已定价。
func (s *BillingService) getModelPricingAt(model string, pricingAt time.Time) (*ModelPricing, error) {
pricing, err := s.getModelPricingAtOnce(model, pricingAt, false)
if err == nil {
return pricing, nil
}
if stripped, ok := normalizePricingModelNameForLookup(model); ok {
if retry, retryErr := s.getModelPricingAtOnce(stripped, pricingAt, true); retryErr == nil {
// 带 ":tag" 模型:先做字面确定性识别(保证 "foo:0" 与 bedrock "...-v1:0" 优先于剥后名),
// 再做剥 ":tag" 正价确定性识别(防止第一轮家族/OpenAI catch-all 在生产目录含 gpt-5.4 时把
// "gpt-4o-mini:free" / "claude-haiku-4-5:latest" 短路成错价,同时避免目录中的 $0 家族基名占位
// 遮蔽 "gpt-oss:120b-cloud" 的内置正价),最后回退字面完整链。
if pricing, err := s.getModelPricingAtOnce(model, pricingAt, true); err == nil {
return pricing, nil
}
retry, retryErr := s.getModelPricingAtOnce(stripped, pricingAt, true)
if retryErr == nil && (retry.InputPricePerToken > 0 || retry.OutputPricePerToken > 0) {
return retry, nil
}
if pricing, err := s.getModelPricingAtOnce(model, pricingAt, false); err == nil {
return pricing, nil
}
if retryErr == nil {
return retry, nil
}
return nil, ErrModelPricingUnavailable
}
return nil, err
return s.getModelPricingAtOnce(model, pricingAt, false)
}
// getModelPricingAtOnce 跑一遍查找链;identifiedOnly 时只接受确定性命中。
@@ -3,10 +3,33 @@ package service
import (
"context"
"strings"
"sync/atomic"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
"github.com/Wei-Shaw/sub2api/internal/pkg/xai"
)
type cachedGrokNativeMapping struct {
defaultText string
mapping map[string]string
}
var grokCompositeNativeMappingCache atomic.Value
func grokNativeDefaultModelMapping() map[string]string {
opts := xai.RuntimeModelMappingOptions()
opts.EnableCrossClientMap = false
if cached, ok := grokCompositeNativeMappingCache.Load().(cachedGrokNativeMapping); ok && cached.defaultText == opts.DefaultText {
return cached.mapping
}
built := xai.ModelMappingWithOptions(opts)
grokCompositeNativeMappingCache.Store(cachedGrokNativeMapping{
defaultText: opts.DefaultText,
mapping: built,
})
return built
}
// CompositeClaimStrength 表达账号对某模型的声明强度。ownership 据此分层:
// 存在强声明平台时池/单平台仅由强声明平台构成,完全无强声明才回退通配命中
// 平台集合,避免 catch-all 通配账号与显式声明平台混池(如 grok 精确别名被
@@ -51,6 +74,16 @@ func CompositeAccountClaimStrength(account *Account, model string) CompositeClai
// 「anthropic + 混合调度 antigravity」会被静默改成账号池,antigravity 按自身
// 平台计配额,绕过 anthropic 配额。
mapping = stringMappingFromRaw(account.Credentials["model_mapping"])
} else if account.Platform == PlatformGrok {
// grok 空 mapping 时保留原生 Grok 模型目录,但剔除全局 grok_cross_client_model_map_enabled
// 默认开启所注入的跨客户端桥接通配(gpt-* / claude-* / codex-* / o1* / o3* / o4*):
// 避免空映射 grok 账号在 composite 组内劫持混合调度 Antigravity 或故障期 Claude/GPT 流量。
// 管理员在账号 credentials.model_mapping 上显式配置的通配仍原样保留。
if raw := stringMappingFromRaw(account.Credentials["model_mapping"]); len(raw) > 0 {
mapping = raw
} else {
mapping = grokNativeDefaultModelMapping()
}
}
if len(mapping) == 0 {
if account.IsOllamaCloud() {
@@ -0,0 +1,329 @@
//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/Wei-Shaw/sub2api/internal/pkg/xai"
"github.com/stretchr/testify/require"
)
// P0-1 回归:非 composite 的国产/OpenCode/Ollama 分组(及无具体回退模型的账号)
// 配置带显式单价的 "*" 通配卡片时,claude-* 请求必须按该显式单价入账,不得静默归零。
func TestHostedModels_WildcardExplicitRateCardBillsExplicitRateNotZero(t *testing.T) {
catalog := `{
"claude-sonnet-4-5": {"input_cost_per_token": 3e-06, "output_cost_per_token": 15e-06, "litellm_provider": "anthropic", "mode": "chat"},
"qwen3.5:397b": {"input_cost_per_token": 0.60e-06, "output_cost_per_token": 3.60e-06, "litellm_provider": "ollama", "mode": "chat"}
}`
cfg := &config.Config{RunMode: config.RunModeStandard}
cfg.Default.RateMultiplier = 1
bs := NewBillingService(cfg, newStubPricingServiceFromJSON(t, catalog))
t.Run("non_composite_zhipu_per_request_wildcard_bills_per_request_rate", func(t *testing.T) {
groupID := int64(9601)
perReq := 0.05
group := &Group{
ID: groupID,
Platform: PlatformZhipu,
Status: StatusActive,
Hydrated: true,
RateMultiplier: 1,
ModelPricing: []ChannelModelPricing{{
Models: []string{"*"},
BillingMode: BillingModePerRequest,
PerRequestPrice: &perReq,
}},
}
apiKey := &APIKey{ID: 1, GroupID: &groupID, Group: group, User: &User{ID: 1}}
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: "zhipu_wildcard_per_req",
Model: "claude-sonnet-4-5",
BillingModel: "claude-sonnet-4-5",
UpstreamModel: "claude-sonnet-4-5",
Usage: OpenAIUsage{InputTokens: 10_000, OutputTokens: 2_000},
},
APIKey: apiKey,
User: apiKey.User,
Account: &Account{ID: 21, Platform: PlatformZhipu, Type: AccountTypeAPIKey},
QuotaPlatform: PlatformZhipu,
})
require.NoError(t, err)
require.NotNil(t, usageRepo.lastLog)
require.InDelta(t, 0.05, usageRepo.lastLog.TotalCost, 1e-9, "explicit '*' per-request rate must not drop to $0")
})
t.Run("ollama_cloud_explicit_token_wildcard_passes_preflight_and_bills", func(t *testing.T) {
groupID := int64(9602)
inRate := 1e-6
outRate := 4e-6
group := &Group{
ID: groupID,
Platform: PlatformOllamaCloud,
Status: StatusActive,
Hydrated: true,
RateMultiplier: 1,
ModelPricing: []ChannelModelPricing{{
Models: []string{"*"},
BillingMode: BillingModeToken,
InputPrice: &inRate,
OutputPrice: &outRate,
}},
}
resolver := NewModelPricingResolver(nil, bs)
ctx := context.WithValue(context.Background(), ctxkey.Group, group)
require.False(t, ollamaCloudModelUnpricedForBilling(ctx, resolver, "claude-sonnet-4-5"),
"explicit token rate on '*' card must pass preflight")
apiKey := &APIKey{ID: 2, GroupID: &groupID, Group: group, User: &User{ID: 1}}
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
svc := newGatewayRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{})
svc.billingService = bs
svc.resolver = resolver
err := svc.RecordUsage(ctx, &RecordUsageInput{
Result: &ForwardResult{
RequestID: "ollama_wildcard_token_rate",
Model: "claude-sonnet-4-5",
UpstreamModel: "claude-sonnet-4-5",
Usage: ClaudeUsage{InputTokens: 100_000, OutputTokens: 10_000},
Duration: time.Second,
},
QuotaPlatform: PlatformOllamaCloud,
APIKey: apiKey,
User: apiKey.User,
Account: &Account{ID: 22, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey},
})
require.NoError(t, err)
require.NotNil(t, usageRepo.lastLog)
require.InDelta(t, 0.14, usageRepo.lastLog.TotalCost, 1e-9, "100k*$1e-6 + 10k*$4e-6 = $0.14")
})
t.Run("composite_alias_still_prefers_concrete_model_card_over_wildcard_card", func(t *testing.T) {
groupID := int64(9603)
compGroup := &Group{ID: groupID, Platform: PlatformComposite, Status: StatusActive, Hydrated: true, RateMultiplier: 1}
specificIn, specificOut := 0.5e-6, 2.0e-6
wildIn, wildOut := 5.0e-6, 15.0e-6
ch := Channel{
ID: 9610,
Status: StatusActive,
GroupIDs: []int64{groupID},
ModelPricing: []ChannelModelPricing{
{Platform: PlatformOllamaCloud, Models: []string{"qwen3.5:397b"}, BillingMode: BillingModeToken, InputPrice: &specificIn, OutputPrice: &specificOut},
{Platform: PlatformOllamaCloud, Models: []string{"*"}, BillingMode: BillingModeToken, InputPrice: &wildIn, OutputPrice: &wildOut},
},
}
chSvc := &ChannelService{}
chSvc.cache.Store(populateChannelCache([]Channel{ch}, map[int64]string{groupID: PlatformComposite}))
resolver := NewModelPricingResolver(chSvc, bs)
apiKey := &APIKey{ID: 3, GroupID: &groupID, Group: compGroup, User: &User{ID: 1}}
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
oaSvc := &OpenAIGatewayService{
cfg: cfg,
usageLogRepo: usageRepo,
userRepo: &openAIRecordUsageUserRepoStub{},
billingService: bs,
channelService: chSvc,
resolver: resolver,
}
err := oaSvc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
Result: &OpenAIForwardResult{
RequestID: "comp_concrete_wins",
Model: "claude-sonnet-4-5",
BillingModel: "qwen3.5:397b",
UpstreamModel: "qwen3.5:397b",
Usage: OpenAIUsage{InputTokens: 100_000, OutputTokens: 10_000},
},
APIKey: apiKey,
User: apiKey.User,
Account: &Account{ID: 23, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey},
QuotaPlatform: PlatformOllamaCloud,
ChannelUsageFields: ChannelUsageFields{
OriginalModel: "claude-sonnet-4-5",
ChannelMappedModel: "claude-sonnet-4-5",
BillingModelSource: BillingModelSourceRequested,
},
})
require.NoError(t, err)
require.InDelta(t, 0.07, usageRepo.lastLog.TotalCost, 1e-9, "concrete qwen3.5:397b card ($0.07) must win over '*' ($0.65)")
})
}
// P0-4 回归:生产目录始终含 DefaultTestModel("gpt-5.4") 与家族兜底模型,
// 带 ":tag" 的模型必须先命中剥 tag 确定性基础价,不得被第一轮模糊/catch-all 短路。
func TestGetModelPricing_ColonTaggedModelsNotShortCircuitedByProductionCatalog(t *testing.T) {
catalog := `{
"gpt-5.4": {"input_cost_per_token": 2.5e-06, "output_cost_per_token": 15e-06, "litellm_provider": "openai", "mode": "chat"},
"gpt-4.1": {"input_cost_per_token": 2.0e-06, "output_cost_per_token": 8.0e-06, "litellm_provider": "openai", "mode": "chat"},
"gpt-4.1-nano": {"input_cost_per_token": 0.10e-06, "output_cost_per_token": 0.40e-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-haiku-4-5": {"input_cost_per_token": 1.0e-06, "output_cost_per_token": 5.0e-06, "litellm_provider": "anthropic", "mode": "chat"},
"claude-3-haiku-20240307": {"input_cost_per_token": 0.25e-06, "output_cost_per_token": 1.25e-06, "litellm_provider": "anthropic", "mode": "chat"}
}`
bs := NewBillingService(&config.Config{}, newStubPricingServiceFromJSON(t, catalog))
pMini, err := bs.getModelPricingAt("gpt-4o-mini:free", ollamaPricingAt)
require.NoError(t, err)
require.InDelta(t, 0.15e-6, pMini.InputPricePerToken, 1e-12, "must hit gpt-4o-mini, not gpt-5.4 catch-all")
require.InDelta(t, 0.60e-6, pMini.OutputPricePerToken, 1e-12)
pNano, err := bs.getModelPricingAt("gpt-4.1-nano:latest", ollamaPricingAt)
require.NoError(t, err)
require.InDelta(t, 0.10e-6, pNano.InputPricePerToken, 1e-12, "must hit gpt-4.1-nano, not gpt-4.1")
pHaiku, err := bs.getModelPricingAt("claude-haiku-4-5:latest", ollamaPricingAt)
require.NoError(t, err)
require.InDelta(t, 1.0e-6, pHaiku.InputPricePerToken, 1e-12, "must hit claude-haiku-4-5, not claude-3-haiku family fallback")
_, err = bs.getModelPricingAt("gpt-j:6b", ollamaPricingAt)
require.ErrorIs(t, err, ErrModelPricingUnavailable, "unpriced tagged gpt-* must fail closed, not bill at gpt-5.4")
// 二轮回归:即便动态价格表包含 $0 的家族基名占位(如本地 ollama 的 "gpt-oss": $0),
// "gpt-oss:120b-cloud" 仍须命中内置 $0.15/$0.60 正价,不得被剥 tag 二级 $0 占位遮蔽。
zeroBaseCatalog := `{
"gpt-oss": {"input_cost_per_token": 0.0, "output_cost_per_token": 0.0, "litellm_provider": "ollama", "mode": "chat"}
}`
bsZeroBase := NewBillingService(&config.Config{}, newStubPricingServiceFromJSON(t, zeroBaseCatalog))
pCloud, err := bsZeroBase.getModelPricingAt("gpt-oss:120b-cloud", ollamaPricingAt)
require.NoError(t, err)
require.InDelta(t, 0.15e-6, pCloud.InputPricePerToken, 1e-12, "$0 base placeholder must not shadow gpt-oss:120b-cloud fallback")
}
// P0-3 回归:生产环境默认开启 grok_cross_client_model_map_enabled=true 时,空映射 Grok
// 账号不得在 composite 组内把跨端桥接通配(gpt-* / claude-*)当作归属声明。
func TestCompositeGrokRuntimeCrossClientDefaultDoesNotHijackClaudeOrGPT(t *testing.T) {
prevOpts := xai.RuntimeModelMappingOptions()
t.Cleanup(func() { xai.SetRuntimeModelMappingOptions(prevOpts) })
xai.SetRuntimeModelMappingOptions(xai.ModelMappingOptions{
DefaultText: "grok-4.6",
EnableCrossClientMap: true,
})
unmappedGrok := Account{ID: 1, Platform: PlatformGrok, Type: AccountTypeAPIKey}
mixedAntigravity := Account{ID: 2, Platform: PlatformAntigravity, Type: AccountTypeOAuth, Extra: map[string]any{"mixed_scheduling": true}}
require.Equal(t, CompositeClaimExplicit, CompositeAccountClaimStrength(&unmappedGrok, "grok-4.3"))
require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(&unmappedGrok, "claude-sonnet-4-5"))
require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(&unmappedGrok, "gpt-5.4"))
const groupID = int64(9611)
resolver, _ := newOllamaOwnershipResolver(
compositeOwnershipScopedRecord{groupID: groupID, platform: PlatformGrok, schedulable: true, account: unmappedGrok},
compositeOwnershipScopedRecord{groupID: groupID, platform: PlatformAntigravity, schedulable: true, account: mixedAntigravity},
)
decision, err := resolver.Resolve(context.Background(), groupID, "claude-sonnet-4-5", CompositeRouteEndpointMessages)
require.NoError(t, err)
require.True(t, decision.Matched)
require.Equal(t, PlatformAnthropic, decision.TargetPlatform, "must fall through to detector->anthropic for mixed antigravity, never hijacked by unmapped grok")
explicitWildcardGrok := Account{
ID: 3,
Platform: PlatformGrok,
Type: AccountTypeAPIKey,
Credentials: map[string]any{"model_mapping": map[string]any{"gpt-*": "grok-4.6"}},
}
require.Equal(t, CompositeClaimWildcard, CompositeAccountClaimStrength(&explicitWildcardGrok, "gpt-5.4"),
"admin-configured explicit wildcard on Grok account must still be respected")
}
// P1-6 / P1-7 / 后缀归一回归:
// 1) 池临时限流诊断按候选平台集合查询,不因组内无关平台账号误报 404 model_not_found;
// 2) OpenAI OAuth 透传账号在池内不劫持自定义公开别名;
// 3) OpenAI 族池 /v1/messages 剥离推理后缀后仍能命中账号级公开模型声明。
func TestCompositePool_DiagnosisAndOAuthPassthroughAndReasoningSuffix(t *testing.T) {
groupID := int64(9620)
resetAt := time.Now().Add(45 * time.Second)
zhipuAcc := Account{
ID: 9621,
Platform: PlatformZhipu,
Type: AccountTypeAPIKey,
Status: StatusActive,
Schedulable: true,
GroupIDs: []int64{groupID},
RateLimitResetAt: &resetAt,
Credentials: map[string]any{"model_mapping": map[string]any{"glm-5.3": "glm-5.3", "gpt-5.4-high": "glm-5.3"}},
}
ollamaAcc := Account{
ID: 9622,
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Status: StatusActive,
Schedulable: true,
GroupIDs: []int64{groupID},
RateLimitResetAt: &resetAt,
Credentials: map[string]any{"model_mapping": map[string]any{"glm-5.3": "glm-5.3"}},
}
unrelatedOpenAIOAuth := Account{
ID: 9623,
Platform: PlatformOpenAI,
Type: AccountTypeOAuth,
Status: StatusActive,
Schedulable: true,
GroupIDs: []int64{groupID},
}
scopedRepo := &compositeOwnershipScopedRepo{records: []compositeOwnershipScopedRecord{
{groupID: groupID, platform: PlatformZhipu, schedulable: true, account: zhipuAcc},
{groupID: groupID, platform: PlatformOllamaCloud, schedulable: true, account: ollamaAcc},
{groupID: groupID, platform: PlatformOpenAI, schedulable: true, account: unrelatedOpenAIOAuth},
}}
poolCtx := WithCompositeRouteDecision(context.Background(), CompositeRouteDecision{
Matched: true,
Source: CompositeRouteSourceAccountPool,
GroupID: groupID,
PublicModel: "glm-5.3",
CandidatePlatforms: []string{PlatformOllamaCloud, PlatformZhipu},
RequiredClaimStrength: CompositeClaimExplicit,
})
oaSvc := &OpenAIGatewayService{accountRepo: scopedRepo, cfg: &config.Config{}}
oaDiag := oaSvc.DiagnoseModelAvailabilityForPlatform(poolCtx, &groupID, "glm-5.3", PlatformOpenAI)
require.True(t, oaDiag.HasAccountsInPool)
require.True(t, oaDiag.HasModelSupport, "transiently rate-limited pool must NOT diagnose HasModelSupport=false via unrelated openai OAuth account")
require.Greater(t, oaDiag.RetryAfterSeconds, 0)
gwSvc := &GatewayService{accountRepo: scopedRepo, cfg: &config.Config{}}
gwDiag := gwSvc.DiagnoseModelAvailabilityForPlatform(poolCtx, &groupID, "glm-5.3", PlatformComposite)
require.True(t, gwDiag.HasAccountsInPool)
require.True(t, gwDiag.HasModelSupport)
require.Greater(t, gwDiag.RetryAfterSeconds, 0)
aliasPoolCtx := WithCompositeRouteDecision(context.Background(), CompositeRouteDecision{
Matched: true,
Source: CompositeRouteSourceAccountPool,
GroupID: groupID,
PublicModel: "team-sonnet",
CandidatePlatforms: []string{PlatformOpenAI, PlatformZhipu},
RequiredClaimStrength: CompositeClaimExplicit,
})
oauthPassthrough := &Account{
ID: 9624,
Platform: PlatformOpenAI,
Type: AccountTypeOAuth,
Extra: map[string]any{"openai_oauth_passthrough": true},
}
require.False(t, openAISchedulingModelSupported(aliasPoolCtx, oauthPassthrough, "team-sonnet", false))
require.False(t, gwSvc.gatewaySchedulingModelSupported(aliasPoolCtx, oauthPassthrough, "team-sonnet"))
suffixPoolCtx := WithCompositeRouteDecision(context.Background(), CompositeRouteDecision{
Matched: true,
Source: CompositeRouteSourceAccountPool,
GroupID: groupID,
PublicModel: "gpt-5.4-high",
CandidatePlatforms: []string{PlatformOpenAI, PlatformZhipu},
RequiredClaimStrength: CompositeClaimExplicit,
})
require.True(t, openAISchedulingModelSupported(suffixPoolCtx, &zhipuAcc, "gpt-5.4", false),
"Messages suffix-normalized routingModel ('gpt-5.4') must still match public claim 'gpt-5.4-high'")
}
@@ -68,7 +68,8 @@ func (s *GatewayService) DiagnoseModelAvailabilityForPlatform(
// No model specified — cannot decide model_not_found. Caller falls back to 503.
return ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true}
}
if strings.TrimSpace(platform) == "" {
poolActive := GenericCompositePoolActive(ctx)
if !poolActive && strings.TrimSpace(platform) == "" {
// Without a platform we cannot scope the lookup; bail out to the
// 503 branch rather than make an unscoped scan.
return ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true}
@@ -78,10 +79,21 @@ func (s *GatewayService) DiagnoseModelAvailabilityForPlatform(
return ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true}
}
useMixed := platform == PlatformAnthropic || platform == PlatformGemini
platforms := []string{platform}
if useMixed {
platforms = append(platforms, PlatformAntigravity)
useMixed := false
var platforms []string
cachePlatform := platform
if poolActive {
platforms = activeCompositePoolPlatformsForDiagnosis(ctx)
if len(platforms) == 0 {
return ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true}
}
cachePlatform = "pool:" + strings.Join(platforms, ",")
} else {
useMixed = platform == PlatformAnthropic || platform == PlatformGemini
platforms = []string{platform}
if useMixed {
platforms = append(platforms, PlatformAntigravity)
}
}
queryGroupID := groupID
@@ -98,7 +110,7 @@ func (s *GatewayService) DiagnoseModelAvailabilityForPlatform(
}
key := modelAvailabilityDiagnosisCacheKey{
platform: platform,
platform: cachePlatform,
model: requestedModel,
noGroup: queryGroupID == nil,
grouped: includeGrouped,
@@ -126,8 +138,17 @@ func (s *GatewayService) DiagnoseModelAvailabilityForPlatform(
if useMixed && accounts[i].Platform == PlatformAntigravity && !accounts[i].IsMixedSchedulingEnabled() {
continue
}
if poolActive && !genericCompositePoolAccountServable(&accounts[i]) {
continue
}
diag.HasAccountsInPool = true
if s.isModelSupportedByAccountWithContext(ctx, &accounts[i], requestedModel) {
supported := false
if poolActive {
supported = s.gatewaySchedulingModelSupported(ctx, &accounts[i], requestedModel)
} else {
supported = s.isModelSupportedByAccountWithContext(ctx, &accounts[i], requestedModel)
}
if supported {
diag.HasModelSupport = true
if remaining := accountCooldownRemaining(ctx, &accounts[i], requestedModel); remaining > 0 {
if earliestRecovery == 0 || remaining < earliestRecovery {
@@ -1305,8 +1305,12 @@ func (s *GatewayService) gatewaySchedulingModelSupported(ctx context.Context, ac
return true
}
if GenericCompositePoolActive(ctx) {
passthroughUnfiltered := account.IsOpenAIPassthroughEnabled() && !account.IsOpenAIPassthroughModelFilterEnabled()
if !CompositeAccountMeetsClaimTier(ctx, account, requestedModel) && !passthroughUnfiltered {
claimModel := requestedModel
if publicModel, ok := RequestedPublicModelFromContext(ctx); ok && publicModel != "" {
claimModel = publicModel
}
passthroughUnfiltered := account.IsOpenAIPassthroughEnabled() && !account.IsOpenAIPassthroughModelFilterEnabled() && !account.IsOpenAIOAuthLike()
if !CompositeAccountMeetsClaimTier(ctx, account, claimModel) && !passthroughUnfiltered {
return false
}
}
@@ -987,11 +987,12 @@ func (s *GatewayService) recordUsageBillingModel(ctx context.Context, apiKey *AP
billingModel = s.billableModelWithFallback(ctx, apiKey, billingModel, result.UpstreamModel, result.Model)
if hostedModels {
// 与 OpenAI 链 filterCNProviderBillingModelCandidates 一致:claude-* 名不会被
// 托管上游真正服务,未显式定价时不得按 Claude 价计费;候选全部落空则走零成本告警。
// 托管上游真正服务,未显式配置分组/渠道单价(含带单价的 "*" 卡,排除纯倍率卡)时
// 不得落入全局 Claude 价卡;候选全部落空则走零成本告警。
billingModel = firstUsageBillingModel(dropUnpricedClaudeBillingCandidates(
usageBillingModelCandidates(billingModel, concreteBillingModel),
func(model string) bool {
return compositeAliasHasExplicitChannelPrice(s.resolveChannelPricing(ctx, model, apiKey), model)
return hasExplicitChannelOrGroupRate(s.resolveChannelPricing(ctx, model, apiKey))
},
))
}
@@ -1170,17 +1171,24 @@ func channelModelPricingHasExplicitRate(chPricing *ChannelModelPricing) bool {
return false
}
// hasExplicitChannelOrGroupRate 判断解析到的定价是否来自显式填写了单价(含按次价与区间单价、
// 排除纯倍率卡)的分组或渠道定价卡。用于托管模型上游对 claude-* 的门禁:只要分组/渠道显式给了
// 单价(包括带单价的 "*" 统一计价卡),计费就走该卡而不会落入全局 Claude 目录价。
func hasExplicitChannelOrGroupRate(resolved *ResolvedPricing) bool {
if resolved == nil || (resolved.Source != PricingSourceGroup && resolved.Source != PricingSourceChannel) {
return false
}
return channelModelPricingHasExplicitRate(resolved.channelPricing)
}
// compositeAliasHasExplicitChannelPrice 判断公开别名是否具备针对该模型显式配置的渠道/分组定价
// (排除裸 "*" 全局通配卡片与无单价的纯倍率卡片,避免 "*" 卡片把别名误留作计费模型)。
// 与 lookupChannelPricingNormalized 对齐:同时支持字面名、Codex 归一化名与剥 ":tag" 名。
func compositeAliasHasExplicitChannelPrice(resolved *ResolvedPricing, model string) bool {
if resolved == nil || (resolved.Source != PricingSourceGroup && resolved.Source != PricingSourceChannel) {
if !hasExplicitChannelOrGroupRate(resolved) {
return false
}
chPricing := resolved.channelPricing
if !channelModelPricingHasExplicitRate(chPricing) {
return false
}
targets := make([]string, 0, 3)
appendTarget := func(name string) {
normalized := normalizeChannelPricingModelName(name)
@@ -7,6 +7,7 @@ import (
"sync"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
"golang.org/x/sync/singleflight"
)
@@ -166,9 +167,28 @@ func modelAvailabilityDiagnosisContextKey(ctx context.Context) string {
_, _ = b.WriteString(";public_model=")
_, _ = b.WriteString(model)
}
if required, ok := ctx.Value(ctxkey.CompositeRequiredClaimStrength).(CompositeClaimStrength); ok {
_, _ = b.WriteString(";claim_tier=")
_, _ = b.WriteString(strconv.Itoa(int(required)))
}
if enabled, ok := ThinkingEnabledFromContext(ctx); ok {
_, _ = b.WriteString(";thinking=")
_, _ = b.WriteString(strconv.FormatBool(enabled))
}
return b.String()
}
func activeCompositePoolPlatformsForDiagnosis(ctx context.Context) []string {
candidates := CompositeCandidatePlatformsFromContext(ctx)
if len(candidates) == 0 {
return nil
}
out := make([]string, 0, len(candidates))
for _, platform := range candidates {
if compositePoolPlatformDenied(ctx, platform) {
continue
}
out = append(out, platform)
}
return out
}
@@ -2610,6 +2610,9 @@ func (s *OpenAIGatewayService) isOpenAIAccountTransportCompatible(account *Accou
return false
}
if requiredTransport == OpenAIUpstreamTransportResponsesWebsocketV2Ingress {
if account.Platform == PlatformGrok {
return true
}
if s.cfg == nil || !s.cfg.Gateway.OpenAIWS.ModeRouterV2Enabled {
return s.getOpenAIWSProtocolResolver().Resolve(account).Transport == OpenAIUpstreamTransportResponsesWebsocketV2
}
@@ -33,7 +33,19 @@ func (s *OpenAIGatewayService) DiagnoseModelAvailabilityForPlatform(
return ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true}
}
platform = NormalizeOpenAICompatiblePlatform(platform)
poolActive := openAICompositePoolActive(ctx)
var platforms []string
cachePlatform := NormalizeOpenAICompatiblePlatform(platform)
if poolActive {
platforms = activeCompositePoolPlatformsForDiagnosis(ctx)
if len(platforms) == 0 {
return ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true}
}
cachePlatform = "pool:" + strings.Join(platforms, ",")
} else {
platforms = []string{cachePlatform}
}
queryGroupID := groupID
includeGrouped := false
if s.cfg.UsesSharedSimpleModePool() {
@@ -41,10 +53,11 @@ func (s *OpenAIGatewayService) DiagnoseModelAvailabilityForPlatform(
includeGrouped = true
}
key := modelAvailabilityDiagnosisCacheKey{
platform: platform,
model: requestedModel,
noGroup: queryGroupID == nil,
grouped: includeGrouped,
platform: cachePlatform,
model: requestedModel,
noGroup: queryGroupID == nil,
grouped: includeGrouped,
contextKey: modelAvailabilityDiagnosisContextKey(ctx),
}
if queryGroupID != nil {
key.groupID = *queryGroupID
@@ -53,7 +66,7 @@ func (s *OpenAIGatewayService) DiagnoseModelAvailabilityForPlatform(
accounts, err := s.accountRepo.ListModelAvailabilityCandidates(
ctx,
queryGroupID,
[]string{platform},
platforms,
includeGrouped,
)
if err != nil {
@@ -75,11 +88,13 @@ func (s *OpenAIGatewayService) DiagnoseModelAvailabilityForPlatform(
if isRetiredOpenAISubscriptionModel(&accounts[i], resolveOpenAIAccountUpstreamModelForRequest(&accounts[i], requestedModel, false)) {
diag.HasRetiredSubscriptionModel = true
}
// Mirrors the per-candidate filter used during account selection
// (openai_account_scheduler.isAccountRequestCompatible): empty
// model_mapping accepts everything; otherwise the explicit / wildcard
// mapping must match.
if accounts[i].IsModelSupported(requestedModel) {
supported := false
if poolActive {
supported = openAISchedulingModelSupported(ctx, &accounts[i], requestedModel, false)
} else {
supported = accounts[i].IsModelSupported(requestedModel)
}
if supported {
diag.HasModelSupport = true
if remaining := accountCooldownRemaining(ctx, &accounts[i], requestedModel); remaining > 0 {
if earliestRecovery == 0 || remaining < earliestRecovery {
@@ -188,10 +188,9 @@ func ollamaCloudModelUnpricedForBilling(ctx context.Context, resolver *ModelPric
return true
}
// 与 RecordUsage 的 dropUnpricedClaudeBillingCandidates 对齐:ollama_cloud 上游不按全局
// Claude 价卡对 claude-* 出站名计费,仅针对该模型显式配置分组/渠道单价卡时放行
// (排除裸 "*" 通配卡与纯倍率卡,保证预检与通用链/OpenAI 链计费口径完全一致)。
// Claude 价卡对 claude-* 出站名计费,仅分组/渠道显式配置了单价卡(排除纯倍率卡)时放行。
if strings.Contains(strings.ToLower(strings.TrimSpace(model)), "claude") &&
!compositeAliasHasExplicitChannelPrice(resolved, model) {
!hasExplicitChannelOrGroupRate(resolved) {
return true
}
// 与 CalculateCostUnified 的模式分发一致:按次/图片/视频模式由
@@ -371,12 +371,19 @@ func openAISchedulingModelSupported(ctx context.Context, account *Account, reque
if account == nil || requestedModel == "" {
return true
}
claimModel := requestedModel
if openAICompositePoolActive(ctx) {
passthroughUnfiltered := account.IsOpenAIPassthroughEnabled() && !account.IsOpenAIPassthroughModelFilterEnabled()
if !CompositeAccountMeetsClaimTier(ctx, account, requestedModel) && !passthroughUnfiltered {
if publicModel, ok := RequestedPublicModelFromContext(ctx); ok && publicModel != "" {
claimModel = publicModel
}
passthroughUnfiltered := account.IsOpenAIPassthroughEnabled() && !account.IsOpenAIPassthroughModelFilterEnabled() && !account.IsOpenAIOAuthLike()
if !CompositeAccountMeetsClaimTier(ctx, account, claimModel) && !passthroughUnfiltered {
return false
}
}
if claimModel != requestedModel && supportsOpenAIRequestModel(account, claimModel, requireCompact) {
return true
}
return supportsOpenAIRequestModel(account, requestedModel, requireCompact)
}
@@ -1071,7 +1071,7 @@ func (s *OpenAIGatewayService) filterCNProviderBillingModelCandidates(ctx contex
return candidates
}
return dropUnpricedClaudeBillingCandidates(candidates, func(model string) bool {
return compositeAliasHasExplicitChannelPrice(s.resolveOpenAIChannelPricing(ctx, model, apiKey), model)
return hasExplicitChannelOrGroupRate(s.resolveOpenAIChannelPricing(ctx, model, apiKey))
})
}
+7 -13
View File
@@ -1309,14 +1309,13 @@ func (s *PricingService) GetModelPricing(modelName string) *LiteLLMModelPricing
}
// 5. OpenAI 模型回退策略
// gpt-oss:<tag> 是开放权重模型(ollama cloud 等托管),不属于 OpenAI 模型家族:
// 不进本回退链 —— 否则 matchOpenAIModel 的末端 catch-all 会把它落到
// DefaultTestModel("gpt-5.4") 的价卡($2.5/$15 per MTok)上静默误计。
// 返回 nil 交还 BillingService 走 fallbackPrices 的 ollama 专属价卡。
// 排除收窄到带 ":tag" 的 gpt-oss 系列(ollama 命名形态,含 gpt-oss-safeguard:20b
// 等变体);无 tag 的连字符形态如 Antigravity 的 "gpt-oss-120b-medium" 不在排除内,
// 保持进 OpenAI 链的既有行为。
if strings.HasPrefix(lookupCandidates[0], "gpt-") && !isTaggedGPTOSSModel(lookupCandidates[0]) {
// 带 ":tag" 的名字(如 gpt-oss:<tag>、gpt-j:6b 等 Ollama/OpenRouter 变体)不属于官方
// OpenAI API 模型命名:不进本回退链 —— 否则 matchOpenAIModel 的末端 catch-all 会把未定价的
// 带 tag 模型落到 DefaultTestModel("gpt-5.4") 的价卡($2.5/$15 per MTok)上静默误计并绕过
// ollama_cloud 无价门禁;合法基础模型带 ":tag"(如 gpt-5.4:latest、gpt-4o-mini:free)已在
// BillingService 剥 tag 二级确定性查价中命中。无 tag 的连字符形态如 Antigravity 的
// "gpt-oss-120b-medium" 不在排除内,保持进 OpenAI 链的既有行为。
if strings.HasPrefix(lookupCandidates[0], "gpt-") && !strings.Contains(lookupCandidates[0], ":") {
return s.matchOpenAIModel(lookupCandidates[0])
}
@@ -1924,8 +1923,3 @@ func isNumeric(s string) bool {
}
return true
}
// isTaggedGPTOSSModel 报告模型名是否为带 ":tag" 的 gpt-oss 开放权重模型(ollama 命名)。
func isTaggedGPTOSSModel(model string) bool {
return strings.HasPrefix(model, "gpt-oss") && strings.Contains(model, ":")
}