diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 6dad5c9722..6a23382ee0 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -115,9 +115,19 @@ type Config struct { SimpleModeKeyRateLimitEnabled bool `mapstructure:"simple_mode_key_rate_limit_enabled" yaml:"simple_mode_key_rate_limit_enabled"` } -// SimpleModeConfig controls startup behavior in simple mode. +// SimpleModeConfig controls optional behavior in simple mode. type SimpleModeConfig struct { AutoCreateDefaultGroups bool `mapstructure:"auto_create_default_groups" yaml:"auto_create_default_groups"` + GroupIsolation bool `mapstructure:"group_isolation" yaml:"group_isolation"` +} + +// UsesSharedSimpleModePool reports whether scheduling may ignore account group bindings. +func (c *Config) UsesSharedSimpleModePool() bool { + return c != nil && c.RunMode == RunModeSimple && !c.SimpleMode.GroupIsolation +} + +func (c *Config) SimpleModeGroupIsolationEnabled() bool { + return c != nil && c.RunMode == RunModeSimple && c.SimpleMode.GroupIsolation } // MCPConfig fixes the public resource URL used by OAuth discovery and tokens. @@ -2134,6 +2144,7 @@ func setDefaults() { viper.SetDefault("run_mode", RunModeStandard) viper.SetDefault("gateway.min_output_tokens", 128) viper.SetDefault("simple_mode.auto_create_default_groups", true) + viper.SetDefault("simple_mode.group_isolation", false) viper.SetDefault("simple_mode_key_rate_limit_enabled", false) // Server diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go index 0160b4b657..77bc19df0a 100644 --- a/backend/internal/config/config_test.go +++ b/backend/internal/config/config_test.go @@ -219,6 +219,32 @@ func TestLoadSimpleModeKeyRateLimitEnabledFromEnvironment(t *testing.T) { require.True(t, cfg.SimpleModeKeyRateLimitEnabled) } +func TestLoadSimpleModeGroupIsolation(t *testing.T) { + for _, tt := range []struct { + name, mode, yaml, env string + shared, isolated bool + }{ + {"default", RunModeSimple, "", "", true, false}, + {"yaml with empty env", RunModeSimple, "simple_mode:\n group_isolation: true\n", "", false, true}, + {"env opt-in", RunModeSimple, "", "true", false, true}, + {"explicit opt-out", RunModeSimple, "simple_mode:\n group_isolation: true\n", "false", true, false}, + {"standard", RunModeStandard, "", "true", false, false}, + } { + t.Run(tt.name, func(t *testing.T) { + resetViperWithJWTSecret(t) + path := filepath.Join(t.TempDir(), "config.yaml") + require.NoError(t, os.WriteFile(path, []byte(tt.yaml), 0o600)) + t.Setenv("CONFIG_FILE", path) + t.Setenv("RUN_MODE", tt.mode) + t.Setenv("SIMPLE_MODE_GROUP_ISOLATION", tt.env) + cfg, err := Load() + require.NoError(t, err) + require.Equal(t, tt.shared, cfg.UsesSharedSimpleModePool()) + require.Equal(t, tt.isolated, cfg.SimpleModeGroupIsolationEnabled()) + }) + } +} + func TestLoadRedisUsernameFromEnvironment(t *testing.T) { resetViperWithJWTSecret(t) t.Setenv("REDIS_USERNAME", "app-user") diff --git a/backend/internal/repository/scheduler_snapshot_membership_integration_test.go b/backend/internal/repository/scheduler_snapshot_membership_integration_test.go index 457fcce5a7..100945e928 100644 --- a/backend/internal/repository/scheduler_snapshot_membership_integration_test.go +++ b/backend/internal/repository/scheduler_snapshot_membership_integration_test.go @@ -61,23 +61,26 @@ func TestSchedulerSnapshotConfiguredMembership(t *testing.T) { } } - for _, scope := range []string{"simple", "group", "ungrouped"} { + for _, scope := range []struct { + name, mode string + isolate bool + keyGroup *int64 + bucket int64 + members []int64 + }{ + {"simple", config.RunModeSimple, false, &group.ID, 0, []int64{0, group.ID, other.ID}}, + {"group", config.RunModeStandard, false, &group.ID, group.ID, []int64{group.ID}}, + {"ungrouped", config.RunModeStandard, false, nil, 0, []int64{0}}, + {"isolated_group", config.RunModeSimple, true, &group.ID, group.ID, []int64{group.ID}}, + {"isolated_ungrouped", config.RunModeSimple, true, nil, 0, []int64{0}}, + } { for _, forced := range []bool{false, true} { - t.Run(fmt.Sprintf("%s/forced=%t", scope, forced), func(t *testing.T) { - cfg := &config.Config{RunMode: config.RunModeStandard} + t.Run(fmt.Sprintf("%s/forced=%t", scope.name, forced), func(t *testing.T) { + cfg := &config.Config{RunMode: scope.mode, SimpleMode: config.SimpleModeConfig{GroupIsolation: scope.isolate}} cfg.Gateway.Scheduling.DbFallbackEnabled = true - var groupID *int64 - groups := []int64{0} - if scope == "group" { - groupID, groups = &group.ID, []int64{group.ID} - } - if scope == "simple" { - cfg.RunMode = config.RunModeSimple - groupID, groups = &group.ID, []int64{0, group.ID, other.ID} - } mixed := platform != service.PlatformOpenAI && !forced var wantReady, wantMembers []int64 - for _, gid := range groups { + for _, gid := range scope.members { wantReady = append(wantReady, ids[gid]["ready"]) wantMembers = append(wantMembers, ids[gid]["ready"], ids[gid]["cooling"], ids[gid]["expired"]) if mixed { @@ -95,15 +98,12 @@ func TestSchedulerSnapshotConfiguredMembership(t *testing.T) { return out } for range 2 { - accounts, useMixed, err := svc.ListSchedulableAccounts(ctx, groupID, platform, forced) + accounts, useMixed, err := svc.ListSchedulableAccounts(ctx, scope.keyGroup, platform, forced) require.NoError(t, err) require.Equal(t, mixed, useMixed) require.ElementsMatch(t, wantReady, accountIDs(accounts), "both DB fallback and cache hit enforce current eligibility") } - bucket := service.SchedulerBucket{Platform: platform, Mode: service.SchedulerModeSingle} - if scope == "group" { - bucket.GroupID = group.ID - } + bucket := service.SchedulerBucket{GroupID: scope.bucket, Platform: platform, Mode: service.SchedulerModeSingle} if forced { bucket.Mode = service.SchedulerModeForced } else if mixed { diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index a59813ce5c..b53359098c 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -148,6 +148,25 @@ type TempUnschedulableRule struct { Scope string `json:"scope,omitempty"` } +// matchesSchedulingGroup accepts both the full account and the scheduler projection. +func (a *Account) matchesSchedulingGroup(groupID *int64) bool { + if a == nil { + return false + } + if groupID == nil { + return len(a.GroupIDs) == 0 && len(a.AccountGroups) == 0 + } + if slices.Contains(a.GroupIDs, *groupID) { + return true + } + for _, binding := range a.AccountGroups { + if binding.GroupID == *groupID { + return true + } + } + return false +} + func (a *Account) IsActive() bool { return a.Status == StatusActive } diff --git a/backend/internal/service/anthropic_models_list.go b/backend/internal/service/anthropic_models_list.go index e337693594..639d43a981 100644 --- a/backend/internal/service/anthropic_models_list.go +++ b/backend/internal/service/anthropic_models_list.go @@ -7,13 +7,11 @@ import ( ) func (s *GatewayService) ExpandAnthropicLongContextModels(ctx context.Context, group *Group, models []string) []string { - var accounts []Account - var err error + var groupID *int64 if group != nil { - accounts, err = s.accountRepo.ListSchedulableByGroupID(ctx, group.ID) - } else { - accounts, err = s.accountRepo.ListSchedulable(ctx) + groupID = &group.ID } + accounts, err := s.listModelCatalogAccounts(ctx, groupID) if err != nil { return models } diff --git a/backend/internal/service/batch_image_public.go b/backend/internal/service/batch_image_public.go index c417ada1b4..1654af696d 100644 --- a/backend/internal/service/batch_image_public.go +++ b/backend/internal/service/batch_image_public.go @@ -36,6 +36,7 @@ const ( type BatchImageAccountSelectionRepository interface { GetByID(ctx context.Context, id int64) (*Account, error) ListSchedulableByPlatform(ctx context.Context, platform string) ([]Account, error) + ListSchedulableUngroupedByPlatform(ctx context.Context, platform string) ([]Account, error) ListSchedulableByGroupIDAndPlatform(ctx context.Context, groupID int64, platform string) ([]Account, error) } @@ -974,6 +975,9 @@ func (s *BatchImagePublicService) listCandidateAccounts(ctx context.Context, gro if groupID != nil && *groupID > 0 { return s.AccountRepo.ListSchedulableByGroupIDAndPlatform(ctx, *groupID, platform) } + if s.Config.SimpleModeGroupIsolationEnabled() { + return s.AccountRepo.ListSchedulableUngroupedByPlatform(ctx, platform) + } return s.AccountRepo.ListSchedulableByPlatform(ctx, platform) } diff --git a/backend/internal/service/batch_image_public_test.go b/backend/internal/service/batch_image_public_test.go index 67ec00e13a..7ab14bb561 100644 --- a/backend/internal/service/batch_image_public_test.go +++ b/backend/internal/service/batch_image_public_test.go @@ -871,6 +871,16 @@ func (r *publicBatchImageAccountRepo) ListSchedulableByPlatform(_ context.Contex return out, nil } +func (r *publicBatchImageAccountRepo) ListSchedulableUngroupedByPlatform(_ context.Context, platform string) ([]Account, error) { + var accounts []Account + for _, acc := range r.accounts { + if acc.Platform == platform && acc.matchesSchedulingGroup(nil) { + accounts = append(accounts, acc) + } + } + return accounts, nil +} + func (r *publicBatchImageAccountRepo) ListSchedulableByGroupIDAndPlatform(ctx context.Context, _ int64, platform string) ([]Account, error) { return r.ListSchedulableByPlatform(ctx, platform) } diff --git a/backend/internal/service/gateway_model_availability.go b/backend/internal/service/gateway_model_availability.go index 1edc1d809a..7cdd32ff9b 100644 --- a/backend/internal/service/gateway_model_availability.go +++ b/backend/internal/service/gateway_model_availability.go @@ -3,8 +3,6 @@ package service import ( "context" "strings" - - "github.com/Wei-Shaw/sub2api/internal/config" ) // ModelAvailabilityDiagnosis describes whether the requested model can be @@ -83,10 +81,10 @@ func (s *GatewayService) DiagnoseModelAvailabilityForPlatform( if useMixed { // Preserve the generic scheduler's scope rules: an explicit group wins // for mixed scheduling, while group-less simple mode scans all accounts. - if groupID == nil && s.cfg != nil && s.cfg.RunMode == config.RunModeSimple { + if groupID == nil && s.cfg.UsesSharedSimpleModePool() { includeGrouped = true } - } else if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple { + } else if s.cfg.UsesSharedSimpleModePool() { queryGroupID = nil includeGrouped = true } diff --git a/backend/internal/service/gateway_profit_control_v2_test.go b/backend/internal/service/gateway_profit_control_v2_test.go index c05f4501e1..04f2f8bd2e 100644 --- a/backend/internal/service/gateway_profit_control_v2_test.go +++ b/backend/internal/service/gateway_profit_control_v2_test.go @@ -396,7 +396,7 @@ func TestGatewayProfitControlSelectionCarriesGateToHandlerContext(t *testing.T) expensive := gatewayProfitTestAccount(161, PlatformAnthropic, 0.9, group.ID) gateCtx := svc.withGatewayProfitControlGate(gatewayProfitTestContext(group), &group.ID) - selection, err := svc.newSelectionResult(gateCtx, &expensive, true, nil, nil) + selection, err := svc.newSelectionResult(gateCtx, nil, &expensive, true, nil, nil) require.NoError(t, err) require.True(t, selection.ProfitGateActive(), "选号结果必须携带调度栈内生效的门") @@ -411,7 +411,7 @@ func TestGatewayProfitControlSelectionCarriesGateToHandlerContext(t *testing.T) require.NotNil(t, latest) // 无门选号不携带门,重放为无操作。 - plain, err := svc.newSelectionResult(context.Background(), &expensive, true, nil, nil) + plain, err := svc.newSelectionResult(context.Background(), nil, &expensive, true, nil, nil) require.NoError(t, err) require.False(t, plain.ProfitGateActive()) require.Equal(t, context.Background(), ContextWithSelectionProfitGate(context.Background(), plain)) diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go index 146acb33a3..c9624f15f5 100644 --- a/backend/internal/service/gateway_scheduling.go +++ b/backend/internal/service/gateway_scheduling.go @@ -82,7 +82,7 @@ func (s *GatewayService) SelectAccountForModelWithExclusions(ctx context.Context if err != nil { return nil, err } - return s.hydrateSelectedAccount(ctx, account) + return s.schedulerSnapshot.hydrateSelectedAccount(ctx, groupID, account) } // antigravity 分组、强制平台模式或无分组使用单平台选择 @@ -91,7 +91,7 @@ func (s *GatewayService) SelectAccountForModelWithExclusions(ctx context.Context if err != nil { return nil, err } - return s.hydrateSelectedAccount(ctx, account) + return s.schedulerSnapshot.hydrateSelectedAccount(ctx, groupID, account) } // SelectAccountWithLoadAwareness selects account with load-awareness and wait plan. @@ -182,7 +182,7 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro localExcluded[account.ID] = struct{}{} // 排除此账号 continue // 重新选择 } - return s.newSelectionResult(ctx, account, true, result.ReleaseFunc, nil) + return s.newSelectionResult(ctx, groupID, account, true, result.ReleaseFunc, nil) } // 对于等待计划的情况,也需要先检查会话限制 @@ -194,7 +194,7 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro if stickyAccountID > 0 && stickyAccountID == account.ID && s.concurrencyService != nil { waitingCount, _ := s.concurrencyService.GetAccountWaitingCount(ctx, account.ID) if waitingCount < cfg.StickySessionMaxWaiting { - return s.newSelectionResult(ctx, account, false, nil, &AccountWaitPlan{ + return s.newSelectionResult(ctx, groupID, account, false, nil, &AccountWaitPlan{ AccountID: account.ID, MaxConcurrency: account.Concurrency, Timeout: cfg.StickySessionWaitTimeout, @@ -202,7 +202,7 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro }) } } - return s.newSelectionResult(ctx, account, false, nil, &AccountWaitPlan{ + return s.newSelectionResult(ctx, groupID, account, false, nil, &AccountWaitPlan{ AccountID: account.ID, MaxConcurrency: account.Concurrency, Timeout: cfg.FallbackWaitTimeout, @@ -382,7 +382,7 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro if s.debugModelRoutingEnabled() { logger.LegacyPrintf("service.gateway", "[ModelRoutingDebug] routed sticky hit: group_id=%v model=%s session=%s account=%d", derefGroupID(groupID), requestedModel, shortSessionHash(sessionHash), stickyAccountID) } - return s.newSelectionResult(ctx, stickyAccount, true, result.ReleaseFunc, nil) + return s.newSelectionResult(ctx, groupID, stickyAccount, true, result.ReleaseFunc, nil) } } @@ -397,7 +397,7 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro // 必须走 newSelectionResult 以 hydrate 账号凭证: // 调度快照中的账号是精简版(OAuth token 等被剥离), // 直接返回会导致后续转发缺少凭证而鉴权失败。 - return s.newSelectionResult(ctx, stickyAccount, false, nil, &AccountWaitPlan{ + return s.newSelectionResult(ctx, groupID, stickyAccount, false, nil, &AccountWaitPlan{ AccountID: stickyAccountID, MaxConcurrency: stickyAccount.Concurrency, Timeout: cfg.StickySessionWaitTimeout, @@ -493,7 +493,7 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro if s.debugModelRoutingEnabled() { logger.LegacyPrintf("service.gateway", "[ModelRoutingDebug] routed select: group_id=%v model=%s session=%s account=%d", derefGroupID(groupID), requestedModel, shortSessionHash(sessionHash), item.account.ID) } - return s.newSelectionResult(ctx, item.account, true, result.ReleaseFunc, nil) + return s.newSelectionResult(ctx, groupID, item.account, true, result.ReleaseFunc, nil) } } @@ -506,7 +506,7 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro if s.debugModelRoutingEnabled() { logger.LegacyPrintf("service.gateway", "[ModelRoutingDebug] routed wait: group_id=%v model=%s session=%s account=%d", derefGroupID(groupID), requestedModel, shortSessionHash(sessionHash), item.account.ID) } - return s.newSelectionResult(ctx, item.account, false, nil, &AccountWaitPlan{ + return s.newSelectionResult(ctx, groupID, item.account, false, nil, &AccountWaitPlan{ AccountID: item.account.ID, MaxConcurrency: item.account.Concurrency, Timeout: cfg.StickySessionWaitTimeout, @@ -585,7 +585,7 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro if s.cache != nil { _ = s.cache.RefreshSessionTTL(ctx, derefGroupID(groupID), sessionHash, stickySessionTTL) } - return s.newSelectionResult(ctx, account, true, result.ReleaseFunc, nil) + return s.newSelectionResult(ctx, groupID, account, true, result.ReleaseFunc, nil) } } else { slog.Debug("sticky.layer1_5_no_routing_slot_busy", @@ -605,7 +605,7 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro "session", shortSessionHash(sessionHash), "result", "wait_plan", ) - return s.newSelectionResult(ctx, account, false, nil, &AccountWaitPlan{ + return s.newSelectionResult(ctx, groupID, account, false, nil, &AccountWaitPlan{ AccountID: accountID, MaxConcurrency: account.Concurrency, Timeout: cfg.StickySessionWaitTimeout, @@ -760,7 +760,7 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro if sessionHash != "" && s.cache != nil { _ = s.bindGatewayStickySessionDuringSelection(ctx, groupID, sessionHash, selected.account.ID) } - return s.newSelectionResult(ctx, selected.account, true, result.ReleaseFunc, nil) + return s.newSelectionResult(ctx, groupID, selected.account, true, result.ReleaseFunc, nil) } } @@ -783,7 +783,7 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro if !s.checkAndRegisterSession(ctx, acc, sessionHash) { continue // 会话限制已满,尝试下一个账号 } - return s.newSelectionResult(ctx, acc, false, nil, &AccountWaitPlan{ + return s.newSelectionResult(ctx, groupID, acc, false, nil, &AccountWaitPlan{ AccountID: acc.ID, MaxConcurrency: acc.Concurrency, Timeout: cfg.FallbackWaitTimeout, @@ -808,7 +808,7 @@ func (s *GatewayService) tryAcquireByLegacyOrder(ctx context.Context, candidates if sessionHash != "" && s.cache != nil { _ = s.bindGatewayStickySessionDuringSelection(ctx, groupID, sessionHash, acc.ID) } - selection, err := s.newSelectionResult(ctx, acc, true, result.ReleaseFunc, nil) + selection, err := s.newSelectionResult(ctx, groupID, acc, true, result.ReleaseFunc, nil) if err != nil { return nil, false, err } @@ -1045,7 +1045,7 @@ func (s *GatewayService) listSchedulableAccounts(ctx context.Context, groupID *i var err error if groupID != nil { accounts, err = s.accountRepo.ListSchedulableByGroupIDAndPlatforms(ctx, *groupID, platforms) - } else if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple { + } else if s.cfg.UsesSharedSimpleModePool() { accounts, err = s.accountRepo.ListSchedulableByPlatforms(ctx, platforms) } else { accounts, err = s.accountRepo.ListSchedulableUngroupedByPlatforms(ctx, platforms) @@ -1085,7 +1085,7 @@ func (s *GatewayService) listSchedulableAccounts(ctx context.Context, groupID *i var accounts []Account var err error - if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple { + if s.cfg.UsesSharedSimpleModePool() { accounts, err = s.accountRepo.ListSchedulableByPlatform(ctx, platform) } else if groupID != nil { accounts, err = s.accountRepo.ListSchedulableByGroupIDAndPlatform(ctx, *groupID, platform) @@ -1175,19 +1175,7 @@ func (s *GatewayService) isAccountSchedulableForModelSelection(ctx context.Conte // isAccountInGroup checks if the account belongs to the specified group. // When groupID is nil, returns true only for ungrouped accounts (no group assignments). func (s *GatewayService) isAccountInGroup(account *Account, groupID *int64) bool { - if account == nil { - return false - } - if groupID == nil { - // 无分组的 API Key 只能使用未分组的账号 - return len(account.AccountGroups) == 0 - } - for _, ag := range account.AccountGroups { - if ag.GroupID == *groupID { - return true - } - } - return false + return account.matchesSchedulingGroup(groupID) } func (s *GatewayService) tryAcquireAccountSlot(ctx context.Context, accountID int64, maxConcurrency int) (*AcquireResult, error) { @@ -1573,22 +1561,8 @@ func (s *GatewayService) isAccountBlockedBySchedulingThreshold(ctx context.Conte return s.rateLimitService.ApplyAccountSchedulingThreshold(ctx, account) } -func (s *GatewayService) hydrateSelectedAccount(ctx context.Context, account *Account) (*Account, error) { - if account == nil || s.schedulerSnapshot == nil { - return account, nil - } - hydrated, err := s.schedulerSnapshot.GetAccount(ctx, account.ID) - if err != nil { - return nil, err - } - if hydrated == nil { - return nil, fmt.Errorf("selected gateway account %d not found during hydration", account.ID) - } - return hydrated, nil -} - -func (s *GatewayService) newSelectionResult(ctx context.Context, account *Account, acquired bool, release func(), waitPlan *AccountWaitPlan) (*AccountSelectionResult, error) { - hydrated, err := s.hydrateSelectedAccount(ctx, account) +func (s *GatewayService) newSelectionResult(ctx context.Context, groupID *int64, account *Account, acquired bool, release func(), waitPlan *AccountWaitPlan) (*AccountSelectionResult, error) { + hydrated, err := s.schedulerSnapshot.hydrateSelectedAccount(ctx, groupID, account) if err != nil { // release 只在成功结果里返回给调用方;hydrate 失败时这里不释放的话, // 已从 Redis 占用的槽位会一直泄漏到 TTL 到期。 diff --git a/backend/internal/service/gateway_scheduling_slot_release_test.go b/backend/internal/service/gateway_scheduling_slot_release_test.go index 8f1e4cb1c8..a2c889db43 100644 --- a/backend/internal/service/gateway_scheduling_slot_release_test.go +++ b/backend/internal/service/gateway_scheduling_slot_release_test.go @@ -20,7 +20,7 @@ func TestGatewayServiceNewSelectionResultReleasesSlotOnHydrationError(t *testing cancel() released := 0 - selection, err := svc.newSelectionResult(ctx, &Account{ID: 42}, true, func() { released++ }, nil) + selection, err := svc.newSelectionResult(ctx, nil, &Account{ID: 42}, true, func() { released++ }, nil) require.Error(t, err) require.Nil(t, selection) @@ -38,7 +38,7 @@ func TestGatewayServiceNewSelectionResultKeepsReleaseOnSuccess(t *testing.T) { } released := 0 - selection, err := svc.newSelectionResult(context.Background(), account, true, func() { released++ }, nil) + selection, err := svc.newSelectionResult(context.Background(), nil, account, true, func() { released++ }, nil) require.NoError(t, err) require.NotNil(t, selection) diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 425845b606..1d720d982e 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -1514,6 +1514,16 @@ func mixedListingModelAllowed(groupPlatform, model string) bool { return groupPlatform == PlatformGemini && isAntigravityGeminiModel(model) } +func (s *GatewayService) listModelCatalogAccounts(ctx context.Context, groupID *int64) ([]Account, error) { + if groupID != nil { + return s.accountRepo.ListSchedulableByGroupID(ctx, *groupID) + } + if s.cfg.SimpleModeGroupIsolationEnabled() { + return s.accountRepo.ListSchedulableUngroupedByPlatforms(ctx, domain.ConcretePlatformIDs()) + } + return s.accountRepo.ListSchedulable(ctx) +} + func (s *GatewayService) GetAvailableModels(ctx context.Context, groupID *int64, platform string) []string { cacheKey := modelsListCacheKey(groupID, platform) if s.modelsListCache != nil { @@ -1526,14 +1536,7 @@ func (s *GatewayService) GetAvailableModels(ctx context.Context, groupID *int64, } modelsListCacheMissTotal.Add(1) - var accounts []Account - var err error - - if groupID != nil { - accounts, err = s.accountRepo.ListSchedulableByGroupID(ctx, *groupID) - } else { - accounts, err = s.accountRepo.ListSchedulable(ctx) - } + accounts, err := s.listModelCatalogAccounts(ctx, groupID) if err != nil || len(accounts) == 0 { return nil @@ -1696,13 +1699,7 @@ func (s *GatewayService) GetSchedulablePlatforms(ctx context.Context, groupID *i return platforms } - var accounts []Account - var err error - if groupID != nil { - accounts, err = s.accountRepo.ListSchedulableByGroupID(ctx, *groupID) - } else { - accounts, err = s.accountRepo.ListSchedulable(ctx) - } + accounts, err := s.listModelCatalogAccounts(ctx, groupID) if err != nil { return platforms } diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index f5754e41f0..b5ce4af8d7 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -138,7 +138,7 @@ func (s *GeminiMessagesCompatService) SelectAccountForModelWithExclusions(ctx co return nil, fmt.Errorf("query accounts failed: %w", err) } // 强制平台模式下,分组中找不到账户时回退查询全部 - if len(accounts) == 0 && groupID != nil && hasForcePlatform { + if len(accounts) == 0 && groupID != nil && hasForcePlatform && !s.cfg.SimpleModeGroupIsolationEnabled() { accounts, err = s.listSchedulableAccountsOnce(ctx, nil, platform, hasForcePlatform) if err != nil { return nil, fmt.Errorf("query accounts failed: %w", err) @@ -162,7 +162,7 @@ func (s *GeminiMessagesCompatService) SelectAccountForModelWithExclusions(ctx co _ = s.cache.SetSessionAccountID(ctx, derefGroupID(groupID), cacheKey, selected.ID, geminiStickySessionTTL) } - return s.hydrateSelectedAccount(ctx, selected) + return s.schedulerSnapshot.hydrateSelectedAccount(ctx, groupID, selected) } // resolvePlatformAndSchedulingMode 解析目标平台和调度模式。 @@ -229,7 +229,7 @@ func (s *GeminiMessagesCompatService) tryStickySessionHit( // 检查账号是否需要清理粘性会话 // Check if sticky session should be cleared - if shouldClearStickySession(account, requestedModel) { + if shouldClearStickySession(account, requestedModel) || (s.cfg.SimpleModeGroupIsolationEnabled() && !account.matchesSchedulingGroup(groupID)) { _ = s.cache.DeleteSessionAccountID(ctx, derefGroupID(groupID), cacheKey) return nil } @@ -441,20 +441,6 @@ func (s *GeminiMessagesCompatService) getSchedulableAccount(ctx context.Context, return s.accountRepo.GetByID(ctx, accountID) } -func (s *GeminiMessagesCompatService) hydrateSelectedAccount(ctx context.Context, account *Account) (*Account, error) { - if account == nil || s.schedulerSnapshot == nil { - return account, nil - } - hydrated, err := s.schedulerSnapshot.GetAccount(ctx, account.ID) - if err != nil { - return nil, err - } - if hydrated == nil { - return nil, fmt.Errorf("selected gemini account %d not found during hydration", account.ID) - } - return hydrated, nil -} - func (s *GeminiMessagesCompatService) listSchedulableAccountsOnce(ctx context.Context, groupID *int64, platform string, hasForcePlatform bool) ([]Account, error) { if s.schedulerSnapshot != nil { accounts, _, err := s.schedulerSnapshot.ListSchedulableAccounts(ctx, groupID, platform, hasForcePlatform) @@ -470,7 +456,7 @@ func (s *GeminiMessagesCompatService) listSchedulableAccountsOnce(ctx context.Co if groupID != nil { return s.accountRepo.ListSchedulableByGroupIDAndPlatforms(ctx, *groupID, queryPlatforms) } - if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple { + if s.cfg.UsesSharedSimpleModePool() { return s.accountRepo.ListSchedulableByPlatforms(ctx, queryPlatforms) } return s.accountRepo.ListSchedulableUngroupedByPlatforms(ctx, queryPlatforms) diff --git a/backend/internal/service/gemini_models_endpoints.go b/backend/internal/service/gemini_models_endpoints.go index f7a311d6a0..0364cd1f5a 100644 --- a/backend/internal/service/gemini_models_endpoints.go +++ b/backend/internal/service/gemini_models_endpoints.go @@ -127,7 +127,7 @@ func (s *GeminiMessagesCompatService) SelectAccountForModelsEndpoints(ctx contex if selected == nil { return nil, errors.New("no available Gemini accounts") } - return s.hydrateSelectedAccount(ctx, selected) + return s.schedulerSnapshot.hydrateSelectedAccount(ctx, groupID, selected) } // modelsEndpointAccountRank 返回账号在模型接口选号中的优先级,数值越小越优先,顺序见 SelectAccountForModelsEndpoints。 diff --git a/backend/internal/service/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go index c5912f892d..8e1a9dbd2b 100644 --- a/backend/internal/service/openai_account_scheduler.go +++ b/backend/internal/service/openai_account_scheduler.go @@ -413,7 +413,7 @@ func (s *defaultOpenAIAccountScheduler) Select( if selection != nil && selection.Account != nil { compatible, _ := s.isAccountRequestCompatibleReason(withOpenAIImageSizeStickyAccount(ctx, selection.Account.ID), selection.Account, req) hasGroupMetadata := len(selection.Account.GroupIDs) > 0 || len(selection.Account.AccountGroups) > 0 - groupCompatible := !hasGroupMetadata || openAIStickyAccountMatchesGroup(selection.Account, req.GroupID) + groupCompatible := !hasGroupMetadata || selection.Account.matchesSchedulingGroup(req.GroupID) if hasGroupMetadata && s.service != nil { groupCompatible = s.service.openAIAccountMatchesSchedulingGroup(selection.Account, req.GroupID) } @@ -615,26 +615,6 @@ func (s *defaultOpenAIAccountScheduler) selectBySessionHash( return nil, false, nil } -func openAIStickyAccountMatchesGroup(account *Account, groupID *int64) bool { - if account == nil { - return false - } - if groupID == nil { - return len(account.AccountGroups) == 0 && len(account.GroupIDs) == 0 - } - for _, accountGroupID := range account.GroupIDs { - if accountGroupID == *groupID { - return true - } - } - for _, accountGroup := range account.AccountGroups { - if accountGroup.GroupID == *groupID { - return true - } - } - return false -} - func openAIAccountSchedulingPriority(account *Account) int { if account == nil { return 0 diff --git a/backend/internal/service/openai_account_scheduler_test.go b/backend/internal/service/openai_account_scheduler_test.go index 6a31e46cc5..5da24c3e03 100644 --- a/backend/internal/service/openai_account_scheduler_test.go +++ b/backend/internal/service/openai_account_scheduler_test.go @@ -73,7 +73,7 @@ type schedulerGroupAwareOpenAIAccountRepo struct { func (r schedulerGroupAwareOpenAIAccountRepo) ListSchedulableByGroupIDAndPlatform(ctx context.Context, groupID int64, platform string) ([]Account, error) { var result []Account for _, acc := range r.accounts { - if acc.Platform == platform && openAIStickyAccountMatchesGroup(&acc, &groupID) { + if acc.Platform == platform && acc.matchesSchedulingGroup(&groupID) { result = append(result, acc) } } @@ -83,7 +83,7 @@ func (r schedulerGroupAwareOpenAIAccountRepo) ListSchedulableByGroupIDAndPlatfor func (r schedulerGroupAwareOpenAIAccountRepo) ListSchedulableUngroupedByPlatform(ctx context.Context, platform string) ([]Account, error) { var result []Account for _, acc := range r.accounts { - if acc.Platform == platform && openAIStickyAccountMatchesGroup(&acc, nil) { + if acc.Platform == platform && acc.matchesSchedulingGroup(nil) { result = append(result, acc) } } diff --git a/backend/internal/service/openai_gateway_model_availability.go b/backend/internal/service/openai_gateway_model_availability.go index 21693a4d23..a5bec21d86 100644 --- a/backend/internal/service/openai_gateway_model_availability.go +++ b/backend/internal/service/openai_gateway_model_availability.go @@ -3,8 +3,6 @@ package service import ( "context" "strings" - - "github.com/Wei-Shaw/sub2api/internal/config" ) // DiagnoseModelAvailabilityForPlatform reports whether the requested model @@ -37,7 +35,7 @@ func (s *OpenAIGatewayService) DiagnoseModelAvailabilityForPlatform( platform = NormalizeOpenAICompatiblePlatform(platform) queryGroupID := groupID includeGrouped := false - if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple { + if s.cfg.UsesSharedSimpleModePool() { queryGroupID = nil includeGrouped = true } diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index 90728a3f96..b950659d2f 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -935,7 +935,7 @@ func (s *OpenAIGatewayService) selectAccountForModelWithExclusionsStickyHit(ctx return nil, false, noAvailableOpenAISelectionError(requestedModel, compactBlocked, filterStats.summary("")) } - hydrated, err := s.hydrateSelectedAccount(ctx, selected) + hydrated, err := s.schedulerSnapshot.hydrateSelectedAccount(ctx, groupID, selected) if err != nil { return nil, false, err } @@ -1165,13 +1165,13 @@ func (s *OpenAIGatewayService) selectAccountWithLoadAwareness(ctx context.Contex } result, err := s.tryAcquireAccountSlot(ctx, account.ID, account.Concurrency) if err == nil && result != nil && result.Acquired { - selection, selectErr := s.newAcquiredSelectionResult(ctx, account, result.ReleaseFunc) + selection, selectErr := s.newAcquiredSelectionResult(ctx, groupID, account, result.ReleaseFunc) return markStickySessionHit(selection, stickyHit), selectErr } if stickyAccountID > 0 && stickyAccountID == account.ID && s.concurrencyService != nil { waitingCount, _ := s.concurrencyService.GetAccountWaitingCount(ctx, account.ID) if waitingCount < cfg.StickySessionMaxWaiting { - selection, selectErr := s.newSelectionResult(ctx, account, false, nil, &AccountWaitPlan{ + selection, selectErr := s.newSelectionResult(ctx, groupID, account, false, nil, &AccountWaitPlan{ AccountID: account.ID, MaxConcurrency: account.Concurrency, Timeout: cfg.StickySessionWaitTimeout, @@ -1180,7 +1180,7 @@ func (s *OpenAIGatewayService) selectAccountWithLoadAwareness(ctx context.Contex return markStickySessionHit(selection, stickyHit), selectErr } } - selection, selectErr := s.newSelectionResult(ctx, account, false, nil, &AccountWaitPlan{ + selection, selectErr := s.newSelectionResult(ctx, groupID, account, false, nil, &AccountWaitPlan{ AccountID: account.ID, MaxConcurrency: account.Concurrency, Timeout: cfg.FallbackWaitTimeout, @@ -1235,7 +1235,7 @@ func (s *OpenAIGatewayService) selectAccountWithLoadAwareness(ctx context.Contex } else { result, err := s.tryAcquireAccountSlot(ctx, accountID, account.Concurrency) if err == nil && result != nil && result.Acquired { - selection, selectErr := s.newAcquiredSelectionResult(ctx, account, result.ReleaseFunc) + selection, selectErr := s.newAcquiredSelectionResult(ctx, groupID, account, result.ReleaseFunc) if selectErr != nil { return nil, selectErr } @@ -1245,7 +1245,7 @@ func (s *OpenAIGatewayService) selectAccountWithLoadAwareness(ctx context.Contex waitingCount, _ := s.concurrencyService.GetAccountWaitingCount(ctx, accountID) if waitingCount < cfg.StickySessionMaxWaiting { - selection, selectErr := s.newSelectionResult(ctx, account, false, nil, &AccountWaitPlan{ + selection, selectErr := s.newSelectionResult(ctx, groupID, account, false, nil, &AccountWaitPlan{ AccountID: accountID, MaxConcurrency: account.Concurrency, Timeout: cfg.StickySessionWaitTimeout, @@ -1401,7 +1401,7 @@ func (s *OpenAIGatewayService) selectAccountWithLoadAwareness(ctx context.Contex } result, err := s.tryAcquireAccountSlot(ctx, fresh.ID, fresh.Concurrency) if err == nil && result != nil && result.Acquired { - selection, selectErr := s.newAcquiredSelectionResult(ctx, fresh, result.ReleaseFunc) + selection, selectErr := s.newAcquiredSelectionResult(ctx, groupID, fresh, result.ReleaseFunc) if selectErr != nil { return nil, true, selectErr } @@ -1440,7 +1440,7 @@ func (s *OpenAIGatewayService) selectAccountWithLoadAwareness(ctx context.Contex } result, err := s.tryAcquireAccountSlot(ctx, fresh.ID, fresh.Concurrency) if err == nil && result != nil && result.Acquired { - selection, selectErr := s.newAcquiredSelectionResult(ctx, fresh, result.ReleaseFunc) + selection, selectErr := s.newAcquiredSelectionResult(ctx, groupID, fresh, result.ReleaseFunc) if selectErr != nil { return nil, selectErr } @@ -1488,7 +1488,7 @@ func (s *OpenAIGatewayService) selectAccountWithLoadAwareness(ctx context.Contex if needsUpstreamCheck && s.isUpstreamModelRestrictedByChannel(ctx, *groupID, fresh, requestedModel, requireCompact) { continue } - return s.newSelectionResult(ctx, fresh, false, nil, &AccountWaitPlan{ + return s.newSelectionResult(ctx, groupID, fresh, false, nil, &AccountWaitPlan{ AccountID: fresh.ID, MaxConcurrency: fresh.Concurrency, Timeout: cfg.FallbackWaitTimeout, @@ -1517,7 +1517,7 @@ func (s *OpenAIGatewayService) listSchedulableAccounts(ctx context.Context, grou } var accounts []Account var err error - if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple { + if s.cfg.UsesSharedSimpleModePool() { accounts, err = s.accountRepo.ListSchedulableByPlatform(ctx, platform) } else if groupID != nil { accounts, err = s.accountRepo.ListSchedulableByGroupIDAndPlatform(ctx, *groupID, platform) @@ -1663,10 +1663,10 @@ func (s *OpenAIGatewayService) recheckSelectedOpenAIAccountFromDBBeforeProfit(ct } func (s *OpenAIGatewayService) openAIAccountMatchesSchedulingGroup(account *Account, groupID *int64) bool { - if s != nil && s.cfg != nil && s.cfg.RunMode == config.RunModeSimple { + if s != nil && s.cfg.UsesSharedSimpleModePool() { return account != nil } - return openAIStickyAccountMatchesGroup(account, groupID) + return account.matchesSchedulingGroup(groupID) } func (s *OpenAIGatewayService) getSchedulableAccount(ctx context.Context, accountID int64) (*Account, error) { @@ -1725,22 +1725,8 @@ func (s *OpenAIGatewayService) isOpenAIAccountBlockedBySchedulingThreshold(ctx c return s.rateLimitService.ApplyAccountSchedulingThreshold(ctx, account) } -func (s *OpenAIGatewayService) hydrateSelectedAccount(ctx context.Context, account *Account) (*Account, error) { - if account == nil || s.schedulerSnapshot == nil { - return account, nil - } - hydrated, err := s.schedulerSnapshot.GetAccount(ctx, account.ID) - if err != nil { - return nil, err - } - if hydrated == nil { - return nil, fmt.Errorf("selected openai account %d not found during hydration", account.ID) - } - return hydrated, nil -} - -func (s *OpenAIGatewayService) newSelectionResult(ctx context.Context, account *Account, acquired bool, release func(), waitPlan *AccountWaitPlan) (*AccountSelectionResult, error) { - hydrated, err := s.hydrateSelectedAccount(ctx, account) +func (s *OpenAIGatewayService) newSelectionResult(ctx context.Context, groupID *int64, account *Account, acquired bool, release func(), waitPlan *AccountWaitPlan) (*AccountSelectionResult, error) { + hydrated, err := s.schedulerSnapshot.hydrateSelectedAccount(ctx, groupID, account) if err != nil { return nil, err } @@ -1752,8 +1738,8 @@ func (s *OpenAIGatewayService) newSelectionResult(ctx context.Context, account * }), nil } -func (s *OpenAIGatewayService) newAcquiredSelectionResult(ctx context.Context, account *Account, release func()) (*AccountSelectionResult, error) { - selection, err := s.newSelectionResult(ctx, account, true, release, nil) +func (s *OpenAIGatewayService) newAcquiredSelectionResult(ctx context.Context, groupID *int64, account *Account, release func()) (*AccountSelectionResult, error) { + selection, err := s.newSelectionResult(ctx, groupID, account, true, release, nil) if err != nil && release != nil { release() } diff --git a/backend/internal/service/openai_gateway_service_test.go b/backend/internal/service/openai_gateway_service_test.go index 39b2854157..12f4e06f8b 100644 --- a/backend/internal/service/openai_gateway_service_test.go +++ b/backend/internal/service/openai_gateway_service_test.go @@ -231,7 +231,7 @@ type groupAwareStubOpenAIAccountRepo struct { func (r groupAwareStubOpenAIAccountRepo) ListSchedulableByGroupIDAndPlatform(ctx context.Context, groupID int64, platform string) ([]Account, error) { var result []Account for _, acc := range r.accounts { - if acc.Platform == platform && openAIStickyAccountMatchesGroup(&acc, &groupID) { + if acc.Platform == platform && acc.matchesSchedulingGroup(&groupID) { result = append(result, acc) } } @@ -241,7 +241,7 @@ func (r groupAwareStubOpenAIAccountRepo) ListSchedulableByGroupIDAndPlatform(ctx func (r groupAwareStubOpenAIAccountRepo) ListSchedulableUngroupedByPlatform(ctx context.Context, platform string) ([]Account, error) { var result []Account for _, acc := range r.accounts { - if acc.Platform == platform && openAIStickyAccountMatchesGroup(&acc, nil) { + if acc.Platform == platform && acc.matchesSchedulingGroup(nil) { result = append(result, acc) } } diff --git a/backend/internal/service/openai_image_size_routing.go b/backend/internal/service/openai_image_size_routing.go index 7b73a8c6ce..57181a5151 100644 --- a/backend/internal/service/openai_image_size_routing.go +++ b/backend/internal/service/openai_image_size_routing.go @@ -8,8 +8,6 @@ import ( "strings" "sync/atomic" "time" - - "github.com/Wei-Shaw/sub2api/internal/config" ) // AccountExtraOpenAIImageSizeTiers 是账号允许承接的生图尺寸档位列表,档位口径与 @@ -307,7 +305,7 @@ func (s *OpenAIGatewayService) OpenAIImageSizeTierUnsupported( requestedModel = strings.TrimSpace(requestedModel) queryGroupID := groupID includeGrouped := false - if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple { + if s.cfg.UsesSharedSimpleModePool() { queryGroupID = nil includeGrouped = true } diff --git a/backend/internal/service/openai_ws_forwarder_support.go b/backend/internal/service/openai_ws_forwarder_support.go index 704156f133..d8fff37a2d 100644 --- a/backend/internal/service/openai_ws_forwarder_support.go +++ b/backend/internal/service/openai_ws_forwarder_support.go @@ -552,7 +552,7 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability( } account, err := s.getSchedulableAccount(ctx, accountID) - if err != nil || account == nil { + if err != nil || account == nil || (s.cfg.SimpleModeGroupIsolationEnabled() && !account.matchesSchedulingGroup(groupID)) { _ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID) return 0, nil, "", nil } diff --git a/backend/internal/service/scheduler_snapshot_hydration_test.go b/backend/internal/service/scheduler_snapshot_hydration_test.go index e87aac180d..effe89b31b 100644 --- a/backend/internal/service/scheduler_snapshot_hydration_test.go +++ b/backend/internal/service/scheduler_snapshot_hydration_test.go @@ -146,7 +146,7 @@ func TestOpenAINewAcquiredSelectionResult_ReleasesSlotWhenHydrationFails(t *test } releaseCalls := 0 - selection, err := svc.newAcquiredSelectionResult(context.Background(), &Account{ID: 1001}, func() { + selection, err := svc.newAcquiredSelectionResult(context.Background(), nil, &Account{ID: 1001}, func() { releaseCalls++ }) diff --git a/backend/internal/service/scheduler_snapshot_service.go b/backend/internal/service/scheduler_snapshot_service.go index 9c9538eaae..62d4cc8f35 100644 --- a/backend/internal/service/scheduler_snapshot_service.go +++ b/backend/internal/service/scheduler_snapshot_service.go @@ -7,6 +7,7 @@ import ( "fmt" "log/slog" "runtime/debug" + "slices" "sort" "strconv" "sync" @@ -234,6 +235,11 @@ func (s *SchedulerSnapshotService) ListSchedulableAccounts(ctx context.Context, if err != nil { logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] cache read failed: bucket=%s err=%v", bucket.String(), err) } else if hit { + // A shared-mode instance may have populated this bucket before the + // operator enabled isolation. Snapshot rows retain group membership. + if s.cfg.SimpleModeGroupIsolationEnabled() { + cached = slices.DeleteFunc(cached, func(a Account) bool { return !a.matchesSchedulingGroup(groupID) }) + } return cached, useMixed, nil } } @@ -343,6 +349,24 @@ func (s *SchedulerSnapshotService) loadAndPublishFallback(ctx context.Context, b return accounts, nil } +// hydrateSelectedAccount checks the full account before handing it to the forwarder. +func (s *SchedulerSnapshotService) hydrateSelectedAccount(ctx context.Context, groupID *int64, account *Account) (*Account, error) { + if s == nil || account == nil { + return account, nil + } + hydrated, err := s.GetAccount(ctx, account.ID) + if err != nil { + return nil, err + } + if hydrated == nil { + return nil, fmt.Errorf("selected account %d not found during hydration", account.ID) + } + if s.cfg.SimpleModeGroupIsolationEnabled() && !hydrated.matchesSchedulingGroup(groupID) { + return nil, ErrNoAvailableAccounts + } + return hydrated, nil +} + func (s *SchedulerSnapshotService) GetAccount(ctx context.Context, accountID int64) (*Account, error) { if accountID <= 0 { return nil, nil @@ -758,7 +782,7 @@ func (s *SchedulerSnapshotService) handleAccountEvent(ctx context.Context, accou } func (s *SchedulerSnapshotService) handleGroupEvent(ctx context.Context, groupID *int64, seen map[batchSeenKey]struct{}) error { - if groupID == nil || *groupID <= 0 || s.isRunModeSimple() { + if groupID == nil || *groupID <= 0 || s.cfg.UsesSharedSimpleModePool() { return nil } if seen != nil { @@ -790,7 +814,7 @@ func (s *SchedulerSnapshotService) reconcileGroupLifecycle(ctx context.Context, // active 仅 Reopen canonical bucket;missing/inactive 同时 Retire canonical 与已登记历史 bucket; // group event 路径只有在权威决策和后续重建全部成功后才会标记 seen。 func (s *SchedulerSnapshotService) prepareGroupLifecycle(ctx context.Context, groupID int64, knownHistorical []SchedulerBucket) (plan schedulerGroupLifecyclePlan, retErr error) { - if groupID <= 0 || s.isRunModeSimple() { + if groupID <= 0 || s.cfg.UsesSharedSimpleModePool() { return schedulerGroupLifecyclePlan{}, nil } if s.cache == nil || s.groupRepo == nil { @@ -1119,16 +1143,15 @@ func (s *SchedulerSnapshotService) rebuildFullSnapshot(ctx context.Context, reas return ErrSchedulerCacheNotReady } - // 当前模式所需的全局读取必须先成功:桶注册表始终必需,standard 还需活跃分组 ID; - // 失败时不执行 Capture/Retire/Reopen 或 DB 查询。 - // simple 模式不获取分组生命周期权威;standard 的 stale candidate 仍须在租约内 fresh 确认后才能退休。 + // 所有模式均依赖桶注册表。按分组调度时还要读取活跃分组 ID, + // 并在租约内确认分组状态后才可退休历史桶。 registered, err := s.cache.ListBuckets(ctx) if err != nil { return err } registered = dedupeBuckets(registered) - if s.isRunModeSimple() { + if s.cfg.UsesSharedSimpleModePool() { canonical := schedulerCanonicalBuckets(0) captured, err := s.captureFullRebuildCanonicalTasks(ctx, canonical) if err != nil { @@ -1544,7 +1567,7 @@ func (s *SchedulerSnapshotService) loadAccountsFromDB(ctx context.Context, bucke return nil, ErrSchedulerCacheNotReady } var groupID *int64 - if !s.isRunModeSimple() && bucket.GroupID > 0 { + if !s.cfg.UsesSharedSimpleModePool() && bucket.GroupID > 0 { groupID = &bucket.GroupID } platforms := []string{bucket.Platform} @@ -1553,7 +1576,7 @@ func (s *SchedulerSnapshotService) loadAccountsFromDB(ctx context.Context, bucke } // Cache the configured pool, as model availability does. Time-based blocks // must be checked on each read so expiry needs no write or outbox event. - accounts, err := s.accountRepo.ListModelAvailabilityCandidates(ctx, groupID, platforms, s.isRunModeSimple()) + accounts, err := s.accountRepo.ListModelAvailabilityCandidates(ctx, groupID, platforms, s.cfg.UsesSharedSimpleModePool()) if err != nil || !useMixed { return accounts, err } @@ -1600,7 +1623,7 @@ func (s *SchedulerSnapshotService) bucketFor(groupID *int64, platform string, mo } func (s *SchedulerSnapshotService) normalizeGroupID(groupID *int64) int64 { - if s.isRunModeSimple() { + if s.cfg.UsesSharedSimpleModePool() { return 0 } if groupID == nil || *groupID <= 0 { @@ -1610,7 +1633,7 @@ func (s *SchedulerSnapshotService) normalizeGroupID(groupID *int64) int64 { } func (s *SchedulerSnapshotService) normalizeGroupIDs(groupIDs []int64) []int64 { - if s.isRunModeSimple() { + if s.cfg.UsesSharedSimpleModePool() { return []int64{0} } if len(groupIDs) == 0 { @@ -1680,10 +1703,6 @@ func (s *SchedulerSnapshotService) withSharedFallbackTimeout(ctx context.Context return context.WithTimeout(ctx, timeout) } -func (s *SchedulerSnapshotService) isRunModeSimple() bool { - return s.cfg != nil && s.cfg.RunMode == config.RunModeSimple -} - func (s *SchedulerSnapshotService) outboxPollInterval() time.Duration { if s.cfg == nil { return time.Second diff --git a/backend/internal/service/simple_mode_group_isolation_test.go b/backend/internal/service/simple_mode_group_isolation_test.go new file mode 100644 index 0000000000..6549cc9a3e --- /dev/null +++ b/backend/internal/service/simple_mode_group_isolation_test.go @@ -0,0 +1,134 @@ +//go:build unit + +package service + +import ( + "context" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/stretchr/testify/require" +) + +func TestSimpleModeGroupIsolationOpenAISelection(t *testing.T) { + groupA, groupB, emptyGroup := int64(10), int64(20), int64(30) + accounts := []Account{ + {ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true, Priority: 1, GroupIDs: []int64{groupA}}, + {ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true, Priority: 2, GroupIDs: []int64{groupB}}, + {ID: 3, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true, Priority: 3}, + } + repo := schedulerGroupAwareOpenAIAccountRepo{schedulerTestOpenAIAccountRepo{accounts: accounts}} + for _, tt := range []struct { + name string + isolate bool + group *int64 + wantID int64 + }{ + {"default shared pool", false, &groupB, 1}, + {"bound key", true, &groupB, 2}, + {"unbound key", true, nil, 3}, + {"empty group", true, &emptyGroup, 0}, + } { + t.Run(tt.name, func(t *testing.T) { + svc := &OpenAIGatewayService{accountRepo: repo, cfg: &config.Config{ + RunMode: config.RunModeSimple, SimpleMode: config.SimpleModeConfig{GroupIsolation: tt.isolate}, + }} + account, err := svc.SelectAccountForModel(context.Background(), tt.group, "", "gpt-5.1") + if tt.wantID == 0 { + require.Error(t, err) + require.Nil(t, account) + return + } + require.NoError(t, err) + require.Equal(t, tt.wantID, account.ID) + }) + } +} + +func TestSimpleModeGroupIsolationSnapshot(t *testing.T) { + cfg := &config.Config{RunMode: config.RunModeSimple, SimpleMode: config.SimpleModeConfig{GroupIsolation: true}} + cfg.Gateway.Scheduling.DbFallbackEnabled = true + groupA, groupB := int64(10), int64(20) + repo := newBatchAccountQueryRepo() + svc := NewSchedulerSnapshotService(nil, nil, repo, nil, cfg) + bucket := svc.bucketFor(&groupB, PlatformOpenAI, SchedulerModeSingle) + require.Equal(t, groupB, bucket.GroupID) + require.ElementsMatch(t, []int64{groupA, groupB}, svc.normalizeGroupIDs([]int64{groupA, groupB})) + _, _, err := svc.ListSchedulableAccounts(context.Background(), &groupB, PlatformOpenAI, false) + require.NoError(t, err) + require.Equal(t, 1, repo.callCount(batchAccountQueryKey{groupID: groupB, platform: PlatformOpenAI})) + + // A previous shared-mode process may have published the full platform pool. + svc.cache = &openAISnapshotCacheStub{snapshotAccounts: []*Account{ + {ID: 1, Status: StatusActive, Schedulable: true, GroupIDs: []int64{groupA}}, + {ID: 2, Status: StatusActive, Schedulable: true, AccountGroups: []AccountGroup{{GroupID: groupB}}}, + {ID: 3, Status: StatusActive, Schedulable: true}, + }} + for _, tt := range []struct { + group *int64 + id int64 + }{{&groupB, 2}, {nil, 3}} { + got, _, err := svc.ListSchedulableAccounts(context.Background(), tt.group, PlatformOpenAI, false) + require.NoError(t, err) + require.Len(t, got, 1) + require.Equal(t, tt.id, got[0].ID) + } +} + +func TestSimpleModeGroupIsolationGeminiForcedAndSticky(t *testing.T) { + ctx := context.WithValue(context.Background(), ctxkey.ForcePlatform, PlatformGemini) + group := int64(20) + foreign := Account{ID: 1, Platform: PlatformGemini, Status: StatusActive, Schedulable: true, GroupIDs: []int64{10}} + for _, session := range []string{"", "old-session"} { + cache := &mockGatewayCacheForGemini{sessionBindings: map[string]int64{"gemini:old-session": foreign.ID}} + svc := &GeminiMessagesCompatService{ + cfg: &config.Config{RunMode: config.RunModeSimple, SimpleMode: config.SimpleModeConfig{GroupIsolation: true}}, + cache: cache, + accountRepo: &mockAccountRepoForGemini{ + accountsByID: map[int64]*Account{foreign.ID: &foreign}, + listByGroupFunc: func(context.Context, int64, []string) ([]Account, error) { + return nil, nil + }, + listByPlatformFunc: func(context.Context, []string) ([]Account, error) { + t.Fatal("an empty group must not fall back to the platform pool") + return nil, nil + }, + }, + } + account, err := svc.SelectAccountForModel(ctx, &group, session, "gemini-2.5-flash") + require.Error(t, err) + require.Nil(t, account) + } +} + +func TestSimpleModeGroupIsolationPreviousResponse(t *testing.T) { + ctx := context.Background() + group := int64(20) + foreign := Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true} + store := NewOpenAIWSStateStore(&schedulerTestGatewayCache{}) + svc := &OpenAIGatewayService{ + cfg: &config.Config{RunMode: config.RunModeSimple, SimpleMode: config.SimpleModeConfig{GroupIsolation: true}}, + accountRepo: schedulerTestOpenAIAccountRepo{accounts: []Account{foreign}}, + openaiWSStateStore: store, + } + const responseID = "resp_pre_isolation" + require.NoError(t, store.BindResponseAccount(ctx, group, responseID, foreign.ID, time.Hour)) + selection, err := svc.SelectAccountByPreviousResponseID(ctx, &group, responseID, "gpt-5.1", nil, false) + require.NoError(t, err) + require.Nil(t, selection) +} + +func TestSimpleModeGroupIsolationRechecksHydratedAccount(t *testing.T) { + group := int64(20) + candidate := &Account{ID: 1, GroupIDs: []int64{group}} + cache := &snapshotHydrationCache{accounts: map[int64]*Account{1: {ID: 1, GroupIDs: []int64{10}}}} + cfg := &config.Config{RunMode: config.RunModeSimple, SimpleMode: config.SimpleModeConfig{GroupIsolation: true}} + svc := &GatewayService{cfg: cfg, schedulerSnapshot: NewSchedulerSnapshotService(cache, nil, nil, nil, cfg)} + released := 0 + selection, err := svc.newSelectionResult(context.Background(), &group, candidate, true, func() { released++ }, nil) + require.ErrorIs(t, err, ErrNoAvailableAccounts) + require.Nil(t, selection) + require.Equal(t, 1, released) +} diff --git a/deploy/.env.example b/deploy/.env.example index f16e3483d0..a96f319d36 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -128,6 +128,8 @@ RUN_MODE=standard # 简易模式启动时自动补齐默认分组;留空或未设置时使用 YAML 配置,未配置时应用默认 true # 显式 true/false 会覆盖 YAML;false 由用户自行管理,已有分组和运行时行为不变 SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS= +# In simple mode, set true to schedule bound keys within their group and unbound keys on ungrouped accounts. +SIMPLE_MODE_GROUP_ISOLATION= # Opt into API-key 5h/1d/7d spending windows while RUN_MODE=simple. Default false. # SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED=false diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index 66cac12786..94c6e9da75 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -104,6 +104,9 @@ simple_mode: # 仅控制简易模式启动时补齐默认分组;false 不删除已有分组,不改变运行时自动绑定或管理员并发设置。 # 环境变量:SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS auto_create_default_groups: true + # 简易模式按 API Key 分组选账号。开启后,未绑定分组的 Key 只可使用未分组账号。 + # Set SIMPLE_MODE_GROUP_ISOLATION=true to opt into group-scoped scheduling. + group_isolation: false # Enforce API-key 5h/1d/7d spending windows in simple mode; other billing stays disabled. simple_mode_key_rate_limit_enabled: false diff --git a/deploy/docker-compose.dev.yml b/deploy/docker-compose.dev.yml index fd13301f69..fdd4cd64ea 100644 --- a/deploy/docker-compose.dev.yml +++ b/deploy/docker-compose.dev.yml @@ -32,6 +32,7 @@ services: - MCP_PUBLIC_URL=${MCP_PUBLIC_URL:-} - RUN_MODE=${RUN_MODE:-standard} - SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS=${SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS:-} + - SIMPLE_MODE_GROUP_ISOLATION=${SIMPLE_MODE_GROUP_ISOLATION:-} - SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED=${SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED:-false} - DATABASE_HOST=postgres - DATABASE_PORT=5432 diff --git a/deploy/docker-compose.local.yml b/deploy/docker-compose.local.yml index ea2827da5a..bb4df5d955 100644 --- a/deploy/docker-compose.local.yml +++ b/deploy/docker-compose.local.yml @@ -57,6 +57,7 @@ services: - MCP_PUBLIC_URL=${MCP_PUBLIC_URL:-} - RUN_MODE=${RUN_MODE:-standard} - SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS=${SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS:-} + - SIMPLE_MODE_GROUP_ISOLATION=${SIMPLE_MODE_GROUP_ISOLATION:-} - SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED=${SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED:-false} - UPDATE_GITHUB_TOKEN=${UPDATE_GITHUB_TOKEN:-} diff --git a/deploy/docker-compose.standalone.yml b/deploy/docker-compose.standalone.yml index 0c544bd9ca..a364073c70 100644 --- a/deploy/docker-compose.standalone.yml +++ b/deploy/docker-compose.standalone.yml @@ -43,6 +43,7 @@ services: - MCP_PUBLIC_URL=${MCP_PUBLIC_URL:-} - RUN_MODE=${RUN_MODE:-standard} - SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS=${SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS:-} + - SIMPLE_MODE_GROUP_ISOLATION=${SIMPLE_MODE_GROUP_ISOLATION:-} - SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED=${SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED:-false} - UPDATE_GITHUB_TOKEN=${UPDATE_GITHUB_TOKEN:-} diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 4d94afb1ab..e6f0e3e001 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -53,6 +53,7 @@ services: - MCP_PUBLIC_URL=${MCP_PUBLIC_URL:-} - RUN_MODE=${RUN_MODE:-standard} - SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS=${SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS:-} + - SIMPLE_MODE_GROUP_ISOLATION=${SIMPLE_MODE_GROUP_ISOLATION:-} - SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED=${SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED:-false} - UPDATE_GITHUB_TOKEN=${UPDATE_GITHUB_TOKEN:-} - ALIPAY_MOBILE_PRECREATE_DEEP_LINK=${ALIPAY_MOBILE_PRECREATE_DEEP_LINK:-}