fix(openai): 生图尺寸溢出选号后按首轮前的绑定处理会话粘性

未指定尺寸的生图请求逐层选号时:

- 较早轮次只拿到排队结果后,后续轮次选号不写会话粘性绑定;
- 溢出轮次抢到槽位时,会话仍绑定在首轮选号前的账号上则保留该绑定,
  否则(首轮前没有绑定,或绑定在选号中被清除、改写)绑定实际服务的账号;
- 各轮都只能排队时,绑定保持首轮选号后的状态。

旧调度器顺序模式在抢槽前写绑定,此前会让首轮前没有可用绑定的会话在溢出后仍绑定在排队账号上。
This commit is contained in:
feeeei committed 2026-11-03 23:56:39 +08:00
1 parent e452e41e40
commit 6b565e45a6
3 files changed
+148 -14

No files matched your search

@@ -2201,7 +2201,9 @@ func (s *OpenAIGatewayService) selectAccountWithScheduler(
// selectAccountWithSchedulerBySize runs selectAccountWithSchedulerOnce once per
// image size pass recorded by WithOpenAIImageSizeRouting, or once when the
// request carries no image size.
// request carries no image size. A spillover pass that acquires a slot hands
// the session binding to bindOpenAIImageSizeSpilloverAccount together with the
// binding read before the first pass.
func (s *OpenAIGatewayService) selectAccountWithSchedulerBySize(
ctx context.Context,
groupID *int64,
@@ -2217,8 +2219,18 @@ func (s *OpenAIGatewayService) selectAccountWithSchedulerBySize(
previousResponseCanMove bool,
useUpstreamTokenCost bool,
) (*AccountSelectionResult, OpenAIAccountScheduleDecision, error) {
var initialStickyAccountID int64
if strings.TrimSpace(sessionHash) != "" && openAIImageSizeRoutingUsesPreference(ctx) {
if accountID, err := s.getStickySessionAccountID(ctx, groupID, sessionHash); err == nil {
initialStickyAccountID = accountID
}
}
return selectOpenAIAccountByImageSizePasses(ctx, func(passCtx context.Context) (*AccountSelectionResult, OpenAIAccountScheduleDecision, error) {
return s.selectAccountWithSchedulerOnce(passCtx, groupID, previousResponseID, sessionHash, requestedModel, excludedIDs, requiredTransport, requiredCapability, requiredImageCapability, requireCompact, platform, previousResponseCanMove, useUpstreamTokenCost)
selection, decision, err := s.selectAccountWithSchedulerOnce(passCtx, groupID, previousResponseID, sessionHash, requestedModel, excludedIDs, requiredTransport, requiredCapability, requiredImageCapability, requireCompact, platform, previousResponseCanMove, useUpstreamTokenCost)
if err == nil && selection != nil && selection.Acquired && openAIImageSizeSpilloverPass(passCtx) {
s.bindOpenAIImageSizeSpilloverAccount(passCtx, groupID, sessionHash, initialStickyAccountID, selection)
}
return selection, decision, err
})
}
@@ -2351,7 +2363,7 @@ func (s *OpenAIGatewayService) selectAccountWithSchedulerOnce(
}
platform = NormalizeOpenAICompatiblePlatform(platform)
decision := OpenAIAccountScheduleDecision{}
preserveStickyBinding := preserveOpenAIGuardianParentBinding(ctx, sessionHash) || s.openAIImageSizeSpilloverKeepsStickyBinding(ctx, groupID, sessionHash)
preserveStickyBinding := preserveOpenAIGuardianParentBinding(ctx, sessionHash) || openAIImageSizeSpilloverPass(ctx)
guardianParentAccountID := int64(0)
if strings.TrimSpace(previousResponseID) == "" {
guardianParentAccountID = s.resolveOpenAIGuardianParentAccountID(ctx, groupID)
@@ -194,18 +194,43 @@ func openAIImageSizeVetoReason(ctx context.Context, account *Account) (bool, str
return true, openAIImageSizeTierUnsupportedReason
}
// openAIImageSizeSpilloverKeepsStickyBinding 报告本轮是否保留会话已有的粘性绑定:较早轮次已只拿到
// 排队结果时,本轮选中的账号只是临时溢出,不改写已有绑定;会话尚无绑定时照常绑定。
func (s *OpenAIGatewayService) openAIImageSizeSpilloverKeepsStickyBinding(ctx context.Context, groupID *int64, sessionHash string) bool {
if ctx == nil || strings.TrimSpace(sessionHash) == "" {
// openAIImageSizeRoutingUsesPreference 报告 ctx 记录的生图尺寸是否按偏好层级逐层选号(未传、auto 或无法识别的尺寸)。
func openAIImageSizeRoutingUsesPreference(ctx context.Context) bool {
size, ok := openAIImageSizeRoutingFromContext(ctx)
if !ok {
return false
}
_, explicit := ClassifyImageBillingTier(size)
return !explicit
}
// openAIImageSizeSpilloverPass 报告本轮是否在较早轮次只拿到排队结果之后进行。这些轮次选号时不写会话粘性绑定,
// 抢到槽位后由 bindOpenAIImageSizeSpilloverAccount 处理绑定。
func openAIImageSizeSpilloverPass(ctx context.Context) bool {
if ctx == nil {
return false
}
pass, _ := ctx.Value(openAIImageSizePassCtxKey{}).(*openAIImageSizePass)
if pass == nil || len(pass.queuedIDs) == 0 {
return false
return pass != nil && len(pass.queuedIDs) > 0
}
// bindOpenAIImageSizeSpilloverAccount 处理溢出轮次抢到槽位的选号结果的会话粘性绑定:会话仍绑定在首轮选号前的
// 账号 initialAccountID 上时保留该绑定,溢出选中的账号只服务本次请求;首轮选号前没有绑定,或绑定已在选号过程中
// 被清除、改写时,绑定选中的账号。选号结果带利润门时由 handler 在终检通过后绑定,会话保留守护父账号绑定时不改写,
// 这两种情况这里都不绑定。
func (s *OpenAIGatewayService) bindOpenAIImageSizeSpilloverAccount(ctx context.Context, groupID *int64, sessionHash string, initialAccountID int64, selection *AccountSelectionResult) {
if strings.TrimSpace(sessionHash) == "" || selection == nil || selection.Account == nil || selection.Account.ID <= 0 {
return
}
accountID, err := s.getStickySessionAccountID(ctx, groupID, sessionHash)
return err == nil && accountID > 0
if selection.ProfitGateActive() || preserveOpenAIGuardianParentBinding(ctx, sessionHash) {
return
}
if initialAccountID > 0 {
if current, err := s.getStickySessionAccountID(ctx, groupID, sessionHash); err == nil && current == initialAccountID {
return
}
}
_ = s.BindStickySession(ctx, groupID, sessionHash, selection.Account.ID)
}
type openAIAccountSelectFunc func(ctx context.Context) (*AccountSelectionResult, OpenAIAccountScheduleDecision, error)
@@ -283,9 +283,6 @@ func TestSelectAccountWithSchedulerForImages_SpilloverToRestrictedAccountKeepsSt
func TestSelectAccountWithSchedulerForImages_SpilloverWithoutBindingBindsServedAccount(t *testing.T) {
for _, mode := range openAIImageSizeSchedulerModes {
if !mode.loadBatch {
continue
}
t.Run(mode.name, func(t *testing.T) {
groupID := int64(93012)
sessionHash := "image-size-spillover-unbound"
@@ -312,6 +309,74 @@ func TestSelectAccountWithSchedulerForImages_SpilloverWithoutBindingBindsServedA
}
}
func TestSelectAccountWithSchedulerForImages_SpilloverReplacesClearedStaleBinding(t *testing.T) {
for _, mode := range openAIImageSizeSchedulerModes {
t.Run(mode.name, func(t *testing.T) {
groupID := int64(93014)
sessionHash := "image-size-spillover-stale"
accounts := []Account{
newOpenAIImageSizeTestAccount(81161, 0),
newOpenAIImageSizeTestAccount(81162, 9, "4K"),
newOpenAIImageSizeTestAccount(81163, 0),
}
accounts[2].Schedulable = false
for i := range accounts {
accounts[i].GroupIDs = []int64{groupID}
}
cache := &schedulerTestGatewayCache{sessionBindings: map[string]int64{"openai:" + sessionHash: 81163}}
concurrency := schedulerTestConcurrencyCache{
acquireResults: map[int64]bool{81161: false},
waitCounts: map[int64]int{81161: 3},
loadMap: map[int64]*AccountLoadInfo{81161: {AccountID: 81161, LoadRate: 100, WaitingCount: 3}},
}
svc := newOpenAIImageSizeSchedulerTestService(mode, accounts, cache, concurrency)
selection, err := selectOpenAIImageSizeTestAccount(t, svc, groupID, sessionHash, "")
require.NoError(t, err)
require.Equal(t, int64(81162), selection.Account.ID)
require.True(t, selection.Acquired)
require.Equal(t, int64(81162), cache.sessionBindings["openai:"+sessionHash], "a binding that is no longer usable is replaced by the served account")
})
}
}
func TestSelectAccountWithSchedulerForImages_AllPassesQueuedKeepBindingOnReturnedAccount(t *testing.T) {
for _, mode := range openAIImageSizeSchedulerModes {
t.Run(mode.name, func(t *testing.T) {
groupID := int64(93015)
sessionHash := "image-size-all-queued"
accounts := []Account{
newOpenAIImageSizeTestAccount(81171, 0),
newOpenAIImageSizeTestAccount(81172, 9, "4K"),
}
for i := range accounts {
accounts[i].GroupIDs = []int64{groupID}
}
cache := &schedulerTestGatewayCache{}
concurrency := schedulerTestConcurrencyCache{
acquireResults: map[int64]bool{81171: false, 81172: false},
waitCounts: map[int64]int{81171: 3, 81172: 3},
loadMap: map[int64]*AccountLoadInfo{
81171: {AccountID: 81171, LoadRate: 100, WaitingCount: 3},
81172: {AccountID: 81172, LoadRate: 100, WaitingCount: 3},
},
}
svc := newOpenAIImageSizeSchedulerTestService(mode, accounts, cache, concurrency)
selection, err := selectOpenAIImageSizeTestAccount(t, svc, groupID, sessionHash, "")
require.NoError(t, err)
require.Equal(t, int64(81171), selection.Account.ID)
require.NotNil(t, selection.WaitPlan)
bound, ok := cache.sessionBindings["openai:"+sessionHash]
if mode.loadBatch {
require.False(t, ok, "a queued selection does not bind the session")
} else {
require.Equal(t, int64(81171), bound, "eager sequential binding stays on the returned queued account")
}
})
}
}
func TestSelectAccountWithSchedulerForImages_UnspecifiedSizePrefersHealthyProxyOverQuarantinedUnrestricted(t *testing.T) {
for _, mode := range openAIImageSizeSchedulerModes {
t.Run(mode.name, func(t *testing.T) {
@@ -371,6 +436,38 @@ func TestSelectAccountWithSchedulerForImages_StickyAccountUnderSizeRouting(t *te
}
}
func TestSelectAccountWithSchedulerForImages_BusyStickyAccountMatchesUnroutedSelection(t *testing.T) {
for _, mode := range openAIImageSizeSchedulerModes {
t.Run(mode.name, func(t *testing.T) {
groupID := int64(93013)
sessionHash := "image-size-busy-sticky"
selectWith := func(ctx context.Context) (int64, bool) {
accounts := []Account{
newOpenAIImageSizeTestAccount(81151, 0),
newOpenAIImageSizeTestAccount(81152, 9, "4K"),
}
for i := range accounts {
accounts[i].GroupIDs = []int64{groupID}
}
cache := &schedulerTestGatewayCache{sessionBindings: map[string]int64{"openai:" + sessionHash: 81151}}
concurrency := schedulerTestConcurrencyCache{
acquireResults: map[int64]bool{81151: false},
loadMap: map[int64]*AccountLoadInfo{81151: {AccountID: 81151, LoadRate: 100}},
}
svc := newOpenAIImageSizeSchedulerTestService(mode, accounts, cache, concurrency)
selection, _, err := svc.SelectAccountWithSchedulerForImages(ctx, &groupID, sessionHash, "gpt-image-2", nil, OpenAIImagesCapabilityNative)
require.NoError(t, err)
require.NotNil(t, selection.Account)
return selection.Account.ID, selection.Acquired
}
routedID, routedAcquired := selectWith(WithOpenAIImageSizeRouting(context.Background(), ""))
unroutedID, unroutedAcquired := selectWith(context.Background())
require.Equal(t, unroutedID, routedID, "a busy sticky account is waited on or escaped exactly as without size routing")
require.Equal(t, unroutedAcquired, routedAcquired)
})
}
}
func TestSelectAccountWithScheduler_PreviousResponseAccountUnderSizeRouting(t *testing.T) {
for _, mode := range openAIImageSizeSchedulerModes {
t.Run(mode.name, func(t *testing.T) {