test(contract): refresh settings goldens and fix ollama conversation null handling

- api_contract_test: default_platform_quotas goldens now include ollama_cloud
  (actual settings response is correct; goldens were stale)
- api_contract_test: stubAccountRepo.GetByIDs returns the bulk-update fixture
  accounts (101/102) required by the BulkUpdateAccounts prefetch
- openai_gateway: conversation gate rejects only non-null values
  (gjson Type != Null); conversation: null is treated as an omitted field and
  forwarded, with a Forward-layer regression test covering both paths
- ollama_cloud pricing gate: message now states the global base pricing
  requirement and that channel/group-only pricing is not accepted; doc comment
  records the deliberate stricter-than-runtime design limitation
This commit is contained in:
alfadb committed 2026-10-08 15:24:05 +08:00
1 parent 96223b157f
commit ae2e438589
4 files changed
+76 -10

No files matched your search

+16 -4
View File
@@ -863,7 +863,7 @@ func TestAPIContracts(t *testing.T) {
"force_email_on_third_party_signup": false,
"default_concurrency": 5,
"default_balance": 1.25,
"default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
"default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"ollama_cloud":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
"auth_source_default_email_platform_quotas": null,
"auth_source_default_github_platform_quotas": null,
"auth_source_default_google_platform_quotas": null,
@@ -1189,7 +1189,7 @@ func TestAPIContracts(t *testing.T) {
"purchase_subscription_url": "",
"table_default_page_size": 20,
"table_page_size_options": [10, 20, 50],
"default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
"default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"ollama_cloud":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
"auth_source_default_email_platform_quotas": null,
"auth_source_default_github_platform_quotas": null,
"auth_source_default_google_platform_quotas": null,
@@ -1468,7 +1468,12 @@ func newContractDeps(t *testing.T) *contractDeps {
apiKeyCache := stubApiKeyCache{}
groupRepo := &stubGroupRepo{}
userSubRepo := &stubUserSubscriptionRepo{}
accountRepo := stubAccountRepo{}
accountRepo := stubAccountRepo{
accounts: map[int64]*service.Account{
101: {ID: 101, Name: "bulk-anthropic-1", Platform: service.PlatformAnthropic, Status: service.StatusActive, Schedulable: true},
102: {ID: 102, Name: "bulk-anthropic-2", Platform: service.PlatformAnthropic, Status: service.StatusActive, Schedulable: true},
},
}
proxyRepo := stubProxyRepo{}
redeemRepo := &stubRedeemCodeRepo{}
@@ -1868,6 +1873,7 @@ func (stubGroupRepo) CreateFromSource(ctx context.Context, group *service.Group,
type stubAccountRepo struct {
bulkUpdateIDs []int64
accounts map[int64]*service.Account
}
func (s *stubAccountRepo) Create(ctx context.Context, account *service.Account) error {
@@ -1883,7 +1889,13 @@ func (s *stubAccountRepo) GetByID(ctx context.Context, id int64) (*service.Accou
}
func (s *stubAccountRepo) GetByIDs(ctx context.Context, ids []int64) ([]*service.Account, error) {
return nil, errors.New("not implemented")
out := make([]*service.Account, 0, len(ids))
for _, id := range ids {
if account, ok := s.accounts[id]; ok {
out = append(out, account)
}
}
return out, nil
}
func (s *stubAccountRepo) ExistsByID(ctx context.Context, id int64) (bool, error) {
@@ -37,6 +37,14 @@ type accountModelPricingLookup interface {
// openai_gateway_usage.go 的 pricing_missing_record_zero_cost 分支)。
// lookup 为 nil 时跳过(生产 wire 必然注入 *BillingService;仅直接构造
// struct 的单元测试/内部调用会出现)。
//
// 与请求期转发前预检的刻意不对称(设计限制,非缺陷):请求期预检走完整定价
// 解析链(Group → Channel → LiteLLM → fallback),「只有渠道价/分组价」的模型
// 运行时允许出站;本门禁只查全局基础价(GetModelPricing,LiteLLM → fallback),
// 因此仅在渠道/分组层配置定价的模型会在保存时被 MODEL_PRICING_MISSING 拒绝。
// 这是刻意比运行时更严格的策略:账号与分组是多对多,保存时拿不到确定的
// channel/group 上下文,「门禁查渠道价」在语义上不成立;而 ollama 的真实模型
// 全部有全局基础价,实践中不会误拒。
func validateOllamaCloudAccountModelPricingGate(lookup accountModelPricingLookup, account *Account) error {
if lookup == nil || account == nil || !account.IsOllamaCloud() {
return nil
@@ -57,7 +65,7 @@ func validateOllamaCloudAccountModelPricingGate(lookup accountModelPricingLookup
}
if len(unpriced) > 0 {
return infraerrors.BadRequest("MODEL_PRICING_MISSING",
fmt.Sprintf("以下 ollama_cloud 模型缺少定价,无法保证计费(请先补价或调整 model_mapping/%s): %s",
fmt.Sprintf("以下 ollama_cloud 模型缺少全局基础定价,无法保证计费。此校验要求每个可出站模型都有全局基础价(LiteLLM 或内置 fallback),仅在渠道/分组层配置的定价不会被接受:请先在全局模型定价中补价,或调整 model_mapping/extra.%s。缺价模型: %s",
OllamaCloudAllowedModelsExtraKey, strings.Join(unpriced, ", ")))
}
return nil
@@ -81,3 +81,45 @@ func TestForwardConversationFieldRejectedWithBadRequest(t *testing.T) {
require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool())
})
}
// TestForwardConversationNullTreatedAsStateless 是 conversation 门禁的兼容性回归:
// gjson 的 Exists() 对 JSON null 也返回 true,若据此判定会把「客户端把可选字段
// 序列化成 null」这一常见形态误拒为 400。conversation: null 语义上与省略字段
// 等价,必须按无会话依赖正常出站;非 null 值仍 400 且不出站(对照,门禁对
// 显式会话依赖的拒绝语义不放松)。
func TestForwardConversationNullTreatedAsStateless(t *testing.T) {
gin.SetMode(gin.TestMode)
t.Run("conversation null is forwarded like an omitted field", func(t *testing.T) {
upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil)
body := []byte(`{"model":"gpt-oss:120b-cloud","conversation":null,"input":"full standalone input","stream":false}`)
recorder := newConversationGuardRecorder("/v1/responses", body)
_, err := svc.Forward(context.Background(), recorder.c, account, body)
require.Error(t, err)
var statelessErr *openAIResponsesStatelessFieldError
require.NotErrorAs(t, err, &statelessErr, "conversation:null 不得触发无状态字段 400")
require.NotNil(t, upstream.lastReq, "conversation:null 必须正常出站")
require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String())
require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool())
require.NotEqual(t, http.StatusBadRequest, recorder.rec.Code, "client-visible 状态码不得是 400")
})
t.Run("non-null conversation still gets 400 and no upstream call", func(t *testing.T) {
upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")}
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil)
body := []byte(`{"model":"gpt-oss:120b-cloud","conversation":"conv_x","input":"hi","stream":false}`)
recorder := newConversationGuardRecorder("/v1/responses", body)
_, err := svc.Forward(context.Background(), recorder.c, account, body)
require.Error(t, err)
var statelessErr *openAIResponsesStatelessFieldError
require.ErrorAs(t, err, &statelessErr)
require.Nil(t, upstream.lastReq, "非 null conversation 请求不得出站")
require.Equal(t, http.StatusBadRequest, recorder.rec.Code, "client-visible 状态码必须是 400")
require.Contains(t, gjson.Get(recorder.rec.Body.String(), "error.type").String(), "invalid_request_error")
})
}
@@ -137,12 +137,16 @@ func deleteOpenAIResponsesNoneReasoningEffortFromObject(account *Account, body m
// 账号同样走这条出站改写(Codex 贴图会 422 missing field url)。
// 非 CN / 非 DeepSeek 上游原样返回。
//
// 请求体携带 conversation 时返回 *openAIResponsesStatelessFieldError 且不改写
// body:一律 400 是产品选择——显式失败优于静默丢上下文——不是该用法不存在。
// 依赖 conversation 的客户端把历史存在服务端、通常不重发 input,静默剥离等于
// 静默丢上下文(回答质量下降且零错误信号)。已知代价是 conversation + 完整
// 请求体携带非 null 的 conversation 时返回 *openAIResponsesStatelessFieldError
// 且不改写 body:一律 400 是产品选择——显式失败优于静默丢上下文——不是该用法
// 不存在。依赖 conversation 的客户端把历史存在服务端、通常不重发 input,静默剥离
// 等于静默丢上下文(回答质量下降且零错误信号)。已知代价是 conversation + 完整
// input 的 non-stream 用法被误伤;出现真实此类客户端时按平台/账号开关显式
// 放行,不得回退静默剥离。
//
// 判定用 Type != gjson.Null 而非 Exists():gjson 对 JSON null 也返回
// Exists()==true(Raw 非空),而 conversation: null 语义上与「省略该字段」等价
// (很多客户端会把可选字段序列化成 null),必须按无会话依赖正常出站。
func normalizeDeepSeekResponsesRequestBody(account *Account, body []byte) ([]byte, error) {
if account == nil {
return body, nil
@@ -152,7 +156,7 @@ func normalizeDeepSeekResponsesRequestBody(account *Account, body []byte) ([]byt
if !applyStateless && !applyImages {
return body, nil
}
if applyStateless && gjson.GetBytes(body, "conversation").Exists() {
if applyStateless && gjson.GetBytes(body, "conversation").Type != gjson.Null {
return body, &openAIResponsesStatelessFieldError{field: "conversation"}
}