From 1ee684fbf090cc94898c103f4f7e6bf82ec54c2f Mon Sep 17 00:00:00 2001 From: kittimzhe Date: Wed, 28 Oct 2026 11:03:37 +0800 Subject: [PATCH] fix(channel): make retries skip tried channels and restore the top tier after affinity - retries exclude channels already attempted in this request, recorded in the use_channel trail, and prefer fresh candidates first - the first retry after a session-affinity attempt restarts from the highest priority tier instead of tier index 1, because the affinity attempt bypassed the priority ladder without consuming a tier - selection walks down priority tiers left empty by the exclusion instead of failing or re-rolling an already tried channel - when every eligible channel has been tried, the pool is retried so a single channel with a transient failure can still recover, which TestResponsesHTTPHealthCountsFinalResult covers end to end Fixes #8063 --- constant/context_key.go | 4 + controller/model_management_test.go | 8 +- model/ability.go | 35 ++- model/channel_cache.go | 116 ++++++---- model/task_plugin_channel_select_test.go | 61 ++++-- relay/responses_websocket_test.go | 2 +- service/channel_select.go | 43 +++- service/channel_select_retry_test.go | 261 +++++++++++++++++++++++ 8 files changed, 461 insertions(+), 69 deletions(-) create mode 100644 service/channel_select_retry_test.go diff --git a/constant/context_key.go b/constant/context_key.go index 743b4b5ce090..23c4859ca50a 100644 --- a/constant/context_key.go +++ b/constant/context_key.go @@ -39,6 +39,10 @@ const ( ContextKeyChannelIsMultiKey ContextKey = "channel_is_multi_key" ContextKeyChannelMultiKeyIndex ContextKey = "channel_multi_key_index" ContextKeyChannelKey ContextKey = "channel_key" + // ContextKeyChannelAffinityAttempted marks that the request's first + // attempt was served by session affinity, which bypasses the priority + // ladder; retry selection then starts from the highest priority again. + ContextKeyChannelAffinityAttempted ContextKey = "channel_affinity_attempted" // ContextKeyUpstreamRequestOrigin is the scheme and host of the last upstream // request, which differs from the base URL for absolute Advanced Custom routes diff --git a/controller/model_management_test.go b/controller/model_management_test.go index a66668162dc1..6fb803208ff3 100644 --- a/controller/model_management_test.go +++ b/controller/model_management_test.go @@ -1345,7 +1345,7 @@ func TestModelDeletionDatabaseMatrix(t *testing.T) { } common.MemoryCacheEnabled = true model.InitChannelCache() - cached, err := model.GetRandomSatisfiedChannel("default", name, 0, nil) + cached, err := model.GetRandomSatisfiedChannel("default", name, 0, nil, nil) require.NoError(t, err) require.NotNil(t, cached) baseline, err := model.GetModelPricingSnapshot([]string{name}) @@ -1385,7 +1385,7 @@ func TestModelDeletionDatabaseMatrix(t *testing.T) { require.NoError(t, db.First(&after, original.Id).Error) assert.Equal(t, original, after) } - cached, err = model.GetRandomSatisfiedChannel("default", name, 0, nil) + cached, err = model.GetRandomSatisfiedChannel("default", name, 0, nil, nil) require.NoError(t, err) require.NotNil(t, cached) recorder := modelManagementRequest(t, BatchDeleteModelMeta, http.MethodPost, "/api/models/delete", body, &response) @@ -1414,10 +1414,10 @@ func TestModelDeletionDatabaseMatrix(t *testing.T) { } } for _, group := range []string{"default", "vip", "last-model-group"} { - cached, _ = model.GetRandomSatisfiedChannel(group, name, 0, nil) + cached, _ = model.GetRandomSatisfiedChannel(group, name, 0, nil, nil) assert.Nil(t, cached) } - cached, err = model.GetRandomSatisfiedChannel("default", name+"-keep", 0, nil) + cached, err = model.GetRandomSatisfiedChannel("default", name+"-keep", 0, nil, nil) require.NoError(t, err) require.NotNil(t, cached) pricingAfter, err := model.GetModelPricingSnapshot([]string{name, second.ModelName}) diff --git a/model/ability.go b/model/ability.go index be411872353c..e5a40e520336 100644 --- a/model/ability.go +++ b/model/ability.go @@ -110,6 +110,7 @@ func GetChannel( model string, retry int, filters []dto.ChannelFilter, + excludeChannelIds []int, ) (*Channel, error) { var abilities []Ability err := DB.Where(commonGroupCol+" = ? and model = ? and enabled = ?", group, model, true).Order("priority DESC, weight DESC").Find(&abilities).Error @@ -126,6 +127,22 @@ func GetChannel( } abilities = filterAbilitiesByConstraints(abilities, model, filters) } + // Prefer channels this request has not attempted yet, so a retry walks + // fresh channels first. When every eligible channel was already tried + // (for example a single channel with a transient failure), fall back to + // the full pool instead of failing the request. + if len(excludeChannelIds) > 0 { + excluded := make(map[int]bool, len(excludeChannelIds)) + for _, channelId := range excludeChannelIds { + excluded[channelId] = true + } + keptAbilities := lo.Filter(abilities, func(ability Ability, _ int) bool { + return !excluded[ability.ChannelId] + }) + if len(keptAbilities) > 0 { + abilities = keptAbilities + } + } if len(abilities) > 0 { priorities := make([]int64, 0) seen := make(map[int64]bool) @@ -143,10 +160,20 @@ func GetChannel( if retry >= len(priorities) { retry = len(priorities) - 1 } - targetPriority := priorities[retry] - abilities = lo.Filter(abilities, func(ability Ability, _ int) bool { - return ability.Priority == nil && targetPriority == 0 || ability.Priority != nil && *ability.Priority == targetPriority - }) + // Walk from the retry tier downwards and pick the first tier that + // still has candidates, so tiers exhausted by this request are + // skipped instead of failing or re-rolling an already tried channel. + for idx := retry; idx < len(priorities); idx++ { + targetPriority := priorities[idx] + targetAbilities := lo.Filter(abilities, func(ability Ability, _ int) bool { + return ability.Priority == nil && targetPriority == 0 || ability.Priority != nil && *ability.Priority == targetPriority + }) + if len(targetAbilities) == 0 { + continue + } + abilities = targetAbilities + break + } } channel := Channel{} if len(abilities) > 0 { diff --git a/model/channel_cache.go b/model/channel_cache.go index 5bdf1404244a..44a7cd4de601 100644 --- a/model/channel_cache.go +++ b/model/channel_cache.go @@ -1,7 +1,6 @@ package model import ( - "errors" "fmt" "math/rand" "sort" @@ -119,10 +118,11 @@ func GetRandomSatisfiedChannel( model string, retry int, filters []dto.ChannelFilter, + excludeChannelIds []int, ) (*Channel, error) { // if memory cache is disabled, get channel directly from database if !common.MemoryCacheEnabled { - return GetChannel(group, model, retry, filters) + return GetChannel(group, model, retry, filters, excludeChannelIds) } channelSyncLock.RLock() @@ -137,19 +137,39 @@ func GetRandomSatisfiedChannel( channels, _ = filterCandidateIDs(group2model2channels[group][normalizedModel], model, filters) } - if len(channels) == 0 { + // Prefer channels this request has not attempted yet, so a retry walks + // fresh channels first. When every eligible channel was already tried + // (for example a single channel with a transient failure), fall back to + // the full pool instead of failing the request. + candidates := channels + if len(candidates) == 0 { return nil, nil } + if len(excludeChannelIds) > 0 { + excluded := make(map[int]bool, len(excludeChannelIds)) + for _, channelId := range excludeChannelIds { + excluded[channelId] = true + } + kept := make([]int, 0, len(channels)) + for _, channelId := range channels { + if !excluded[channelId] { + kept = append(kept, channelId) + } + } + if len(kept) > 0 { + candidates = kept + } + } - if len(channels) == 1 { - if channel, ok := channelsIDM[channels[0]]; ok { + if len(candidates) == 1 { + if channel, ok := channelsIDM[candidates[0]]; ok { return channel, nil } - return nil, fmt.Errorf("database consistency error: channel #%d does not exist, please contact the administrator", channels[0]) + return nil, fmt.Errorf("database consistency error: channel #%d does not exist, please contact the administrator", candidates[0]) } uniquePriorities := make(map[int]bool) - for _, channelId := range channels { + for _, channelId := range candidates { if channel, ok := channelsIDM[channelId]; ok { uniquePriorities[int(channel.GetPriority())] = true } else { @@ -165,55 +185,59 @@ func GetRandomSatisfiedChannel( if retry >= len(uniquePriorities) { retry = len(uniquePriorities) - 1 } - targetPriority := int64(sortedUniquePriorities[retry]) - // get the priority for the given retry number - var sumWeight = 0 - var targetChannels []*Channel - for _, channelId := range channels { - if channel, ok := channelsIDM[channelId]; ok { - if channel.GetPriority() == targetPriority { - sumWeight += channel.GetWeight() - targetChannels = append(targetChannels, channel) + // Walk from the retry tier downwards and pick the first tier that still + // has candidates, so tiers left empty by the exclusion above are skipped + // instead of failing or re-rolling an already tried channel. + for idx := retry; idx < len(sortedUniquePriorities); idx++ { + targetPriority := int64(sortedUniquePriorities[idx]) + + var sumWeight = 0 + var targetChannels []*Channel + for _, channelId := range candidates { + if channel, ok := channelsIDM[channelId]; ok { + if channel.GetPriority() == targetPriority { + sumWeight += channel.GetWeight() + targetChannels = append(targetChannels, channel) + } + } else { + return nil, fmt.Errorf("database consistency error: channel #%d does not exist, please contact the administrator", channelId) } - } else { - return nil, fmt.Errorf("database consistency error: channel #%d does not exist, please contact the administrator", channelId) } - } - - if len(targetChannels) == 0 { - return nil, errors.New(fmt.Sprintf("no channel found, group: %s, model: %s, priority: %d", group, model, targetPriority)) - } + if len(targetChannels) == 0 { + continue + } - // smoothing factor and adjustment - smoothingFactor := 1 - smoothingAdjustment := 0 + // smoothing factor and adjustment + smoothingFactor := 1 + smoothingAdjustment := 0 - if sumWeight == 0 { - // when all channels have weight 0, set sumWeight to the number of channels and set smoothing adjustment to 100 - // each channel's effective weight = 100 - sumWeight = len(targetChannels) * 100 - smoothingAdjustment = 100 - } else if sumWeight/len(targetChannels) < 10 { - // when the average weight is less than 10, set smoothing factor to 100 - smoothingFactor = 100 - } + if sumWeight == 0 { + // when all channels have weight 0, set sumWeight to the number of channels and set smoothing adjustment to 100 + // each channel's effective weight = 100 + sumWeight = len(targetChannels) * 100 + smoothingAdjustment = 100 + } else if sumWeight/len(targetChannels) < 10 { + // when the average weight is less than 10, set smoothing factor to 100 + smoothingFactor = 100 + } - // Calculate the total weight of all channels up to endIdx - totalWeight := sumWeight * smoothingFactor + // Calculate the total weight of all channels up to endIdx + totalWeight := sumWeight * smoothingFactor - // Generate a random value in the range [0, totalWeight) - randomWeight := rand.Intn(totalWeight) + // Generate a random value in the range [0, totalWeight) + randomWeight := rand.Intn(totalWeight) - // Find a channel based on its weight - for _, channel := range targetChannels { - randomWeight -= channel.GetWeight()*smoothingFactor + smoothingAdjustment - if randomWeight < 0 { - return channel, nil + // Find a channel based on its weight + for _, channel := range targetChannels { + randomWeight -= channel.GetWeight()*smoothingFactor + smoothingAdjustment + if randomWeight < 0 { + return channel, nil + } } } - // return null if no channel is not found - return nil, errors.New("channel not found") + // no tier holds a pickable channel; unreachable for a non-empty pool + return nil, nil } func CacheGetChannel(id int) (*Channel, error) { diff --git a/model/task_plugin_channel_select_test.go b/model/task_plugin_channel_select_test.go index 8daa050faa5b..45b1529a7f98 100644 --- a/model/task_plugin_channel_select_test.go +++ b/model/task_plugin_channel_select_test.go @@ -28,22 +28,22 @@ func TestTaskPluginChannelSelectionFiltersBothCachePaths(t *testing.T) { require.NoError(t, channels[i].Insert()) } - selected, err := GetChannel("default", "shared", 0, identityFilters("alpha", nil)) + selected, err := GetChannel("default", "shared", 0, identityFilters("alpha", nil), nil) require.NoError(t, err) require.NotNil(t, selected) assert.Equal(t, "alpha", selected.Name) - selected, err = GetChannel("default", "shared", 0, identityFilters("", nil)) + selected, err = GetChannel("default", "shared", 0, identityFilters("", nil), nil) require.NoError(t, err) assert.Nil(t, selected) - selected, err = GetChannel("default", "ordinary", 0, identityFilters("", nil)) + selected, err = GetChannel("default", "ordinary", 0, identityFilters("", nil), nil) require.NoError(t, err) require.NotNil(t, selected) assert.Equal(t, "ordinary", selected.Name) - selected, err = GetChannel("default", "legacy", 0, identityFilters("legacy-alpha", []int{constant.ChannelTypeKling})) + selected, err = GetChannel("default", "legacy", 0, identityFilters("legacy-alpha", []int{constant.ChannelTypeKling}), nil) require.NoError(t, err) require.NotNil(t, selected) assert.Equal(t, "legacy-alpha", selected.Name) - selected, err = GetChannel("default", "legacy", 0, identityFilters("legacy-alpha", []int{constant.ChannelTypeKling, constant.ChannelTypeJimeng})) + selected, err = GetChannel("default", "legacy", 0, identityFilters("legacy-alpha", []int{constant.ChannelTypeKling, constant.ChannelTypeJimeng}), nil) require.NoError(t, err) require.NotNil(t, selected) assert.Contains(t, []string{"legacy-alpha", "legacy-beta"}, selected.Name) @@ -96,23 +96,23 @@ func TestNewAPIChannelServesExtendedTaskPlugins(t *testing.T) { require.NoError(t, channels[i].Insert()) } - selected, err := GetChannel("default", "shared", 0, identityFilters("alpha", nil)) + selected, err := GetChannel("default", "shared", 0, identityFilters("alpha", nil), nil) require.NoError(t, err) require.NotNil(t, selected) assert.Equal(t, "gateway", selected.Name) - selected, err = GetChannel("default", "shared", 0, identityFilters("delta", nil)) + selected, err = GetChannel("default", "shared", 0, identityFilters("delta", nil), nil) require.NoError(t, err) require.NotNil(t, selected) assert.Equal(t, "gateway-single", selected.Name, "a single task_plugin_key still binds a New API channel") - selected, err = GetChannel("default", "shared", 0, identityFilters("beta", nil)) + selected, err = GetChannel("default", "shared", 0, identityFilters("beta", nil), nil) require.NoError(t, err) assert.Nil(t, selected, "unbound plugins never reach the gateway channel") shared := []dto.ChannelFilter{{Kind: dto.FilterTaskPluginIdentity, TaskPluginKey: "beta", TaskPluginKeys: []string{"beta", "gamma"}}} - selected, err = GetChannel("default", "shared", 0, shared) + selected, err = GetChannel("default", "shared", 0, shared, nil) require.NoError(t, err) require.NotNil(t, selected) assert.Equal(t, "gateway", selected.Name, "a bound shared-model candidate admits the channel") - selected, err = GetChannel("default", "chat", 0, identityFilters("", nil)) + selected, err = GetChannel("default", "chat", 0, identityFilters("", nil), nil) require.NoError(t, err) require.NotNil(t, selected) assert.Equal(t, "gateway", selected.Name, "requests without a pinned plugin keep using the gateway") @@ -128,12 +128,49 @@ func TestModelModifierNamesRouteWithAndWithoutMemoryCache(t *testing.T) { for _, memoryCache := range []bool{false, true} { common.MemoryCacheEnabled = memoryCache InitChannelCache() - selected, err := GetRandomSatisfiedChannel("default", "deepseek-flash@effort:max", 0, nil) + selected, err := GetRandomSatisfiedChannel("default", "deepseek-flash@effort:max", 0, nil, nil) require.NoError(t, err) require.NotNil(t, selected, "memory cache %v", memoryCache) assert.Equal(t, "deepseek", selected.Name) - selected, err = GetRandomSatisfiedChannel("default", "deepseek-pro@effort:max", 0, nil) + selected, err = GetRandomSatisfiedChannel("default", "deepseek-pro@effort:max", 0, nil, nil) require.NoError(t, err) assert.Nil(t, selected, "memory cache %v", memoryCache) } } + +// TestGetChannelSkipsTriedChannelsAndExhaustedTiers covers the database path +// of issue #8063: a retry must not reselect a channel this request already +// attempted and must fall through tiers emptied by that exclusion; once every +// channel is tried the pool is retried instead of failing the request. +func TestGetChannelSkipsTriedChannelsAndExhaustedTiers(t *testing.T) { + truncateTables(t) + p4 := int64(4) + p3 := int64(3) + w3 := uint(3) + w1 := uint(1) + for _, ch := range []Channel{ + {Id: 910024, Type: constant.ChannelTypeOpenAI, Status: common.ChannelStatusEnabled, Name: "p4-a", Models: "tier-model", Group: "default", Priority: &p4, Weight: &w3}, + {Id: 910026, Type: constant.ChannelTypeOpenAI, Status: common.ChannelStatusEnabled, Name: "p4-b", Models: "tier-model", Group: "default", Priority: &p4, Weight: &w3}, + {Id: 910028, Type: constant.ChannelTypeOpenAI, Status: common.ChannelStatusEnabled, Name: "p4-c", Models: "tier-model", Group: "default", Priority: &p4, Weight: &w3}, + {Id: 910025, Type: constant.ChannelTypeOpenAI, Status: common.ChannelStatusEnabled, Name: "p3-a", Models: "tier-model", Group: "default", Priority: &p3, Weight: &w1}, + {Id: 910027, Type: constant.ChannelTypeOpenAI, Status: common.ChannelStatusEnabled, Name: "p3-b", Models: "tier-model", Group: "default", Priority: &p3, Weight: &w1}, + {Id: 910029, Type: constant.ChannelTypeOpenAI, Status: common.ChannelStatusEnabled, Name: "p3-c", Models: "tier-model", Group: "default", Priority: &p3, Weight: &w1}, + } { + require.NoError(t, ch.Insert()) + } + + selected, err := GetChannel("default", "tier-model", 0, nil, []int{910024, 910026, 910028}) + require.NoError(t, err) + require.NotNil(t, selected) + assert.EqualValues(t, p3, *selected.Priority, "excluded top-tier channels must not be reselected; fall through to the next tier") + + selected, err = GetChannel("default", "tier-model", 5, nil, nil) + require.NoError(t, err) + require.NotNil(t, selected) + assert.EqualValues(t, p3, *selected.Priority, "a retry index past the tier count still clamps to the lowest tier") + + selected, err = GetChannel("default", "tier-model", 0, nil, []int{910024, 910026, 910028, 910025, 910027, 910029}) + require.NoError(t, err) + require.NotNil(t, selected) + assert.Contains(t, []int64{p4, p3}, *selected.Priority, "with every channel tried the pool is retried instead of failing the request") +} diff --git a/relay/responses_websocket_test.go b/relay/responses_websocket_test.go index 7e2cf2129df7..8589ca52466a 100644 --- a/relay/responses_websocket_test.go +++ b/relay/responses_websocket_test.go @@ -251,7 +251,7 @@ func TestResponsesWSChannelRoutingRequiresExplicitOptIn(t *testing.T) { require.Nil(t, apiErr) require.NotNil(t, channel) assert.Equal(t, enabled.Id, channel.Id) - httpChannel, err := model.GetRandomSatisfiedChannel("default", "ws-model", 0, nil) + httpChannel, err := model.GetRandomSatisfiedChannel("default", "ws-model", 0, nil, nil) require.NoError(t, err) require.NotNil(t, httpChannel) assert.Equal(t, legacy.Id, httpChannel.Id) diff --git a/service/channel_select.go b/service/channel_select.go index 113e4a3530e0..534bb2c60a4d 100644 --- a/service/channel_select.go +++ b/service/channel_select.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "net/http" + "strconv" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/constant" @@ -117,6 +118,7 @@ func CacheGetRandomSatisfiedChannel(param *RetryParam) (*model.Channel, string, selectGroup := param.TokenGroup userGroup := common.GetContextKeyString(param.Ctx, constant.ContextKeyUserGroup) filters := GetChannelConstraints(param.Ctx).Filters + excludeChannelIds := attemptedChannelIds(param.Ctx) if param.TokenGroup == "auto" { autoGroups := GetRequestAutoGroups(param.Ctx, userGroup) @@ -139,7 +141,7 @@ func CacheGetRandomSatisfiedChannel(param *RetryParam) (*model.Channel, string, autoGroup := autoGroups[i] // Calculate priorityRetry for current group // 计算当前分组的 priorityRetry - priorityRetry := param.GetRetry() + priorityRetry := priorityTierStartIndex(param) // If moved to a new group, reset priorityRetry and update startRetryIndex // 如果切换到新分组,重置 priorityRetry 并更新 startRetryIndex if i > startGroupIndex { @@ -152,6 +154,7 @@ func CacheGetRandomSatisfiedChannel(param *RetryParam) (*model.Channel, string, param.ModelName, priorityRetry, filters, + excludeChannelIds, ) if channel == nil { // Current group has no available channel for this model, try next group @@ -193,8 +196,9 @@ func CacheGetRandomSatisfiedChannel(param *RetryParam) (*model.Channel, string, channel, err = model.GetRandomSatisfiedChannel( param.TokenGroup, param.ModelName, - param.GetRetry(), + priorityTierStartIndex(param), filters, + excludeChannelIds, ) if err != nil { return nil, param.TokenGroup, err @@ -337,6 +341,12 @@ func SelectChannelForRequest(c *gin.Context, modelName string, retry *RetryParam MarkChannelAffinityUsed(c, usingGroup, preferred.Id) } } + if affinityUsable { + // Session affinity supplied attempt 0 without walking the + // priority ladder; priorityTierStartIndex relies on this to + // restart retries from the highest priority tier. + common.SetContextKey(c, constant.ContextKeyChannelAffinityAttempted, true) + } if !affinityUsable && !ShouldKeepChannelAffinityOnChannelDisabled() { ClearCurrentChannelAffinityCache(c) } @@ -385,6 +395,35 @@ func pinnedChannelUnavailable(pin dto.ChannelPin, statusCode int, messageID stri return &ChannelSelectError{StatusCode: statusCode, MessageID: messageID} } +// priorityTierStartIndex maps the request's retry counter to the priority +// tier index a fresh selection should start from. A session-affinity attempt +// bypasses the priority ladder without consuming a tier, so the first retry +// after a failed affinity channel starts from the highest priority again +// instead of tier index 1. +func priorityTierStartIndex(param *RetryParam) int { + tier := param.GetRetry() + if tier > 0 && common.GetContextKeyBool(param.Ctx, constant.ContextKeyChannelAffinityAttempted) { + tier-- + } + return tier +} + +// attemptedChannelIds returns the channel IDs already tried in this request, +// as recorded in the use_channel trail by AppendUsedChannel. +func attemptedChannelIds(c *gin.Context) []int { + trail := c.GetStringSlice("use_channel") + if len(trail) == 0 { + return nil + } + ids := make([]int, 0, len(trail)) + for _, entry := range trail { + if id, err := strconv.Atoi(entry); err == nil { + ids = append(ids, id) + } + } + return ids +} + // AppendUsedChannel records an attempted channel in the request's channel // trail, which the retry log and the consume log's admin_info both read. func AppendUsedChannel(c *gin.Context, channelID int) { diff --git a/service/channel_select_retry_test.go b/service/channel_select_retry_test.go new file mode 100644 index 000000000000..ef8380d8c53f --- /dev/null +++ b/service/channel_select_retry_test.go @@ -0,0 +1,261 @@ +package service + +import ( + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/constant" + "github.com/QuantumNous/new-api/model" + "github.com/QuantumNous/new-api/setting/operation_setting" + "github.com/gin-gonic/gin" + "github.com/glebarez/sqlite" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/gorm" +) + +// Regression tests for issue #8063: a retry that follows a failed channel +// must skip the channels already attempted in this request, and the first +// retry after a session-affinity attempt must restart from the highest +// priority tier instead of tier index 1. + +const channelSelectRetryModel = "retry-tier-model" + +func setupChannelSelectRetryTest(t *testing.T) *gorm.DB { + t.Helper() + + originalDB := model.DB + originalMemoryCacheEnabled := common.MemoryCacheEnabled + + dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", strings.ReplaceAll(t.Name(), "/", "_")) + db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{}) + require.NoError(t, err) + require.NoError(t, db.AutoMigrate(&model.Channel{}, &model.Ability{})) + model.DB = db + common.MemoryCacheEnabled = true + + t.Cleanup(func() { + model.DB = originalDB + common.MemoryCacheEnabled = originalMemoryCacheEnabled + if originalMemoryCacheEnabled && originalDB != nil && + originalDB.Migrator().HasTable(&model.Channel{}) && originalDB.Migrator().HasTable(&model.Ability{}) { + model.InitChannelCache() + } + sqlDB, err := db.DB() + if err == nil { + require.NoError(t, sqlDB.Close()) + } + }) + + return db +} + +func createChannelSelectRetryChannel(t *testing.T, db *gorm.DB, id int, group, modelName string, priority int64, weight uint) { + t.Helper() + require.NoError(t, db.Create(&model.Channel{ + Id: id, + Type: constant.ChannelTypeOpenAI, + Key: fmt.Sprintf("key-%d", id), + Status: common.ChannelStatusEnabled, + Name: fmt.Sprintf("channel-%d", id), + Weight: &weight, + Models: modelName, + Group: group, + Priority: &priority, + }).Error) + require.NoError(t, db.Create(&model.Ability{ + Group: group, + Model: modelName, + ChannelId: id, + Enabled: true, + Priority: &priority, + Weight: weight, + }).Error) +} + +// seedChannelSelectRetryTiers mirrors the topology of issue #8063: priority 4 +// carries channels 24/26/28 weighted 3:3:6 and priority 3 carries 25/27/29. +func seedChannelSelectRetryTiers(t *testing.T, db *gorm.DB) { + t.Helper() + for _, ch := range []struct { + id int + priority int64 + weight uint + }{ + {24, 4, 3}, {26, 4, 3}, {28, 4, 6}, + {25, 3, 1}, {27, 3, 1}, {29, 3, 1}, + } { + createChannelSelectRetryChannel(t, db, ch.id, "default", channelSelectRetryModel, ch.priority, ch.weight) + } + model.InitChannelCache() +} + +func newChannelSelectRetryContext(t *testing.T, usedChannels []string) *gin.Context { + t.Helper() + gin.SetMode(gin.TestMode) + ctx, _ := gin.CreateTestContext(httptest.NewRecorder()) + if len(usedChannels) > 0 { + ctx.Set("use_channel", usedChannels) + } + return ctx +} + +func newChannelSelectRetryParam(ctx *gin.Context, retry int) *RetryParam { + return &RetryParam{ + Ctx: ctx, + TokenGroup: "default", + ModelName: channelSelectRetryModel, + RequestPath: "/v1/chat/completions", + Retry: &retry, + } +} + +func TestCacheGetRandomSatisfiedChannelExcludesTriedChannel(t *testing.T) { + db := setupChannelSelectRetryTest(t) + seedChannelSelectRetryTiers(t, db) + + ctx := newChannelSelectRetryContext(t, []string{"24"}) + channel, _, err := CacheGetRandomSatisfiedChannel(newChannelSelectRetryParam(ctx, 0)) + require.NoError(t, err) + require.NotNil(t, channel) + assert.EqualValues(t, 4, channel.GetPriority(), "the first attempt still uses the top priority tier") + assert.Contains(t, []int{26, 28}, channel.Id, "an already tried channel must not be selected again") +} + +func TestCacheGetRandomSatisfiedChannelRestoresTopTierAfterAffinityRetry(t *testing.T) { + db := setupChannelSelectRetryTest(t) + seedChannelSelectRetryTiers(t, db) + + // The session-affinity attempt landed on channel 27 (priority 3) and + // failed; the retry must restart from the highest priority tier and skip 27. + ctx := newChannelSelectRetryContext(t, []string{"27"}) + common.SetContextKey(ctx, constant.ContextKeyChannelAffinityAttempted, true) + channel, _, err := CacheGetRandomSatisfiedChannel(newChannelSelectRetryParam(ctx, 1)) + require.NoError(t, err) + require.NotNil(t, channel) + assert.EqualValues(t, 4, channel.GetPriority(), "retry after a failed affinity attempt must restart from the top tier") + assert.NotEqual(t, 27, channel.Id) + + // Without affinity the retry ladder is unchanged: retry 1 targets the + // second priority tier. + plainCtx := newChannelSelectRetryContext(t, []string{"27"}) + channel, _, err = CacheGetRandomSatisfiedChannel(newChannelSelectRetryParam(plainCtx, 1)) + require.NoError(t, err) + require.NotNil(t, channel) + assert.EqualValues(t, 3, channel.GetPriority()) +} + +func TestCacheGetRandomSatisfiedChannelSkipsExhaustedTiers(t *testing.T) { + db := setupChannelSelectRetryTest(t) + seedChannelSelectRetryTiers(t, db) + + // Priority 3 is exhausted by this request; the retry index would clamp + // into it, so selection must fall back to the still-populated top tier + // instead of re-rolling an already tried channel. + ctx := newChannelSelectRetryContext(t, []string{"25", "27", "29"}) + channel, _, err := CacheGetRandomSatisfiedChannel(newChannelSelectRetryParam(ctx, 2)) + require.NoError(t, err) + require.NotNil(t, channel) + assert.EqualValues(t, 4, channel.GetPriority()) + assert.Contains(t, []int{24, 26, 28}, channel.Id) +} + +func TestCacheGetRandomSatisfiedChannelFallsBackWhenAllChannelsTried(t *testing.T) { + db := setupChannelSelectRetryTest(t) + seedChannelSelectRetryTiers(t, db) + + // Once every eligible channel was attempted, the request still retries + // the existing pool instead of failing (transient failures recover on a + // second attempt, which TestResponsesHTTPHealthCountsFinalResult covers + // end to end for a single channel). + ctx := newChannelSelectRetryContext(t, []string{"24", "26", "28", "25", "27", "29"}) + channel, _, err := CacheGetRandomSatisfiedChannel(newChannelSelectRetryParam(ctx, 0)) + require.NoError(t, err) + require.NotNil(t, channel) + assert.Contains(t, []int{24, 26, 28, 25, 27, 29}, channel.Id) + + // A single-channel group retries that channel. + const singleModel = "retry-single-model" + createChannelSelectRetryChannel(t, db, 30, "default", singleModel, 7, 1) + model.InitChannelCache() + singleCtx := newChannelSelectRetryContext(t, []string{"30"}) + retry := 0 + channel, _, err = CacheGetRandomSatisfiedChannel(&RetryParam{ + Ctx: singleCtx, + TokenGroup: "default", + ModelName: singleModel, + RequestPath: "/v1/chat/completions", + Retry: &retry, + }) + require.NoError(t, err) + require.NotNil(t, channel) + assert.Equal(t, 30, channel.Id) +} + +func TestSelectChannelForRequestMarksAffinityAttempt(t *testing.T) { + db := setupChannelSelectRetryTest(t) + const modelName = "affinity-flag-model" + createChannelSelectRetryChannel(t, db, 27, "default", modelName, 3, 1) + model.InitChannelCache() + + rule := operation_setting.ChannelAffinityRule{ + Name: "retry-flag-affinity", + ModelRegex: []string{"^affinity-flag-.*$"}, + KeySources: []operation_setting.ChannelAffinityKeySource{ + {Type: "request_header", Key: "X-Affinity-Key"}, + }, + } + affinityValue := fmt.Sprintf("retry-flag-%d", time.Now().UnixNano()) + cacheKeySuffix := buildChannelAffinityCacheKeySuffix(rule, modelName, "default", affinityValue) + cache := getChannelAffinityCache() + require.NoError(t, cache.SetWithTTL(cacheKeySuffix, 27, time.Minute)) + t.Cleanup(func() { + _, _ = cache.DeleteMany([]string{cacheKeySuffix}) + }) + + setting := operation_setting.GetChannelAffinitySetting() + originalRules := setting.Rules + setting.Rules = append([]operation_setting.ChannelAffinityRule{rule}, originalRules...) + t.Cleanup(func() { + setting.Rules = originalRules + }) + + ctx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + ctx.Request.Header.Set("X-Affinity-Key", affinityValue) + + retry := 0 + channel, selectGroup, selectErr := SelectChannelForRequest(ctx, modelName, &RetryParam{ + Ctx: ctx, + TokenGroup: "default", + ModelName: modelName, + RequestPath: "/v1/chat/completions", + Retry: &retry, + }) + require.Nil(t, selectErr) + require.NotNil(t, channel) + assert.Equal(t, 27, channel.Id) + assert.Equal(t, "default", selectGroup) + assert.True(t, common.GetContextKeyBool(ctx, constant.ContextKeyChannelAffinityAttempted), + "an affinity-served first attempt must be marked so retries restart from the top priority tier") + + plainCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + plainCtx.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + plainRetry := 0 + plainChannel, _, plainErr := SelectChannelForRequest(plainCtx, modelName, &RetryParam{ + Ctx: plainCtx, + TokenGroup: "default", + ModelName: modelName, + RequestPath: "/v1/chat/completions", + Retry: &plainRetry, + }) + require.Nil(t, plainErr) + require.NotNil(t, plainChannel) + assert.False(t, common.GetContextKeyBool(plainCtx, constant.ContextKeyChannelAffinityAttempted), + "a plain random selection must not consume the affinity tier adjustment") +}