Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
224 changes: 216 additions & 8 deletions controller/channel_pin_retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,28 @@ package controller
import (
"errors"
"fmt"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/i18n"
"github.com/QuantumNous/new-api/middleware"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/setting"
"github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/QuantumNous/new-api/setting/ratio_setting"
"io"
"net/http"
"net/http/httptest"
"os"
"slices"
"strings"
"sync"
"testing"
"time"

"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/i18n"
"github.com/QuantumNous/new-api/middleware"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting"
"github.com/QuantumNous/new-api/setting/config"
"github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/QuantumNous/new-api/setting/ratio_setting"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -217,3 +221,207 @@ func TestRequestPolicyRoutingDatabaseMatrix(t *testing.T) {
})
}
}

func TestRelayRetryPrefersUntriedChannels(t *testing.T) {
require.NoError(t, i18n.Init())
service.InitHttpClient()
previousMetrics := config.GlobalConfig.ExportAllConfigs()["perf_metrics_setting.enabled"]
config.UpdateConfigFromMap(config.GlobalConfig.Get("perf_metrics_setting"), map[string]string{"enabled": "false"})
t.Cleanup(func() {
config.UpdateConfigFromMap(config.GlobalConfig.Get("perf_metrics_setting"), map[string]string{"enabled": previousMetrics})
})
previousRetries, previousDisable := common.RetryTimes, common.AutomaticDisableChannelEnabled
previousCount, previousErrors, previousConsume := constant.CountToken, constant.ErrorLogEnabled, common.LogConsumeEnabled
previousSensitive := setting.CheckSensitiveEnabled
previousFreePreConsume := operation_setting.GetQuotaSetting().EnableFreeModelPreConsume
operation_setting.GetQuotaSetting().EnableFreeModelPreConsume = false
common.RetryTimes, common.AutomaticDisableChannelEnabled = 3, false
constant.CountToken, constant.ErrorLogEnabled, common.LogConsumeEnabled = false, false, false
setting.CheckSensitiveEnabled = false
t.Cleanup(func() {
common.RetryTimes, common.AutomaticDisableChannelEnabled = previousRetries, previousDisable
constant.CountToken, constant.ErrorLogEnabled, common.LogConsumeEnabled = previousCount, previousErrors, previousConsume
setting.CheckSensitiveEnabled = previousSensitive
operation_setting.GetQuotaSetting().EnableFreeModelPreConsume = previousFreePreConsume
})
for _, dialect := range []struct{ kind, env string }{{"sqlite", ""}, {"mysql", "TEST_MYSQL_DSN"}, {"postgres", "TEST_POSTGRES_DSN"}} {
t.Run(dialect.kind, func(t *testing.T) {
if dialect.env != "" && os.Getenv(dialect.env) == "" {
t.Skip("set " + dialect.env + " to run this database")
}
db := modelManagementDB(t, dialect.kind, os.Getenv(dialect.env))
require.NoError(t, db.Create(&model.User{Id: 1, Username: "retry-user", Group: "default"}).Error)
require.NoError(t, ratio_setting.UpdateModelPriceByJSONString(`{"retry-test":0}`))
for _, cached := range []bool{false, true} {
for _, tc := range []struct {
name string
backupPriority int64
strict bool
}{
{"same_priority", 0, false},
{"lower_priority_affinity", 10, false},
{"strict_affinity", 10, true},
} {
t.Run(fmt.Sprintf("cache=%t/%s", cached, tc.name), func(t *testing.T) {
common.MemoryCacheEnabled = cached
require.NoError(t, db.Where("1 = 1").Delete(&model.Ability{}).Error)
require.NoError(t, db.Where("1 = 1").Delete(&model.Channel{}).Error)
var mu sync.Mutex
var calls []int
var upstreams []*httptest.Server
for id := range 2 {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/v1/images/generations", r.URL.Path)
mu.Lock()
calls = append(calls, id+1)
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
if id == 0 {
w.WriteHeader(http.StatusServiceUnavailable)
_, _ = io.WriteString(w, `{"error":{"message":"temporarily unavailable","type":"server_error","code":"unavailable"}}`)
return
}
_, _ = io.WriteString(w, `{"created":1,"data":[{"b64_json":"dGVzdA=="}]}`)
}))
t.Cleanup(upstream.Close)
upstreams = append(upstreams, upstream)
priority := int64(0)
if id == 1 {
priority = tc.backupPriority
}
channel := model.Channel{Id: id + 1, Name: fmt.Sprintf("upstream-%d", id+1), Type: constant.ChannelTypeOpenAI, Status: common.ChannelStatusEnabled, Key: "test-only", BaseURL: &upstream.URL, Models: "retry-test", Group: "default", Priority: &priority, Weight: common.GetPointer(uint(100 * (1 - id)))}
require.NoError(t, db.Create(&channel).Error)
require.NoError(t, channel.AddAbilities(db))
}
model.InitChannelCache()
const body = `{"model":"retry-test","prompt":"a red square","n":1}`
for id, upstream := range upstreams {
response, err := http.Post(upstream.URL+"/v1/images/generations", "application/json", strings.NewReader(body))
require.NoError(t, err)
_, err = io.Copy(io.Discard, response.Body)
require.NoError(t, err)
require.NoError(t, response.Body.Close())
assert.Equal(t, []int{503, 200}[id], response.StatusCode)
}
mu.Lock()
calls = nil
mu.Unlock()
affinity := operation_setting.GetChannelAffinitySetting()
previousAffinity := *affinity
t.Cleanup(func() { *affinity = previousAffinity })
sessionMode := "prefer"
if tc.strict {
sessionMode = "strict"
}
snapshot, err := model.BuildRequestPolicy(map[string]string{
"channel_affinity_setting.enabled": "true",
"channel_affinity_setting.session_mode": sessionMode,
"channel_affinity_setting.rules": `[{"name":"retry-session","model_regex":[".*"],"key_sources":[{"type":"request_header","key":"X-Session"}],"session_mode":"inherit"}]`,
})
require.NoError(t, err)
*affinity = snapshot.Affinity
seed := newPinRetryContext()
seed.Request.Header.Set("X-Session", t.Name())
_, _ = service.GetPreferredChannelByAffinity(seed, "retry-test", "default")
seed.Set("channel_id", 1)
service.RecordChannelAffinity(seed, 1)
t.Cleanup(func() { service.ClearCurrentChannelAffinityCache(seed) })
engine := gin.New()
var trail []string
engine.POST("/v1/images/generations", func(c *gin.Context) {
c.Set("id", 1)
common.SetContextKey(c, constant.ContextKeyUserGroup, "default")
common.SetContextKey(c, constant.ContextKeyTokenGroup, "default")
common.SetContextKey(c, constant.ContextKeyUsingGroup, "default")
common.SetContextKey(c, constant.ContextKeyRequestStartTime, time.Now())
}, middleware.Distribute(), func(c *gin.Context) {
Relay(c, types.RelayFormatOpenAIImage)
trail = c.GetStringSlice("use_channel")
})
request := httptest.NewRequest(http.MethodPost, "/v1/images/generations", strings.NewReader(body))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("X-Session", t.Name())
response := httptest.NewRecorder()
engine.ServeHTTP(response, request)
mu.Lock()
actualCalls := slices.Clone(calls)
mu.Unlock()
t.Logf("direct upstreams: A=503 B=200; gateway=%d calls=%v trail=%v", response.Code, actualCalls, trail)
if tc.strict {
assert.Equal(t, http.StatusServiceUnavailable, response.Code)
assert.Equal(t, []int{1}, actualCalls)
assert.Equal(t, []string{"1"}, trail)
return
}
assert.Equal(t, http.StatusOK, response.Code, response.Body.String())
assert.Contains(t, response.Body.String(), `"b64_json":"dGVzdA=="`)
assert.Equal(t, []int{1, 2}, actualCalls)
assert.Equal(t, []string{"1", "2"}, trail)
})
}
}
})
}
}

