mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 16:04:24 +00:00
fix(composite): 修复账号池续链永久断链、跨族池续链错发与推理强度策略失效
- 续链永久断链:归属账号限流/过载/临时不可调度时 resolveAccountByPreviousResponseID 删除续链绑定,账号池守卫随后对整条会话链永久返回 400。池上下文中改为只在归属账号 永久不可用(停用、关闭调度、过期、平台不符)时删除,瞬态只跳过本次复用(非池保持原 语义);池守卫在归属账号本次失败时返回其可重试错误,绑定仍在时返回 503,仅无绑定时 400。 - 跨族池续链:generic /v1/responses 池从不处理 previous_response_id,续链会落到 Anthropic 等无该响应状态的账号(静默丢上下文、无租户校验)。续链绑定只由 OpenAI 网关链创建,入口 对池续链把候选收窄到 OpenAI 兼容族交 OpenAI handler 钉住归属,无兼容族候选时 400; generic 池委派前记录下游响应归属,并对到达 generic 的池续链明确拒绝。 - 推理强度:跨族池(generic handler)选中 openai 账号时绕过分组推理强度上限与映射。 Responses / Chat Completions 按选中账号应用策略,Messages 池绑定分组策略供委派链应用。
This commit is contained in:
1 parent
fce2d45a36
commit
db7579218a
10 files changed
+413
-12
No files matched your search
@@ -0,0 +1,103 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func poolOpenAIAccount(id int64, groupID int64, priority int) *service.Account {
|
||||
return &service.Account{
|
||||
ID: id, Name: fmt.Sprintf("openai-%d", id), Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true,
|
||||
Concurrency: 1, Priority: priority,
|
||||
AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}},
|
||||
Credentials: map[string]any{
|
||||
"api_key": "openai-key",
|
||||
"base_url": "https://openai.example",
|
||||
"model_mapping": map[string]any{"my-model": "gpt-5.4"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// openAIResponsesSSEOKResponse 是最小的 Responses 流式成功响应(openai 平台委派链以流式访问上游)。
|
||||
func openAIResponsesSSEOKResponse(model string) *http.Response {
|
||||
body := "data: " + fmt.Sprintf(`{"type":"response.completed","response":{"id":"resp_pool_sse","object":"response","status":"completed","model":%q,"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}]}],"usage":{"input_tokens":5,"output_tokens":3}}}`, model) + "\n\n"
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
}
|
||||
}
|
||||
|
||||
// 跨族账号池(generic handler)选中 openai 账号时同样受分组推理强度上限约束,
|
||||
// 与纯 OpenAI 族池 / 单目标 openai 同语义。
|
||||
func TestCompositeCrossFamilyPoolAppliesReasoningEffortCap(t *testing.T) {
|
||||
cases := []struct {
|
||||
name, path, body, effortPath string
|
||||
respond func() *http.Response
|
||||
}{
|
||||
{
|
||||
name: "responses",
|
||||
path: "/v1/responses",
|
||||
body: `{"model":"my-model","stream":false,"input":"hello","reasoning":{"effort":"xhigh"}}`,
|
||||
effortPath: "reasoning.effort",
|
||||
respond: func() *http.Response { return openAIResponsesOKResponse("gpt-5.4", 5, 3) },
|
||||
},
|
||||
{
|
||||
name: "chat_completions",
|
||||
path: "/v1/chat/completions",
|
||||
body: `{"model":"my-model","stream":false,"messages":[{"role":"user","content":"hello"}],"reasoning_effort":"xhigh"}`,
|
||||
effortPath: "reasoning_effort",
|
||||
respond: func() *http.Response { return openAIResponsesSSEOKResponse("gpt-5.4") },
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolOpenAIAccount(44101, 41011, 0)})
|
||||
h.group.MaxReasoningEffort = "medium"
|
||||
h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { return tc.respond() }
|
||||
|
||||
c, rec := h.newRequest(t, tc.path, tc.body, service.PlatformAnthropic, service.PlatformOpenAI)
|
||||
if tc.path == "/v1/responses" {
|
||||
h.handler.Responses(c)
|
||||
} else {
|
||||
h.handler.ChatCompletions(c)
|
||||
}
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
calls := h.openAIUpstream.snapshot()
|
||||
require.Len(t, calls, 1)
|
||||
effort := gjson.GetBytes(calls[0].Body, "reasoning.effort").String()
|
||||
if effort == "" {
|
||||
effort = gjson.GetBytes(calls[0].Body, "reasoning_effort").String()
|
||||
}
|
||||
require.Equal(t, "medium", effort, "upstream body=%s", calls[0].Body)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Messages 入口:委派 OpenAI 网关链时按分组上限压低 output_config.effort。
|
||||
func TestCompositeCrossFamilyPoolMessagesAppliesReasoningEffortCap(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolOpenAIAccount(44201, 41011, 0)})
|
||||
h.group.MaxReasoningEffort = "medium"
|
||||
h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return openAIResponsesSSEOKResponse("gpt-5.4")
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/messages",
|
||||
`{"model":"my-model","max_tokens":64,"stream":false,"messages":[{"role":"user","content":"hello"}],"output_config":{"effort":"max"}}`,
|
||||
service.PlatformAnthropic, service.PlatformOpenAI)
|
||||
h.handler.Messages(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
calls := h.openAIUpstream.snapshot()
|
||||
require.Len(t, calls, 1)
|
||||
require.Equal(t, "medium", gjson.GetBytes(calls[0].Body, "reasoning.effort").String(), "upstream body=%s", calls[0].Body)
|
||||
}
|
||||
@@ -172,6 +172,11 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
reqStream := parsedReq.Stream
|
||||
bindRequestedReasoningEffort(c, body, reqModel)
|
||||
ensureCompositeTargetPlatform(c, apiKey, reqModel)
|
||||
// 账号池没有单一目标平台,准入期判不出策略族:绑定分组策略,委派 OpenAI 网关链选中
|
||||
// openai 账号时由 ForwardAsAnthropic 应用(与 OpenAI handler Messages 同语义)。
|
||||
if service.GenericCompositePoolActive(c.Request.Context()) {
|
||||
bindOpenAIReasoningEffortPolicyForMessagesRequest(c, apiKey, body)
|
||||
}
|
||||
if policyBody, changed, err := applyAnthropicReasoningEffortPolicyForRequest(c, apiKey, body); err != nil {
|
||||
respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse)
|
||||
return
|
||||
|
||||
@@ -349,6 +349,20 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
if attemptChannelMapping.Mapped {
|
||||
forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel)
|
||||
}
|
||||
// 账号池按选中账号应用分组推理强度策略(与 OpenAI handler 同语义,仅 openai 账号)。
|
||||
if isPoolRequest {
|
||||
cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody)
|
||||
if policyErr != nil {
|
||||
if accountReleaseFunc != nil {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
respondOpenAIReasoningEffortPolicyError(c, policyErr, h.chatCompletionsErrorResponse)
|
||||
return
|
||||
}
|
||||
if changed {
|
||||
forwardBody = cappedBody
|
||||
}
|
||||
}
|
||||
var result *service.ForwardResult
|
||||
// 池委派 OpenAI 网关链时的原始结果:按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。
|
||||
var delegatedResult *service.OpenAIForwardResult
|
||||
|
||||
@@ -184,6 +184,17 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
// generic 调度器共用同一谓词(ctx 携带候选池且无 resolved 平台);非池请求
|
||||
// poolDenials 恒为空、attempt 策略与委派分支不生效,整条路径零变化。
|
||||
isPoolRequest := service.GenericCompositePoolActive(requestCtx)
|
||||
if isPoolRequest {
|
||||
// 续链只能由 OpenAI 兼容族归属账号服务(路由层已把这类请求收窄后交 OpenAI
|
||||
// handler);到达这里说明候选池无法承接,明确拒绝而不是静默丢弃上下文。
|
||||
if strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) != "" {
|
||||
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error",
|
||||
"previous_response_id is not supported for this composite model; resend the full conversation without previous_response_id")
|
||||
return
|
||||
}
|
||||
// 委派 OpenAI 网关链创建的响应须记录下游归属,后续续链经 OpenAI handler 校验租户。
|
||||
service.SetOpenAIHTTPResponseOwner(c, subject.UserID, apiKey.ID)
|
||||
}
|
||||
poolDenials := newCompositePoolPlatformDenials()
|
||||
|
||||
// 3. Account selection + failover loop
|
||||
@@ -350,6 +361,20 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
if attemptChannelMapping.Mapped {
|
||||
forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel)
|
||||
}
|
||||
// 账号池按选中账号应用分组推理强度策略(与 OpenAI handler 同语义,仅 openai 账号)。
|
||||
if isPoolRequest {
|
||||
cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody)
|
||||
if policyErr != nil {
|
||||
if accountReleaseFunc != nil {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
respondOpenAIReasoningEffortPolicyError(c, policyErr, h.responsesErrorResponse)
|
||||
return
|
||||
}
|
||||
if changed {
|
||||
forwardBody = cappedBody
|
||||
}
|
||||
}
|
||||
var result *service.ForwardResult
|
||||
// 池委派 OpenAI 网关链时的原始结果:按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。
|
||||
var delegatedResult *service.OpenAIForwardResult
|
||||
|
||||
@@ -783,6 +783,18 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
// 持有的槽位(Acquired=true 时 ReleaseFunc 非空,恰一次)。
|
||||
if previousResponseID != "" && compositePoolResponseStateGuardApplies(c, apiKey) && !scheduleDecision.StickyPreviousHit {
|
||||
releaseCompositePoolSelection(selection)
|
||||
// 归属账号本次已失败被排除(如 429):返回其可重试错误,不能变成永久性的 400。
|
||||
if lastFailoverErr != nil {
|
||||
h.handleFailoverExhausted(c, lastFailoverErr, streamStarted)
|
||||
return
|
||||
}
|
||||
// 绑定仍在但归属账号暂时不可用(限流、过载、临时不可调度等):可重试。
|
||||
if h.gatewayService.HasPreviousResponseBinding(c.Request.Context(), apiKey.GroupID, previousResponseID) {
|
||||
markOpsRoutingCapacityLimited(c)
|
||||
h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error",
|
||||
"the account that owns previous_response_id is temporarily unavailable; retry later", streamStarted)
|
||||
return
|
||||
}
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error",
|
||||
"previous_response_id belongs to a response owned by a different account; continue on the account that owns this response state or start a new response")
|
||||
return
|
||||
|
||||
@@ -662,6 +662,16 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver)
|
||||
writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q cannot be resolved to any platform in this composite group (%s)", model, decision.Reason))
|
||||
return
|
||||
}
|
||||
if isCompositePoolResponsesContinuation(c, decision, body) {
|
||||
// 续链绑定只由 OpenAI 网关链创建,归属账号必然属于 OpenAI 兼容族:候选池收窄到
|
||||
// 兼容族后由 OpenAI handler 按归属账号钉住与守卫,避免跨族池选到无该响应状态的
|
||||
// 账号(静默丢失上下文或跨租户续链)。
|
||||
decision.CandidatePlatforms = openAICompatibleCandidatePlatforms(decision.CandidatePlatforms)
|
||||
if len(decision.CandidatePlatforms) == 0 {
|
||||
writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q has no OpenAI-compatible account in this composite group to continue previous_response_id; resend the full conversation without previous_response_id", model))
|
||||
return
|
||||
}
|
||||
}
|
||||
c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision))
|
||||
if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) {
|
||||
if _, modelPath := requestmodel.JSONModelPathForRoute(routePath, body); modelPath != "" {
|
||||
@@ -736,6 +746,29 @@ func compositeGeminiModelFromParams(c *gin.Context) string {
|
||||
return modelAction
|
||||
}
|
||||
|
||||
// isCompositePoolResponsesContinuation 报告请求是否为 composite 账号池上的 Responses
|
||||
// 续链(带 previous_response_id)。
|
||||
func isCompositePoolResponsesContinuation(c *gin.Context, decision service.CompositeRouteDecision, body []byte) bool {
|
||||
if c == nil || c.Request == nil || c.Request.URL == nil || !strings.Contains(c.Request.URL.Path, "/responses") {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(decision.TargetPlatform) != "" || len(decision.CandidatePlatforms) == 0 {
|
||||
return false
|
||||
}
|
||||
return strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) != ""
|
||||
}
|
||||
|
||||
// openAICompatibleCandidatePlatforms 返回候选平台中经 OpenAI 网关转发的平台(保持顺序)。
|
||||
func openAICompatibleCandidatePlatforms(candidates []string) []string {
|
||||
out := make([]string, 0, len(candidates))
|
||||
for _, platform := range candidates {
|
||||
if isOpenAICompatibleGatewayFamilyPlatform(platform) {
|
||||
out = append(out, platform)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func compositeRouteEndpointForPath(path string) string {
|
||||
switch {
|
||||
case strings.Contains(path, "/messages/count_tokens"):
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//go:build unit
|
||||
|
||||
package routes
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// 跨族账号池上的 Responses 续链:归属账号必然是 OpenAI 兼容族(只有 OpenAI 网关链
|
||||
// 创建续链绑定),候选池收窄到兼容族后交 OpenAI handler 按归属钉住并校验租户;
|
||||
// 首轮经 generic 池委派创建的响应同样记录了下游归属,续链可继续。
|
||||
func TestCompositeCrossFamilyPoolContinuationPinsOwner(t *testing.T) {
|
||||
upstream := &captureUpstream{}
|
||||
deepseek := newPoolPolicyAccountWithMapping(4301, service.PlatformDeepseek, 0, map[string]any{"xpool-model": "deepseek-chat"})
|
||||
deepseek.Credentials["api_protocol"] = service.APIProtocolResponses
|
||||
anthropic := newPoolPolicyAccountWithMapping(4302, service.PlatformAnthropic, 5, map[string]any{"xpool-model": "claude-sonnet-4-5"})
|
||||
router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
|
||||
group: newPoolPolicyGroup(nil),
|
||||
accounts: []service.Account{deepseek, anthropic},
|
||||
upstream: upstream,
|
||||
})
|
||||
|
||||
first := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"xpool-model","input":"hi","prompt_cache_key":"sess-x-a","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, first.Code, first.Body.String())
|
||||
responseID := gjson.GetBytes(first.Body.Bytes(), "id").String()
|
||||
require.True(t, strings.HasPrefix(responseID, "resp_"), "got %q", responseID)
|
||||
captured := upstream.capturedSnapshot()
|
||||
require.Len(t, captured, 1)
|
||||
require.Equal(t, "deepseek-pool-fake.test", captured[0].host)
|
||||
|
||||
before := len(upstream.capturedSnapshot())
|
||||
second := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"xpool-model","input":"continue","prompt_cache_key":"sess-x-b","previous_response_id":"`+responseID+`","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, second.Code, second.Body.String())
|
||||
after := upstream.capturedSnapshot()[before:]
|
||||
require.NotEmpty(t, after)
|
||||
for _, record := range after {
|
||||
require.Equal(t, "deepseek-pool-fake.test", record.host, "continuation must stay on the owning account")
|
||||
}
|
||||
}
|
||||
|
||||
// 续链请求里优先级更高的 Anthropic 账号绝不能收到带 previous_response_id 的请求。
|
||||
func TestCompositeCrossFamilyPoolContinuationNeverReachesNonOpenAIAccount(t *testing.T) {
|
||||
upstream := &captureUpstream{}
|
||||
deepseek := newPoolPolicyAccountWithMapping(4311, service.PlatformDeepseek, 5, map[string]any{
|
||||
"ds-only": "deepseek-chat",
|
||||
"xpool-model": "deepseek-chat",
|
||||
})
|
||||
deepseek.Credentials["api_protocol"] = service.APIProtocolResponses
|
||||
anthropic := newPoolPolicyAccountWithMapping(4312, service.PlatformAnthropic, 0, map[string]any{"xpool-model": "claude-sonnet-4-5"})
|
||||
router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
|
||||
group: newPoolPolicyGroup(nil),
|
||||
accounts: []service.Account{deepseek, anthropic},
|
||||
upstream: upstream,
|
||||
})
|
||||
|
||||
first := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"ds-only","input":"hi","prompt_cache_key":"sess-y-a","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, first.Code, first.Body.String())
|
||||
responseID := gjson.GetBytes(first.Body.Bytes(), "id").String()
|
||||
require.True(t, strings.HasPrefix(responseID, "resp_"), "got %q", responseID)
|
||||
|
||||
before := len(upstream.capturedSnapshot())
|
||||
second := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"xpool-model","input":"continue","prompt_cache_key":"sess-y-b","previous_response_id":"`+responseID+`","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, second.Code, second.Body.String())
|
||||
for _, record := range upstream.capturedSnapshot()[before:] {
|
||||
require.Equal(t, "deepseek-pool-fake.test", record.host)
|
||||
}
|
||||
}
|
||||
|
||||
// 候选池没有 OpenAI 兼容族时续链无法继续:入口明确拒绝,不转发任何请求。
|
||||
func TestCompositePoolContinuationWithoutOpenAICompatibleCandidateRejected(t *testing.T) {
|
||||
upstream := &captureUpstream{}
|
||||
router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
|
||||
group: newPoolPolicyGroup(nil),
|
||||
accounts: []service.Account{
|
||||
newPoolPolicyAccountWithMapping(4321, service.PlatformAnthropic, 0, map[string]any{"np-model": "claude-sonnet-4-5"}),
|
||||
newPoolPolicyAccountWithMapping(4322, service.PlatformGemini, 1, map[string]any{"np-model": "gemini-3.1-pro"}),
|
||||
},
|
||||
upstream: upstream,
|
||||
})
|
||||
|
||||
w := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"np-model","input":"continue","previous_response_id":"resp_abc","stream":false}`)
|
||||
require.Equal(t, http.StatusBadRequest, w.Code, w.Body.String())
|
||||
require.Contains(t, w.Body.String(), "previous_response_id")
|
||||
require.Empty(t, upstream.capturedSnapshot())
|
||||
}
|
||||
@@ -287,7 +287,7 @@ func newCompositePoolPolicyTestRouter(t *testing.T, in poolPolicyRouterInput) (*
|
||||
|
||||
handlers := &handler.Handlers{
|
||||
Gateway: handler.NewGatewayHandler(
|
||||
genericGateway, nil, nil, nil, nil,
|
||||
genericGateway, openAIGateway, nil, nil, nil,
|
||||
concurrencyService, billingCache, nil, nil, nil, nil, nil, nil,
|
||||
cfg, nil,
|
||||
),
|
||||
@@ -542,8 +542,9 @@ func TestCompositePoolCNPreviousResponseIDPinBeatsPriorityAndSeed(t *testing.T)
|
||||
}
|
||||
|
||||
// CN→CN 未 hit 跨账号转移必须拒绝:resp id 归属 deepseek,deepseek 首跳 429
|
||||
// failover 后选中另一 CN 候选(kimi)时,状态守卫在任何转发前 400 终止,
|
||||
// kimi 不收到带旧 prevID 的请求(该用例在 2A 修复前后都必须保持绿)。
|
||||
// failover 后不得转给另一 CN 候选(kimi),kimi 不收到带旧 prevID 的请求。归属账号
|
||||
// 的 429 是可重试错误,必须原样返回而不是永久性的 400,且续链绑定保留:上游恢复后
|
||||
// 同一 previous_response_id 仍回到 deepseek 继续。
|
||||
func TestCompositePoolPreviousResponseIDRejectsCrossCNSelection(t *testing.T) {
|
||||
upstream := &captureUpstream{}
|
||||
group := newPoolPolicyGroup(nil)
|
||||
@@ -577,12 +578,25 @@ func TestCompositePoolPreviousResponseIDRejectsCrossCNSelection(t *testing.T) {
|
||||
wB := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"pool-model","input":"continue","prompt_cache_key":"sess-cross-b","previous_response_id":"`+responseID+`","stream":false}`)
|
||||
|
||||
require.Equal(t, http.StatusBadRequest, wB.Code, wB.Body.String())
|
||||
require.Contains(t, wB.Body.String(), "previous_response_id")
|
||||
require.Equal(t, http.StatusTooManyRequests, wB.Code, wB.Body.String())
|
||||
for _, record := range upstream.capturedSnapshot()[capturedBefore:] {
|
||||
require.NotEqual(t, "kimi-pool-fake.test", record.host,
|
||||
"the non-owning CN account must never receive the old prevID")
|
||||
}
|
||||
|
||||
// 第三条:上游恢复,同一续链仍由归属账号服务(绑定未因 429 被删除)。
|
||||
upstream.mu.Lock()
|
||||
upstream.failHost = nil
|
||||
upstream.mu.Unlock()
|
||||
capturedBefore = len(upstream.capturedSnapshot())
|
||||
wC := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"pool-model","input":"continue again","prompt_cache_key":"sess-cross-c","previous_response_id":"`+responseID+`","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, wC.Code, wC.Body.String())
|
||||
after := upstream.capturedSnapshot()[capturedBefore:]
|
||||
require.NotEmpty(t, after)
|
||||
for _, record := range after {
|
||||
require.Equal(t, "deepseek-pool-fake.test", record.host, "continuation must return to the owning account")
|
||||
}
|
||||
}
|
||||
|
||||
// claude-* 别名被两个兼容族账号同时 claim 时,/v1/messages 不套 gpt-5.x
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// composite 账号池要求续链命中归属账号:归属账号限流等瞬态不可用时只跳过本次复用,
|
||||
// 不删除续链绑定,否则冷却结束后整条会话链被永久拒绝。永久不可用(关闭调度)仍删除。
|
||||
func TestSelectAccountByPreviousResponseIDKeepsBindingOnTransientOwnerStateInPool(t *testing.T) {
|
||||
groupID := int64(31)
|
||||
poolCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformKimi})
|
||||
rateLimitedUntil := time.Now().Add(30 * time.Minute)
|
||||
newSvc := func(account Account) (*OpenAIGatewayService, OpenAIWSStateStore) {
|
||||
cache := &stubGatewayCache{}
|
||||
store := NewOpenAIWSStateStore(cache)
|
||||
return &OpenAIGatewayService{
|
||||
accountRepo: stubOpenAIAccountRepo{accounts: []Account{account}},
|
||||
cache: cache,
|
||||
cfg: newOpenAIWSV2TestConfig(),
|
||||
concurrencyService: NewConcurrencyService(stubConcurrencyCache{}),
|
||||
openaiWSStateStore: store,
|
||||
}, store
|
||||
}
|
||||
|
||||
rateLimited := Account{ID: 41, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive,
|
||||
Schedulable: true, Concurrency: 1, RateLimitResetAt: &rateLimitedUntil}
|
||||
svc, store := newSvc(rateLimited)
|
||||
require.NoError(t, store.BindResponseAccount(poolCtx, groupID, "resp_pool_rl", rateLimited.ID, time.Hour))
|
||||
selection, err := svc.SelectAccountByPreviousResponseID(poolCtx, &groupID, "resp_pool_rl", "gpt-5.1", nil, false)
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, selection)
|
||||
bound, err := store.GetResponseAccount(poolCtx, groupID, "resp_pool_rl")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, rateLimited.ID, bound, "瞬态不可用不得删除池内续链绑定")
|
||||
require.True(t, svc.HasPreviousResponseBinding(poolCtx, &groupID, "resp_pool_rl"))
|
||||
|
||||
disabled := Account{ID: 42, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive,
|
||||
Schedulable: false, Concurrency: 1}
|
||||
svc, store = newSvc(disabled)
|
||||
require.NoError(t, store.BindResponseAccount(poolCtx, groupID, "resp_pool_off", disabled.ID, time.Hour))
|
||||
selection, err = svc.SelectAccountByPreviousResponseID(poolCtx, &groupID, "resp_pool_off", "gpt-5.1", nil, false)
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, selection)
|
||||
bound, err = store.GetResponseAccount(poolCtx, groupID, "resp_pool_off")
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, bound, "关闭调度属永久不可用,删除绑定")
|
||||
require.False(t, svc.HasPreviousResponseBinding(poolCtx, &groupID, "resp_pool_off"))
|
||||
}
|
||||
@@ -566,9 +566,19 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability(
|
||||
}
|
||||
}
|
||||
|
||||
// composite 账号池要求续链必须命中归属账号(handler 池守卫),删除绑定即永久断链:
|
||||
// 池上下文中只在归属账号永久不可用时删除(previousResponseOwnerPermanentlyUnusable),
|
||||
// 限流、过载、临时不可调度、运行时熔断、调度阈值门等瞬态与配额暂停、利润否决同语义,
|
||||
// 只跳过本次复用、保留绑定。非池请求保持原语义:瞬态即删除,会话改锚到新账号。
|
||||
keepOnTransient := openAICompositePoolActive(ctx)
|
||||
dropTransient := func() {
|
||||
if !keepOnTransient {
|
||||
_ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID)
|
||||
}
|
||||
}
|
||||
account, err := s.getSchedulableAccount(ctx, accountID)
|
||||
if err != nil || account == nil {
|
||||
_ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID)
|
||||
dropTransient()
|
||||
return 0, nil, "", nil
|
||||
}
|
||||
// OAuth/SetupToken continuation state lives on the WSv2 session and cannot
|
||||
@@ -581,11 +591,14 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability(
|
||||
s.getOpenAIWSProtocolResolver().Resolve(account).Transport != OpenAIUpstreamTransportResponsesWebsocketV2 {
|
||||
return 0, nil, "", nil
|
||||
}
|
||||
if shouldClearStickySession(account, requestedModel) ||
|
||||
(!account.IsOpenAI() && !openAICompositePoolHTTPResponsesOwner(ctx, account)) || !account.IsSchedulable() {
|
||||
if previousResponseOwnerPermanentlyUnusable(ctx, account) {
|
||||
_ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID)
|
||||
return 0, nil, "", nil
|
||||
}
|
||||
if shouldClearStickySession(account, requestedModel) {
|
||||
dropTransient()
|
||||
return 0, nil, "", nil
|
||||
}
|
||||
if !parentHealthyForShadow(account, s.parentAccountLookup(ctx)) {
|
||||
_ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID)
|
||||
return 0, nil, "", nil
|
||||
@@ -611,15 +624,22 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability(
|
||||
}
|
||||
if s.schedulerSnapshot != nil && s.accountRepo != nil {
|
||||
latest, latestErr := s.accountRepo.GetByID(ctx, account.ID)
|
||||
if latestErr != nil || latest == nil {
|
||||
if latestErr != nil {
|
||||
dropTransient()
|
||||
return 0, nil, "", nil
|
||||
}
|
||||
if latest == nil {
|
||||
_ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID)
|
||||
return 0, nil, "", nil
|
||||
}
|
||||
if shouldClearStickySession(latest, requestedModel) ||
|
||||
(!latest.IsOpenAI() && !openAICompositePoolHTTPResponsesOwner(ctx, latest)) || !latest.IsSchedulable() {
|
||||
if previousResponseOwnerPermanentlyUnusable(ctx, latest) {
|
||||
_ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID)
|
||||
return 0, nil, "", nil
|
||||
}
|
||||
if shouldClearStickySession(latest, requestedModel) {
|
||||
dropTransient()
|
||||
return 0, nil, "", nil
|
||||
}
|
||||
if !s.openAIAccountMatchesSchedulingGroup(latest, groupID) {
|
||||
return 0, nil, "", nil
|
||||
}
|
||||
@@ -644,7 +664,7 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability(
|
||||
return 0, nil, "", nil
|
||||
}
|
||||
if s.isOpenAIAccountRequestRuntimeBlocked(latest, requestedModel) {
|
||||
_ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID)
|
||||
dropTransient()
|
||||
return 0, nil, "", nil
|
||||
}
|
||||
account = latest
|
||||
@@ -656,6 +676,33 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability(
|
||||
return accountID, account, responseID, store
|
||||
}
|
||||
|
||||
// previousResponseOwnerPermanentlyUnusable 报告续链归属账号是否已永久不能继续该响应链
|
||||
// (停用、关闭调度、已过期、平台不符),此时删除绑定;其余不可用状态均为瞬态。
|
||||
func previousResponseOwnerPermanentlyUnusable(ctx context.Context, account *Account) bool {
|
||||
if account == nil || !account.IsActive() || !account.Schedulable {
|
||||
return true
|
||||
}
|
||||
if account.AutoPauseOnExpired && account.ExpiresAt != nil && !time.Now().Before(*account.ExpiresAt) {
|
||||
return true
|
||||
}
|
||||
return !account.IsOpenAI() && !openAICompositePoolHTTPResponsesOwner(ctx, account)
|
||||
}
|
||||
|
||||
// HasPreviousResponseBinding 报告 previous_response_id 是否仍绑定到某个账号(不校验
|
||||
// 账号当前是否可用)。供 composite 池守卫区分「归属账号暂时不可用」与「无归属」。
|
||||
func (s *OpenAIGatewayService) HasPreviousResponseBinding(ctx context.Context, groupID *int64, previousResponseID string) bool {
|
||||
responseID := strings.TrimSpace(previousResponseID)
|
||||
if s == nil || responseID == "" {
|
||||
return false
|
||||
}
|
||||
store := s.getOpenAIWSStateStore()
|
||||
if store == nil {
|
||||
return false
|
||||
}
|
||||
accountID, err := store.GetResponseAccount(ctx, derefGroupID(groupID), responseID)
|
||||
return err == nil && accountID > 0
|
||||
}
|
||||
|
||||
func classifyOpenAIWSAcquireError(err error) string {
|
||||
if err == nil {
|
||||
return "acquire_conn"
|
||||
|
||||
Reference in new issue
Block a user