fix(relay): return 404 for models missing from all eligible groups (#8480)

This commit is contained in:
Calcium-Ion authored and GitHub committed 2026-11-27 21:37:26 +08:00
1 parent 5456425f98
commit 50a9767024
10 files changed
+211 -80

No files matched your search

+1
View File
@@ -31,6 +31,7 @@ const (
MsgDistributorInvalidPlayground = "distributor.invalid_playground_request"
MsgDistributorGroupAccessDenied = "distributor.group_access_denied"
MsgDistributorGetChannelFailed = "distributor.get_channel_failed"
MsgDistributorModelNotFound = "distributor.model_not_found"
MsgDistributorNoAvailableChannel = "distributor.no_available_channel"
MsgDistributorNoAvailableChannelTaskPlugin = "distributor.no_available_channel_task_plugin"
MsgDistributorInvalidParseModel = "distributor.invalid_request_parse_model"
+1
View File
@@ -23,6 +23,7 @@ distributor.model_name_required: "Model name not specified, model name cannot be
distributor.invalid_playground_request: "Invalid playground request: {{.Error}}"
distributor.group_access_denied: "No permission to access this group"
distributor.get_channel_failed: "Failed to get available channel for model {{.Model}} under group {{.Group}} (distributor): {{.Error}}"
distributor.model_not_found: "Model {{.Model}} is not configured for any group available to this request"
distributor.no_available_channel: "No available channel for model {{.Model}} under group {{.Group}} (distributor)"
distributor.no_available_channel_task_plugin: "No available channel for model {{.Model}} under group {{.Group}}: the model is claimed by a task plugin, which has no enabled channel serving it (distributor)"
distributor.invalid_request_parse_model: "unable to parse model"
+1
View File
@@ -24,6 +24,7 @@ distributor.model_name_required: "未指定模型名称,模型名称不能为
distributor.invalid_playground_request: "无效的playground请求,{{.Error}}"
distributor.group_access_denied: "无权访问该分组"
distributor.get_channel_failed: "获取分组 {{.Group}} 下模型 {{.Model}} 的可用渠道失败(distributor):{{.Error}}"
distributor.model_not_found: "当前请求可用的分组中未配置模型 {{.Model}}"
distributor.no_available_channel: "分组 {{.Group}} 下模型 {{.Model}} 无可用渠道(distributor)"
distributor.no_available_channel_task_plugin: "分组 {{.Group}} 下模型 {{.Model}} 无可用渠道:该模型由任务插件认领,但当前没有启用的渠道可服务此模型(distributor)"
distributor.invalid_request_parse_model: "无法解析模型"
+1
View File
@@ -24,6 +24,7 @@ distributor.model_name_required: "未指定模型名稱,模型名稱不能為
distributor.invalid_playground_request: "無效的playground請求,{{.Error}}"
distributor.group_access_denied: "無權存取該分組"
distributor.get_channel_failed: "獲取分組 {{.Group}} 下模型 {{.Model}} 的可用管道失敗(distributor):{{.Error}}"
distributor.model_not_found: "目前請求可用的分組中未設定模型 {{.Model}}"
distributor.no_available_channel: "分組 {{.Group}} 下模型 {{.Model}} 無可用管道(distributor)"
distributor.no_available_channel_task_plugin: "分組 {{.Group}} 下模型 {{.Model}} 無可用管道:該模型由任務插件認領,但目前沒有啟用的管道可服務此模型(distributor)"
distributor.invalid_request_parse_model: "無法解析模型"
+8 -7
View File
@@ -122,7 +122,7 @@ func Distribute() func(c *gin.Context) {
}
message := selectErr.Message
if selectErr.NoAvailableChannel {
message = noAvailableChannelMessage(c, usingGroup, modelRequest.Model)
message = noAvailableChannelMessage(c, usingGroup, modelRequest.Model, selectErr.MessageID)
} else if selectErr.MessageID != "" {
message = i18n.T(c, selectErr.MessageID, selectErr.Params)
}
@@ -139,10 +139,9 @@ func Distribute() func(c *gin.Context) {
}
}
// noAvailableChannelMessage explains a 503 for a task-plugin-claimed model.
// The response tells the caller the model is plugin-claimed without naming the
// plugin; the candidate plugin keys go to the server log under the request id.
func noAvailableChannelMessage(c *gin.Context, group, modelName string) string {
// noAvailableChannelMessage logs candidate plugin keys under the request ID.
// A 503 also tells the caller when a task plugin claims the model.
func noAvailableChannelMessage(c *gin.Context, group, modelName, messageID string) string {
value, exists := c.Get(jsplugin.ContextKeyPinnedPlugin)
pinned, ok := value.(jsplugin.PinnedPlugin)
if exists && ok && pinned.Plugin != nil {
@@ -156,9 +155,11 @@ func noAvailableChannelMessage(c *gin.Context, group, modelName string) string {
}
}
logger.LogWarn(c, common.LogText("task_plugin subsystem=distribution event=no_available_channel group=%q model=%q plugins=%q reason=no_eligible_channel", group, modelName, strings.Join(keys, ",")))
return i18n.T(c, i18n.MsgDistributorNoAvailableChannelTaskPlugin, map[string]any{"Group": group, "Model": modelName})
if messageID == i18n.MsgDistributorNoAvailableChannel {
messageID = i18n.MsgDistributorNoAvailableChannelTaskPlugin
}
}
return i18n.T(c, i18n.MsgDistributorNoAvailableChannel, map[string]any{"Group": group, "Model": modelName})
return i18n.T(c, messageID, map[string]any{"Group": group, "Model": modelName})
}
func channelMatchesExpectedTaskPlugin(c *gin.Context, channel *model.Channel, expected string) bool {
+100 -5
View File
@@ -16,10 +16,13 @@ import (
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/pkg/jsplugin"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/setting"
"github.com/QuantumNous/new-api/setting/model_setting"
"github.com/QuantumNous/new-api/setting/ratio_setting"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
type streamedBodyStorage struct {
@@ -326,13 +329,105 @@ func TestTokenModelLimitAllowsExemptAtNameByFullName(t *testing.T) {
assert.False(t, TokenModelLimitAllows(baseOnly, "opaque@sha256:deadbeef"))
}
func TestDistributeModelAvailability(t *testing.T) {
require.NoError(t, i18n.Init())
autoGroups := setting.AutoGroups2JsonString()
usableGroups := setting.UserUsableGroups2JSONString()
groupRatios := ratio_setting.GroupRatio2JSONString()
t.Cleanup(func() {
require.NoError(t, setting.UpdateAutoGroupsByJsonString(autoGroups))
require.NoError(t, setting.UpdateUserUsableGroupsByJSONString(usableGroups))
require.NoError(t, ratio_setting.UpdateGroupRatioByJSONString(groupRatios))
})
require.NoError(t, setting.UpdateAutoGroupsByJsonString(`["default","vip"]`))
require.NoError(t, setting.UpdateUserUsableGroupsByJSONString(`{"default":"Default","vip":"VIP"}`))
require.NoError(t, ratio_setting.UpdateGroupRatioByJSONString(`{"default":1,"vip":1}`))
for _, dialect := range []string{"sqlite", "mysql", "postgres"} {
t.Run(dialect, func(t *testing.T) {
db := setupChannelRoutingTestDB(t, dialect)
for _, channel := range []*model.Channel{
{Group: "default", Models: "online", Status: common.ChannelStatusEnabled},
{Group: "default", Models: "auto-paused", Status: common.ChannelStatusAutoDisabled},
{Group: "vip", Models: "deepseek-flash", Status: common.ChannelStatusManuallyDisabled},
{Group: "private", Models: "private-only", Status: common.ChannelStatusEnabled},
} {
channel.Type = constant.ChannelTypeOpenAI
channel.Key = "routing-test"
require.NoError(t, db.Create(channel).Error)
require.NoError(t, channel.AddAbilities(db))
}
for _, cache := range []bool{false, true} {
common.MemoryCacheEnabled = cache
model.InitChannelCache()
for _, tc := range []struct {
name, group, model, path string
tokenGroups []string
status int
lookupFailure bool
}{
{name: "unknown", group: "default", model: "unknown", status: http.StatusNotFound},
{name: "other group only", path: "/v1/messages", group: "default", model: "private-only", status: http.StatusNotFound},
{name: "manually disabled", path: "/v1/messages", group: "vip", model: "deepseek-flash", status: http.StatusServiceUnavailable},
{name: "automatically disabled", group: "default", model: "auto-paused", status: http.StatusServiceUnavailable},
{name: "normalized model in later auto group", group: "auto", model: "deepseek-flash@effort:max", status: http.StatusServiceUnavailable},
{name: "restricted auto groups", group: "auto", tokenGroups: []string{"default"}, model: "deepseek-flash", status: http.StatusNotFound},
{name: "enabled", group: "auto", model: "online", status: http.StatusNoContent},
{name: "lookup error", group: "auto", model: "unknown", status: http.StatusServiceUnavailable, lookupFailure: true},
{name: "healthy group after lookup error", group: "auto", tokenGroups: []string{"vip", "default"}, model: "online", status: http.StatusNoContent, lookupFailure: true},
} {
t.Run(fmt.Sprintf("cache=%t/%s", cache, tc.name), func(t *testing.T) {
if tc.lookupFailure {
failNext := true
queries := db.Callback().Query()
abilityTable := db.NamingStrategy.TableName("Ability")
const callback = "test:fail_first_route_lookup"
require.NoError(t, queries.Before("gorm:query").Register(callback, func(tx *gorm.DB) {
if failNext && tx.Statement.Table == abilityTable {
failNext = false
tx.AddError(errors.New("channel lookup failed"))
}
}))
t.Cleanup(func() {
require.NoError(t, queries.Remove(callback))
assert.Equal(t, cache && tc.status == http.StatusNoContent, failNext)
})
}
path := common.GetStringIfEmpty(tc.path, "/v1/chat/completions")
router := gin.New()
router.POST(path, func(c *gin.Context) {
common.SetContextKey(c, constant.ContextKeyUsingGroup, tc.group)
common.SetContextKey(c, constant.ContextKeyUserGroup, "default")
if tc.tokenGroups != nil {
common.SetContextKey(c, constant.ContextKeyTokenAutoGroups, tc.tokenGroups)
}
}, Distribute(), func(c *gin.Context) { c.Status(http.StatusNoContent) })
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(fmt.Sprintf(`{"model":%q}`, tc.model)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept-Language", "en")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
require.Equal(t, tc.status, w.Code, w.Body.String())
if tc.status == http.StatusNotFound {
assert.Contains(t, w.Body.String(), `"code":"model_not_found"`)
assert.Contains(t, w.Body.String(), "Model "+tc.model+" is not configured for any group available to this request")
}
})
}
}
})
}
}
func TestDistributeHidesTaskPluginDetailsButLogsDiagnostics(t *testing.T) {
require.NoError(t, i18n.Init())
previousCacheEnabled := common.MemoryCacheEnabled
common.MemoryCacheEnabled = true
t.Cleanup(func() { common.MemoryCacheEnabled = previousCacheEnabled })
const group = "private-plugin-error-test-group"
db := setupChannelRoutingTestDB(t, "sqlite")
channel := &model.Channel{Type: constant.ChannelTypeKling, Group: group, Models: "task-model", Status: common.ChannelStatusManuallyDisabled}
require.NoError(t, db.Create(channel).Error)
require.NoError(t, channel.AddAbilities(db))
common.MemoryCacheEnabled = true
model.InitChannelCache()
for _, locale := range []struct{ language, message string }{
{"en", "No available channel for model task-model under group " + group + ": the model is claimed by a task plugin, which has no enabled channel serving it (distributor)"},
{"zh-CN", "分组 " + group + " 下模型 task-model 无可用渠道:该模型由任务插件认领,但当前没有启用的渠道可服务此模型(distributor)"},
@@ -407,7 +502,7 @@ func TestNoAvailableChannelMessageWithoutPlugin(t *testing.T) {
plain, _ := gin.CreateTestContext(nil)
plain.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
plain.Request.Header.Set("Accept-Language", "en")
generic := noAvailableChannelMessage(plain, "default", "gpt-4o")
generic := noAvailableChannelMessage(plain, "default", "gpt-4o", i18n.MsgDistributorNoAvailableChannel)
assert.NotContains(t, generic, "task plugin")
assert.Contains(t, generic, "gpt-4o")
}
+50 -44
View File
@@ -2098,54 +2098,60 @@ func TestPrepareTaskPluginEndpointFiltersEachSharedCandidate(t *testing.T) {
}
}
func setupChannelRoutingTestDB(t *testing.T, dialect string) *gorm.DB {
t.Helper()
dsn := ""
if dialect != "sqlite" {
dsn = os.Getenv("TEST_" + strings.ToUpper(dialect) + "_DSN")
if dsn == "" {
t.Skip("database test DSN not configured")
}
}
previousDB, previousMain, previousLog := model.DB, common.MainDatabaseType(), common.LogDatabaseType()
previousPath, previousMaster := common.SQLitePath, common.IsMasterNode
previousCache, previousRedis := common.MemoryCacheEnabled, common.RedisEnabled
common.SQLitePath, common.IsMasterNode = t.TempDir()+"/routing.db", false
common.RedisEnabled = false
t.Setenv("SQL_DSN", dsn)
require.NoError(t, model.InitDB())
database := model.DB
// Every table belongs to this run, including when a developer points
// a test DSN at a database shared with another test suite.
database.Config.NamingStrategy = schema.NamingStrategy{TablePrefix: "endpoint_route_" + common.GetUUID() + "_"}
require.NoError(t, database.AutoMigrate(&model.Channel{}, &model.Ability{}, &model.Task{}))
t.Cleanup(func() {
for _, table := range []any{&model.Ability{}, &model.Channel{}, &model.Task{}} {
require.NoError(t, database.Session(&gorm.Session{AllowGlobalUpdate: true}).Delete(table).Error)
}
common.MemoryCacheEnabled = true
model.InitChannelCache()
require.NoError(t, database.Migrator().DropTable(&model.Ability{}, &model.Channel{}, &model.Task{}))
model.DB = previousDB
common.SetDatabaseTypes(previousMain, previousLog)
common.SQLitePath, common.IsMasterNode = previousPath, previousMaster
common.MemoryCacheEnabled, common.RedisEnabled = previousCache, previousRedis
if previousDB != nil {
model.InitChannelCache()
}
sqlDB, err := database.DB()
require.NoError(t, err)
require.NoError(t, sqlDB.Close())
})
query := "SELECT version()"
if dialect == "sqlite" {
query = "SELECT sqlite_version()"
}
var version string
require.NoError(t, database.Raw(query).Scan(&version).Error)
t.Logf("database version: %s", version)
return database
}
func TestRouteTaskPluginEndpointUsesSelectedChannel(t *testing.T) {
require.NoError(t, appI18n.Init())
for _, dialect := range []string{"sqlite", "mysql", "postgres"} {
t.Run(dialect, func(t *testing.T) {
dsn := ""
if dialect != "sqlite" {
dsn = os.Getenv("TEST_" + strings.ToUpper(dialect) + "_DSN")
if dsn == "" {
t.Skip("database test DSN not configured")
}
}
previousDB, previousMain, previousLog := model.DB, common.MainDatabaseType(), common.LogDatabaseType()
previousPath, previousMaster := common.SQLitePath, common.IsMasterNode
previousCache, previousRedis := common.MemoryCacheEnabled, common.RedisEnabled
common.SQLitePath, common.IsMasterNode = t.TempDir()+"/routing.db", false
common.RedisEnabled = false
t.Setenv("SQL_DSN", dsn)
require.NoError(t, model.InitDB())
database := model.DB
// Every table belongs to this run, including when a developer points
// a test DSN at a database shared with another test suite.
database.Config.NamingStrategy = schema.NamingStrategy{TablePrefix: "endpoint_route_" + common.GetUUID() + "_"}
require.NoError(t, database.AutoMigrate(&model.Channel{}, &model.Ability{}, &model.Task{}))
t.Cleanup(func() {
for _, table := range []any{&model.Ability{}, &model.Channel{}, &model.Task{}} {
require.NoError(t, database.Session(&gorm.Session{AllowGlobalUpdate: true}).Delete(table).Error)
}
common.MemoryCacheEnabled = true
model.InitChannelCache()
require.NoError(t, database.Migrator().DropTable(&model.Ability{}, &model.Channel{}, &model.Task{}))
model.DB = previousDB
common.SetDatabaseTypes(previousMain, previousLog)
common.SQLitePath, common.IsMasterNode = previousPath, previousMaster
common.MemoryCacheEnabled, common.RedisEnabled = previousCache, previousRedis
if previousDB != nil {
model.InitChannelCache()
}
sqlDB, err := database.DB()
require.NoError(t, err)
require.NoError(t, sqlDB.Close())
})
query := "SELECT version()"
if dialect == "sqlite" {
query = "SELECT sqlite_version()"
}
var version string
require.NoError(t, database.Raw(query).Scan(&version).Error)
t.Logf("database version: %s", version)
database := setupChannelRoutingTestDB(t, dialect)
for _, memoryCache := range []bool{false, true} {
t.Run(fmt.Sprintf("memory_cache=%t", memoryCache), func(t *testing.T) {
+12
View File
@@ -47,6 +47,18 @@ func GetGroupEnabledModels(group string) []string {
return models
}
// IsModelConfiguredForGroups checks enabled and disabled channel abilities for
// the requested model and its routing name.
func IsModelConfiguredForGroups(groups []string, modelName string) (bool, error) {
names := []string{modelName}
if normalized := ratio_setting.RoutingMatchModelName(modelName); normalized != "" && normalized != modelName {
names = append(names, normalized)
}
var ability Ability
result := DB.Select("channel_id").Where(map[string]any{"group": groups, "model": names}).Limit(1).Find(&ability)
return result.RowsAffected > 0, result.Error
}
func GetEnabledModels() []string {
var models []string
// Find distinct models
+1 -1
View File
@@ -140,7 +140,7 @@ func TestGeminiRelayHandsLongRunningPredictionToPluginRoute(t *testing.T) {
return
}
// The relay looks for a Gemini channel serving the model; there is none.
assert.Equal(t, http.StatusServiceUnavailable, recorder.Code)
assert.Equal(t, http.StatusNotFound, recorder.Code)
assert.Contains(t, recorder.Body.String(), `"code":"model_not_found"`)
})
}
+36 -23
View File
@@ -117,17 +117,14 @@ func (p *RetryParam) ResetRetryNextTry() {
// Retry=3: GroupB, priority1 (startRetryIndex=2, priorityRetry=1)
// 分组B, 优先级1
func CacheGetRandomSatisfiedChannel(param *RetryParam) (*model.Channel, string, error) {
var channel *model.Channel
var err error
selectGroup := param.TokenGroup
userGroup := common.GetContextKeyString(param.Ctx, constant.ContextKeyUserGroup)
filters := GetChannelConstraints(param.Ctx).Filters
affinityRetryOffset := param.Ctx.GetInt(ginKeyChannelAffinityRetryOffset)
if param.TokenGroup == "auto" {
userGroup := common.GetContextKeyString(param.Ctx, constant.ContextKeyUserGroup)
autoGroups := GetRequestAutoGroups(param.Ctx, userGroup)
if len(autoGroups) == 0 {
return nil, selectGroup, errors.New("auto groups is not enabled")
return nil, param.TokenGroup, errors.New("auto groups is not enabled")
}
// startGroupIndex: the group index to start searching from
@@ -141,6 +138,8 @@ func CacheGetRandomSatisfiedChannel(param *RetryParam) (*model.Channel, string,
}
}
// A later group can still serve the model after an earlier lookup fails.
var lookupErr error
for i := startGroupIndex; i < len(autoGroups); i++ {
autoGroup := autoGroups[i]
// Calculate priorityRetry for current group
@@ -153,13 +152,16 @@ func CacheGetRandomSatisfiedChannel(param *RetryParam) (*model.Channel, string,
priorityRetry := max(groupRetry-affinityRetryOffset, 0)
logger.LogDebug(param.Ctx, "Auto selecting group: %s, priorityRetry: %d", autoGroup, priorityRetry)
channel, _ = model.GetRandomSatisfiedChannel(
candidate, groupErr := model.GetRandomSatisfiedChannel(
autoGroup,
param.ModelName,
priorityRetry,
filters,
)
if channel == nil {
if groupErr != nil {
lookupErr = groupErr
}
if groupErr != nil || candidate == nil {
// Current group has no available channel for this model, try next group
// 当前分组没有该模型的可用渠道,尝试下一个分组
logger.LogDebug(param.Ctx, "No available channel in group %s for model %s at priorityRetry %d, trying next group", autoGroup, param.ModelName, priorityRetry)
@@ -174,7 +176,6 @@ func CacheGetRandomSatisfiedChannel(param *RetryParam) (*model.Channel, string,
continue
}
common.SetContextKey(param.Ctx, constant.ContextKeyAutoGroup, autoGroup)
selectGroup = autoGroup
logger.LogDebug(param.Ctx, "Auto selected group: %s", autoGroup)
// Prepare state for next retry
@@ -196,20 +197,21 @@ func CacheGetRandomSatisfiedChannel(param *RetryParam) (*model.Channel, string,
// 保持在当前分组,保存当前状态
common.SetContextKey(param.Ctx, constant.ContextKeyAutoGroupIndex, i)
}
break
}
} else {
channel, err = model.GetRandomSatisfiedChannel(
param.TokenGroup,
param.ModelName,
max(param.GetRetry()-affinityRetryOffset, 0),
filters,
)
if err != nil {
return nil, param.TokenGroup, err
return candidate, autoGroup, nil
}
return nil, param.TokenGroup, lookupErr
}
return channel, selectGroup, nil
channel, err := model.GetRandomSatisfiedChannel(
param.TokenGroup,
param.ModelName,
max(param.GetRetry()-affinityRetryOffset, 0),
filters,
)
if err != nil {
return nil, param.TokenGroup, err
}
return channel, param.TokenGroup, nil
}
func pinnedTaskPluginIdentities(c *gin.Context, expected string) ([]int, []string) {
@@ -289,8 +291,7 @@ type ChannelSelectError struct {
// FilterKind and Channel identify a candidate rejected by request filters.
FilterKind dto.ChannelFilterKind
Channel *model.Channel
// NoAvailableChannel marks the "no channel for this group and model"
// outcome so the distributor can name the claiming task plugin.
// NoAvailableChannel lets the distributor log any plugins claiming the model.
NoAvailableChannel bool
}
@@ -368,7 +369,15 @@ func SelectChannelForRequest(c *gin.Context, modelName string, retry *RetryParam
if channel == nil {
var err error
var configured bool
channel, selectGroup, err = CacheGetRandomSatisfiedChannel(retry)
if channel == nil && err == nil {
groups := []string{usingGroup}
if usingGroup == "auto" {
groups = GetRequestAutoGroups(c, common.GetContextKeyString(c, constant.ContextKeyUserGroup))
}
configured, err = model.IsModelConfiguredForGroups(groups, modelName)
}
if err != nil {
showGroup := usingGroup
if usingGroup == "auto" {
@@ -380,8 +389,12 @@ func SelectChannelForRequest(c *gin.Context, modelName string, retry *RetryParam
}
}
if channel == nil {
status, messageID := http.StatusNotFound, i18n.MsgDistributorModelNotFound
if configured {
status, messageID = http.StatusServiceUnavailable, i18n.MsgDistributorNoAvailableChannel
}
return nil, selectGroup, &ChannelSelectError{
StatusCode: http.StatusServiceUnavailable, Code: types.ErrorCodeModelNotFound, MessageID: i18n.MsgDistributorNoAvailableChannel,
StatusCode: status, Code: types.ErrorCodeModelNotFound, MessageID: messageID,
Params: map[string]any{"Group": usingGroup, "Model": modelName}, NoAvailableChannel: true,
}
}