func TestRetryChannelSelectionKeepsFallbackAndPins(t *testing.T) {
for _, cached := range []bool{false, true} {
t.Run(fmt.Sprintf("cache=%t", cached), func(t *testing.T) {
db := modelManagementDB(t, "sqlite", "")
common.MemoryCacheEnabled = cached
channels := []model.Channel{
{Id: 1, Name: "single", Type: 1, Key: "test-only", Status: common.ChannelStatusEnabled, Models: "retry-test", Group: "default", Priority: common.GetPointer(int64(10))},
{Id: 2, Name: "multi", Type: 1, Key: "first\nsecond", Status: common.ChannelStatusEnabled, Models: "retry-test", Group: "default", Priority: common.GetPointer(int64(5)), ChannelInfo: model.ChannelInfo{IsMultiKey: true, MultiKeySize: 2, MultiKeyMode: constant.MultiKeyModePolling}},
}
for i := range channels {
require.NoError(t, db.Create(&channels[i]).Error)
require.NoError(t, channels[i].AddAbilities(db))
}
model.InitChannelCache()
for _, tc := range []struct {
name string
used []string
pinned bool
auto bool
want int
}{
{"untried_backup", []string{"1"}, false, false, 2},
{"untried_higher_priority", []string{"2"}, false, false, 1},
{"pool_exhausted_preserves_retry", []string{"1", "2"}, false, false, 2},
{"pin_preserves_existing_selection", []string{"2"}, true, false, 2},
{"auto_untried_backup", []string{"1"}, false, true, 2},
} {
t.Run(tc.name, func(t *testing.T) {
c := newPinRetryContext()
c.Set("use_channel", tc.used)
if tc.pinned {
service.GetChannelConstraints(c).AddPin(dto.ChannelPin{ChannelId: 2, Source: dto.PinSourceOriginTask, RetryMode: dto.PinRetrySameChannel})
}
param := &service.RetryParam{Ctx: c, TokenGroup: "default", ModelName: "retry-test", Retry: common.GetPointer(1)}
if tc.auto {
param.TokenGroup = "auto"
common.SetContextKey(c, constant.ContextKeyUserGroup, "default")
common.SetContextKey(c, constant.ContextKeyTokenAutoGroups, []string{"default"})
}
channel, group, err := service.CacheGetRandomSatisfiedChannel(param)
require.NoError(t, err)
require.NotNil(t, channel)
assert.Equal(t, tc.want, channel.Id)
assert.Equal(t, "default", group)
assert.Equal(t, 1, param.GetRetry(), "preference must not change the retry budget")
})
}
// With only one channel left, a transient failure must retain its
// configured retry opportunity instead of exhausting the pool.
require.NoError(t, db.Model(&model.Ability{}).Where("channel_id = ?", 1).Update("enabled", false).Error)
require.NoError(t, db.Model(&model.Channel{}).Where("id = ?", 1).Update("status", common.ChannelStatusManuallyDisabled).Error)
model.InitChannelCache()
c := newPinRetryContext()
c.Set("use_channel", []string{"2"})
channel, _, err := service.CacheGetRandomSatisfiedChannel(&service.RetryParam{Ctx: c, TokenGroup: "default", ModelName: "retry-test", Retry: common.GetPointer(1)})
require.NoError(t, err)
require.NotNil(t, channel)
assert.Equal(t, 2, channel.Id)
})
}
}
2 changes: 2 additions & 0 deletions dto/channel_constraints.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ type ChannelPin struct {
type ChannelFilterKind string

const (
FilterExcludeChannels ChannelFilterKind = "exclude_channels"
FilterRequestPath ChannelFilterKind = "request_path"
FilterTaskPluginEndpoint ChannelFilterKind = "task_plugin_endpoint"
FilterTaskPluginIdentity ChannelFilterKind = "task_plugin_identity"
Expand All @@ -44,6 +45,7 @@ const (

type ChannelFilter struct {
Kind ChannelFilterKind
ExcludedChannelIDs []int
RequestPath string
TaskPluginKey string
TaskPluginKeys []string
Expand Down
9 changes: 6 additions & 3 deletions model/channel_constraint.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
)

var filterEvalOrder = []dto.ChannelFilterKind{
dto.FilterExcludeChannels,
dto.FilterRequestPath,
dto.FilterTaskPluginEndpoint,
dto.FilterTaskPluginIdentity,
Expand Down Expand Up @@ -36,8 +37,8 @@ func ChannelSatisfiesFilters(ch *Channel, modelName string, filters []dto.Channe

// filterCandidateIDs applies filters to a cached candidate id list.
// Caller must hold channelSyncLock (read lock). The input slice is never mutated.
// A missing id in channelsIDM is kept for request_path (downstream consistency
// error) and dropped for the other filters.
// A missing id in channelsIDM is kept for request_path and exclusions
// (downstream consistency error) and dropped for the other filters.
func filterCandidateIDs(ids []int, modelName string, filters []dto.ChannelFilter) (kept []int, emptiedBy dto.ChannelFilterKind) {
if len(ids) == 0 {
return ids, ""
Expand Down Expand Up @@ -74,7 +75,7 @@ func filtersByKind(filters []dto.ChannelFilter, kind dto.ChannelFilterKind) []dt
}

func candidatePassesKindFilters(ch *Channel, exists bool, modelName string, kind dto.ChannelFilterKind, filters []dto.ChannelFilter) bool {
if kind == dto.FilterRequestPath && !exists {
if !exists && (kind == dto.FilterRequestPath || kind == dto.FilterExcludeChannels) {
return true
}
if !exists || ch == nil {
Expand All @@ -90,6 +91,8 @@ func candidatePassesKindFilters(ch *Channel, exists bool, modelName string, kind

func channelMatchesFilter(ch *Channel, modelName string, filter dto.ChannelFilter) bool {
switch filter.Kind {
case dto.FilterExcludeChannels:
return !slices.Contains(filter.ExcludedChannelIDs, ch.Id)
case dto.FilterRequestPath:
if filter.RequestPath == "" {
return true
Expand Down
41 changes: 29 additions & 12 deletions service/channel_select.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"net/http"
"strconv"

"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
Expand Down Expand Up @@ -147,12 +148,10 @@ func CacheGetRandomSatisfiedChannel(param *RetryParam) (*model.Channel, string,
}
logger.LogDebug(param.Ctx, "Auto selecting group: %s, priorityRetry: %d", autoGroup, priorityRetry)

channel, _ = model.GetRandomSatisfiedChannel(
autoGroup,
param.ModelName,
priorityRetry,
filters,
)
channel, err = getRetryChannel(param, autoGroup, priorityRetry, filters)
if err != nil {
return nil, autoGroup, err
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if channel == nil {
// Current group has no available channel for this model, try next group
// 当前分组没有该模型的可用渠道,尝试下一个分组
Expand Down Expand Up @@ -190,19 +189,37 @@ func CacheGetRandomSatisfiedChannel(param *RetryParam) (*model.Channel, string,
break
}
} else {
channel, err = model.GetRandomSatisfiedChannel(
param.TokenGroup,
param.ModelName,
param.GetRetry(),
filters,
)
channel, err = getRetryChannel(param, param.TokenGroup, param.GetRetry(), filters)
if err != nil {
return nil, param.TokenGroup, err
}
}
return channel, selectGroup, nil
}

// getRetryChannel prefers candidates not yet attempted by this request. Once
// every eligible channel has been tried, retain the existing priority retry
// behavior so single-channel and multi-key requests can still recover.
func getRetryChannel(param *RetryParam, group string, retry int, filters []dto.ChannelFilter) (*model.Channel, error) {
used := param.Ctx.GetStringSlice("use_channel")
_, pinned, _ := GetChannelConstraints(param.Ctx).ResolvedPin()
if len(used) > 0 && !pinned {
excluded := make([]int, 0, len(used))
for _, value := range used {
if id, err := strconv.Atoi(value); err == nil {
excluded = append(excluded, id)
}
}
candidateFilters := append([]dto.ChannelFilter(nil), filters...)
candidateFilters = append(candidateFilters, dto.ChannelFilter{Kind: dto.FilterExcludeChannels, ExcludedChannelIDs: excluded})
channel, err := model.GetRandomSatisfiedChannel(group, param.ModelName, 0, candidateFilters)
if err != nil || channel != nil {
return channel, err
}
}
return model.GetRandomSatisfiedChannel(group, param.ModelName, retry, filters)
}

func pinnedTaskPluginIdentities(c *gin.Context, expected string) ([]int, []string) {
if c == nil || expected == "" {
return nil, nil
Expand Down