mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-11-30 23:39:10 +00:00
fix(groups): merge main and resolve model allowlist conflicts
Resolve three conflicts from main's #6680 (supplementUnmappedOpenAIModels): 1. gateway_handler.go — keep PR's allowlist refactoring (ModelAllowlistEnabled, writeAllowlistedModelsList, modelListingSource); main's OpenAI branch in writeModelsList was auto-merged. 2. group_models_list.go (modify/delete) — delete file per PR intent; relocate supplementUnmappedOpenAIModels to group_model_allowlist.go where gateway_service and openai_codex_models_service can still call it. 3. openai_codex_models_service.go — combine main's supplementUnmappedOpenAIModels wrapping with PR's ModelAllowlistEnabled() guard. Also fix two auto-merged test files that still referenced the old GroupModelsListConfig / ModelsListConfig types.
This commit is contained in:
commit
2031c1d5ad
92 files changed
+3056
-299
No files matched your search
@@ -1840,9 +1840,10 @@ func (a *Account) SupportsOpenAIEndpointCapability(capability OpenAIEndpointCapa
|
||||
}
|
||||
|
||||
// GrokMediaGenerationEligibility reports whether a Grok account may receive
|
||||
// new image/video generation requests. OAuth media fails closed unless billing
|
||||
// observations provide positive paid-entitlement evidence. An explicit
|
||||
// operator override takes precedence over probe data.
|
||||
// new image/video generation requests. Explicit evidence of a forbidden or
|
||||
// free account blocks media, while an incomplete successful billing response
|
||||
// remains eligible for backwards compatibility. An explicit operator
|
||||
// override takes precedence over probe data.
|
||||
func (a *Account) GrokMediaGenerationEligibility() (bool, string) {
|
||||
if a == nil || !a.IsGrok() {
|
||||
return false, "not_grok"
|
||||
@@ -1868,7 +1869,12 @@ func (a *Account) GrokMediaGenerationEligibility() (bool, string) {
|
||||
return false, "billing_free_tier"
|
||||
}
|
||||
if !grokBillingHasAuthoritativeQuota(billing) {
|
||||
return false, "billing_inconclusive"
|
||||
// Billing endpoints can return 200 with an account-specific schema that
|
||||
// omits plan/quota fields (for example, some SuperGrok accounts). An
|
||||
// incomplete observation is not proof of ineligibility; keep the account
|
||||
// routable and expose the reason for diagnostics. Operators can still
|
||||
// quarantine a known-bad account with grok_media_eligible=false.
|
||||
return true, "billing_inconclusive"
|
||||
}
|
||||
return true, "eligible"
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ func TestGrokMediaGenerationEligibility(t *testing.T) {
|
||||
{name: "non grok account", account: &Account{Platform: PlatformOpenAI}, want: false, wantReason: "not_grok"},
|
||||
{name: "non oauth grok account stays eligible", account: &Account{Platform: PlatformGrok, Type: AccountTypeAPIKey}, want: true, wantReason: "non_oauth"},
|
||||
{name: "unobserved oauth fails closed", account: &Account{Platform: PlatformGrok, Type: AccountTypeOAuth}, want: false, wantReason: "billing_unobserved"},
|
||||
{name: "inconclusive successful billing remains eligible", account: &Account{Platform: PlatformGrok, Type: AccountTypeOAuth, Extra: map[string]any{grokBillingExtraKey: &xai.BillingSummary{StatusCode: http.StatusOK, Partial: true}}}, want: true, wantReason: "billing_inconclusive"},
|
||||
{name: "weekly paid usage is eligible without inferring from period type", account: &Account{Platform: PlatformGrok, Type: AccountTypeOAuth, Extra: map[string]any{grokBillingExtraKey: weeklyAllowance}}, want: true, wantReason: "eligible"},
|
||||
{name: "billing forbidden is rejected", account: &Account{Platform: PlatformGrok, Type: AccountTypeOAuth, Extra: map[string]any{grokBillingExtraKey: forbiddenBilling}}, want: false, wantReason: "billing_forbidden"},
|
||||
{name: "weekly billing forbidden is rejected after partial success", account: &Account{Platform: PlatformGrok, Type: AccountTypeOAuth, Extra: map[string]any{grokBillingExtraKey: weeklyForbidden}}, want: false, wantReason: "billing_forbidden"},
|
||||
@@ -65,7 +66,7 @@ func TestGrokMediaGenerationEligibility(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGrokMediaCapabilityKeepsOnlyUnobservedOAuthAsProbeCandidate(t *testing.T) {
|
||||
func TestGrokMediaCapabilityKeepsUnobservedAndInconclusiveOAuthAsCandidates(t *testing.T) {
|
||||
unobserved := &Account{Platform: PlatformGrok, Type: AccountTypeOAuth}
|
||||
eligible, reason := unobserved.GrokMediaGenerationEligibility()
|
||||
require.False(t, eligible)
|
||||
@@ -80,7 +81,10 @@ func TestGrokMediaCapabilityKeepsOnlyUnobservedOAuthAsProbeCandidate(t *testing.
|
||||
Partial: true,
|
||||
}},
|
||||
}
|
||||
require.False(t, inconclusive.SupportsOpenAIEndpointCapability(OpenAIEndpointCapabilityGrokMediaGeneration))
|
||||
eligible, reason = inconclusive.GrokMediaGenerationEligibility()
|
||||
require.True(t, eligible)
|
||||
require.Equal(t, "billing_inconclusive", reason)
|
||||
require.True(t, inconclusive.SupportsOpenAIEndpointCapability(OpenAIEndpointCapabilityGrokMediaGeneration))
|
||||
}
|
||||
|
||||
func TestGrokMediaCapabilityFiltersOnlyGeneration(t *testing.T) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// resolveAccountStatsCost 计算账号统计定价费用。
|
||||
@@ -17,6 +18,7 @@ import (
|
||||
// upstreamModel 是最终发往上游的模型 ID。
|
||||
// totalCost 是本次请求的客户计费(倍率前),用于优先级 2。
|
||||
// serviceTier 是最终参与用户计费的 OpenAI 服务层级,用于优先级 3。
|
||||
// pricingAt 与本次客户计费使用同一时刻,避免跨峰谷请求的成本与售价错位。
|
||||
// reasoningEffort 是最终转发等级;Fable 5.1 max 默认按 3 倍额度消耗。
|
||||
func resolveAccountStatsCost(
|
||||
ctx context.Context,
|
||||
@@ -29,6 +31,7 @@ func resolveAccountStatsCost(
|
||||
requestCount int,
|
||||
totalCost float64,
|
||||
serviceTier string,
|
||||
pricingAt time.Time,
|
||||
reasoningEfforts ...string,
|
||||
) *float64 {
|
||||
reasoningEffort := ""
|
||||
@@ -61,7 +64,7 @@ func resolveAccountStatsCost(
|
||||
|
||||
// 优先级 3:模型定价文件(LiteLLM)默认价格
|
||||
if billingService != nil {
|
||||
return tryModelFilePricing(billingService, upstreamModel, tokens, serviceTier, reasoningEffort)
|
||||
return tryModelFilePricing(billingService, upstreamModel, tokens, serviceTier, pricingAt, reasoningEffort)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -69,20 +72,26 @@ func resolveAccountStatsCost(
|
||||
|
||||
// tryModelFilePricing 使用模型定价文件(LiteLLM/fallback)中的价格计算费用。
|
||||
// 与用户计费共用同一条定价管线,避免这里维护第二份"单价 × token 数"实现后,
|
||||
// 每加一个定价特性都要手工镜像一次。channelPricing 为 nil,保持优先级 3 的
|
||||
// 语义:只取模型定价文件,不引入渠道自定义定价。
|
||||
func tryModelFilePricing(billingService *BillingService, model string, tokens UsageTokens, serviceTier string, reasoningEfforts ...string) *float64 {
|
||||
// 每加一个定价特性都要手工镜像一次。解析器不配置渠道或分组,保持优先级 3 的
|
||||
// 语义:只取模型定价文件,不引入自定义售价。
|
||||
func tryModelFilePricing(billingService *BillingService, model string, tokens UsageTokens, serviceTier string, pricingAt time.Time, reasoningEfforts ...string) *float64 {
|
||||
reasoningEffort := ""
|
||||
if len(reasoningEfforts) > 0 {
|
||||
reasoningEffort = reasoningEfforts[0]
|
||||
}
|
||||
breakdown, err := billingService.CalculateCostWithServiceTier(
|
||||
model, tokens, 1, normalizeBillingServiceTier(serviceTier),
|
||||
)
|
||||
breakdown, err := billingService.CalculateCostUnified(CostInput{
|
||||
Ctx: context.Background(),
|
||||
Model: model,
|
||||
Tokens: tokens,
|
||||
RateMultiplier: 1,
|
||||
ServiceTier: normalizeBillingServiceTier(serviceTier),
|
||||
ReasoningEffort: reasoningEffort,
|
||||
PricingAt: pricingAt,
|
||||
Resolver: NewModelPricingResolver(nil, billingService),
|
||||
})
|
||||
if err != nil || breakdown == nil || breakdown.TotalCost <= 0 {
|
||||
return nil
|
||||
}
|
||||
applyCostBreakdownMultiplier(breakdown, maxReasoningEffortBillingMultiplier(model, reasoningEffort, nil))
|
||||
return &breakdown.TotalCost
|
||||
}
|
||||
|
||||
@@ -253,6 +262,7 @@ func applyAccountStatsCost(
|
||||
upstreamModel, requestedModel string,
|
||||
tokens UsageTokens,
|
||||
totalCost float64,
|
||||
pricingAt time.Time,
|
||||
) {
|
||||
model := upstreamModel
|
||||
if model == "" {
|
||||
@@ -271,6 +281,6 @@ func applyAccountStatsCost(
|
||||
reasoningEffort = *usageLog.ReasoningEffort
|
||||
}
|
||||
usageLog.AccountStatsCost = resolveAccountStatsCost(
|
||||
ctx, cs, bs, accountID, groupID, model, tokens, requestCount, totalCost, serviceTier, reasoningEffort,
|
||||
ctx, cs, bs, accountID, groupID, model, tokens, requestCount, totalCost, serviceTier, pricingAt, reasoningEffort,
|
||||
)
|
||||
}
|
||||
@@ -472,7 +472,7 @@ func TestTryModelFilePricing_Success(t *testing.T) {
|
||||
},
|
||||
})
|
||||
tokens := UsageTokens{InputTokens: 100, OutputTokens: 50}
|
||||
result := tryModelFilePricing(bs, "claude-sonnet-4", tokens, "")
|
||||
result := tryModelFilePricing(bs, "claude-sonnet-4", tokens, "", time.Time{})
|
||||
require.NotNil(t, result)
|
||||
// 100*0.001 + 50*0.002 = 0.1 + 0.1 = 0.2
|
||||
require.InDelta(t, 0.2, *result, 1e-12)
|
||||
@@ -483,8 +483,8 @@ func TestTryModelFilePricing_Fable51MaxEffortUsesTripleQuota(t *testing.T) {
|
||||
"claude-fable-5-1": {InputPricePerToken: 0.001},
|
||||
})
|
||||
tokens := UsageTokens{InputTokens: 100}
|
||||
standard := tryModelFilePricing(bs, "claude-fable-5-1", tokens, "", "xhigh")
|
||||
max := tryModelFilePricing(bs, "claude-fable-5-1", tokens, "", "max")
|
||||
standard := tryModelFilePricing(bs, "claude-fable-5-1", tokens, "", time.Time{}, "xhigh")
|
||||
max := tryModelFilePricing(bs, "claude-fable-5-1", tokens, "", time.Time{}, "max")
|
||||
require.NotNil(t, standard)
|
||||
require.NotNil(t, max)
|
||||
require.InDelta(t, *standard*3, *max, 1e-12)
|
||||
@@ -503,7 +503,7 @@ func TestTryModelFilePricing_AppliesLongContextPricing(t *testing.T) {
|
||||
})
|
||||
tokens := UsageTokens{InputTokens: 101, OutputTokens: 10, CacheReadTokens: 5}
|
||||
|
||||
result := tryModelFilePricing(bs, "gpt-5.6-sol", tokens, "")
|
||||
result := tryModelFilePricing(bs, "gpt-5.6-sol", tokens, "", time.Time{})
|
||||
|
||||
require.NotNil(t, result)
|
||||
// Input and cache-read use the 2x input tier; output uses the 1.5x tier.
|
||||
@@ -542,7 +542,7 @@ func TestTryModelFilePricing_AppliesServiceTierPricing(t *testing.T) {
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := tryModelFilePricing(bs, "gpt-5.6-sol", tokens, tt.serviceTier)
|
||||
result := tryModelFilePricing(bs, "gpt-5.6-sol", tokens, tt.serviceTier, time.Time{})
|
||||
require.NotNil(t, result)
|
||||
require.InDelta(t, tt.want, *result, 1e-12)
|
||||
})
|
||||
@@ -572,7 +572,7 @@ func TestTryModelFilePricing_CombinesPriorityAndLongContextPricing(t *testing.T)
|
||||
CacheReadTokens: 5,
|
||||
}
|
||||
|
||||
result := tryModelFilePricing(bs, "gpt-5.6-sol", tokens, "priority")
|
||||
result := tryModelFilePricing(bs, "gpt-5.6-sol", tokens, "priority", time.Time{})
|
||||
|
||||
require.NotNil(t, result)
|
||||
// priority 单价先应用,再叠加长上下文输入 2x、输出 1.5x。
|
||||
@@ -583,7 +583,7 @@ func TestTryModelFilePricing_PricingNotFound(t *testing.T) {
|
||||
// "nonexistent-model" does not match any fallback pattern
|
||||
bs := newTestBillingServiceWithPrices(map[string]*ModelPricing{})
|
||||
tokens := UsageTokens{InputTokens: 100, OutputTokens: 50}
|
||||
result := tryModelFilePricing(bs, "nonexistent-model", tokens, "")
|
||||
result := tryModelFilePricing(bs, "nonexistent-model", tokens, "", time.Time{})
|
||||
require.Nil(t, result)
|
||||
}
|
||||
|
||||
@@ -593,7 +593,7 @@ func TestTryModelFilePricing_NilFallback(t *testing.T) {
|
||||
"claude-sonnet-4": nil,
|
||||
})
|
||||
tokens := UsageTokens{InputTokens: 100}
|
||||
result := tryModelFilePricing(bs, "claude-sonnet-4", tokens, "")
|
||||
result := tryModelFilePricing(bs, "claude-sonnet-4", tokens, "", time.Time{})
|
||||
require.Nil(t, result)
|
||||
}
|
||||
|
||||
@@ -605,7 +605,7 @@ func TestTryModelFilePricing_ZeroCost(t *testing.T) {
|
||||
},
|
||||
})
|
||||
tokens := UsageTokens{} // all zero tokens → cost = 0 → nil
|
||||
result := tryModelFilePricing(bs, "claude-sonnet-4", tokens, "")
|
||||
result := tryModelFilePricing(bs, "claude-sonnet-4", tokens, "", time.Time{})
|
||||
require.Nil(t, result)
|
||||
}
|
||||
|
||||
@@ -622,7 +622,7 @@ func TestTryModelFilePricing_WithImageOutput(t *testing.T) {
|
||||
OutputTokens: 50,
|
||||
ImageOutputTokens: 10,
|
||||
}
|
||||
result := tryModelFilePricing(bs, "claude-sonnet-4", tokens, "")
|
||||
result := tryModelFilePricing(bs, "claude-sonnet-4", tokens, "", time.Time{})
|
||||
require.NotNil(t, result)
|
||||
// ImageOutputTokens 是 OutputTokens 的子集,先扣除再按图片单价计。
|
||||
// 100*0.001 + (50-10)*0.002 + 10*0.01 = 0.1 + 0.08 + 0.1 = 0.28
|
||||
@@ -644,13 +644,111 @@ func TestTryModelFilePricing_WithCacheTokens(t *testing.T) {
|
||||
CacheCreationTokens: 200,
|
||||
CacheReadTokens: 300,
|
||||
}
|
||||
result := tryModelFilePricing(bs, "claude-sonnet-4", tokens, "")
|
||||
result := tryModelFilePricing(bs, "claude-sonnet-4", tokens, "", time.Time{})
|
||||
require.NotNil(t, result)
|
||||
// 100*0.001 + 50*0.002 + 200*0.003 + 300*0.0005
|
||||
// = 0.1 + 0.1 + 0.6 + 0.15 = 0.95
|
||||
require.InDelta(t, 0.95, *result, 1e-12)
|
||||
}
|
||||
|
||||
func TestTryModelFilePricing_DeepSeekPeakPricing(t *testing.T) {
|
||||
weekday := func(hour, minute int) time.Time {
|
||||
return time.Date(2026, time.August, 24, hour, minute, 0, 0, time.UTC)
|
||||
}
|
||||
for _, model := range []struct {
|
||||
name string
|
||||
input, output, cacheReadPrice float64
|
||||
}{
|
||||
{"deepseek-v4-flash", 2.2e-7, 6.6e-7, 7e-9},
|
||||
{"deepseek-v4-pro", 6.6e-7, 1.98e-6, 2.2e-8},
|
||||
} {
|
||||
for _, usage := range []struct {
|
||||
name string
|
||||
tokens UsageTokens
|
||||
}{
|
||||
{"input", UsageTokens{InputTokens: 1000}},
|
||||
{"output", UsageTokens{OutputTokens: 500}},
|
||||
{"cache_read", UsageTokens{CacheReadTokens: 1000}},
|
||||
{"mixed", UsageTokens{InputTokens: 1000, OutputTokens: 500, CacheReadTokens: 1000}},
|
||||
} {
|
||||
t.Run(model.name+"/"+usage.name, func(t *testing.T) {
|
||||
bs := newTestBillingService()
|
||||
tokens := usage.tokens
|
||||
baseCost := float64(tokens.InputTokens)*model.input +
|
||||
float64(tokens.OutputTokens)*model.output + float64(tokens.CacheReadTokens)*model.cacheReadPrice
|
||||
for _, slot := range []struct {
|
||||
name string
|
||||
at time.Time
|
||||
multiplier float64
|
||||
}{
|
||||
{"before_morning_peak", weekday(0, 59), 1},
|
||||
{"morning_peak_start", weekday(1, 0), 2},
|
||||
{"morning_peak_last_minute", weekday(3, 59), 2},
|
||||
{"morning_peak_end", weekday(4, 0), 1},
|
||||
{"afternoon_peak_start", weekday(6, 0), 2},
|
||||
{"afternoon_peak_last_minute", weekday(9, 59), 2},
|
||||
{"afternoon_peak_end", weekday(10, 0), 1},
|
||||
{"saturday", time.Date(2026, time.August, 22, 2, 0, 0, 0, time.UTC), 1},
|
||||
{"sunday", time.Date(2026, time.August, 23, 7, 0, 0, 0, time.UTC), 1},
|
||||
} {
|
||||
t.Run(slot.name, func(t *testing.T) {
|
||||
cost := tryModelFilePricing(bs, model.name, tokens, "", slot.at)
|
||||
require.NotNil(t, cost)
|
||||
require.InDelta(t, baseCost*slot.multiplier, *cost, 1e-12)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveAccountStatsCost_DeepSeekPricingPriority(t *testing.T) {
|
||||
peak := time.Date(2026, time.August, 24, 2, 0, 0, 0, time.UTC)
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
customRule bool
|
||||
applyPricing bool
|
||||
noChannel bool
|
||||
want float64
|
||||
}{
|
||||
{name: "catalog", want: 1000 * 2.2e-7 * 2},
|
||||
{name: "custom_rule", customRule: true, want: 1},
|
||||
{name: "custom_rule_before_customer_price", customRule: true, applyPricing: true, want: 1},
|
||||
{name: "customer_price", applyPricing: true, want: 0.75},
|
||||
{name: "no_channel", noChannel: true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
channel := &Channel{
|
||||
ID: 1, Status: StatusActive, ApplyPricingToAccountStats: tt.applyPricing,
|
||||
ModelPricing: []ChannelModelPricing{{
|
||||
Models: []string{"deepseek-v4-flash"}, InputPrice: testPtrFloat64(0.02),
|
||||
}},
|
||||
}
|
||||
if tt.customRule {
|
||||
channel.AccountStatsPricingRules = []AccountStatsPricingRule{{
|
||||
AccountIDs: []int64{1},
|
||||
Pricing: []ChannelModelPricing{{
|
||||
Models: []string{"deepseek-v4-flash"}, InputPrice: testPtrFloat64(0.001),
|
||||
}},
|
||||
}}
|
||||
}
|
||||
cs := newTestChannelServiceForStats(t, channel, 10, PlatformDeepseek)
|
||||
groupID := int64(10)
|
||||
if tt.noChannel {
|
||||
groupID = 99
|
||||
}
|
||||
cost := resolveAccountStatsCost(context.Background(), cs, newTestBillingService(),
|
||||
1, groupID, "deepseek-v4-flash", UsageTokens{InputTokens: 1000}, 1, 0.75, "", peak)
|
||||
if tt.noChannel {
|
||||
require.Nil(t, cost)
|
||||
return
|
||||
}
|
||||
require.NotNil(t, cost)
|
||||
require.InDelta(t, tt.want, *cost, 1e-12)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// resolveAccountStatsCost — integration tests covering the 4-level priority chain
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -661,7 +759,7 @@ func TestResolveAccountStatsCost_NilChannelService(t *testing.T) {
|
||||
nil, // channelService is nil
|
||||
newTestBillingServiceWithPrices(map[string]*ModelPricing{}),
|
||||
1, 1, "claude-sonnet-4",
|
||||
UsageTokens{InputTokens: 100}, 1, 0.5, "",
|
||||
UsageTokens{InputTokens: 100}, 1, 0.5, "", time.Time{},
|
||||
)
|
||||
require.Nil(t, result)
|
||||
}
|
||||
@@ -677,7 +775,7 @@ func TestResolveAccountStatsCost_EmptyUpstreamModel(t *testing.T) {
|
||||
cs,
|
||||
newTestBillingServiceWithPrices(map[string]*ModelPricing{}),
|
||||
1, 1, "", // empty upstream model
|
||||
UsageTokens{InputTokens: 100}, 1, 0.5, "",
|
||||
UsageTokens{InputTokens: 100}, 1, 0.5, "", time.Time{},
|
||||
)
|
||||
require.Nil(t, result)
|
||||
}
|
||||
@@ -694,7 +792,7 @@ func TestResolveAccountStatsCost_GetChannelForGroupReturnsNil(t *testing.T) {
|
||||
cs,
|
||||
newTestBillingServiceWithPrices(map[string]*ModelPricing{}),
|
||||
1, 99, "claude-sonnet-4", // groupID 99 has no channel
|
||||
UsageTokens{InputTokens: 100}, 1, 0.5, "",
|
||||
UsageTokens{InputTokens: 100}, 1, 0.5, "", time.Time{},
|
||||
)
|
||||
require.Nil(t, result)
|
||||
}
|
||||
@@ -725,7 +823,7 @@ func TestResolveAccountStatsCost_HitsCustomRule(t *testing.T) {
|
||||
context.Background(),
|
||||
cs, nil, // billingService not needed when custom rule hits
|
||||
1, 10, "claude-sonnet-4",
|
||||
tokens, 1, 999.0, "priority", // 自定义账号价格不叠加服务层级倍率
|
||||
tokens, 1, 999.0, "priority", time.Time{}, // 自定义账号价格不叠加服务层级倍率
|
||||
)
|
||||
require.NotNil(t, result)
|
||||
// 100*0.01 + 50*0.02 = 1.0 + 1.0 = 2.0
|
||||
@@ -747,7 +845,7 @@ func TestResolveAccountStatsCost_ApplyPricingToAccountStats_UsesTotalCost(t *tes
|
||||
context.Background(),
|
||||
cs, nil,
|
||||
1, 10, "claude-sonnet-4",
|
||||
tokens, 1, 0.75, "priority", // 已完成用户计费,不再重复应用服务层级倍率
|
||||
tokens, 1, 0.75, "priority", time.Time{}, // 已完成用户计费,不再重复应用服务层级倍率
|
||||
)
|
||||
require.NotNil(t, result)
|
||||
require.InDelta(t, 0.75, *result, 1e-12)
|
||||
@@ -765,7 +863,7 @@ func TestResolveAccountStatsCost_ApplyPricingToAccountStats_ZeroTotalCost_Return
|
||||
context.Background(),
|
||||
cs, nil,
|
||||
1, 10, "claude-sonnet-4",
|
||||
UsageTokens{}, 1, 0.0, "", // totalCost = 0
|
||||
UsageTokens{}, 1, 0.0, "", time.Time{}, // totalCost = 0
|
||||
)
|
||||
require.Nil(t, result)
|
||||
}
|
||||
@@ -792,7 +890,7 @@ func TestResolveAccountStatsCost_FallsBackToLiteLLM(t *testing.T) {
|
||||
context.Background(),
|
||||
cs, bs,
|
||||
1, 10, "claude-sonnet-4",
|
||||
tokens, 1, 999.0, "", // totalCost ignored
|
||||
tokens, 1, 999.0, "", time.Time{}, // totalCost ignored
|
||||
)
|
||||
require.NotNil(t, result)
|
||||
// 100*0.001 + 50*0.002 = 0.1 + 0.1 = 0.2
|
||||
@@ -813,7 +911,7 @@ func TestResolveAccountStatsCost_FallbackHonorsAnthropicFast(t *testing.T) {
|
||||
context.Background(), cs, bs,
|
||||
1, 10, "claude-opus-5",
|
||||
UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000},
|
||||
1, 0, "fast",
|
||||
1, 0, "fast", time.Time{},
|
||||
)
|
||||
require.NotNil(t, result)
|
||||
require.InDelta(t, 60, *result, 1e-12)
|
||||
@@ -832,7 +930,7 @@ func TestResolveAccountStatsCost_Gemini36FlashTierUsesFallbackPricing(t *testing
|
||||
context.Background(),
|
||||
cs, bs,
|
||||
1, 10, "gemini-3.6-flash-low",
|
||||
UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000, CacheReadTokens: 1_000_000}, 1, 0, "",
|
||||
UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000, CacheReadTokens: 1_000_000}, 1, 0, "", time.Time{},
|
||||
)
|
||||
require.NotNil(t, result)
|
||||
require.InDelta(t, 9.15, *result, 1e-12)
|
||||
@@ -856,7 +954,7 @@ func TestResolveAccountStatsCost_AllMiss_ReturnsNil(t *testing.T) {
|
||||
context.Background(),
|
||||
cs, bs,
|
||||
1, 10, "totally-unknown-model",
|
||||
tokens, 1, 0.0, "",
|
||||
tokens, 1, 0.0, "", time.Time{},
|
||||
)
|
||||
require.Nil(t, result)
|
||||
}
|
||||
@@ -873,7 +971,7 @@ func TestResolveAccountStatsCost_NilBillingService_SkipsLiteLLM(t *testing.T) {
|
||||
context.Background(),
|
||||
cs, nil, // billingService is nil
|
||||
1, 10, "claude-sonnet-4",
|
||||
UsageTokens{InputTokens: 100}, 1, 0.0, "",
|
||||
UsageTokens{InputTokens: 100}, 1, 0.0, "", time.Time{},
|
||||
)
|
||||
require.Nil(t, result)
|
||||
}
|
||||
@@ -906,7 +1004,7 @@ func TestResolveAccountStatsCost_CustomRulePriorityOverApplyPricing(t *testing.T
|
||||
context.Background(),
|
||||
cs, nil,
|
||||
1, 10, "claude-sonnet-4",
|
||||
tokens, 1, 99.0, "", // totalCost = 99.0 (would be used if ApplyPricing wins)
|
||||
tokens, 1, 99.0, "", time.Time{}, // totalCost = 99.0 (would be used if ApplyPricing wins)
|
||||
)
|
||||
require.NotNil(t, result)
|
||||
// Custom rule: 100*0.05 = 5.0 (NOT 99.0 from totalCost)
|
||||
@@ -934,7 +1032,7 @@ func TestApplyAccountStatsCost_UsesUsageLogServiceTier(t *testing.T) {
|
||||
applyAccountStatsCost(
|
||||
context.Background(), usageLog, cs, bs,
|
||||
1, 10, "gpt-5.6-sol", "gpt-5.6-sol",
|
||||
UsageTokens{InputTokens: 100, OutputTokens: 50}, 999,
|
||||
UsageTokens{InputTokens: 100, OutputTokens: 50}, 999, time.Time{},
|
||||
)
|
||||
|
||||
require.NotNil(t, usageLog.AccountStatsCost)
|
||||
|
||||
@@ -19,13 +19,14 @@ const ContextPricingBasisWholeRequest ContextPricingBasis = "whole_request"
|
||||
// ContextPricingTier (MinTokens, MaxTokens] 区间内的有效 per-token 单价(USD)。
|
||||
// nil 表示该项无价/不计费;MaxTokens 为 nil 表示无上限。
|
||||
type ContextPricingTier struct {
|
||||
MinTokens int
|
||||
MaxTokens *int
|
||||
Label string
|
||||
Input *float64
|
||||
Output *float64
|
||||
CacheWrite *float64
|
||||
CacheRead *float64
|
||||
MinTokens int
|
||||
MaxTokens *int
|
||||
Label string
|
||||
Input *float64
|
||||
Output *float64
|
||||
CacheWrite *float64
|
||||
CacheWrite1h *float64
|
||||
CacheRead *float64
|
||||
}
|
||||
|
||||
// TimePricingPeriod 分时倍率时段:配置时区当天 [StartTime, EndTime) 内整单费用乘 Multiplier。
|
||||
@@ -289,6 +290,10 @@ func probeContextTier(seg contextSegment, resolved *ResolvedPricing, probe func(
|
||||
return tier, err
|
||||
}
|
||||
// 输出价只随上下文所在档变化:固定上下文 c,对输出 token 数做差商(固定部分相减抵消)。
|
||||
tier.CacheWrite1h, err = probeComponentPrice(func(n int) UsageTokens { return UsageTokens{CacheCreationTokens: n, CacheCreation1hTokens: n} }, c, delta, probe)
|
||||
if err != nil {
|
||||
return tier, err
|
||||
}
|
||||
tier.Output, err = probeComponentPrice(func(n int) UsageTokens { return UsageTokens{InputTokens: c, OutputTokens: n} }, 0, contextProbeDelta, probe)
|
||||
if err != nil {
|
||||
return tier, err
|
||||
@@ -298,6 +303,7 @@ func probeContextTier(seg contextSegment, resolved *ResolvedPricing, probe func(
|
||||
tier.Input = contextPricePtr(tier.Input, explicit.input)
|
||||
tier.Output = contextPricePtr(tier.Output, explicit.output)
|
||||
tier.CacheWrite = contextPricePtr(tier.CacheWrite, explicit.cacheWrite)
|
||||
tier.CacheWrite1h = contextPricePtr(tier.CacheWrite1h, explicit.cacheWrite1h)
|
||||
tier.CacheRead = contextPricePtr(tier.CacheRead, explicit.cacheRead)
|
||||
return tier, nil
|
||||
}
|
||||
@@ -341,7 +347,7 @@ func roundContextPrice(v float64) float64 {
|
||||
}
|
||||
|
||||
type explicitContextFields struct {
|
||||
input, output, cacheWrite, cacheRead bool
|
||||
input, output, cacheWrite, cacheWrite1h, cacheRead bool
|
||||
}
|
||||
|
||||
// explicitContextPricingFields 判断各项是否被分组卡/渠道定价(含命中区间)显式配置。
|
||||
@@ -355,11 +361,13 @@ func explicitContextPricingFields(resolved *ResolvedPricing, contextTokens int)
|
||||
out.input = cp.InputPrice != nil
|
||||
out.output = cp.OutputPrice != nil
|
||||
out.cacheWrite = cp.CacheWritePrice != nil
|
||||
out.cacheWrite1h = cp.CacheWrite1hPrice != nil || cp.CacheWritePrice != nil
|
||||
out.cacheRead = cp.CacheReadPrice != nil
|
||||
if iv := FindMatchingInterval(resolved.Intervals, contextTokens); iv != nil {
|
||||
out.input = out.input || iv.InputPrice != nil
|
||||
out.output = out.output || iv.OutputPrice != nil
|
||||
out.cacheWrite = out.cacheWrite || iv.CacheWritePrice != nil
|
||||
out.cacheWrite1h = out.cacheWrite1h || iv.CacheWrite1hPrice != nil || iv.CacheWritePrice != nil
|
||||
out.cacheRead = out.cacheRead || iv.CacheReadPrice != nil
|
||||
}
|
||||
return out
|
||||
@@ -393,7 +401,7 @@ func mergeEqualContextTiers(tiers []ContextPricingTier) []ContextPricingTier {
|
||||
|
||||
func sameContextPrices(a, b ContextPricingTier) bool {
|
||||
return samePricePtr(a.Input, b.Input) && samePricePtr(a.Output, b.Output) &&
|
||||
samePricePtr(a.CacheWrite, b.CacheWrite) && samePricePtr(a.CacheRead, b.CacheRead)
|
||||
samePricePtr(a.CacheWrite, b.CacheWrite) && samePricePtr(a.CacheWrite1h, b.CacheWrite1h) && samePricePtr(a.CacheRead, b.CacheRead)
|
||||
}
|
||||
|
||||
func samePricePtr(a, b *float64) bool {
|
||||
|
||||
@@ -385,6 +385,24 @@ func TestResolveContextPricingSchedule_NilResolver(t *testing.T) {
|
||||
require.Nil(t, sched)
|
||||
}
|
||||
|
||||
func TestPlazaSchedulePreservesCacheWrite1h(t *testing.T) {
|
||||
cp := sonnetChannel(PricingInterval{MinTokens: 272000, CacheWriteMultiplier: testPtrFloat64(2)})
|
||||
cp[0].CacheWritePrice = testPtrFloat64(12.5e-6)
|
||||
cp[0].CacheWrite1hPrice = testPtrFloat64(20e-6)
|
||||
group := enabledGroup(PlatformAnthropic)
|
||||
bs, resolver := newScheduleTestEnv(t, scheduleScenario{channel: cp, groupPlatform: PlatformAnthropic})
|
||||
sched, err := bs.ResolveContextPricingSchedule(context.Background(), resolver, ContextPricingScheduleInput{Model: "claude-sonnet-4", Group: group, Platform: PlatformAnthropic})
|
||||
require.NoError(t, err)
|
||||
display := plazaPricingFromSchedule(&cp[0], sched)
|
||||
requirePrice(t, testPtrFloat64(20e-6), display.CacheWrite1hPrice, "base 1h")
|
||||
require.Len(t, display.Intervals, 2)
|
||||
requirePrice(t, testPtrFloat64(25e-6), display.Intervals[1].CacheWritePrice, "tier 5m")
|
||||
requirePrice(t, testPtrFloat64(40e-6), display.Intervals[1].CacheWrite1hPrice, "tier 1h")
|
||||
a := ContextPricingTier{CacheWrite1h: testPtrFloat64(1)}
|
||||
b := ContextPricingTier{CacheWrite1h: testPtrFloat64(2)}
|
||||
require.Len(t, mergeEqualContextTiers([]ContextPricingTier{a, b}), 2)
|
||||
}
|
||||
|
||||
// --- 对账:阶梯表推算的费用必须等于真实计费函数 ---
|
||||
|
||||
type tokenKind int
|
||||
|
||||
@@ -586,7 +586,20 @@ func (s *BillingService) initFallbackPricing() {
|
||||
// Source: https://docs.z.ai/guides/overview/pricing (USD per 1M tokens)
|
||||
// 注意:CacheReadPricePerToken 即"缓存命中"价格,CacheCreationPricePerToken 留空(智谱未公开写入价,按 0 处理)。
|
||||
// GLM-4.6 与 GLM-4.5 在 z.ai 国际版上定价一致;GLM-4.5 国内按 ¥0.8/¥2,汇率换算后约 $0.112/$0.28,与国际版 $0.6/$2.2 不同,本分支采用国际版 USD 口径与现有 Claude/GPT 一致。
|
||||
// GLM-5.2 与 GLM-5.1 在 z.ai 上同价。
|
||||
// GLM-5.3 / GLM-5.2 与 GLM-5.1 在 z.ai 上同价。
|
||||
// GLM-5.3-Flash 列表价 $0.15/$0.50(2026-09-09 前五折促销,此处按列表价,与其它模型口径一致)。
|
||||
s.fallbackPrices["glm-5.3-flash"] = &ModelPricing{
|
||||
InputPricePerToken: 0.15e-6, // $0.15 per MTok
|
||||
OutputPricePerToken: 0.5e-6, // $0.50 per MTok
|
||||
CacheReadPricePerToken: 0.03e-6,
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
s.fallbackPrices["glm-5.3"] = &ModelPricing{
|
||||
InputPricePerToken: 1.4e-6, // $1.40 per MTok
|
||||
OutputPricePerToken: 4.4e-6, // $4.40 per MTok
|
||||
CacheReadPricePerToken: 0.26e-6,
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
s.fallbackPrices["glm-5.2"] = &ModelPricing{
|
||||
InputPricePerToken: 1.4e-6, // $1.40 per MTok
|
||||
OutputPricePerToken: 4.4e-6, // $4.40 per MTok
|
||||
@@ -924,9 +937,16 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing {
|
||||
// 匹配策略:长 key 优先(具体模型 → 系列 / 厂商),未知型号不回退以避免误计价。
|
||||
// 与 DeepSeek 一样采用"白名单"语义:未在本表命中的国产模型 alias 一律不返回兜底价。
|
||||
|
||||
// 智谱 GLM(z.ai 公开 SKU:glm-5.2 / glm-5.1 / glm-5 / glm-5-turbo / glm-4.7 / glm-4.6 / glm-4.5 等)
|
||||
// 智谱 GLM(z.ai 公开 SKU:glm-5.3 / glm-5.3-flash / glm-5.2 / glm-5.1 / glm-5 / glm-5-turbo / glm-4.7 / glm-4.6 / glm-4.5 等)
|
||||
// 匹配顺序:先判别最高 tier,再依次降级。
|
||||
// 注意:带小数点的型号必须排在裸 "glm-5" 之前,否则会被 strings.Contains 抢走。
|
||||
// 注意:带小数点的型号必须排在裸 "glm-5" 之前,否则会被 strings.Contains 抢走;
|
||||
// glm-5.3-flash 必须排在 glm-5.3 之前(前者包含后者子串)。
|
||||
if strings.Contains(modelLower, "glm-5.3-flash") || strings.Contains(modelLower, "glm-5.3flash") {
|
||||
return s.fallbackPrices["glm-5.3-flash"]
|
||||
}
|
||||
if strings.Contains(modelLower, "glm-5.3") {
|
||||
return s.fallbackPrices["glm-5.3"]
|
||||
}
|
||||
if strings.Contains(modelLower, "glm-5.2") {
|
||||
return s.fallbackPrices["glm-5.2"]
|
||||
}
|
||||
|
||||
@@ -549,6 +549,20 @@ func TestGetFallbackPricing_FamilyMatching(t *testing.T) {
|
||||
},
|
||||
|
||||
// ---- 智谱 GLM(z.ai USD 口径)----
|
||||
{
|
||||
name: "glm 5.3 flagship",
|
||||
model: "glm-5.3",
|
||||
expectedInput: 1.4e-6,
|
||||
expectedOutput: floatPtr(4.4e-6),
|
||||
expectedCacheRead: floatPtr(0.26e-6),
|
||||
},
|
||||
{
|
||||
name: "glm 5.3 flash",
|
||||
model: "glm-5.3-flash",
|
||||
expectedInput: 0.15e-6,
|
||||
expectedOutput: floatPtr(0.5e-6),
|
||||
expectedCacheRead: floatPtr(0.03e-6),
|
||||
},
|
||||
{
|
||||
name: "glm 5.2 flagship",
|
||||
model: "glm-5.2",
|
||||
@@ -639,7 +653,21 @@ func TestGetFallbackPricing_FamilyMatching(t *testing.T) {
|
||||
expectedInput: 0.1e-6,
|
||||
expectedOutput: floatPtr(0.1e-6),
|
||||
},
|
||||
// 关键:5.1 / 5.2 必须先于 5 匹配(避免被 glm-5 抢走)
|
||||
// 关键:5.1 / 5.2 / 5.3 必须先于 5 匹配(避免被 glm-5 抢走)
|
||||
{
|
||||
name: "glm 5.3-flash vs glm 5.3 ordering (verbatim 5.3-flash)",
|
||||
model: "glm-5.3-flash",
|
||||
expectedInput: 0.15e-6, // = glm-5.3-flash 价格(不是 glm-5.3 的 1.4e-6,更不是 glm-5 的 1e-6)
|
||||
expectedOutput: floatPtr(0.5e-6),
|
||||
expectedCacheRead: floatPtr(0.03e-6),
|
||||
},
|
||||
{
|
||||
name: "glm 5.3 vs glm 5 ordering (verbatim 5.3)",
|
||||
model: "glm-5.3",
|
||||
expectedInput: 1.4e-6, // = glm-5.3 价格(不是 glm-5 的 1e-6)
|
||||
expectedOutput: floatPtr(4.4e-6),
|
||||
expectedCacheRead: floatPtr(0.26e-6),
|
||||
},
|
||||
{
|
||||
name: "glm 5.1 vs glm 5 ordering (verbatim 5.1)",
|
||||
model: "glm-5.1",
|
||||
|
||||
@@ -114,6 +114,23 @@ func TestSanitizeAnthropicBodyForBetaTokens_EmptyBody(t *testing.T) {
|
||||
require.Empty(t, out)
|
||||
}
|
||||
|
||||
func TestSanitizeAnthropicBodyForBetaTokens_ThinkingBlockBindingKeptWhenBetaPresent(t *testing.T) {
|
||||
body := []byte(`{"model":"claude-fable-5-1","thinking":{"type":"adaptive","display":"summarized","block_binding":{"prefix_mismatch_behavior":"drop_block"}},"messages":[]}`)
|
||||
out, changed := sanitizeAnthropicBodyForBetaTokens(body, claude.BetaThinkingBindingControls)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, "drop_block",
|
||||
gjson.GetBytes(out, "thinking.block_binding.prefix_mismatch_behavior").String())
|
||||
}
|
||||
|
||||
func TestSanitizeAnthropicBodyForBetaTokens_ThinkingBlockBindingStrippedWhenBetaMissing(t *testing.T) {
|
||||
body := []byte(`{"model":"claude-fable-5-1","thinking":{"type":"adaptive","display":"summarized","block_binding":{"prefix_mismatch_behavior":"drop_block"}},"messages":[]}`)
|
||||
out, changed := sanitizeAnthropicBodyForBetaTokens(body, claude.BetaContextManagement)
|
||||
require.True(t, changed)
|
||||
require.False(t, gjson.GetBytes(out, "thinking.block_binding").Exists())
|
||||
require.Equal(t, "adaptive", gjson.GetBytes(out, "thinking.type").String())
|
||||
require.Equal(t, "summarized", gjson.GetBytes(out, "thinking.display").String())
|
||||
}
|
||||
|
||||
// ★ 关键回归断言:能力维度 sanitize 解决了 "真 CC + haiku" 路径的过度删除问题。
|
||||
// 真实 Claude Code CLI 2.1.87+ 客户端 header 含 context-management beta;
|
||||
// 即使 model 是 haiku,sanitize 也不应剥离功能字段。
|
||||
@@ -145,6 +162,8 @@ func TestComputeFinalAnthropicBeta_OAuthMimic_NonHaiku_IncludesContextManagement
|
||||
"OAuth mimic non-haiku 必须注入完整 CC mimicry beta,含 context-management-2025-06-27")
|
||||
require.True(t, anthropicBetaTokensContains(final, claude.BetaOAuth))
|
||||
require.True(t, anthropicBetaTokensContains(final, claude.BetaClaudeCode))
|
||||
require.True(t, anthropicBetaTokensContains(final, claude.BetaThinkingBindingControls),
|
||||
"OAuth mimic 必须注入 thinking block binding 所需的 beta")
|
||||
}
|
||||
|
||||
func TestComputeFinalAnthropicBeta_OAuthMimic_Haiku_IncludesFullClaudeCodeBetas(t *testing.T) {
|
||||
|
||||
@@ -194,6 +194,42 @@ func TestGatewayServiceRecordUsage_PreservesRequestedAndUpstreamModels(t *testin
|
||||
require.Equal(t, mappedModel, *usageRepo.lastLog.UpstreamModel)
|
||||
}
|
||||
|
||||
func TestGatewayServiceRecordUsage_GeminiFlashThinkingTierUsesCatalogPrice(t *testing.T) {
|
||||
for _, baseModel := range []string{"gemini-3.7-flash", "gemini-3.8-flash"} {
|
||||
t.Run(baseModel, func(t *testing.T) {
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
|
||||
userRepo := &openAIRecordUsageUserRepoStub{}
|
||||
svc := newGatewayRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{})
|
||||
svc.billingService = NewBillingService(svc.cfg, &PricingService{pricingData: map[string]*LiteLLMModelPricing{
|
||||
baseModel: {InputCostPerToken: 0.75e-6, OutputCostPerToken: 3.75e-6, CacheReadInputTokenCost: 0.075e-6},
|
||||
}})
|
||||
svc.resolver = NewModelPricingResolver(nil, svc.billingService)
|
||||
group := &Group{ID: 27, Platform: PlatformGemini, RateMultiplier: 0.15}
|
||||
model := baseModel + "-medium"
|
||||
|
||||
err := svc.RecordUsage(context.Background(), &RecordUsageInput{
|
||||
Result: &ForwardResult{
|
||||
RequestID: "gemini_thinking_tier",
|
||||
Model: model,
|
||||
UpstreamModel: model,
|
||||
Usage: ClaudeUsage{InputTokens: 8498, OutputTokens: 469, CacheReadInputTokens: 159248},
|
||||
Duration: time.Second,
|
||||
},
|
||||
APIKey: &APIKey{ID: 501, GroupID: &group.ID, Group: group},
|
||||
User: &User{ID: 601},
|
||||
Account: &Account{ID: 701, Platform: PlatformGemini, Type: AccountTypeAPIKey},
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, usageRepo.lastLog)
|
||||
require.Equal(t, model, usageRepo.lastLog.Model)
|
||||
require.InDelta(t, 0.02007585, usageRepo.lastLog.TotalCost, 1e-12)
|
||||
require.InDelta(t, 0.0030113775, usageRepo.lastLog.ActualCost, 1e-12)
|
||||
require.InDelta(t, 0.0030113775, userRepo.lastAmount, 1e-12)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayServiceRecordUsage_PreservesChannelMappedUpstreamModel(t *testing.T) {
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
|
||||
svc := newGatewayRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{})
|
||||
@@ -424,6 +460,69 @@ func TestGatewayServiceRecordUsage_UsesExplicitPricingAtForPeakRate(t *testing.T
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayServiceRecordUsage_DeepSeekAccountStatsUsesRequestPricingAtAndUpstreamModel(t *testing.T) {
|
||||
for _, model := range []struct {
|
||||
name string
|
||||
offPeakCost float64
|
||||
}{
|
||||
{"deepseek-v4-flash", 1000*2.2e-7 + 500*6.6e-7 + 1000*7e-9},
|
||||
{"deepseek-v4-pro", 1000*6.6e-7 + 500*1.98e-6 + 1000*2.2e-8},
|
||||
} {
|
||||
for _, slot := range []struct {
|
||||
name string
|
||||
pricingAt time.Time
|
||||
multiplier float64
|
||||
}{
|
||||
{"peak", time.Date(2026, time.August, 24, 2, 0, 0, 0, time.UTC), 2},
|
||||
{"off_peak", time.Date(2026, time.August, 24, 12, 0, 0, 0, time.UTC), 1},
|
||||
} {
|
||||
t.Run(model.name+"/"+slot.name, func(t *testing.T) {
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
|
||||
userRepo := &openAIRecordUsageUserRepoStub{}
|
||||
svc := newGatewayRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{})
|
||||
groupID := int64(905)
|
||||
svc.channelService = newTestChannelServiceForStats(t, &Channel{ID: 1, Status: StatusActive}, groupID, PlatformDeepseek)
|
||||
svc.resolver = NewModelPricingResolver(svc.channelService, svc.billingService)
|
||||
alias := "customer-chat"
|
||||
inputPrice, outputPrice, cachePrice := 1e-6, 2e-6, 1e-7
|
||||
group := &Group{ID: groupID, Platform: PlatformDeepseek, RateMultiplier: 0.8,
|
||||
ModelPricing: []ChannelModelPricing{{
|
||||
Models: []string{alias}, BillingMode: BillingModeToken,
|
||||
InputPrice: &inputPrice, OutputPrice: &outputPrice, CacheReadPrice: &cachePrice,
|
||||
}},
|
||||
}
|
||||
err := svc.RecordUsage(context.Background(), &RecordUsageInput{
|
||||
Result: &ForwardResult{
|
||||
RequestID: "gateway_deepseek_account_stats_" + model.name + "_" + slot.name,
|
||||
Model: alias, UpstreamModel: model.name,
|
||||
Usage: ClaudeUsage{InputTokens: 1000, OutputTokens: 500, CacheReadInputTokens: 1000},
|
||||
},
|
||||
APIKey: &APIKey{ID: 805, GroupID: &groupID, Group: group},
|
||||
User: &User{ID: 605}, Account: &Account{ID: 705, Platform: PlatformDeepseek},
|
||||
PricingAt: slot.pricingAt,
|
||||
ChannelUsageFields: ChannelUsageFields{OriginalModel: alias, BillingModelSource: BillingModelSourceRequested},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, usageRepo.lastLog)
|
||||
log := usageRepo.lastLog
|
||||
require.Equal(t, alias, log.RequestedModel)
|
||||
require.NotNil(t, log.UpstreamModel)
|
||||
require.Equal(t, model.name, *log.UpstreamModel)
|
||||
require.WithinDuration(t, time.Now(), log.CreatedAt, time.Minute)
|
||||
require.False(t, log.CreatedAt.Equal(slot.pricingAt), "request pricing time must differ from record creation")
|
||||
customerTotal := 1000*inputPrice + 500*outputPrice + 1000*cachePrice
|
||||
require.InDelta(t, customerTotal, log.TotalCost, 1e-12)
|
||||
require.InDelta(t, customerTotal*0.8, log.ActualCost, 1e-12)
|
||||
require.Equal(t, 1, userRepo.deductCalls)
|
||||
require.InDelta(t, customerTotal*0.8, userRepo.lastAmount, 1e-12)
|
||||
require.NotNil(t, log.AccountStatsCost)
|
||||
require.InDelta(t, model.offPeakCost*slot.multiplier, *log.AccountStatsCost, 1e-12,
|
||||
"account cost must use the upstream model and historical PricingAt")
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayServiceRecordUsage_UsageLogWriteErrorDoesNotSkipBilling(t *testing.T) {
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{inserted: false, err: MarkUsageLogCreateNotPersisted(context.Canceled)}
|
||||
userRepo := &openAIRecordUsageUserRepoStub{}
|
||||
|
||||
@@ -912,6 +912,12 @@ const anthropicBetaContextManagementToken = "context-management-2025-06-27"
|
||||
// FullClaudeCodeMimicryBetas 覆盖客户端 beta(该列表不含 fallback beta),
|
||||
// 若不 strip,body 字段与 header 不对称 → 所有模型 400
|
||||
//
|
||||
// thinking.block_binding 场景:
|
||||
// - Claude Fable 5.1 的会话前缀绑定控制受
|
||||
// `thinking-binding-controls-2026-08-01` beta 保护
|
||||
// - 缺 token 时上游拒收:
|
||||
// "thinking.adaptive.block_binding: Extra inputs are not permitted"
|
||||
//
|
||||
// 本函数按最终发送的 anthropic-beta header 决定是否保留 body 中的上述字段:
|
||||
// 缺对应 beta token → strip;客户端 header 已带对应 beta → 保留(不过度删除)。
|
||||
// 这将限制完全建立在 "能力维度" 上,与 model 名 / token type / mimicry 子路径无关。
|
||||
@@ -935,6 +941,13 @@ func sanitizeAnthropicBodyForBetaTokens(body []byte, anthropicBetaHeader string)
|
||||
body, changed = b, true
|
||||
}
|
||||
|
||||
// thinking.block_binding:需要 thinking-binding-controls beta。
|
||||
if b, deleted := stripAnthropicBodyFieldUnlessBeta(
|
||||
body, "thinking.block_binding", anthropicBetaHeader, claude.BetaThinkingBindingControls,
|
||||
); deleted {
|
||||
body, changed = b, true
|
||||
}
|
||||
|
||||
// fallbacks:server-side refusal fallback,仅接受 server-side-fallback beta。
|
||||
if b, deleted := stripAnthropicBodyFieldUnlessBeta(
|
||||
body, "fallbacks", anthropicBetaHeader, claude.BetaServerSideFallback,
|
||||
|
||||
@@ -1452,6 +1452,10 @@ func (s *GatewayService) GetAvailableModels(ctx context.Context, groupID *int64,
|
||||
}
|
||||
sort.Strings(models)
|
||||
|
||||
if platform == PlatformOpenAI {
|
||||
models = supplementUnmappedOpenAIModels(accounts, models)
|
||||
}
|
||||
|
||||
if s.modelsListCache != nil {
|
||||
s.modelsListCache.Set(cacheKey, cloneStringSlice(models), s.modelsListCacheTTL)
|
||||
modelsListCacheStoreTotal.Add(1)
|
||||
|
||||
@@ -831,7 +831,7 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage
|
||||
CacheReadTokens: result.Usage.CacheReadInputTokens,
|
||||
ImageOutputTokens: result.Usage.ImageOutputTokens,
|
||||
},
|
||||
cost.TotalCost,
|
||||
cost.TotalCost, pricingAt,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,11 +2,13 @@ package service
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/claude"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/openai"
|
||||
)
|
||||
|
||||
// GroupModelAllowlist 是 service 层的分组模型白名单(与 domain.GroupModelAllowlist
|
||||
@@ -26,6 +28,22 @@ func GroupModelAllowlistFromDomain(cfg domain.GroupModelAllowlist) GroupModelAll
|
||||
return GroupModelAllowlist{Enabled: cfg.Enabled, Models: cfg.Models}
|
||||
}
|
||||
|
||||
// supplementUnmappedOpenAIModels ensures a partial mapping catalog does not
|
||||
// hide models from unmapped OpenAI accounts. An empty catalog is left unchanged
|
||||
// so callers retain their existing discovery fallback.
|
||||
func supplementUnmappedOpenAIModels(accounts []Account, models []string) []string {
|
||||
if len(models) == 0 {
|
||||
return models
|
||||
}
|
||||
for i := range accounts {
|
||||
account := &accounts[i]
|
||||
if account.Platform == PlatformOpenAI && len(account.GetModelMapping()) == 0 {
|
||||
return dedupeAndSortModelIDs(slices.Concat(models, openai.DefaultModelIDs()))
|
||||
}
|
||||
}
|
||||
return models
|
||||
}
|
||||
|
||||
// normalizeGroupModelAllowlist 归一化管理端提交的分组模型白名单:
|
||||
// 条目 TrimSpace、按小写去重保序;`*` 只允许出现在条目末尾;
|
||||
// enabled=true 且列表为空视为配置错误,返回 400 而不是运行时静默放行/拒绝。
|
||||
|
||||
@@ -269,6 +269,7 @@ func plazaPricingFromSchedule(raw *ChannelModelPricing, sched *ContextPricingSch
|
||||
out.InputPrice = first.Input
|
||||
out.OutputPrice = first.Output
|
||||
out.CacheWritePrice = first.CacheWrite
|
||||
out.CacheWrite1hPrice = first.CacheWrite1h
|
||||
out.CacheReadPrice = first.CacheRead
|
||||
if len(sched.Tiers) > 1 {
|
||||
out.Intervals = plazaIntervalsFromTiers(sched.Tiers)
|
||||
@@ -280,14 +281,15 @@ func plazaIntervalsFromTiers(tiers []ContextPricingTier) []PricingInterval {
|
||||
intervals := make([]PricingInterval, 0, len(tiers))
|
||||
for i, t := range tiers {
|
||||
intervals = append(intervals, PricingInterval{
|
||||
MinTokens: t.MinTokens,
|
||||
MaxTokens: t.MaxTokens,
|
||||
TierLabel: t.Label,
|
||||
InputPrice: t.Input,
|
||||
OutputPrice: t.Output,
|
||||
CacheWritePrice: t.CacheWrite,
|
||||
CacheReadPrice: t.CacheRead,
|
||||
SortOrder: i,
|
||||
MinTokens: t.MinTokens,
|
||||
MaxTokens: t.MaxTokens,
|
||||
TierLabel: t.Label,
|
||||
InputPrice: t.Input,
|
||||
OutputPrice: t.Output,
|
||||
CacheWritePrice: t.CacheWrite,
|
||||
CacheWrite1hPrice: t.CacheWrite1h,
|
||||
CacheReadPrice: t.CacheRead,
|
||||
SortOrder: i,
|
||||
})
|
||||
}
|
||||
return intervals
|
||||
|
||||
@@ -298,6 +298,59 @@ func TestOpenAIStreamCapacityShedAfterOutputRewritesCodeForClient(t *testing.T)
|
||||
require.True(t, logSink.ContainsFieldValue("upstream_request_id", "rid-shed-after-output"))
|
||||
}
|
||||
|
||||
func TestOpenAIStreamProcessingFailureAfterOutputIsRecorded(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
stream := strings.Join([]string{
|
||||
"event: response.created",
|
||||
`data: {"type":"response.created","response":{"id":"resp_processing_failure"}}`,
|
||||
"",
|
||||
"event: response.output_text.delta",
|
||||
`data: {"type":"response.output_text.delta","delta":"partial"}`,
|
||||
"",
|
||||
"event: response.failed",
|
||||
`data: {"type":"response.failed","response":{"id":"resp_processing_failure","status":"failed","error":{"code":"server_error","message":"An error occurred while processing your request. Please include the request ID rid-processing-failure in your message."}}}`,
|
||||
"",
|
||||
}, "\n")
|
||||
|
||||
for _, passthrough := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "native", true: "passthrough"}[passthrough], func(t *testing.T) {
|
||||
svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}}
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
|
||||
resp := &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Body: io.NopCloser(strings.NewReader(stream)),
|
||||
Header: http.Header{"X-Request-Id": []string{"rid-processing-failure"}},
|
||||
}
|
||||
account := &Account{ID: 42, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Name: "codex-account"}
|
||||
|
||||
var err error
|
||||
if passthrough {
|
||||
_, err = svc.handleStreamingResponsePassthrough(c.Request.Context(), resp, c, account, time.Now(), "gpt-5.6-terra", "gpt-5.6-terra")
|
||||
} else {
|
||||
_, err = svc.handleStreamingResponse(c.Request.Context(), resp, c, account, time.Now(), "gpt-5.6-terra", "gpt-5.6-terra")
|
||||
}
|
||||
|
||||
require.Error(t, err)
|
||||
var failoverErr *UpstreamFailoverError
|
||||
require.False(t, errors.As(err, &failoverErr))
|
||||
require.NotEmpty(t, rec.Body.String())
|
||||
require.Contains(t, rec.Body.String(), "response.failed")
|
||||
require.NotNil(t, c)
|
||||
rawEvents, ok := c.Get(OpsUpstreamErrorsKey)
|
||||
require.True(t, ok)
|
||||
events, ok := rawEvents.([]*OpsUpstreamErrorEvent)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, events)
|
||||
event := events[len(events)-1]
|
||||
require.Equal(t, "stream_failed", event.Kind)
|
||||
require.Equal(t, "rid-processing-failure", event.UpstreamRequestID)
|
||||
require.Contains(t, event.Message, "An error occurred while processing your request")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// helper 单测:只有降载码被改写,其余错误码(尤其 rate_limit_exceeded,客户端
|
||||
// 依赖其原码解析重试延时)必须原样保留。
|
||||
func TestSanitizeOpenAICapacityShedErrorCodeForClient(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestBuildCodexModelsManifestForGroupCorrectsOfficialAstraStaleModalities(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const groupID int64 = 780
|
||||
account := Account{
|
||||
ID: 1,
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
}
|
||||
account.SetUpstreamModelMetadataSnapshot(UpstreamModelMetadataSnapshot{
|
||||
Models: map[string]UpstreamModelMetadata{
|
||||
"gpt-6-astra": {ID: "gpt-6-astra", InputModalities: []string{"text"}},
|
||||
},
|
||||
})
|
||||
|
||||
svc := &GatewayService{accountRepo: codexModelsVisibilityAccountRepo{
|
||||
byGroup: map[int64][]Account{groupID: {account}},
|
||||
}}
|
||||
|
||||
body, err := svc.BuildCodexModelsManifestForGroup(
|
||||
context.Background(),
|
||||
&Group{ID: groupID, Platform: PlatformOpenAI},
|
||||
"",
|
||||
[]string{"gpt-6-astra"},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
models := decodeCodexManifestModels(t, body)
|
||||
require.Len(t, models, 1)
|
||||
require.Equal(t, []any{"text", "image"}, models[0]["input_modalities"])
|
||||
}
|
||||
|
||||
func TestBuildCodexModelsManifestForGroupPreservesCompatibleAstraTextOnlyMetadata(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const groupID int64 = 781
|
||||
account := Account{
|
||||
ID: 2,
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "sk-test", "base_url": "https://relay.example.test/v1"},
|
||||
}
|
||||
account.SetUpstreamModelMetadataSnapshot(UpstreamModelMetadataSnapshot{
|
||||
Models: map[string]UpstreamModelMetadata{
|
||||
"gpt-6-astra": {ID: "gpt-6-astra", InputModalities: []string{"text"}},
|
||||
},
|
||||
})
|
||||
|
||||
svc := &GatewayService{accountRepo: codexModelsVisibilityAccountRepo{
|
||||
byGroup: map[int64][]Account{groupID: {account}},
|
||||
}}
|
||||
|
||||
body, err := svc.BuildCodexModelsManifestForGroup(
|
||||
context.Background(),
|
||||
&Group{ID: groupID, Platform: PlatformOpenAI},
|
||||
"",
|
||||
[]string{"gpt-6-astra"},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
models := decodeCodexManifestModels(t, body)
|
||||
require.Len(t, models, 1)
|
||||
require.Equal(t, []any{"text"}, models[0]["input_modalities"])
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
var codexToolCapabilityFields = []string{
|
||||
"supports_search_tool", "apply_patch_tool_type", "comp_hash", "tool_mode", "use_responses_lite",
|
||||
"multi_agent_reasoning_effort", "multi_agent_version",
|
||||
}
|
||||
|
||||
func applyCodexToolCapabilities(dst, src map[string]json.RawMessage, overwrite bool) bool {
|
||||
@@ -18,7 +19,7 @@ func applyCodexToolCapabilities(dst, src map[string]json.RawMessage, overwrite b
|
||||
if len(value) == 0 {
|
||||
continue
|
||||
}
|
||||
// These five Codex fields are nullable booleans or strings, never arbitrary objects.
|
||||
// These Codex fields are nullable booleans or strings, never arbitrary objects.
|
||||
if !bytes.Equal(value, []byte("null")) {
|
||||
if field == "supports_search_tool" || field == "use_responses_lite" {
|
||||
if !bytes.Equal(value, []byte("true")) && !bytes.Equal(value, []byte("false")) {
|
||||
@@ -422,6 +423,8 @@ func configuredCodexReasoningLevelDescription(level string) string {
|
||||
return "Extra-high reasoning depth for difficult tasks"
|
||||
case "max":
|
||||
return "Maximum reasoning depth for complex tasks"
|
||||
case "ultra":
|
||||
return "Maximum reasoning with automatic task delegation"
|
||||
default:
|
||||
return "Reasoning effort supported by the upstream model"
|
||||
}
|
||||
|
||||
@@ -9,6 +9,58 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAstraUltraCatalogPreservesWorkflowMetadata(t *testing.T) {
|
||||
// Ultra is a Codex workflow. Its inference effort must survive catalog sync,
|
||||
// aliases and group generation instead of silently falling back to max.
|
||||
_, metadata, err := extractUpstreamModelCatalog([]byte(`{"models":[{
|
||||
"slug":"gpt-6-astra","supported_reasoning_levels":[{"effort":"high"},{"effort":"ultra"}],
|
||||
"multi_agent_reasoning_effort":"high","multi_agent_version":"v2"
|
||||
}]}`), false)
|
||||
require.NoError(t, err)
|
||||
account := Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{
|
||||
"base_url": "https://relay.example/v1", "model_mapping": map[string]any{"public-astra": "gpt-6-astra"},
|
||||
}}
|
||||
account.SetUpstreamModelMetadataSnapshot(UpstreamModelMetadataSnapshot{Models: metadata})
|
||||
body, err := buildCodexModelsManifestForAccounts(PlatformOpenAI, []string{"public-astra"}, []Account{account}, nil, nil, true)
|
||||
require.NoError(t, err)
|
||||
model := decodeCodexManifestModels(t, body)[0]
|
||||
require.Equal(t, "high", model["multi_agent_reasoning_effort"])
|
||||
require.Equal(t, "v2", model["multi_agent_version"])
|
||||
require.Equal(t, []string{"high", "ultra"}, effortsFromManifestModel(t, model))
|
||||
|
||||
peer := Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: account.Credentials}
|
||||
body, err = buildCodexModelsManifestForAccounts(PlatformOpenAI, []string{"public-astra"}, []Account{account, peer}, nil, nil, true)
|
||||
require.NoError(t, err)
|
||||
model = decodeCodexManifestModels(t, body)[0]
|
||||
require.Nil(t, model["multi_agent_reasoning_effort"], "do not advertise one account's override for all peers")
|
||||
require.Nil(t, model["multi_agent_version"])
|
||||
}
|
||||
|
||||
func TestAstraUltraCatalogPreservesExplicitWorkflowOverrides(t *testing.T) {
|
||||
account := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"base_url": "https://relay.example/v1"}}
|
||||
for _, fields := range []string{
|
||||
`"multi_agent_reasoning_effort":"high","multi_agent_version":"v1"`,
|
||||
`"multi_agent_reasoning_effort":null,"multi_agent_version":null`,
|
||||
} {
|
||||
for _, source := range []string{
|
||||
`{"models":[{"slug":"gpt-6-astra",` + fields + `}]}`,
|
||||
`{"data":[{"id":"gpt-6-astra",` + fields + `}]}`,
|
||||
} {
|
||||
converted := convertOpenAIModelListToCodexManifestForAccount([]byte(source), account)
|
||||
body, err := completeAPIKeyCodexModelsManifestMetadata(converted, true, account)
|
||||
require.NoError(t, err)
|
||||
model := decodeCodexManifestModels(t, body)[0]
|
||||
var expected map[string]any
|
||||
require.NoError(t, json.Unmarshal([]byte(`{`+fields+`}`), &expected))
|
||||
for key, value := range expected {
|
||||
require.Contains(t, model, key)
|
||||
require.Equal(t, value, model[key])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAstraCodexToolCapabilitiesUseAccountScopeAndSharedDeclarations(t *testing.T) {
|
||||
newAccount := func(baseURL string) Account {
|
||||
return Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{
|
||||
@@ -645,7 +697,8 @@ func TestCodexAliasFailoverMappingHonorsModelRouting(t *testing.T) {
|
||||
levels, def, modalities := manifestFieldsOf(t, nil)
|
||||
require.Empty(t, levels, "ambiguous alias target must not advertise reasoning levels")
|
||||
require.Nil(t, def)
|
||||
require.Equal(t, []any{"text"}, modalities)
|
||||
require.Equal(t, []any{"text", "image"}, modalities,
|
||||
"image input is resolved per-account independently of routing rules")
|
||||
})
|
||||
|
||||
t.Run("routing rule resolves the alias", func(t *testing.T) {
|
||||
@@ -657,7 +710,7 @@ func TestCodexAliasFailoverMappingHonorsModelRouting(t *testing.T) {
|
||||
}
|
||||
levels, def, modalities := manifestFieldsOf(t, group)
|
||||
require.Equal(t,
|
||||
[]string{"low", "medium", "high", "xhigh", "max"},
|
||||
[]string{"low", "medium", "high", "xhigh", "max", "ultra"},
|
||||
levels,
|
||||
"routed alias must keep a movable reasoning slider",
|
||||
)
|
||||
|
||||
@@ -116,8 +116,8 @@ type OpenAIModelsResponse struct {
|
||||
NotModified bool
|
||||
}
|
||||
|
||||
// BuildGroupConfiguredCodexModelsManifest builds a Codex catalog exclusively
|
||||
// from the public model names configured on accounts in an OpenAI group. The
|
||||
// BuildGroupConfiguredCodexModelsManifest builds a Codex catalog from configured
|
||||
// public model names, supplemented by defaults for unmapped OpenAI accounts. The
|
||||
// boolean result distinguishes "no explicit configuration" from a configured
|
||||
// catalog that becomes empty after group-level filtering.
|
||||
func (s *OpenAIGatewayService) BuildGroupConfiguredCodexModelsManifest(
|
||||
@@ -295,7 +295,7 @@ func openAIConfiguredCodexModelIDs(accounts []Account) []string {
|
||||
}
|
||||
|
||||
func openAIConfiguredCodexModelIDsForGroup(accounts []Account, group *Group) []string {
|
||||
models := openAIConfiguredCodexModelIDs(accounts)
|
||||
models := supplementUnmappedOpenAIModels(accounts, openAIConfiguredCodexModelIDs(accounts))
|
||||
if group == nil || !group.ModelAllowlistEnabled() {
|
||||
return models
|
||||
}
|
||||
@@ -379,6 +379,7 @@ type configuredCodexModelDescriptor struct {
|
||||
Description string `json:"description"`
|
||||
DefaultReasoningLevel *string `json:"default_reasoning_level,omitempty"`
|
||||
SupportedReasoningLevels []configuredCodexReasoningLevel `json:"supported_reasoning_levels"`
|
||||
MultiAgentReasoningEffort *string `json:"multi_agent_reasoning_effort,omitempty"`
|
||||
ShellType string `json:"shell_type"`
|
||||
Visibility string `json:"visibility"`
|
||||
SupportedInAPI bool `json:"supported_in_api"`
|
||||
@@ -510,6 +511,11 @@ func newConfiguredCodexModelDescriptor(modelID string) configuredCodexModelDescr
|
||||
descriptor.MaxContextWindow = configuredCodexGPT56MaxContext
|
||||
}
|
||||
if isOpenAIGPT6AstraModel(modelID) {
|
||||
// Codex resolves the Ultra workflow to this effort before inference.
|
||||
// openai/codex a9896da3: codex-rs/models-manager/models.json.
|
||||
multiAgentEffort := "xhigh"
|
||||
descriptor.MultiAgentReasoningEffort = &multiAgentEffort
|
||||
descriptor.MultiAgentVersion = "v2"
|
||||
descriptor.ContextWindow = configuredCodexGPT6AstraContext
|
||||
descriptor.MaxContextWindow = configuredCodexGPT6AstraContext
|
||||
}
|
||||
@@ -620,7 +626,7 @@ func configuredCodexGPTReasoningLevels(modelID string) []configuredCodexReasonin
|
||||
Description: "Maximum reasoning depth for complex tasks",
|
||||
})
|
||||
}
|
||||
if normalized == "gpt-5.6-sol" || normalized == "gpt-5.6-terra" {
|
||||
if isOpenAIGPT6AstraModel(modelID) || normalized == "gpt-5.6-sol" || normalized == "gpt-5.6-terra" {
|
||||
levels = append(levels, configuredCodexReasoningLevel{
|
||||
Effort: "ultra",
|
||||
Description: "Maximum reasoning with automatic task delegation",
|
||||
@@ -909,13 +915,15 @@ func buildCodexModelsManifest(
|
||||
seen[modelID] = struct{}{}
|
||||
descriptor := newConfiguredCodexModelDescriptor(metadataModelID)
|
||||
descriptor.Slug = modelID
|
||||
if imageInputModels[modelID] {
|
||||
descriptor.InputModalities = []string{"text", "image"}
|
||||
}
|
||||
descriptor.SupportsSearchTool = searchToolModels[modelID]
|
||||
if metadata, ok := modelMetadata[modelID]; ok {
|
||||
applyUpstreamModelMetadataToCodexDescriptor(&descriptor, metadata)
|
||||
}
|
||||
if imageInputModels[modelID] {
|
||||
// Apply the capability-derived modality after upstream metadata so
|
||||
// a stale official Astra snapshot cannot downgrade the catalog.
|
||||
descriptor.InputModalities = []string{"text", "image"}
|
||||
}
|
||||
if metadataModelID != modelID {
|
||||
descriptor.DisplayName = modelID
|
||||
descriptor.Description = configuredCodexCustomDescription
|
||||
@@ -1207,6 +1215,13 @@ func accountCodexModelSupportsImageInput(account *Account, upstreamModel string)
|
||||
case PlatformOpenAI:
|
||||
if metadata, ok := account.GetUpstreamModelMetadata(upstreamModel); ok {
|
||||
if modalities := normalizeCodexInputModalities(metadata.InputModalities); len(modalities) > 0 {
|
||||
// Official GPT-6 Astra metadata briefly shipped with a stale
|
||||
// text-only modality list. Keep explicit provider metadata
|
||||
// authoritative for compatible hosts, but repair that stale
|
||||
// official snapshot at the capability boundary.
|
||||
if isOpenAIGPT6AstraModel(upstreamModel) && isOfficialOpenAICodexAccount(account) {
|
||||
return true
|
||||
}
|
||||
return stringSliceContains(modalities, "image")
|
||||
}
|
||||
}
|
||||
@@ -1233,6 +1248,16 @@ func accountCodexModelSupportsImageInput(account *Account, upstreamModel string)
|
||||
}
|
||||
}
|
||||
|
||||
func isOfficialOpenAICodexAccount(account *Account) bool {
|
||||
if account == nil || account.Platform != PlatformOpenAI {
|
||||
return false
|
||||
}
|
||||
if account.IsOpenAIOAuth() {
|
||||
return true
|
||||
}
|
||||
return account.IsOpenAIApiKey() && isOfficialOpenAIModelsBaseURL(account.GetOpenAIBaseURL())
|
||||
}
|
||||
|
||||
func isGrokCodexImageInputModel(model string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(model)) {
|
||||
case "grok-4.3",
|
||||
|
||||
@@ -351,10 +351,13 @@ func TestNewConfiguredCodexModelDescriptorUsesProviderMetadataAndSafeFallback(t
|
||||
|
||||
gpt6Astra := newConfiguredCodexModelDescriptor("gpt-6-astra")
|
||||
require.Equal(t, "GPT-6 Astra", gpt6Astra.DisplayName)
|
||||
require.True(t, strings.HasPrefix(strings.TrimSpace(gpt6Astra.ModelMessages.InstructionsTemplate), "You are Codex, an agent based on GPT-6."))
|
||||
require.NotNil(t, gpt6Astra.DefaultReasoningLevel)
|
||||
require.Equal(t, "medium", *gpt6Astra.DefaultReasoningLevel)
|
||||
require.Equal(t, []string{"low", "medium", "high", "xhigh", "max"}, effortsFromConfiguredCodexLevels(gpt6Astra.SupportedReasoningLevels))
|
||||
require.NotContains(t, gpt6Astra.SupportedReasoningLevels, configuredCodexReasoningLevel{Effort: "ultra"})
|
||||
require.Equal(t, []string{"low", "medium", "high", "xhigh", "max", "ultra"}, effortsFromConfiguredCodexLevels(gpt6Astra.SupportedReasoningLevels))
|
||||
require.NotNil(t, gpt6Astra.MultiAgentReasoningEffort)
|
||||
require.Equal(t, "xhigh", *gpt6Astra.MultiAgentReasoningEffort)
|
||||
require.Equal(t, "v2", gpt6Astra.MultiAgentVersion)
|
||||
require.NotContains(t, gpt6Astra.SupportedReasoningLevels, configuredCodexReasoningLevel{Effort: "none"})
|
||||
require.True(t, configuredCodexSupportsPriorityServiceTier("gpt-6-astra"))
|
||||
require.Equal(t, []configuredCodexServiceTier{{
|
||||
@@ -370,7 +373,10 @@ func TestNewConfiguredCodexModelDescriptorUsesProviderMetadataAndSafeFallback(t
|
||||
require.Equal(t, int64(1_050_000), gpt6Astra.MaxContextWindow)
|
||||
gpt6 := newConfiguredCodexModelDescriptor("gpt-6")
|
||||
require.Equal(t, "GPT-6 (Astra)", gpt6.DisplayName)
|
||||
require.Equal(t, []string{"low", "medium", "high", "xhigh", "max"}, effortsFromConfiguredCodexLevels(gpt6.SupportedReasoningLevels))
|
||||
require.True(t, strings.HasPrefix(strings.TrimSpace(gpt6.ModelMessages.InstructionsTemplate), "You are Codex, an agent based on GPT-6."))
|
||||
require.Equal(t, []string{"low", "medium", "high", "xhigh", "max", "ultra"}, effortsFromConfiguredCodexLevels(gpt6.SupportedReasoningLevels))
|
||||
require.NotNil(t, gpt6.MultiAgentReasoningEffort)
|
||||
require.Equal(t, "xhigh", *gpt6.MultiAgentReasoningEffort)
|
||||
require.Equal(t, int64(1_050_000), gpt6.ContextWindow)
|
||||
|
||||
gpt55 := newConfiguredCodexModelDescriptor("gpt-5.5")
|
||||
@@ -409,6 +415,25 @@ func TestNewConfiguredCodexModelDescriptorUsesProviderMetadataAndSafeFallback(t
|
||||
require.Equal(t, configuredCodexTruncationPolicy{Mode: "bytes", Limit: 10_000}, custom.TruncationPolicy)
|
||||
}
|
||||
|
||||
func TestBuildCodexModelsManifestUsesGPT6AstraInstructions(t *testing.T) {
|
||||
body, err := BuildCodexModelsManifest([]string{"gpt-6-astra"})
|
||||
require.NoError(t, err)
|
||||
|
||||
var manifest struct {
|
||||
Models []struct {
|
||||
ModelMessages struct {
|
||||
InstructionsTemplate string `json:"instructions_template"`
|
||||
} `json:"model_messages"`
|
||||
} `json:"models"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(body, &manifest))
|
||||
require.Len(t, manifest.Models, 1)
|
||||
require.True(t, strings.HasPrefix(
|
||||
strings.TrimSpace(manifest.Models[0].ModelMessages.InstructionsTemplate),
|
||||
"You are Codex, an agent based on GPT-6.",
|
||||
))
|
||||
}
|
||||
|
||||
func effortsFromConfiguredCodexLevels(levels []configuredCodexReasoningLevel) []string {
|
||||
efforts := make([]string, 0, len(levels))
|
||||
for _, level := range levels {
|
||||
@@ -1105,7 +1130,7 @@ func TestMergeGroupConfiguredCodexModelsInjectsCurrentGroupAliases(t *testing.T)
|
||||
require.Equal(t, codexModelsManifestBodyETag(manifest.Body), manifest.ETag)
|
||||
}
|
||||
|
||||
// Scenario: OpenAI 分组存在账号模型配置时直接生成本地 Codex 清单。
|
||||
// Mixed groups retain configured metadata alongside defaults for unmapped accounts.
|
||||
func TestBuildGroupConfiguredCodexModelsManifestUsesAdministratorConfiguration(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -1150,8 +1175,10 @@ func TestBuildGroupConfiguredCodexModelsManifestUsesAdministratorConfiguration(t
|
||||
require.NoError(t, err)
|
||||
require.True(t, configured)
|
||||
models := decodeCodexManifestModels(t, manifest.Body)
|
||||
require.Len(t, models, 1)
|
||||
require.Equal(t, "glm-5.3", models[0]["slug"])
|
||||
require.Contains(t, codexManifestModelSlugs(t, manifest.Body), "gpt-5.6-sol")
|
||||
require.NotContains(t, codexManifestModelSlugs(t, manifest.Body), "gpt-image-2")
|
||||
require.NotContains(t, codexManifestModelSlugs(t, manifest.Body), "codex-auto-review")
|
||||
require.Equal(t, "GLM 5.3", models[0]["display_name"])
|
||||
require.Equal(t, []string{"low", "medium", "high"}, effortsFromManifestModel(t, models[0]))
|
||||
require.Equal(t, "medium", models[0]["default_reasoning_level"])
|
||||
|
||||
@@ -115,6 +115,9 @@ func collectOpenAIResponsesToolNameFields(reqBody map[string]any) []codexToolNam
|
||||
}
|
||||
}
|
||||
if choice, ok := reqBody["tool_choice"].(map[string]any); ok {
|
||||
if strings.EqualFold(strings.TrimSpace(firstNonEmptyString(choice["type"])), "allowed_tools") {
|
||||
collectTools(choice["tools"])
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(firstNonEmptyString(choice["type"])), "function") {
|
||||
appendName(choice, "name")
|
||||
if function, ok := choice["function"].(map[string]any); ok {
|
||||
|
||||
@@ -357,6 +357,12 @@ func normalizeCodexToolChoice(reqBody map[string]any) bool {
|
||||
if choiceType == "" {
|
||||
return false
|
||||
}
|
||||
if choiceType == "allowed_tools" {
|
||||
// This is a selection policy, not a declared tool type. Preserve it for
|
||||
// upstream validation (including references to input.additional_tools);
|
||||
// falling back to auto would silently discard the caller's restriction.
|
||||
return false
|
||||
}
|
||||
modified := false
|
||||
if choiceType == "function" {
|
||||
name := strings.TrimSpace(firstNonEmptyString(choiceMap["name"]))
|
||||
@@ -1392,8 +1398,7 @@ func extractPromptLikeInstructionsFromInput(reqBody map[string]any) string {
|
||||
|
||||
// defaultCodexSynthInstructions 返回合成路径在 instructions 为空时应填入的默认提示词。
|
||||
//
|
||||
// 按 model 选择真实 Codex CLI 的 base instructions(codex 系→GPT-5-Codex,
|
||||
// gpt-5.2→GPT-5.2,gpt-5.1/gpt-5→GPT-5.1),使合成请求在提示词层面贴近真实 Codex 行为;
|
||||
// 按 model 选择真实 Codex CLI 的 base instructions,使合成请求在提示词层面贴近真实 Codex 行为;
|
||||
// 若内嵌 prompt 意外为空,回退到最小占位符以保证字段非空。
|
||||
func defaultCodexSynthInstructions(model string) string {
|
||||
if instructions := strings.TrimSpace(openai.CodexBaseInstructionsForModel(model)); instructions != "" {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -477,6 +478,74 @@ func TestApplyCodexOAuthTransform_StringifiesNonStringMessageContentText(t *test
|
||||
require.Equal(t, `["a","b"]`, part["text"])
|
||||
}
|
||||
|
||||
func TestApplyCodexOAuthTransform_PreservesAllowedTools(t *testing.T) {
|
||||
for _, placement := range []string{"top_level", "additional_tools"} {
|
||||
for _, mode := range []string{"auto", "required"} {
|
||||
t.Run(placement+"/"+mode, func(t *testing.T) {
|
||||
decision := map[string]any{"type": "function", "name": "ProbeAccept"}
|
||||
choice := map[string]any{
|
||||
"type": "allowed_tools", "mode": mode,
|
||||
"tools": []any{map[string]any{"type": "function", "name": "ProbeAccept"}},
|
||||
}
|
||||
tools := []any{
|
||||
map[string]any{"type": "function", "name": "ProbeBase"},
|
||||
map[string]any{"type": "web_search"},
|
||||
map[string]any{"type": "image_generation"},
|
||||
}
|
||||
input := []any{map[string]any{"type": "message", "role": "user", "content": "probe"}}
|
||||
if placement == "top_level" {
|
||||
tools = append(tools, decision)
|
||||
} else {
|
||||
input = append(input, map[string]any{
|
||||
"type": "additional_tools", "role": "developer", "tools": []any{decision},
|
||||
})
|
||||
}
|
||||
reqBody := map[string]any{"tools": tools, "input": input, "tool_choice": choice}
|
||||
before, err := json.Marshal(reqBody)
|
||||
require.NoError(t, err)
|
||||
reqBody["model"] = "gpt-6-astra"
|
||||
result := applyCodexOAuthTransform(reqBody, true, false)
|
||||
require.NoError(t, result.Error)
|
||||
after, err := json.Marshal(map[string]any{
|
||||
"tools": reqBody["tools"], "input": reqBody["input"], "tool_choice": reqBody["tool_choice"],
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, string(before), string(after))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexToolChoice_InvalidAllowedToolsNeverBecomesAuto(t *testing.T) {
|
||||
for _, choice := range []map[string]any{
|
||||
{"type": "allowed_tools"},
|
||||
{"type": "allowed_tools", "mode": "invalid", "tools": []any{}},
|
||||
{"type": "allowed_tools", "mode": "required", "tools": "invalid"},
|
||||
{"type": "allowed_tools", "mode": "required", "tools": []any{map[string]any{"type": "function", "name": "missing"}}},
|
||||
} {
|
||||
reqBody := map[string]any{"tool_choice": choice}
|
||||
require.False(t, normalizeCodexToolChoice(reqBody))
|
||||
// The upstream owns schema validation. A malformed restriction must never
|
||||
// silently become permission to call every supplied tool.
|
||||
require.Equal(t, choice, reqBody["tool_choice"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyCodexOAuthTransform_AllowedToolsKeepsReservedNameReferences(t *testing.T) {
|
||||
declaration := map[string]any{"type": "function", "name": "python"}
|
||||
reference := map[string]any{"type": "function", "name": "python"}
|
||||
choice := map[string]any{"type": "allowed_tools", "mode": "required", "tools": []any{reference}}
|
||||
reqBody := map[string]any{
|
||||
"model": "gpt-6-astra", "tools": []any{declaration}, "tool_choice": choice,
|
||||
}
|
||||
result := applyCodexOAuthTransform(reqBody, true, false)
|
||||
require.NoError(t, result.Error)
|
||||
require.Equal(t, choice, reqBody["tool_choice"])
|
||||
require.Equal(t, codexPythonToolAlias, declaration["name"])
|
||||
require.Equal(t, codexPythonToolAlias, reference["name"])
|
||||
require.Equal(t, "python", result.ToolNameReverse[codexPythonToolAlias])
|
||||
}
|
||||
|
||||
func TestApplyCodexOAuthTransform_DowngradesUnknownToolChoice(t *testing.T) {
|
||||
reqBody := map[string]any{
|
||||
"model": "gpt-5.4",
|
||||
@@ -1497,6 +1566,20 @@ func TestApplyCodexOAuthTransform_GPT55SuppliesModelSpecificInstructions(t *test
|
||||
require.True(t, result.Modified)
|
||||
}
|
||||
|
||||
func TestApplyCodexOAuthTransform_GPT6AstraSuppliesModelSpecificInstructions(t *testing.T) {
|
||||
reqBody := map[string]any{
|
||||
"model": "gpt-6-astra",
|
||||
}
|
||||
|
||||
result := applyCodexOAuthTransform(reqBody, true, false)
|
||||
|
||||
instructions, ok := reqBody["instructions"].(string)
|
||||
require.True(t, ok)
|
||||
require.True(t, strings.HasPrefix(strings.TrimSpace(instructions), "You are Codex, an agent based on GPT-6."))
|
||||
require.NotContains(t, instructions, "You are Codex, a coding agent based on GPT-5.")
|
||||
require.True(t, result.Modified)
|
||||
}
|
||||
|
||||
func TestApplyCodexOAuthTransform_NonCodexCLI_PreservesExistingInstructions(t *testing.T) {
|
||||
// 非 Codex CLI 场景:已有 instructions 时保留客户端的值,不再覆盖
|
||||
|
||||
|
||||
@@ -358,12 +358,6 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
return nil, errors.New("image generation disabled for group")
|
||||
}
|
||||
|
||||
instructions := gjson.GetBytes(body, "instructions")
|
||||
instructionsEmpty := !instructions.Exists() || instructions.Type != gjson.String || strings.TrimSpace(instructions.String()) == ""
|
||||
if instructionsEmpty && account.UsesOpenAICodexProtocol() && !compatMessagesBridge && !nativeCNResponses {
|
||||
markPatchSet("instructions", defaultCodexSynthInstructions(reqModel))
|
||||
}
|
||||
|
||||
isCompactRequest := compactPath
|
||||
requestedModel := reqModel
|
||||
billingModel, upstreamModel := resolveOpenAIForwardMappedModels(account, requestedModel, isCompactRequest)
|
||||
@@ -372,6 +366,11 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
upstreamModel = compactModel
|
||||
}
|
||||
}
|
||||
instructions := gjson.GetBytes(body, "instructions")
|
||||
instructionsEmpty := !instructions.Exists() || instructions.Type != gjson.String || strings.TrimSpace(instructions.String()) == ""
|
||||
if instructionsEmpty && account.UsesOpenAICodexProtocol() && !compatMessagesBridge && !nativeCNResponses {
|
||||
markPatchSet("instructions", defaultCodexSynthInstructions(upstreamModel))
|
||||
}
|
||||
if billingModel != requestedModel {
|
||||
logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Model mapping applied: %s -> %s (account: %s, isCodexCLI: %v)", requestedModel, billingModel, account.Name, isCodexCLI)
|
||||
}
|
||||
|
||||
@@ -272,10 +272,9 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic(
|
||||
if account.Platform == PlatformOpenAI {
|
||||
policyBody, changed, policyErr := ApplyOpenAIReasoningEffortPolicyFromContext(ctx, responsesBody)
|
||||
if policyErr != nil {
|
||||
var overLimit *ReasoningEffortOverLimitError
|
||||
if errors.As(policyErr, &overLimit) {
|
||||
if IsReasoningEffortPolicyDenied(policyErr) {
|
||||
MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalPolicyDenied)
|
||||
writeAnthropicError(c, http.StatusForbidden, "forbidden_error", overLimit.Error())
|
||||
writeAnthropicError(c, http.StatusForbidden, "forbidden_error", policyErr.Error())
|
||||
}
|
||||
return nil, policyErr
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -83,10 +82,9 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions(
|
||||
if account.Platform == PlatformOpenAI {
|
||||
policyBody, changed, policyErr := ApplyOpenAIReasoningEffortPolicyFromContext(ctx, chatBody)
|
||||
if policyErr != nil {
|
||||
var overLimit *ReasoningEffortOverLimitError
|
||||
if errors.As(policyErr, &overLimit) {
|
||||
if IsReasoningEffortPolicyDenied(policyErr) {
|
||||
MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalPolicyDenied)
|
||||
writeAnthropicError(c, http.StatusForbidden, "forbidden_error", overLimit.Error())
|
||||
writeAnthropicError(c, http.StatusForbidden, "forbidden_error", policyErr.Error())
|
||||
}
|
||||
return nil, policyErr
|
||||
}
|
||||
|
||||
@@ -2079,6 +2079,11 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthrough(
|
||||
s.handleOpenAIStreamTerminalAccountSideEffects(c, account, dataBytes, failedMessage, resp.Header, mappedModel)
|
||||
bareErrorAccountSideEffectsPending = false
|
||||
}
|
||||
if eventType == "response.failed" {
|
||||
// The stream cannot be replayed after semantic output. Preserve the
|
||||
// terminal event, while making the upstream failure queryable.
|
||||
s.recordOpenAIStreamUpstreamError(c, account, true, upstreamRequestID, "stream_failed", dataBytes, failedMessage)
|
||||
}
|
||||
}
|
||||
if !outputStarted {
|
||||
shouldFailover := false
|
||||
|
||||
@@ -569,6 +569,75 @@ func TestOpenAIGatewayServiceRecordUsage_TimePricingUsesExplicitPricingAt(t *tes
|
||||
require.InDelta(t, baseCost*0.8, usageRepo.lastLog.ActualCost, 1e-12)
|
||||
require.InDelta(t, 0.8, usageRepo.lastLog.RateMultiplier, 1e-12)
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayServiceRecordUsage_DeepSeekAccountStatsUsesRequestPricingAtAndUpstreamModel(t *testing.T) {
|
||||
for _, model := range []struct {
|
||||
name string
|
||||
offPeakCost float64
|
||||
}{
|
||||
{"deepseek-v4-flash", 1000*2.2e-7 + 500*6.6e-7 + 1000*7e-9},
|
||||
{"deepseek-v4-pro", 1000*6.6e-7 + 500*1.98e-6 + 1000*2.2e-8},
|
||||
} {
|
||||
for _, slot := range []struct {
|
||||
name string
|
||||
pricingAt time.Time
|
||||
multiplier float64
|
||||
}{
|
||||
{"peak", time.Date(2026, time.August, 24, 2, 0, 0, 0, time.UTC), 2},
|
||||
{"off_peak", time.Date(2026, time.August, 24, 12, 0, 0, 0, time.UTC), 1},
|
||||
} {
|
||||
t.Run(model.name+"/"+slot.name, func(t *testing.T) {
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
|
||||
userRepo := &openAIRecordUsageUserRepoStub{}
|
||||
svc := newOpenAIRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{}, nil)
|
||||
groupID := int64(18)
|
||||
cache := newEmptyChannelCache()
|
||||
cache.channelByGroupID[groupID] = &Channel{ID: 1, Status: StatusActive}
|
||||
cache.groupPlatform[groupID] = PlatformDeepseek
|
||||
cache.loadedAt = time.Now()
|
||||
svc.channelService = &ChannelService{}
|
||||
svc.channelService.cache.Store(cache)
|
||||
svc.resolver = NewModelPricingResolver(svc.channelService, svc.billingService)
|
||||
alias := "customer-chat"
|
||||
inputPrice, outputPrice, cachePrice := 1e-6, 2e-6, 1e-7
|
||||
group := &Group{ID: groupID, Platform: PlatformDeepseek, RateMultiplier: 0.8,
|
||||
ModelPricing: []ChannelModelPricing{{
|
||||
Models: []string{alias}, BillingMode: BillingModeToken,
|
||||
InputPrice: &inputPrice, OutputPrice: &outputPrice, CacheReadPrice: &cachePrice,
|
||||
}},
|
||||
}
|
||||
err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
|
||||
Result: &OpenAIForwardResult{
|
||||
RequestID: "openai_deepseek_account_stats_" + model.name + "_" + slot.name,
|
||||
Model: alias, BillingModel: alias, UpstreamModel: model.name,
|
||||
Usage: OpenAIUsage{InputTokens: 2000, OutputTokens: 500, CacheReadInputTokens: 1000},
|
||||
},
|
||||
APIKey: &APIKey{ID: 1008, GroupID: &groupID, Group: group},
|
||||
User: &User{ID: 2008}, Account: &Account{ID: 3008, Platform: PlatformDeepseek},
|
||||
PricingAt: slot.pricingAt,
|
||||
ChannelUsageFields: ChannelUsageFields{OriginalModel: alias, BillingModelSource: BillingModelSourceRequested},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, usageRepo.lastLog)
|
||||
log := usageRepo.lastLog
|
||||
require.Equal(t, alias, log.RequestedModel)
|
||||
require.NotNil(t, log.UpstreamModel)
|
||||
require.Equal(t, model.name, *log.UpstreamModel)
|
||||
require.WithinDuration(t, time.Now(), log.CreatedAt, time.Minute)
|
||||
require.False(t, log.CreatedAt.Equal(slot.pricingAt), "request pricing time must differ from record creation")
|
||||
customerTotal := 1000*inputPrice + 500*outputPrice + 1000*cachePrice
|
||||
require.InDelta(t, customerTotal, log.TotalCost, 1e-12)
|
||||
require.InDelta(t, customerTotal*0.8, log.ActualCost, 1e-12)
|
||||
require.Equal(t, 1, userRepo.deductCalls)
|
||||
require.InDelta(t, customerTotal*0.8, userRepo.lastAmount, 1e-12)
|
||||
require.NotNil(t, log.AccountStatsCost)
|
||||
require.InDelta(t, model.offPeakCost*slot.multiplier, *log.AccountStatsCost, 1e-12,
|
||||
"account cost must use the upstream model and historical PricingAt")
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayServiceRecordUsage_IncludesEndpointMetadata(t *testing.T) {
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
|
||||
userRepo := &openAIRecordUsageUserRepoStub{}
|
||||
|
||||
@@ -561,6 +561,12 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context.
|
||||
s.handleOpenAIStreamTerminalAccountSideEffects(c, account, dataBytes, failedMessage, resp.Header, mappedModel)
|
||||
bareErrorAccountSideEffectsPending = false
|
||||
}
|
||||
if eventType == "response.failed" {
|
||||
// Once semantic output is committed, failover replay is unsafe. Keep
|
||||
// the terminal event on the existing stream, but retain the upstream
|
||||
// request ID and payload for operations diagnostics.
|
||||
s.recordOpenAIStreamUpstreamError(c, account, false, upstreamRequestID, "stream_failed", dataBytes, failedMessage)
|
||||
}
|
||||
}
|
||||
if !outputStarted {
|
||||
shouldFailover := false
|
||||
|
||||
@@ -472,7 +472,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec
|
||||
if apiKey.GroupID != nil {
|
||||
applyAccountStatsCost(ctx, usageLog, s.channelService, s.billingService,
|
||||
account.ID, *apiKey.GroupID, result.UpstreamModel, result.Model,
|
||||
tokens, cost.TotalCost,
|
||||
tokens, cost.TotalCost, pricingAt,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
package service
|
||||
|
||||
import "strings"
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/openai"
|
||||
)
|
||||
|
||||
func lastOpenAIModelSegment(model string) string {
|
||||
model = strings.TrimSpace(model)
|
||||
@@ -15,38 +19,7 @@ func lastOpenAIModelSegment(model string) string {
|
||||
}
|
||||
|
||||
func canonicalizeOpenAIModelAliasSpelling(model string) string {
|
||||
model = strings.ToLower(lastOpenAIModelSegment(model))
|
||||
if model == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
normalized := strings.ReplaceAll(model, "_", "-")
|
||||
normalized = strings.Join(strings.Fields(normalized), "-")
|
||||
for strings.Contains(normalized, "--") {
|
||||
normalized = strings.ReplaceAll(normalized, "--", "-")
|
||||
}
|
||||
|
||||
if strings.HasPrefix(normalized, "gpt5") {
|
||||
normalized = "gpt-5" + strings.TrimPrefix(normalized, "gpt5")
|
||||
}
|
||||
if !strings.HasPrefix(normalized, "gpt-") && !strings.Contains(normalized, "codex") {
|
||||
return ""
|
||||
}
|
||||
|
||||
replacements := []struct {
|
||||
from string
|
||||
to string
|
||||
}{
|
||||
{"gpt-5.4mini", "gpt-5.4-mini"},
|
||||
{"gpt-5.4nano", "gpt-5.4-nano"},
|
||||
{"gpt-5.3-codexspark", "gpt-5.3-codex-spark"},
|
||||
{"gpt-5.3codexspark", "gpt-5.3-codex-spark"},
|
||||
{"gpt-5.3codex", "gpt-5.3-codex"},
|
||||
}
|
||||
for _, replacement := range replacements {
|
||||
normalized = strings.ReplaceAll(normalized, replacement.from, replacement.to)
|
||||
}
|
||||
return normalized
|
||||
return openai.CanonicalizeOpenAIModelAliasSpelling(model)
|
||||
}
|
||||
|
||||
func normalizeKnownOpenAICodexModel(model string) string {
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
)
|
||||
|
||||
func TestNormalizeKnownOpenAICodexModelGPT6Astra(t *testing.T) {
|
||||
for _, model := range []string{"gpt-6-astra", "openai/gpt-6-astra", "gpt-6", "openai/gpt-6"} {
|
||||
for _, model := range []string{"gpt-6-astra", "openai/gpt-6-astra", "OPENAI/GPT-6_ASTRA", "gpt-6", "openai/gpt-6"} {
|
||||
require.Equal(t, "gpt-6-astra", normalizeKnownOpenAICodexModel(model))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -936,6 +936,44 @@ func TestOpenAIGatewayService_OAuthPassthrough_CodexMissingInstructionsGetsDefau
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayService_Forward_MissingInstructionsUsesMappedModelTemplate(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil))
|
||||
c.Request.Header.Set("User-Agent", "codex_cli_rs/0.98.0")
|
||||
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid_mapped_astra"}},
|
||||
Body: io.NopCloser(strings.NewReader(strings.Join([]string{
|
||||
`data: {"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`,
|
||||
"", "data: [DONE]", "",
|
||||
}, "\n"))),
|
||||
}}
|
||||
svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream}
|
||||
account := &Account{
|
||||
ID: 123, Name: "acc", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1,
|
||||
Credentials: map[string]any{
|
||||
"access_token": "oauth-token",
|
||||
"chatgpt_account_id": "chatgpt-acc",
|
||||
"model_mapping": map[string]any{"astra-public": "gpt-6-astra"},
|
||||
},
|
||||
Extra: map[string]any{
|
||||
"openai_oauth_responses_websockets_v2_mode": OpenAIWSIngressModeOff,
|
||||
},
|
||||
Status: StatusActive, Schedulable: true, RateMultiplier: f64p(1),
|
||||
}
|
||||
|
||||
result, err := svc.Forward(context.Background(), c, account, []byte(`{"model":"astra-public","stream":true,"store":true,"input":[{"type":"text","text":"hi"}]}`))
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Equal(t, "gpt-6-astra", gjson.GetBytes(upstream.lastBody, "model").String())
|
||||
instructions := gjson.GetBytes(upstream.lastBody, "instructions").String()
|
||||
require.True(t, strings.HasPrefix(strings.TrimSpace(instructions), "You are Codex, an agent based on GPT-6."))
|
||||
require.NotContains(t, instructions, "You are Codex, a coding agent based on GPT-5.")
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayService_OAuthPassthrough_DisabledUsesLegacyTransform(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
@@ -19,6 +20,9 @@ const (
|
||||
ReasoningEffortOverLimitDowngrade = "downgrade"
|
||||
// ReasoningEffortOverLimitDeny rejects the request when the ceiling is exceeded.
|
||||
ReasoningEffortOverLimitDeny = "deny"
|
||||
// ReasoningEffortMappingDeny is a mapping target that rejects the request
|
||||
// when the matching source reasoning effort is present.
|
||||
ReasoningEffortMappingDeny = "deny"
|
||||
)
|
||||
|
||||
var openAIReasoningEffortValues = []string{"minimal", "low", "medium", "high", "xhigh", "max"}
|
||||
@@ -31,6 +35,17 @@ func normalizeReasoningEffortMappingSource(raw string) string {
|
||||
return NormalizeMaxReasoningEffort(raw)
|
||||
}
|
||||
|
||||
func normalizeReasoningEffortMappingTarget(raw string) string {
|
||||
if isReasoningEffortMappingDeny(raw) {
|
||||
return ReasoningEffortMappingDeny
|
||||
}
|
||||
return NormalizeMaxReasoningEffort(raw)
|
||||
}
|
||||
|
||||
func isReasoningEffortMappingDeny(raw string) bool {
|
||||
return strings.EqualFold(strings.TrimSpace(raw), ReasoningEffortMappingDeny)
|
||||
}
|
||||
|
||||
type openAIReasoningEffortPolicyContextKey struct{}
|
||||
type requestedReasoningEffortContextKey struct{}
|
||||
|
||||
@@ -65,6 +80,37 @@ func (e *ReasoningEffortOverLimitError) Error() string {
|
||||
return fmt.Sprintf("reasoning effort %q exceeds this group's limit of %q", requested, max)
|
||||
}
|
||||
|
||||
// ReasoningEffortMappingDeniedError is returned when a group mapping target is
|
||||
// set to deny the explicit reasoning effort on the request.
|
||||
type ReasoningEffortMappingDeniedError struct {
|
||||
Requested string
|
||||
}
|
||||
|
||||
func (e *ReasoningEffortMappingDeniedError) Error() string {
|
||||
if e == nil {
|
||||
return "reasoning effort is denied by this group's mapping policy"
|
||||
}
|
||||
requested := strings.TrimSpace(e.Requested)
|
||||
if requested == "" {
|
||||
return "reasoning effort is denied by this group's mapping policy"
|
||||
}
|
||||
return fmt.Sprintf("reasoning effort %q is denied by this group's mapping policy", requested)
|
||||
}
|
||||
|
||||
// IsReasoningEffortPolicyDenied reports whether err is a local reasoning-effort
|
||||
// policy rejection (ceiling deny or mapping deny).
|
||||
func IsReasoningEffortPolicyDenied(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var overLimit *ReasoningEffortOverLimitError
|
||||
if errors.As(err, &overLimit) {
|
||||
return true
|
||||
}
|
||||
var mappingDenied *ReasoningEffortMappingDeniedError
|
||||
return errors.As(err, &mappingDenied)
|
||||
}
|
||||
|
||||
// NormalizeMaxReasoningEffort validates and canonicalizes a group policy value.
|
||||
// Empty means that the group does not impose a ceiling.
|
||||
func NormalizeMaxReasoningEffort(raw string) string {
|
||||
@@ -298,7 +344,7 @@ func NormalizeReasoningEffortMappings(platform string, raw []ReasoningEffortMapp
|
||||
seen := make(map[string]struct{}, len(raw))
|
||||
for i, mapping := range raw {
|
||||
from := normalizeReasoningEffortMappingSource(mapping.From)
|
||||
to := NormalizeMaxReasoningEffort(mapping.To)
|
||||
to := normalizeReasoningEffortMappingTarget(mapping.To)
|
||||
if from == "" || to == "" {
|
||||
return nil, fmt.Errorf("reasoning effort mapping %d contains an empty or unknown value", i+1)
|
||||
}
|
||||
@@ -315,8 +361,18 @@ func NormalizeReasoningEffortMappings(platform string, raw []ReasoningEffortMapp
|
||||
i+1, PlatformOpenAI, PlatformComposite,
|
||||
)
|
||||
}
|
||||
if _, err := normalizeMaxReasoningEffortForPlatform(platform, to); err != nil {
|
||||
return nil, fmt.Errorf("reasoning effort mapping %d target: %w", i+1, err)
|
||||
if to != ReasoningEffortMappingDeny {
|
||||
if _, err := normalizeMaxReasoningEffortForPlatform(platform, to); err != nil {
|
||||
return nil, fmt.Errorf("reasoning effort mapping %d target: %w", i+1, err)
|
||||
}
|
||||
} else if len(reasoningEffortValuesForPlatform(platform)) == 0 {
|
||||
return nil, fmt.Errorf(
|
||||
"reasoning effort mapping %d target: reasoning effort policy is only supported for platforms %q, %q, and %q",
|
||||
i+1,
|
||||
PlatformAnthropic,
|
||||
PlatformOpenAI,
|
||||
PlatformComposite,
|
||||
)
|
||||
}
|
||||
model := strings.TrimSpace(mapping.Model)
|
||||
if len(model) > maxReasoningEffortModelLen {
|
||||
@@ -439,9 +495,10 @@ func sanitizeGroupReasoningEffortPolicy(group *Group) {
|
||||
// ApplyReasoningEffortPolicy applies one mapping (optionally scoped to
|
||||
// the request model by exact name, prefix, or suffix) and then either caps
|
||||
// known effort levels or rejects the request when the group is configured to
|
||||
// deny values above the ceiling. Omitted values remain untouched so upstream
|
||||
// defaults stay in control. It understands both OpenAI and Anthropic request
|
||||
// field shapes.
|
||||
// deny values above the ceiling. A mapping whose target is deny rejects the
|
||||
// request when that source value is present. Omitted values remain untouched
|
||||
// so upstream defaults stay in control. It understands both OpenAI and
|
||||
// Anthropic request field shapes.
|
||||
func ApplyReasoningEffortPolicy(body []byte, maxEffort string, mappings []ReasoningEffortMapping, overLimit string) ([]byte, bool, error) {
|
||||
maxRank, hasMax := reasoningEffortRank(maxEffort)
|
||||
if len(body) == 0 || (!hasMax && len(mappings) == 0) {
|
||||
@@ -463,7 +520,14 @@ func ApplyReasoningEffortPolicy(body []byte, maxEffort string, mappings []Reason
|
||||
continue
|
||||
}
|
||||
|
||||
effective, _ := mapReasoningEffort(original, mappings, requestModel)
|
||||
effective, mapped := mapReasoningEffort(original, mappings, requestModel)
|
||||
if mapped && isReasoningEffortMappingDeny(effective) {
|
||||
requested := normalizeReasoningEffortMappingSource(original)
|
||||
if requested == "" {
|
||||
requested = original
|
||||
}
|
||||
return body, false, &ReasoningEffortMappingDeniedError{Requested: requested}
|
||||
}
|
||||
if currentRank, recognized := reasoningEffortRank(effective); recognized {
|
||||
effective = NormalizeMaxReasoningEffort(effective)
|
||||
if hasMax && currentRank > maxRank {
|
||||
|
||||
@@ -167,6 +167,27 @@ func TestNormalizeReasoningEffortMappings(t *testing.T) {
|
||||
require.ErrorContains(t, err, "empty or unknown")
|
||||
})
|
||||
|
||||
t.Run("allows deny as a mapping target", func(t *testing.T) {
|
||||
for _, platform := range []string{PlatformOpenAI, PlatformComposite, PlatformAnthropic} {
|
||||
got, err := NormalizeReasoningEffortMappings(platform, []ReasoningEffortMapping{{From: " XHIGH ", To: " DENY "}})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []ReasoningEffortMapping{{From: "xhigh", To: ReasoningEffortMappingDeny}}, got)
|
||||
}
|
||||
|
||||
got, err := NormalizeReasoningEffortMappings(PlatformOpenAI, []ReasoningEffortMapping{
|
||||
{From: "none", To: "deny"},
|
||||
{From: "max", To: "deny", MatchType: "prefix", Model: "gpt"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []ReasoningEffortMapping{
|
||||
{From: "none", To: ReasoningEffortMappingDeny},
|
||||
{From: "max", To: ReasoningEffortMappingDeny, MatchType: domain.ReasoningEffortMatchPrefix, Model: "gpt"},
|
||||
}, got)
|
||||
|
||||
_, err = NormalizeReasoningEffortMappings(PlatformGemini, []ReasoningEffortMapping{{From: "high", To: "deny"}})
|
||||
require.ErrorContains(t, err, "only supported for platforms")
|
||||
})
|
||||
|
||||
t.Run("supports Anthropic values except minimal", func(t *testing.T) {
|
||||
got, err := NormalizeReasoningEffortMappings(PlatformAnthropic, []ReasoningEffortMapping{{From: " MAX ", To: " x-high "}})
|
||||
require.NoError(t, err)
|
||||
@@ -255,15 +276,16 @@ func TestOpenAIReasoningEffortPolicyContext(t *testing.T) {
|
||||
|
||||
func TestApplyOpenAIReasoningEffortPolicy(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
max string
|
||||
overLimit string
|
||||
mappings []ReasoningEffortMapping
|
||||
path string
|
||||
want string
|
||||
changed bool
|
||||
deny bool
|
||||
name string
|
||||
body string
|
||||
max string
|
||||
overLimit string
|
||||
mappings []ReasoningEffortMapping
|
||||
path string
|
||||
want string
|
||||
changed bool
|
||||
deny bool
|
||||
mappingDeny bool
|
||||
}{
|
||||
{name: "nested caps high", body: `{"reasoning":{"effort":"xhigh"}}`, max: "medium", path: "reasoning.effort", want: "medium", changed: true},
|
||||
{name: "flat caps high", body: `{"reasoning_effort":"high"}`, max: "low", path: "reasoning_effort", want: "low", changed: true},
|
||||
@@ -419,6 +441,41 @@ func TestApplyOpenAIReasoningEffortPolicy(t *testing.T) {
|
||||
{name: "deny after mapping still over ceiling", body: `{"reasoning":{"effort":"max"}}`, max: "medium", overLimit: ReasoningEffortOverLimitDeny, mappings: []ReasoningEffortMapping{{From: "max", To: "xhigh"}}, path: "reasoning.effort", want: "max", deny: true},
|
||||
{name: "deny allows mapping under ceiling", body: `{"reasoning":{"effort":"max"}}`, max: "medium", overLimit: ReasoningEffortOverLimitDeny, mappings: []ReasoningEffortMapping{{From: "max", To: "low"}}, path: "reasoning.effort", want: "low", changed: true},
|
||||
{name: "deny ignored without ceiling", body: `{"reasoning_effort":"high"}`, overLimit: ReasoningEffortOverLimitDeny, path: "reasoning_effort", want: "high"},
|
||||
{name: "mapping deny rejects matching nested effort", body: `{"reasoning":{"effort":"xhigh"}}`, mappings: []ReasoningEffortMapping{{From: "xhigh", To: ReasoningEffortMappingDeny}}, path: "reasoning.effort", want: "xhigh", mappingDeny: true},
|
||||
{name: "mapping deny rejects matching flat effort", body: `{"reasoning_effort":"X-HIGH"}`, mappings: []ReasoningEffortMapping{{From: "xhigh", To: " DENY "}}, path: "reasoning_effort", want: "X-HIGH", mappingDeny: true},
|
||||
{name: "mapping deny rejects Anthropic output config", body: `{"output_config":{"effort":"max"}}`, mappings: []ReasoningEffortMapping{{From: "max", To: ReasoningEffortMappingDeny}}, path: "output_config.effort", want: "max", mappingDeny: true},
|
||||
{name: "mapping deny rejects none source", body: `{"reasoning_effort":"none"}`, mappings: []ReasoningEffortMapping{{From: "none", To: ReasoningEffortMappingDeny}}, path: "reasoning_effort", want: "none", mappingDeny: true},
|
||||
{
|
||||
name: "mapping deny respects model scope",
|
||||
body: `{"model":"gpt-5.6-sol","reasoning":{"effort":"xhigh"}}`,
|
||||
mappings: []ReasoningEffortMapping{{From: "xhigh", To: ReasoningEffortMappingDeny, MatchType: domain.ReasoningEffortMatchPrefix, Model: "gpt-5.6-sol"}},
|
||||
path: "reasoning.effort",
|
||||
want: "xhigh",
|
||||
mappingDeny: true,
|
||||
},
|
||||
{
|
||||
name: "mapping deny skips non matching model",
|
||||
body: `{"model":"gpt-5.6-terra","reasoning":{"effort":"xhigh"}}`,
|
||||
mappings: []ReasoningEffortMapping{{From: "xhigh", To: ReasoningEffortMappingDeny, MatchType: domain.ReasoningEffortMatchExact, Model: "gpt-5.6-sol"}},
|
||||
path: "reasoning.effort",
|
||||
want: "xhigh",
|
||||
},
|
||||
{
|
||||
name: "mapping deny leaves other efforts unchanged",
|
||||
body: `{"reasoning_effort":"high"}`,
|
||||
mappings: []ReasoningEffortMapping{{From: "xhigh", To: ReasoningEffortMappingDeny}},
|
||||
path: "reasoning_effort",
|
||||
want: "high",
|
||||
},
|
||||
{
|
||||
name: "mapping deny takes precedence over ceiling rewrite",
|
||||
body: `{"reasoning":{"effort":"xhigh"}}`,
|
||||
max: "medium",
|
||||
mappings: []ReasoningEffortMapping{{From: "xhigh", To: ReasoningEffortMappingDeny}},
|
||||
path: "reasoning.effort",
|
||||
want: "xhigh",
|
||||
mappingDeny: true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
@@ -427,6 +484,20 @@ func TestApplyOpenAIReasoningEffortPolicy(t *testing.T) {
|
||||
require.Error(t, err)
|
||||
var overLimit *ReasoningEffortOverLimitError
|
||||
require.ErrorAs(t, err, &overLimit)
|
||||
require.True(t, IsReasoningEffortPolicyDenied(err))
|
||||
require.False(t, changed)
|
||||
require.Equal(t, tt.body, string(got))
|
||||
return
|
||||
}
|
||||
if tt.mappingDeny {
|
||||
require.Error(t, err)
|
||||
var mappingDenied *ReasoningEffortMappingDeniedError
|
||||
require.ErrorAs(t, err, &mappingDenied)
|
||||
require.True(t, IsReasoningEffortPolicyDenied(err))
|
||||
require.Contains(t, mappingDenied.Error(), "denied by this group's mapping policy")
|
||||
if requested := normalizeReasoningEffortMappingSource(tt.want); requested != "" {
|
||||
require.Equal(t, requested, mappingDenied.Requested)
|
||||
}
|
||||
require.False(t, changed)
|
||||
require.Equal(t, tt.body, string(got))
|
||||
return
|
||||
@@ -442,3 +513,14 @@ func TestApplyOpenAIReasoningEffortPolicy(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReasoningEffortMappingDeniedError(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
err := &ReasoningEffortMappingDeniedError{Requested: "xhigh"}
|
||||
require.Equal(t, `reasoning effort "xhigh" is denied by this group's mapping policy`, err.Error())
|
||||
require.True(t, IsReasoningEffortPolicyDenied(err))
|
||||
require.True(t, IsReasoningEffortPolicyDenied(&ReasoningEffortOverLimitError{Requested: "max", Max: "low"}))
|
||||
require.False(t, IsReasoningEffortPolicyDenied(nil))
|
||||
require.False(t, IsReasoningEffortPolicyDenied(context.Canceled))
|
||||
}
|
||||
@@ -102,6 +102,7 @@ type RelayTraceEvent struct {
|
||||
type relayState struct {
|
||||
usage Usage
|
||||
turnUsage Usage
|
||||
turnWroteDownstream atomic.Bool
|
||||
requestModelMu sync.RWMutex
|
||||
requestModel string
|
||||
pendingTurnStart atomic.Pointer[time.Time]
|
||||
@@ -204,7 +205,8 @@ func Relay(
|
||||
return upstreamConn.WriteFrame(writeCtx, msgType, payload)
|
||||
}
|
||||
writeClientFrameUpstream := func(msgType coderws.MessageType, payload []byte) error {
|
||||
if isClientResponseCreateFrame(msgType, payload) {
|
||||
isResponseCreate := isClientResponseCreateFrame(msgType, payload)
|
||||
if isResponseCreate {
|
||||
state.setRequestModel(strings.TrimSpace(gjson.GetBytes(payload, "model").String()))
|
||||
turnStartedAt := time.Time{}
|
||||
if options.TakeNextTurnStartedAt != nil {
|
||||
@@ -214,8 +216,18 @@ func Relay(
|
||||
turnStartedAt = nowFn()
|
||||
}
|
||||
state.setPendingTurnStartedAt(turnStartedAt)
|
||||
// The policy-enforcing client connection has accepted this turn.
|
||||
// Reset before the write so an immediate upstream response cannot race
|
||||
// with the transport returning from WriteFrame.
|
||||
state.turnWroteDownstream.Store(false)
|
||||
}
|
||||
return writeUpstream(msgType, payload)
|
||||
err := writeUpstream(msgType, payload)
|
||||
if err != nil && isResponseCreate {
|
||||
// The relay exits on this error, but retain the previous turn's state
|
||||
// for accurate diagnostics while the two relay goroutines settle.
|
||||
state.turnWroteDownstream.Store(true)
|
||||
}
|
||||
return err
|
||||
}
|
||||
writeClient := func(msgType coderws.MessageType, payload []byte) error {
|
||||
// 下行写超时故意不挂在 relayCtx 上:coder/websocket 在已武装的 write
|
||||
@@ -538,7 +550,7 @@ func runUpstreamToClient(
|
||||
// the upstream has started a Responses turn, success still requires a
|
||||
// terminal protocol event. Treat an early 1000/EOF as a relay failure so
|
||||
// the adapter does not report relay_completed with an active turn.
|
||||
if graceful && openAIWSRelayActiveTurnID(state) != "" {
|
||||
if graceful && state.hasUnfinishedTurn() {
|
||||
graceful = false
|
||||
err = errors.New("upstream websocket closed before terminal event: " + err.Error())
|
||||
}
|
||||
@@ -559,7 +571,11 @@ func runUpstreamToClient(
|
||||
}
|
||||
markActivity()
|
||||
if beforeWriteClient != nil {
|
||||
if err := beforeWriteClient(msgType, payload, wroteDownstream); err != nil {
|
||||
wroteDownstreamInTurn := wroteDownstream
|
||||
if state != nil {
|
||||
wroteDownstreamInTurn = state.turnWroteDownstream.Load()
|
||||
}
|
||||
if err := beforeWriteClient(msgType, payload, wroteDownstreamInTurn); err != nil {
|
||||
emitRelayTrace(onTrace, RelayTraceEvent{
|
||||
Stage: "upstream_message_rejected",
|
||||
Direction: "upstream_to_client",
|
||||
@@ -585,7 +601,14 @@ func runUpstreamToClient(
|
||||
}
|
||||
observedEvent = observeUpstreamMessage(state, payload, startAt, nowFn, onUsageParseFailure)
|
||||
case coderws.MessageBinary:
|
||||
// binary frame 直接透传,不进入 JSON 观测路径(避免无效解析开销)。
|
||||
// Binary frames remain opaque for usage/result observation, but a JSON
|
||||
// terminal still settles relay lifecycle. Otherwise the pending-turn
|
||||
// disconnect guard would turn an already-delivered terminal into a false
|
||||
// missing-terminal failure when the upstream closes normally.
|
||||
if isTerminalEvent(strings.TrimSpace(gjson.GetBytes(payload, "type").String())) {
|
||||
state.consumePendingTurnStartedAt()
|
||||
openAIWSRelayDiscardActiveTurnTiming(state)
|
||||
}
|
||||
}
|
||||
emitTurnComplete(onTurnComplete, state, observedEvent)
|
||||
if dropDownstreamWrites != nil && dropDownstreamWrites.Load() {
|
||||
@@ -630,6 +653,9 @@ func runUpstreamToClient(
|
||||
return
|
||||
}
|
||||
wroteDownstream = true
|
||||
if state != nil {
|
||||
state.turnWroteDownstream.Store(true)
|
||||
}
|
||||
if afterWriteClient != nil {
|
||||
afterWriteClient(msgType, payload)
|
||||
}
|
||||
@@ -995,6 +1021,13 @@ func (s *relayState) consumePendingTurnStartedAt() time.Time {
|
||||
return *startedAt
|
||||
}
|
||||
|
||||
func (s *relayState) hasUnfinishedTurn() bool {
|
||||
if s == nil {
|
||||
return false
|
||||
}
|
||||
return s.pendingTurnStart.Load() != nil || s.activeTurn != nil
|
||||
}
|
||||
|
||||
func openAIWSRelayDeleteTurnTiming(state *relayState, responseID string) (relayTurnTiming, bool) {
|
||||
if state == nil || state.turnTimingByID == nil {
|
||||
return relayTurnTiming{}, false
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
@@ -309,11 +310,46 @@ func TestRelay_UpstreamDisconnect(t *testing.T) {
|
||||
defer cancel()
|
||||
|
||||
result, relayExit := Relay(ctx, clientConn, upstreamConn, firstPayload, RelayOptions{})
|
||||
// 上游 EOF 属于 disconnect,标记为 graceful
|
||||
require.Nil(t, relayExit, "上游 EOF 应被视为 graceful disconnect")
|
||||
require.NotNil(t, relayExit)
|
||||
require.Equal(t, "read_upstream", relayExit.Stage)
|
||||
require.False(t, relayExit.Graceful)
|
||||
require.ErrorContains(t, relayExit.Err, "upstream websocket closed before terminal event")
|
||||
require.Equal(t, "gpt-4o", result.RequestModel)
|
||||
}
|
||||
|
||||
func TestRelay_UpstreamNormalCloseBeforeResponseIDIsFailure(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
clientConn := newPassthroughTestFrameConn(nil, false)
|
||||
upstreamConn := &eofReplacementFrameConn{
|
||||
FrameConn: newPassthroughTestFrameConn([]passthroughTestFrame{
|
||||
{
|
||||
msgType: coderws.MessageText,
|
||||
payload: []byte(`{"type":"response.created","status":"in_progress"}`),
|
||||
},
|
||||
{
|
||||
msgType: coderws.MessageText,
|
||||
payload: []byte(`{"type":"response.in_progress","status":"in_progress"}`),
|
||||
},
|
||||
}, true),
|
||||
err: coderws.CloseError{Code: coderws.StatusNormalClosure},
|
||||
}
|
||||
|
||||
firstPayload := []byte(`{"type":"response.create","model":"gpt-5.6-sol","input":[]}`)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
result, relayExit := Relay(ctx, clientConn, upstreamConn, firstPayload, RelayOptions{})
|
||||
require.NotNil(t, relayExit)
|
||||
require.Equal(t, "read_upstream", relayExit.Stage)
|
||||
require.False(t, relayExit.Graceful)
|
||||
require.True(t, relayExit.WroteDownstream)
|
||||
require.ErrorContains(t, relayExit.Err, "upstream websocket closed before terminal event")
|
||||
require.Empty(t, result.RequestID)
|
||||
require.Empty(t, result.TerminalEventType)
|
||||
require.Len(t, clientConn.Writes(), 2)
|
||||
}
|
||||
|
||||
func TestRelay_UpstreamNormalCloseBeforeTerminalIsFailure(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -903,6 +939,63 @@ func TestRelay_OnTurnComplete_UsesSubsequentResponseCreateTimeAcrossPricingBound
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelay_BeforeWriteClientTracksDownstreamPerTurn(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
clientConn := newPassthroughTestFrameConn(nil, false)
|
||||
upstreamConn := newPassthroughTestFrameConn(nil, false)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
wroteStates := make(chan bool, 3)
|
||||
done := make(chan *RelayExit, 1)
|
||||
stopErr := errors.New("stop after second-turn error")
|
||||
go func() {
|
||||
_, relayExit := Relay(
|
||||
ctx,
|
||||
clientConn,
|
||||
upstreamConn,
|
||||
[]byte(`{"type":"response.create","model":"gpt-5.3-codex","input":[]}`),
|
||||
RelayOptions{BeforeWriteClient: func(_ coderws.MessageType, payload []byte, wroteDownstream bool) error {
|
||||
wroteStates <- wroteDownstream
|
||||
if strings.Contains(string(payload), `"type":"error"`) {
|
||||
return stopErr
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
)
|
||||
done <- relayExit
|
||||
}()
|
||||
|
||||
require.Eventually(t, func() bool { return len(upstreamConn.Writes()) == 1 }, time.Second, time.Millisecond)
|
||||
upstreamConn.readCh <- passthroughTestFrame{
|
||||
msgType: coderws.MessageText,
|
||||
payload: []byte(`{"type":"response.completed","response":{"id":"resp_first","usage":{"input_tokens":1,"output_tokens":1}}}`),
|
||||
}
|
||||
require.False(t, <-wroteStates)
|
||||
require.Eventually(t, func() bool { return len(clientConn.Writes()) == 1 }, time.Second, time.Millisecond)
|
||||
|
||||
clientConn.readCh <- passthroughTestFrame{
|
||||
msgType: coderws.MessageText,
|
||||
payload: []byte(`{"type":"response.create","model":"gpt-5.3-codex","input":[]}`),
|
||||
}
|
||||
require.Eventually(t, func() bool { return len(upstreamConn.Writes()) == 2 }, time.Second, time.Millisecond)
|
||||
upstreamConn.readCh <- passthroughTestFrame{
|
||||
msgType: coderws.MessageText,
|
||||
payload: []byte(`{"type":"error","error":{"type":"usage_limit_reached"}}`),
|
||||
}
|
||||
require.False(t, <-wroteStates, "the next turn must not inherit the first turn's downstream write")
|
||||
|
||||
select {
|
||||
case relayExit := <-done:
|
||||
require.NotNil(t, relayExit)
|
||||
require.ErrorIs(t, relayExit.Err, stopErr)
|
||||
require.True(t, relayExit.WroteDownstream, "connection-wide diagnostics must retain prior output")
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("relay did not stop after the rejected second-turn event")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelay_BinaryFramePassthrough(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -921,7 +1014,10 @@ func TestRelay_BinaryFramePassthrough(t *testing.T) {
|
||||
defer cancel()
|
||||
|
||||
result, relayExit := Relay(ctx, clientConn, upstreamConn, firstPayload, RelayOptions{})
|
||||
require.Nil(t, relayExit)
|
||||
require.NotNil(t, relayExit)
|
||||
require.Equal(t, "read_upstream", relayExit.Stage)
|
||||
require.False(t, relayExit.Graceful)
|
||||
require.ErrorContains(t, relayExit.Err, "upstream websocket closed before terminal event")
|
||||
// binary frame 不解析 usage
|
||||
require.Equal(t, 0, result.Usage.InputTokens)
|
||||
|
||||
@@ -986,7 +1082,12 @@ func TestRelay_PreservesFirstMessageType(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
clientConn := newPassthroughTestFrameConn(nil, false)
|
||||
upstreamConn := newPassthroughTestFrameConn(nil, true)
|
||||
upstreamConn := newPassthroughTestFrameConn([]passthroughTestFrame{
|
||||
{
|
||||
msgType: coderws.MessageBinary,
|
||||
payload: []byte(`{"type":"response.completed","response":{"id":"resp_binary_first_type"}}`),
|
||||
},
|
||||
}, true)
|
||||
|
||||
firstPayload := []byte(`{"type":"response.create","model":"gpt-4o","input":[]}`)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
@@ -1001,6 +1102,9 @@ func TestRelay_PreservesFirstMessageType(t *testing.T) {
|
||||
require.Len(t, upstreamWrites, 1)
|
||||
require.Equal(t, coderws.MessageBinary, upstreamWrites[0].msgType)
|
||||
require.Equal(t, firstPayload, upstreamWrites[0].payload)
|
||||
clientWrites := clientConn.Writes()
|
||||
require.Len(t, clientWrites, 1)
|
||||
require.Equal(t, coderws.MessageBinary, clientWrites[0].msgType)
|
||||
}
|
||||
|
||||
func TestRelay_UsageParseFailureDoesNotBlockRelay(t *testing.T) {
|
||||
|
||||
@@ -1304,6 +1304,13 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough(
|
||||
truncateOpenAIWSLogValue(errTypeRaw, openAIWSLogValueMaxLen),
|
||||
truncateOpenAIWSLogValue(errMsgRaw, openAIWSLogValueMaxLen),
|
||||
)
|
||||
if completedTurns.Load() > 0 {
|
||||
return NewOpenAIWSClientCloseError(
|
||||
coderws.StatusTryAgainLater,
|
||||
"upstream rate limit exceeded; please reconnect",
|
||||
errors.New("later passthrough turn was rate limited before output"),
|
||||
)
|
||||
}
|
||||
return s.newOpenAIWSRateLimitFailoverError(account, handshakeHeaders, payload, errMsgRaw)
|
||||
},
|
||||
OnTrace: func(event openaiwsv2.RelayTraceEvent) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
@@ -210,6 +211,61 @@ func startPassthroughLifecycleServerWithHooks(
|
||||
return server, serverErr
|
||||
}
|
||||
|
||||
func TestPassthroughLifecycle_LaterTurnPreOutputRateLimitRequestsReconnect(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
controlCtx, cancelControl := context.WithCancelCause(context.Background())
|
||||
defer cancelControl(context.Canceled)
|
||||
upstream := newStagedPassthroughConn()
|
||||
account := passthroughLifecycleAccount()
|
||||
repo := &openAIWSRateLimitSignalRepo{stubOpenAIAccountRepo: stubOpenAIAccountRepo{accounts: []Account{*account}}}
|
||||
svc := newPassthroughLifecycleService(passthroughLifecycleConfig(), upstream)
|
||||
svc.accountRepo = repo
|
||||
svc.rateLimitService = &RateLimitService{accountRepo: repo}
|
||||
|
||||
server, serverErr := startPassthroughLifecycleServer(t, controlCtx, svc, account)
|
||||
defer server.Close()
|
||||
clientConn := dialPassthroughLifecycleClient(t, server)
|
||||
defer func() { _ = clientConn.CloseNow() }()
|
||||
firstRequest := requirePassthroughUpstreamWrite(t, upstream, time.Second)
|
||||
require.Equal(t, "response.create", gjson.GetBytes(firstRequest, "type").String())
|
||||
|
||||
upstream.Send(`{"type":"response.completed","response":{"id":"resp_first","model":"gpt-5.1","usage":{"input_tokens":1,"output_tokens":1}}}`)
|
||||
completed, err := readPassthroughLifecycleFrame(t, clientConn, time.Second)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "response.completed", gjson.GetBytes(completed, "type").String())
|
||||
|
||||
writeCtx, cancelWrite := context.WithTimeout(context.Background(), time.Second)
|
||||
err = clientConn.Write(writeCtx, coderws.MessageText, []byte(`{"type":"response.create","model":"gpt-5.1","stream":false}`))
|
||||
cancelWrite()
|
||||
require.NoError(t, err)
|
||||
secondRequest := requirePassthroughUpstreamWrite(t, upstream, time.Second)
|
||||
require.Equal(t, "response.create", gjson.GetBytes(secondRequest, "type").String())
|
||||
|
||||
resetAt := time.Now().Add(90 * time.Minute).Unix()
|
||||
upstream.Send(fmt.Sprintf(`{"type":"error","error":{"code":"rate_limit_exceeded","type":"usage_limit_reached","message":"The usage limit has been reached","resets_at":%d}}`, resetAt))
|
||||
_, err = readPassthroughLifecycleFrame(t, clientConn, time.Second)
|
||||
var websocketCloseErr coderws.CloseError
|
||||
require.ErrorAs(t, err, &websocketCloseErr)
|
||||
require.Equal(t, coderws.StatusTryAgainLater, websocketCloseErr.Code)
|
||||
require.Equal(t, "upstream rate limit exceeded; please reconnect", websocketCloseErr.Reason)
|
||||
require.Len(t, repo.rateLimitCalls, 1)
|
||||
require.WithinDuration(t, time.Unix(resetAt, 0), repo.rateLimitCalls[0], 2*time.Second)
|
||||
|
||||
select {
|
||||
case err := <-serverErr:
|
||||
var closeErr *OpenAIWSClientCloseError
|
||||
require.ErrorAs(t, err, &closeErr)
|
||||
require.Equal(t, coderws.StatusTryAgainLater, closeErr.StatusCode())
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("later-turn rate limit did not terminate passthrough")
|
||||
}
|
||||
select {
|
||||
case replay := <-upstream.writes:
|
||||
t.Fatalf("later-turn reconnect must not replay the retained first request: %s", replay)
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassthroughLifecycle_CyberTerminalEventsMarkBeforeAfterTurn(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
|
||||
@@ -764,7 +764,7 @@ func TestFulfillmentLeaseVersionRejectsStaleWorker(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestPublicRedeemStillEnforcesFailureLimit(t *testing.T) {
|
||||
cache := &paymentFulfillmentRedeemCacheStub{count: redeemMaxErrorsPerHour}
|
||||
cache := &paymentFulfillmentRedeemCacheStub{count: redeemMaxFailedAttempts}
|
||||
svc := &RedeemService{cache: cache}
|
||||
|
||||
result, err := svc.Redeem(context.Background(), 42, "PUBLIC-CODE")
|
||||
@@ -794,7 +794,7 @@ func TestPublicRedeemStillIncrementsInvalidCodeFailures(t *testing.T) {
|
||||
|
||||
func TestPaymentRedeemDoesNotIncrementFailureLimit(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache := &paymentFulfillmentRedeemCacheStub{count: redeemMaxErrorsPerHour}
|
||||
cache := &paymentFulfillmentRedeemCacheStub{count: redeemMaxFailedAttempts}
|
||||
redeemRepo := &redeemRejectRepo{code: RedeemCode{
|
||||
ID: 1,
|
||||
Code: "PAY-EXPIRED",
|
||||
@@ -835,7 +835,7 @@ func TestExecuteBalanceFulfillmentBypassesUserRedeemRateLimit(t *testing.T) {
|
||||
credited += amount
|
||||
return nil
|
||||
}
|
||||
cache := &paymentFulfillmentRedeemCacheStub{count: redeemMaxErrorsPerHour}
|
||||
cache := &paymentFulfillmentRedeemCacheStub{count: redeemMaxFailedAttempts}
|
||||
redeemService := NewRedeemService(redeemRepo, userRepo, nil, cache, nil, client, nil, nil)
|
||||
svc := &PaymentService{entClient: client, redeemService: redeemService, userRepo: userRepo}
|
||||
|
||||
|
||||
@@ -1207,7 +1207,7 @@ func (s *PricingService) buildModelLookupCandidates(modelLower string) []string
|
||||
normalized := normalizeModelNameForPricing(modelLower)
|
||||
|
||||
// A tier-specific entry should take precedence when the pricing catalog gains
|
||||
// one later. Today Antigravity's Gemini 3.6 Flash tiers share the base rate,
|
||||
// one later. Antigravity's Gemini Flash thinking tiers share the base rate,
|
||||
// so the normalized base remains the fallback after the exact aliases.
|
||||
candidates := rawCandidates
|
||||
if normalizeGeminiThinkingTierAlias(lastSegment(modelLower)) != lastSegment(modelLower) {
|
||||
@@ -1269,15 +1269,16 @@ func normalizeModelNameForPricing(model string) string {
|
||||
return normalizeGeminiThinkingTierAlias(model)
|
||||
}
|
||||
|
||||
// normalizeGeminiThinkingTierAlias maps Antigravity's Gemini 3.6 Flash
|
||||
// normalizeGeminiThinkingTierAlias maps Antigravity's Gemini Flash
|
||||
// thinking-tier model IDs to the public base model. The tier controls reasoning
|
||||
// behavior, not the published token rate, so this keeps -high/-low/-medium and
|
||||
// -tiered requests on the same price card as gemini-3.6-flash.
|
||||
// -tiered requests on the corresponding base model's price card.
|
||||
func normalizeGeminiThinkingTierAlias(model string) string {
|
||||
const baseModel = "gemini-3.6-flash"
|
||||
for _, tier := range []string{"-high", "-low", "-medium", "-tiered"} {
|
||||
if model == baseModel+tier {
|
||||
return baseModel
|
||||
for _, baseModel := range []string{"gemini-3.6-flash", "gemini-3.7-flash", "gemini-3.8-flash"} {
|
||||
for _, tier := range []string{"-high", "-low", "-medium", "-tiered"} {
|
||||
if model == baseModel+tier {
|
||||
return baseModel
|
||||
}
|
||||
}
|
||||
}
|
||||
return model
|
||||
|
||||
@@ -566,38 +566,37 @@ func TestGetModelPricing_OpenAICompactAliasUsesStaticFallback(t *testing.T) {
|
||||
require.InDelta(t, 1.5e-5, got.OutputCostPerToken, 1e-12)
|
||||
}
|
||||
|
||||
func TestPricingService_Gemini36FlashThinkingTiersUseBasePricing(t *testing.T) {
|
||||
func TestPricingService_GeminiFlashThinkingTiersUseBasePricing(t *testing.T) {
|
||||
basePricing := &LiteLLMModelPricing{
|
||||
InputCostPerToken: 1.5e-6,
|
||||
OutputCostPerToken: 7.5e-6,
|
||||
CacheReadInputTokenCost: 0.15e-6,
|
||||
}
|
||||
svc := &PricingService{pricingData: map[string]*LiteLLMModelPricing{
|
||||
"gemini-3.6-flash": basePricing,
|
||||
}}
|
||||
|
||||
for _, model := range []string{
|
||||
"gemini-3.6-flash",
|
||||
"gemini-3.6-flash-high",
|
||||
"gemini-3.6-flash-low",
|
||||
"gemini-3.6-flash-medium",
|
||||
"gemini-3.6-flash-tiered",
|
||||
} {
|
||||
t.Run(model, func(t *testing.T) {
|
||||
require.Same(t, basePricing, svc.GetModelPricing(model))
|
||||
})
|
||||
for _, baseModel := range []string{"gemini-3.6-flash", "gemini-3.7-flash", "gemini-3.8-flash"} {
|
||||
svc := &PricingService{pricingData: map[string]*LiteLLMModelPricing{baseModel: basePricing}}
|
||||
for _, tier := range []string{"", "-high", "-low", "-medium", "-tiered"} {
|
||||
model := baseModel + tier
|
||||
t.Run(model, func(t *testing.T) {
|
||||
require.Same(t, basePricing, svc.GetModelPricing(model))
|
||||
require.Same(t, basePricing, svc.GetIdentifiedModelPricing("models/"+model))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPricingService_Gemini36FlashTierSpecificPricingTakesPrecedence(t *testing.T) {
|
||||
func TestPricingService_GeminiFlashTierSpecificPricingTakesPrecedence(t *testing.T) {
|
||||
basePricing := &LiteLLMModelPricing{InputCostPerToken: 1.5e-6}
|
||||
tierPricing := &LiteLLMModelPricing{InputCostPerToken: 2e-6}
|
||||
svc := &PricingService{pricingData: map[string]*LiteLLMModelPricing{
|
||||
"gemini-3.6-flash": basePricing,
|
||||
"gemini-3.6-flash-low": tierPricing,
|
||||
}}
|
||||
for _, baseModel := range []string{"gemini-3.6-flash", "gemini-3.7-flash", "gemini-3.8-flash"} {
|
||||
t.Run(baseModel, func(t *testing.T) {
|
||||
svc := &PricingService{pricingData: map[string]*LiteLLMModelPricing{
|
||||
baseModel: basePricing,
|
||||
baseModel + "-low": tierPricing,
|
||||
}}
|
||||
|
||||
require.Same(t, tierPricing, svc.GetModelPricing("models/gemini-3.6-flash-low"))
|
||||
require.Same(t, tierPricing, svc.GetModelPricing("models/"+baseModel+"-low"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBillingService_Gemini36FlashThinkingTierFallbacksAreBillable(t *testing.T) {
|
||||
|
||||
@@ -25,7 +25,7 @@ func TestAdminFulfillmentBypassesLimitAndKeepsRedeemAffiliate(t *testing.T) {
|
||||
}
|
||||
userRepo := &mockUserRepo{getByIDUser: &User{ID: userID}}
|
||||
userRepo.updateBalanceFn = func(context.Context, int64, float64) error { return nil }
|
||||
cache := &paymentFulfillmentRedeemCacheStub{count: redeemMaxErrorsPerHour}
|
||||
cache := &paymentFulfillmentRedeemCacheStub{count: redeemMaxFailedAttempts}
|
||||
affiliateRepo := &paymentFulfillmentAffiliateRepoStub{
|
||||
inviteeSummary: &AffiliateSummary{
|
||||
UserID: userID, AffCode: "INVITEE", InviterID: &inviterID, CreatedAt: time.Now().Add(-time.Hour),
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// redeemRateLimitCacheStub 实现 RedeemCache,记录各方法调用次数并允许注入错误。
|
||||
type redeemRateLimitCacheStub struct {
|
||||
count int
|
||||
getErr error
|
||||
incrementErr error
|
||||
getCalls int
|
||||
incrementCalls int
|
||||
acquireCalls int
|
||||
releaseCalls int
|
||||
}
|
||||
|
||||
func (c *redeemRateLimitCacheStub) GetRedeemAttemptCount(context.Context, int64) (int, error) {
|
||||
c.getCalls++
|
||||
return c.count, c.getErr
|
||||
}
|
||||
|
||||
func (c *redeemRateLimitCacheStub) IncrementRedeemAttemptCount(context.Context, int64) error {
|
||||
c.incrementCalls++
|
||||
if c.incrementErr != nil {
|
||||
return c.incrementErr
|
||||
}
|
||||
c.count++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *redeemRateLimitCacheStub) AcquireRedeemLock(context.Context, string, time.Duration) (bool, error) {
|
||||
c.acquireCalls++
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (c *redeemRateLimitCacheStub) ReleaseRedeemLock(context.Context, string) error {
|
||||
c.releaseCalls++
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestPublicRedeemAllowsLastAttemptBeforeLimit(t *testing.T) {
|
||||
cache := &redeemRateLimitCacheStub{count: redeemMaxFailedAttempts - 1}
|
||||
redeemRepo := &redeemRejectRepo{code: RedeemCode{Code: "OTHER"}}
|
||||
svc := &RedeemService{redeemRepo: redeemRepo, cache: cache}
|
||||
|
||||
result, err := svc.Redeem(context.Background(), 42, "MISSING")
|
||||
|
||||
require.Nil(t, result)
|
||||
require.ErrorIs(t, err, ErrRedeemCodeNotFound)
|
||||
require.Equal(t, redeemMaxFailedAttempts, cache.count)
|
||||
require.Equal(t, 1, cache.getCalls)
|
||||
require.Equal(t, 1, cache.incrementCalls)
|
||||
require.Equal(t, 1, cache.acquireCalls)
|
||||
require.Equal(t, 1, cache.releaseCalls)
|
||||
}
|
||||
|
||||
func TestPublicRedeemCountsOnlyConfiguredDomainFailures(t *testing.T) {
|
||||
past := time.Now().Add(-time.Minute)
|
||||
tests := []struct {
|
||||
name string
|
||||
code RedeemCode
|
||||
input string
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
name: "not found",
|
||||
code: RedeemCode{Code: "OTHER"},
|
||||
input: "MISSING",
|
||||
wantErr: ErrRedeemCodeNotFound,
|
||||
},
|
||||
{
|
||||
name: "expired",
|
||||
code: RedeemCode{
|
||||
ID: 1, Code: "EXPIRED", Type: RedeemTypeBalance, Value: 10,
|
||||
Status: StatusUnused, ExpiresAt: &past,
|
||||
},
|
||||
input: "EXPIRED",
|
||||
wantErr: ErrRedeemCodeExpired,
|
||||
},
|
||||
{
|
||||
name: "used",
|
||||
code: RedeemCode{
|
||||
ID: 2, Code: "USED", Type: RedeemTypeBalance, Value: 10,
|
||||
Status: StatusUsed,
|
||||
},
|
||||
input: "USED",
|
||||
wantErr: ErrRedeemCodeUsed,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cache := &redeemRateLimitCacheStub{}
|
||||
svc := &RedeemService{
|
||||
redeemRepo: &redeemRejectRepo{code: tt.code},
|
||||
cache: cache,
|
||||
}
|
||||
|
||||
result, err := svc.Redeem(context.Background(), 42, tt.input)
|
||||
|
||||
require.Nil(t, result)
|
||||
require.ErrorIs(t, err, tt.wantErr)
|
||||
require.Equal(t, 1, cache.getCalls)
|
||||
require.Equal(t, 1, cache.incrementCalls)
|
||||
require.Equal(t, 1, cache.count)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicRedeemRateLimitFailsOpenWhenCounterReadFails(t *testing.T) {
|
||||
cache := &redeemRateLimitCacheStub{
|
||||
count: redeemMaxFailedAttempts,
|
||||
getErr: errors.New("redis unavailable"),
|
||||
}
|
||||
svc := &RedeemService{
|
||||
redeemRepo: &redeemRejectRepo{code: RedeemCode{Code: "OTHER"}},
|
||||
cache: cache,
|
||||
}
|
||||
|
||||
result, err := svc.Redeem(context.Background(), 42, "MISSING")
|
||||
|
||||
require.Nil(t, result)
|
||||
require.ErrorIs(t, err, ErrRedeemCodeNotFound)
|
||||
require.Equal(t, 1, cache.getCalls)
|
||||
require.Equal(t, 1, cache.incrementCalls)
|
||||
}
|
||||
|
||||
func TestPublicRedeemCounterWriteFailurePreservesDomainError(t *testing.T) {
|
||||
cache := &redeemRateLimitCacheStub{incrementErr: errors.New("redis unavailable")}
|
||||
svc := &RedeemService{
|
||||
redeemRepo: &redeemRejectRepo{code: RedeemCode{Code: "OTHER"}},
|
||||
cache: cache,
|
||||
}
|
||||
|
||||
result, err := svc.Redeem(context.Background(), 42, "MISSING")
|
||||
|
||||
require.Nil(t, result)
|
||||
require.ErrorIs(t, err, ErrRedeemCodeNotFound)
|
||||
require.Equal(t, 1, cache.incrementCalls)
|
||||
require.Zero(t, cache.count)
|
||||
}
|
||||
|
||||
func TestSuccessfulPublicRedeemDoesNotMutateFailureCounter(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
client := newPaymentConfigServiceTestClient(t)
|
||||
userID := int64(42)
|
||||
code := &RedeemCode{
|
||||
ID: 101, Code: "PUBLIC-SUCCESS", Type: RedeemTypeBalance, Value: 10, Status: StatusUnused,
|
||||
}
|
||||
redeemRepo := &paymentOrderLifecycleRedeemRepo{
|
||||
codesByCode: map[string]*RedeemCode{code.Code: code},
|
||||
}
|
||||
userRepo := &mockUserRepo{getByIDUser: &User{ID: userID}}
|
||||
userRepo.updateBalanceFn = func(context.Context, int64, float64) error { return nil }
|
||||
cache := &redeemRateLimitCacheStub{count: 7}
|
||||
svc := NewRedeemService(redeemRepo, userRepo, nil, cache, nil, client, nil, nil)
|
||||
|
||||
result, err := svc.Redeem(ctx, userID, code.Code)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Equal(t, 1, cache.getCalls)
|
||||
require.Zero(t, cache.incrementCalls)
|
||||
require.Equal(t, 7, cache.count)
|
||||
require.Equal(t, 1, cache.acquireCalls)
|
||||
require.Equal(t, 1, cache.releaseCalls)
|
||||
require.Len(t, redeemRepo.useCalls, 1)
|
||||
}
|
||||
@@ -25,8 +25,7 @@ var (
|
||||
)
|
||||
|
||||
const (
|
||||
redeemMaxErrorsPerHour = 20
|
||||
redeemRateLimitDuration = time.Hour
|
||||
redeemMaxFailedAttempts = 30
|
||||
redeemLockDuration = 10 * time.Second // 锁超时时间,防止死锁
|
||||
)
|
||||
|
||||
@@ -344,7 +343,7 @@ func (s *RedeemService) checkRedeemRateLimit(ctx context.Context, userID int64)
|
||||
return nil
|
||||
}
|
||||
|
||||
if count >= redeemMaxErrorsPerHour {
|
||||
if count >= redeemMaxFailedAttempts {
|
||||
return ErrRedeemRateLimited
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user