mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 16:02:12 +00:00
Merge pull request #1020 from buddhism5080/fix/selector-skip-credential-material-errors
fix(gateway): skip accounts whose credential material fails to load
This commit is contained in:
5 files changed
+311
-47
No files matched your search
@@ -67,6 +67,67 @@ const defaultFreeQuotaRecoveryPause = 24 * time.Hour
|
||||
|
||||
var errRoutingCredentialStale = errors.New("routing credential is no longer available")
|
||||
|
||||
// credentialMaterialFailureSkipLimit 限制一次选号连续跳过的同类瞬态故障。
|
||||
// 少量失败仍按单号隔离;超过上限时保留原始存储错误,避免大账号池放大系统性故障。
|
||||
const credentialMaterialFailureSkipLimit = 8
|
||||
|
||||
type credentialMaterialFailureTracker struct {
|
||||
class string
|
||||
count int
|
||||
}
|
||||
|
||||
func (tracker *credentialMaterialFailureTracker) record(class string) (int, bool) {
|
||||
if tracker == nil {
|
||||
return 1, true
|
||||
}
|
||||
if tracker.class != class {
|
||||
tracker.class = class
|
||||
tracker.count = 0
|
||||
}
|
||||
tracker.count++
|
||||
return tracker.count, tracker.count <= credentialMaterialFailureSkipLimit
|
||||
}
|
||||
|
||||
func (tracker *credentialMaterialFailureTracker) reset() {
|
||||
if tracker == nil {
|
||||
return
|
||||
}
|
||||
tracker.class = ""
|
||||
tracker.count = 0
|
||||
}
|
||||
|
||||
// skipUnusableCredentialMaterial 只把账号缺失或明确的瞬态存储故障转成可跳过的过期 claim。
|
||||
// 请求取消、永久错误和无法分类的错误保留根因返回,不能伪装成整池无可用账号。
|
||||
func (s *Selector) skipUnusableCredentialMaterial(ctx context.Context, value account.Credential, loadErr error, tracker *credentialMaterialFailureTracker) error {
|
||||
if ctx != nil && ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if errors.Is(loadErr, repository.ErrNotFound) {
|
||||
tracker.reset()
|
||||
s.ApplyInvalidation(repository.InvalidationEvent{Kind: repository.InvalidationAccountStateChanged, Provider: value.Provider, AccountID: value.ID})
|
||||
return errRoutingCredentialStale
|
||||
}
|
||||
failureClass, transient := transientRoutingStoreFailureClass(loadErr)
|
||||
if !transient {
|
||||
return fmt.Errorf("加载账号 %d 的凭据材料: %w", value.ID, loadErr)
|
||||
}
|
||||
consecutiveFailures, allowed := tracker.record(failureClass)
|
||||
if !allowed {
|
||||
return fmt.Errorf("连续加载账号凭据材料失败(%s,%d 次): %w", failureClass, consecutiveFailures, loadErr)
|
||||
}
|
||||
if s.logger != nil {
|
||||
s.logger.Warn(
|
||||
"routing_credential_material_skipped",
|
||||
"account_id", value.ID,
|
||||
"provider", value.Provider,
|
||||
"failure_class", failureClass,
|
||||
"consecutive_failures", consecutiveFailures,
|
||||
"error", loadErr,
|
||||
)
|
||||
}
|
||||
return errRoutingCredentialStale
|
||||
}
|
||||
|
||||
type quotaRecoveryHints struct {
|
||||
Billing *account.Billing
|
||||
}
|
||||
@@ -544,6 +605,7 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model
|
||||
}
|
||||
normalCandidates = append(normalCandidates, index)
|
||||
}
|
||||
materialFailures := credentialMaterialFailureTracker{}
|
||||
if len(normalCandidates) == 0 && len(probeCandidates) == 0 {
|
||||
reason := SelectionNoAccounts
|
||||
switch {
|
||||
@@ -566,7 +628,7 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model
|
||||
return nil, err
|
||||
}
|
||||
for candidate, ok := plan.Next(); ok; candidate, ok = plan.Next() {
|
||||
lease, err := s.claimAccountSlot(ctx, candidate.Credential)
|
||||
lease, err := s.claimAccountSlotTracked(ctx, candidate.Credential, &materialFailures)
|
||||
if err != nil {
|
||||
if errors.Is(err, errRoutingCredentialStale) {
|
||||
staleClaims++
|
||||
@@ -614,7 +676,7 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model
|
||||
stickyID = boundID
|
||||
}
|
||||
if eligible {
|
||||
lease, acquireErr := s.acquirePinnedCapacity(ctx, candidate.Credential)
|
||||
lease, acquireErr := s.acquirePinnedCapacity(ctx, candidate.Credential, &materialFailures)
|
||||
if acquireErr == nil {
|
||||
lease.Billing = candidate.Billing
|
||||
lease.QuotaMode = effectiveQuotaMode(candidate, quotaMode)
|
||||
@@ -642,7 +704,7 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model
|
||||
if candidate.Credential.ID == saturatedStickyID {
|
||||
continue
|
||||
}
|
||||
lease, claimErr := s.claimAccountSlot(ctx, candidate.Credential)
|
||||
lease, claimErr := s.claimAccountSlotTracked(ctx, candidate.Credential, &materialFailures)
|
||||
if claimErr != nil {
|
||||
if errors.Is(claimErr, errRoutingCredentialStale) {
|
||||
continue
|
||||
@@ -660,7 +722,7 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model
|
||||
}
|
||||
activeRequest := s.nextSegmentedActiveRequest(provider, upstreamModel, quotaMode, len(normalCandidates))
|
||||
if activeRequest != nil {
|
||||
lease, acquireErr := s.acquireSegmentedCandidates(ctx, values, normalCandidates, quotaMode, s.resolveTierOrder(provider, upstreamModel, quotaMode), *activeRequest)
|
||||
lease, acquireErr := s.acquireSegmentedCandidates(ctx, values, normalCandidates, quotaMode, s.resolveTierOrder(provider, upstreamModel, quotaMode), *activeRequest, &materialFailures)
|
||||
if acquireErr != nil || lease == nil || stickyKey == "" {
|
||||
return lease, acquireErr
|
||||
}
|
||||
@@ -668,7 +730,7 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model
|
||||
lease.Release()
|
||||
return nil, errors.New("分段选号缺少候选上下文")
|
||||
}
|
||||
return s.completeStickyLease(ctx, stickyKey, values, normalCandidates, *lease.routingCandidate, lease, quotaMode)
|
||||
return s.completeStickyLease(ctx, stickyKey, values, normalCandidates, *lease.routingCandidate, lease, quotaMode, &materialFailures)
|
||||
}
|
||||
_, _, _, capacityWait := s.routingConfig()
|
||||
waitDeadline := time.Now().Add(capacityWait)
|
||||
@@ -681,7 +743,7 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model
|
||||
return nil, err
|
||||
}
|
||||
for candidate, ok := plan.Next(); ok; candidate, ok = plan.Next() {
|
||||
lease, err := s.claimAccountSlot(ctx, candidate.Credential)
|
||||
lease, err := s.claimAccountSlotTracked(ctx, candidate.Credential, &materialFailures)
|
||||
if err != nil {
|
||||
if errors.Is(err, errRoutingCredentialStale) {
|
||||
staleClaims++
|
||||
@@ -693,7 +755,7 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model
|
||||
capacityMisses++
|
||||
continue
|
||||
}
|
||||
return s.completeStickyLease(ctx, stickyKey, values, normalCandidates, candidate, lease, quotaMode)
|
||||
return s.completeStickyLease(ctx, stickyKey, values, normalCandidates, candidate, lease, quotaMode, &materialFailures)
|
||||
}
|
||||
if staleClaims > 0 && capacityMisses == 0 {
|
||||
return nil, &SelectionUnavailableError{Reason: SelectionNoAccounts}
|
||||
@@ -711,7 +773,7 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Selector) completeStickyLease(ctx context.Context, stickyKey string, values []account.RoutingCandidate, normalCandidates []int, candidate account.RoutingCandidate, lease *accountLease, quotaMode string) (*accountLease, error) {
|
||||
func (s *Selector) completeStickyLease(ctx context.Context, stickyKey string, values []account.RoutingCandidate, normalCandidates []int, candidate account.RoutingCandidate, lease *accountLease, quotaMode string, materialFailures *credentialMaterialFailureTracker) (*accountLease, error) {
|
||||
if stickyKey != "" {
|
||||
stickyTTL, _, _, _ := s.routingConfig()
|
||||
now := time.Now().UTC()
|
||||
@@ -722,7 +784,7 @@ func (s *Selector) completeStickyLease(ctx context.Context, stickyKey string, va
|
||||
}
|
||||
if boundID != candidate.Credential.ID {
|
||||
if boundCandidate, eligible := routingCandidateByID(values, normalCandidates, boundID); eligible {
|
||||
boundLease, acquireErr := s.acquirePinnedCapacity(ctx, boundCandidate.Credential)
|
||||
boundLease, acquireErr := s.acquirePinnedCapacity(ctx, boundCandidate.Credential, materialFailures)
|
||||
if acquireErr == nil {
|
||||
lease.Release()
|
||||
lease = boundLease
|
||||
@@ -836,7 +898,7 @@ func (s *Selector) acquirePinned(ctx context.Context, provider account.Provider,
|
||||
}
|
||||
return nil, &SelectionUnavailableError{Reason: SelectionQuotaExhausted, RetryAfter: retryAfter}
|
||||
}
|
||||
lease, err := s.acquirePinnedCapacity(ctx, value)
|
||||
lease, err := s.acquirePinnedCapacity(ctx, value, nil)
|
||||
if err != nil {
|
||||
if errors.Is(err, errRoutingCredentialStale) {
|
||||
return nil, pinnedUnavailableError(accountID, value.Name)
|
||||
@@ -867,7 +929,7 @@ func (s *Selector) acquirePinned(ctx context.Context, provider account.Provider,
|
||||
return nil, &SelectionUnavailableError{Reason: SelectionQuotaExhausted, RetryAfter: retryAfter}
|
||||
}
|
||||
}
|
||||
lease, err := s.acquirePinnedCapacity(ctx, value)
|
||||
lease, err := s.acquirePinnedCapacity(ctx, value, nil)
|
||||
if err != nil {
|
||||
if errors.Is(err, errRoutingCredentialStale) {
|
||||
return nil, pinnedUnavailableError(accountID, value.Name)
|
||||
@@ -1761,39 +1823,54 @@ func canUseStaleRoutingSnapshot(ctx context.Context, err error) bool {
|
||||
if err == nil || ctx != nil && ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return false
|
||||
}
|
||||
_, transient := transientRoutingStoreFailureClass(err)
|
||||
return transient
|
||||
}
|
||||
|
||||
// transientRoutingStoreFailureClass 仅识别带有明确瞬态信号的存储错误,
|
||||
// 同时返回不包含账号或错误正文的稳定分类,供单次选号的故障放大保护使用。
|
||||
func transientRoutingStoreFailureClass(err error) (string, bool) {
|
||||
if err == nil || errors.Is(err, context.Canceled) {
|
||||
return "", false
|
||||
}
|
||||
if errors.Is(err, repository.ErrNotFound) || errors.Is(err, repository.ErrConflict) || errors.Is(err, repository.ErrLimitExceeded) || errors.Is(err, repository.ErrInvalidRecord) || errors.Is(err, repository.ErrAccountPoolMismatch) {
|
||||
return false
|
||||
return "", false
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return "deadline", true
|
||||
}
|
||||
if errors.Is(err, sql.ErrConnDone) || errors.Is(err, driver.ErrBadConn) {
|
||||
return true
|
||||
return "sql_connection", true
|
||||
}
|
||||
var networkError net.Error
|
||||
if errors.As(err, &networkError) && (networkError.Timeout() || networkError.Temporary()) {
|
||||
return true
|
||||
return fmt.Sprintf("network:%T", networkError), true
|
||||
}
|
||||
var temporary interface{ Temporary() bool }
|
||||
if errors.As(err, &temporary) && temporary.Temporary() {
|
||||
return true
|
||||
return fmt.Sprintf("temporary:%T", temporary), true
|
||||
}
|
||||
// modernc SQLite exposes the primary/extended result through Code().
|
||||
// SQLITE_BUSY (5) and SQLITE_LOCKED (6) are safe to retry.
|
||||
var sqliteError interface{ Code() int }
|
||||
if errors.As(err, &sqliteError) {
|
||||
switch sqliteError.Code() & 0xff {
|
||||
primaryCode := sqliteError.Code() & 0xff
|
||||
switch primaryCode {
|
||||
case 5, 6:
|
||||
return true
|
||||
return fmt.Sprintf("sqlite:%d", primaryCode), true
|
||||
}
|
||||
}
|
||||
// pgx exposes SQLSTATE without requiring the application layer to depend on
|
||||
// a concrete PostgreSQL driver type.
|
||||
var postgresError interface{ SQLState() string }
|
||||
if errors.As(err, &postgresError) {
|
||||
switch state := postgresError.SQLState(); {
|
||||
state := postgresError.SQLState()
|
||||
switch {
|
||||
case strings.HasPrefix(state, "08"), strings.HasPrefix(state, "40"), state == "55P03", state == "57P01", state == "57P02", state == "57P03":
|
||||
return true
|
||||
return "postgres:" + state, true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return "", false
|
||||
}
|
||||
|
||||
func (s *Selector) logStaleRoutingFallback(layer string, provider account.Provider, now, staleUntil time.Time, err error) {
|
||||
@@ -1995,6 +2072,10 @@ func (s *Selector) evictCandidate(provider account.Provider, accountID uint64) {
|
||||
}
|
||||
|
||||
func (s *Selector) claimAccountSlot(ctx context.Context, value account.Credential) (*accountLease, error) {
|
||||
return s.claimAccountSlotTracked(ctx, value, nil)
|
||||
}
|
||||
|
||||
func (s *Selector) claimAccountSlotTracked(ctx context.Context, value account.Credential, materialFailures *credentialMaterialFailureTracker) (*accountLease, error) {
|
||||
now := time.Now().UTC()
|
||||
value = s.applyRoutingHealth(value, now)
|
||||
if value.CooldownUntil != nil && now.Before(*value.CooldownUntil) {
|
||||
@@ -2019,12 +2100,9 @@ func (s *Selector) claimAccountSlot(ctx context.Context, value account.Credentia
|
||||
material, loadErr := s.accounts.GetCredentialMaterial(ctx, value.ID, value.Provider)
|
||||
if loadErr != nil {
|
||||
releaseSlot()
|
||||
if errors.Is(loadErr, repository.ErrNotFound) {
|
||||
s.ApplyInvalidation(repository.InvalidationEvent{Kind: repository.InvalidationAccountStateChanged, Provider: value.Provider, AccountID: value.ID})
|
||||
return nil, errRoutingCredentialStale
|
||||
}
|
||||
return nil, fmt.Errorf("加载账号执行凭据: %w", loadErr)
|
||||
return nil, s.skipUnusableCredentialMaterial(ctx, value, loadErr, materialFailures)
|
||||
}
|
||||
materialFailures.reset()
|
||||
hydrated, matched := material.ApplyTo(value)
|
||||
if !matched {
|
||||
releaseSlot()
|
||||
@@ -2041,11 +2119,11 @@ func (s *Selector) claimAccountSlot(ctx context.Context, value account.Credentia
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func (s *Selector) acquirePinnedCapacity(ctx context.Context, value account.Credential) (*accountLease, error) {
|
||||
func (s *Selector) acquirePinnedCapacity(ctx context.Context, value account.Credential, materialFailures *credentialMaterialFailureTracker) (*accountLease, error) {
|
||||
_, _, _, capacityWait := s.routingConfig()
|
||||
deadline := time.Now().Add(capacityWait)
|
||||
for {
|
||||
lease, err := s.claimAccountSlot(ctx, value)
|
||||
lease, err := s.claimAccountSlotTracked(ctx, value, materialFailures)
|
||||
if err != nil || lease != nil {
|
||||
return lease, err
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ type layeredAccountRepository struct {
|
||||
overlayErr error
|
||||
combined []account.RoutingCandidate
|
||||
combinedCalls int
|
||||
materialHook func(context.Context, uint64) error
|
||||
materialErrors map[uint64]error
|
||||
materials map[uint64]account.CredentialMaterial
|
||||
materialCalls []uint64
|
||||
@@ -83,14 +84,28 @@ func (r *layeredAccountRepository) ListRoutingCandidates(context.Context, accoun
|
||||
return r.combined, nil
|
||||
}
|
||||
|
||||
func (r *layeredAccountRepository) GetCredentialMaterial(_ context.Context, accountID uint64, provider account.Provider) (account.CredentialMaterial, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.materialCalls = append(r.materialCalls, accountID)
|
||||
if err := r.materialErrors[accountID]; err != nil {
|
||||
func (r *layeredAccountRepository) GetCredentialMaterial(ctx context.Context, accountID uint64, provider account.Provider) (account.CredentialMaterial, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return account.CredentialMaterial{}, err
|
||||
}
|
||||
if material, ok := r.materials[accountID]; ok {
|
||||
r.mu.Lock()
|
||||
r.materialCalls = append(r.materialCalls, accountID)
|
||||
hook := r.materialHook
|
||||
loadErr := r.materialErrors[accountID]
|
||||
material, materialExists := r.materials[accountID]
|
||||
r.mu.Unlock()
|
||||
if hook != nil {
|
||||
if err := hook(ctx, accountID); err != nil {
|
||||
return account.CredentialMaterial{}, err
|
||||
}
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return account.CredentialMaterial{}, err
|
||||
}
|
||||
if loadErr != nil {
|
||||
return account.CredentialMaterial{}, loadErr
|
||||
}
|
||||
if materialExists {
|
||||
return material, nil
|
||||
}
|
||||
return account.CredentialMaterial{AccountID: accountID, Provider: provider, AuthType: account.AuthTypeOAuth, EncryptedAccessToken: "encrypted"}, nil
|
||||
@@ -642,6 +657,75 @@ func TestSelectorHydratesOnlyClaimedCredentialAndSkipsStaleCandidate(t *testing.
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectorSkipsCredentialMaterialLoadErrorAndUsesNextAccount(t *testing.T) {
|
||||
repo := newLayeredRepositoryFixture()
|
||||
repo.bases = []account.RoutingAccountBase{
|
||||
{Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, Enabled: true, AuthStatus: account.AuthStatusActive, Priority: 20}},
|
||||
{Credential: account.Credential{ID: 2, Provider: account.ProviderBuild, Enabled: true, AuthStatus: account.AuthStatusActive, Priority: 10}},
|
||||
}
|
||||
repo.overlays["model-a"] = account.RoutingOverlaySnapshot{Values: []account.RoutingAccountOverlay{
|
||||
{AccountID: 1, ModelCapabilityKnown: true, SupportsModel: true},
|
||||
{AccountID: 2, ModelCapabilityKnown: true, SupportsModel: true},
|
||||
}}
|
||||
repo.materialErrors = map[uint64]error{1: context.DeadlineExceeded}
|
||||
repo.materials = map[uint64]account.CredentialMaterial{
|
||||
2: {AccountID: 2, Provider: account.ProviderBuild, AuthType: account.AuthTypeOAuth, EncryptedAccessToken: "selected-secret"},
|
||||
}
|
||||
selector := NewSelector(repo, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), nil, time.Hour, time.Second, time.Minute)
|
||||
|
||||
lease, err := selector.Acquire(context.Background(), account.ProviderBuild, 0, "model-a", "", "", nil, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lease.Release()
|
||||
if lease.Credential.ID != 2 || lease.Credential.EncryptedAccessToken != "selected-secret" {
|
||||
t.Fatalf("lease credential = %#v", lease.Credential)
|
||||
}
|
||||
if !reflect.DeepEqual(repo.materialCalls, []uint64{1, 2}) {
|
||||
t.Fatalf("material calls = %v, want [1 2]", repo.materialCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectorCredentialMaterialContextCancelDoesNotDrainPool(t *testing.T) {
|
||||
repo := newLayeredRepositoryFixture()
|
||||
repo.bases = []account.RoutingAccountBase{
|
||||
{Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, Enabled: true, AuthStatus: account.AuthStatusActive, Priority: 20}},
|
||||
{Credential: account.Credential{ID: 2, Provider: account.ProviderBuild, Enabled: true, AuthStatus: account.AuthStatusActive, Priority: 10}},
|
||||
}
|
||||
repo.overlays["model-a"] = account.RoutingOverlaySnapshot{Values: []account.RoutingAccountOverlay{
|
||||
{AccountID: 1, ModelCapabilityKnown: true, SupportsModel: true},
|
||||
{AccountID: 2, ModelCapabilityKnown: true, SupportsModel: true},
|
||||
}}
|
||||
selector := NewSelector(repo, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), nil, time.Hour, time.Second, time.Minute)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
repo.materialHook = func(loadCtx context.Context, accountID uint64) error {
|
||||
if accountID == 1 {
|
||||
cancel()
|
||||
return loadCtx.Err()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
_, err := selector.Acquire(ctx, account.ProviderBuild, 0, "model-a", "", "", nil, false)
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("error = %v, want context canceled", err)
|
||||
}
|
||||
if !reflect.DeepEqual(repo.materialCalls, []uint64{1}) {
|
||||
t.Fatalf("material calls = %v, want cancellation during the first load to stop selection", repo.materialCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkipUnusableCredentialMaterialHonorsCancel(t *testing.T) {
|
||||
selector := NewSelector(nil, nil, nil, nil, time.Hour, time.Second, time.Minute)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
err := selector.skipUnusableCredentialMaterial(ctx, account.Credential{ID: 1, Provider: account.ProviderBuild}, temporaryRoutingLoadError{message: "temporary credential store timeout"}, nil)
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("error = %v, want context canceled", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectorReportsNoAccountsWhenEveryCredentialIsStale(t *testing.T) {
|
||||
repo := newLayeredRepositoryFixture()
|
||||
repo.materialErrors = map[uint64]error{1: repository.ErrNotFound}
|
||||
@@ -672,6 +756,41 @@ func TestSelectorPinnedCredentialDoesNotSwitchWhenMaterialIsStale(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectorRebindsStickySessionAfterCredentialMaterialLoadError(t *testing.T) {
|
||||
repo := newLayeredRepositoryFixture()
|
||||
repo.bases = []account.RoutingAccountBase{
|
||||
{Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, Enabled: true, AuthStatus: account.AuthStatusActive, Priority: 20}},
|
||||
{Credential: account.Credential{ID: 2, Provider: account.ProviderBuild, Enabled: true, AuthStatus: account.AuthStatusActive, Priority: 10}},
|
||||
}
|
||||
repo.overlays["model-a"] = account.RoutingOverlaySnapshot{Values: []account.RoutingAccountOverlay{
|
||||
{AccountID: 1, ModelCapabilityKnown: true, SupportsModel: true},
|
||||
{AccountID: 2, ModelCapabilityKnown: true, SupportsModel: true},
|
||||
}}
|
||||
repo.materialErrors = map[uint64]error{1: temporaryRoutingLoadError{message: "temporary credential store timeout"}}
|
||||
repo.materials = map[uint64]account.CredentialMaterial{
|
||||
2: {AccountID: 2, Provider: account.ProviderBuild, AuthType: account.AuthTypeOAuth, EncryptedAccessToken: "selected-secret"},
|
||||
}
|
||||
sticky := memory.NewStickyStore()
|
||||
affinity := "load-error-session"
|
||||
if err := sticky.Set(context.Background(), stickySessionKey(affinity), 1, time.Now().Add(time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
selector := NewSelector(repo, memory.NewConcurrencyLimiter(), sticky, nil, time.Hour, time.Second, time.Minute)
|
||||
|
||||
lease, err := selector.Acquire(context.Background(), account.ProviderBuild, 0, "model-a", "", affinity, nil, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lease.Release()
|
||||
if lease.Credential.ID != 2 {
|
||||
t.Fatalf("selected account = %d, want fallback account 2", lease.Credential.ID)
|
||||
}
|
||||
boundID, ok, err := sticky.Get(context.Background(), stickySessionKey(affinity), time.Now())
|
||||
if err != nil || !ok || boundID != 2 {
|
||||
t.Fatalf("sticky binding = %d, ok=%v, err=%v", boundID, ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectorRebindsStickySessionAfterCredentialBecomesStale(t *testing.T) {
|
||||
repo := newLayeredRepositoryFixture()
|
||||
repo.bases = []account.RoutingAccountBase{
|
||||
@@ -700,8 +819,16 @@ func TestSelectorRebindsStickySessionAfterCredentialBecomesStale(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectorReleasesCapacityWhenCredentialHydrationFails(t *testing.T) {
|
||||
func TestSelectorPropagatesPermanentCredentialMaterialLoadErrorAndReleasesCapacity(t *testing.T) {
|
||||
repo := newLayeredRepositoryFixture()
|
||||
repo.bases = []account.RoutingAccountBase{
|
||||
{Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, Enabled: true, AuthStatus: account.AuthStatusActive, Priority: 20}},
|
||||
{Credential: account.Credential{ID: 2, Provider: account.ProviderBuild, Enabled: true, AuthStatus: account.AuthStatusActive, Priority: 10}},
|
||||
}
|
||||
repo.overlays["model-a"] = account.RoutingOverlaySnapshot{Values: []account.RoutingAccountOverlay{
|
||||
{AccountID: 1, ModelCapabilityKnown: true, SupportsModel: true},
|
||||
{AccountID: 2, ModelCapabilityKnown: true, SupportsModel: true},
|
||||
}}
|
||||
loadErr := errors.New("credential storage unavailable")
|
||||
repo.materialErrors = map[uint64]error{1: loadErr}
|
||||
limiter := memory.NewConcurrencyLimiter()
|
||||
@@ -709,7 +836,10 @@ func TestSelectorReleasesCapacityWhenCredentialHydrationFails(t *testing.T) {
|
||||
|
||||
_, err := selector.Acquire(context.Background(), account.ProviderBuild, 0, "model-a", "", "", nil, false)
|
||||
if !errors.Is(err, loadErr) {
|
||||
t.Fatalf("error = %v, want credential storage error", err)
|
||||
t.Fatalf("error = %v, want original credential storage error", err)
|
||||
}
|
||||
if !reflect.DeepEqual(repo.materialCalls, []uint64{1}) {
|
||||
t.Fatalf("material calls = %v, want permanent error not to drain the pool", repo.materialCalls)
|
||||
}
|
||||
current, currentErr := limiter.Current(context.Background(), repository.AccountConcurrencyKey(1))
|
||||
if currentErr != nil {
|
||||
@@ -720,6 +850,44 @@ func TestSelectorReleasesCapacityWhenCredentialHydrationFails(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectorStopsAfterRepeatedCredentialMaterialLoadFailures(t *testing.T) {
|
||||
repo := newLayeredRepositoryFixture()
|
||||
candidateCount := credentialMaterialFailureSkipLimit + 2
|
||||
repo.bases = make([]account.RoutingAccountBase, 0, candidateCount)
|
||||
overlays := make([]account.RoutingAccountOverlay, 0, candidateCount)
|
||||
repo.materialErrors = make(map[uint64]error, candidateCount)
|
||||
for index := 0; index < candidateCount; index++ {
|
||||
accountID := uint64(index + 1)
|
||||
repo.bases = append(repo.bases, account.RoutingAccountBase{Credential: account.Credential{
|
||||
ID: accountID, Provider: account.ProviderBuild, Enabled: true, AuthStatus: account.AuthStatusActive, Priority: candidateCount - index,
|
||||
}})
|
||||
overlays = append(overlays, account.RoutingAccountOverlay{AccountID: accountID, ModelCapabilityKnown: true, SupportsModel: true})
|
||||
repo.materialErrors[accountID] = temporaryRoutingLoadError{message: "credential store temporarily unavailable"}
|
||||
}
|
||||
repo.overlays["model-a"] = account.RoutingOverlaySnapshot{Values: overlays}
|
||||
limiter := memory.NewConcurrencyLimiter()
|
||||
selector := NewSelector(repo, limiter, memory.NewStickyStore(), nil, time.Hour, time.Second, time.Minute)
|
||||
|
||||
_, err := selector.Acquire(context.Background(), account.ProviderBuild, 0, "model-a", "", "", nil, false)
|
||||
var temporaryErr temporaryRoutingLoadError
|
||||
if !errors.As(err, &temporaryErr) {
|
||||
t.Fatalf("error = %v, want original temporary credential storage error", err)
|
||||
}
|
||||
wantCalls := credentialMaterialFailureSkipLimit + 1
|
||||
if len(repo.materialCalls) != wantCalls {
|
||||
t.Fatalf("material call count = %d, want %d bounded attempts; calls=%v", len(repo.materialCalls), wantCalls, repo.materialCalls)
|
||||
}
|
||||
for _, accountID := range repo.materialCalls {
|
||||
current, currentErr := limiter.Current(context.Background(), repository.AccountConcurrencyKey(accountID))
|
||||
if currentErr != nil {
|
||||
t.Fatal(currentErr)
|
||||
}
|
||||
if current != 0 {
|
||||
t.Fatalf("account %d concurrency = %d, want released slot", accountID, current)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectorRejectsCrossProviderCredentialMaterial(t *testing.T) {
|
||||
repo := newLayeredRepositoryFixture()
|
||||
repo.materials = map[uint64]account.CredentialMaterial{
|
||||
|
||||
@@ -49,7 +49,7 @@ func (s *Selector) nextSegmentedActiveRequest(provider account.Provider, upstrea
|
||||
return &segmentedSelectorActiveRequest{provider: provider, windowSize: config.windowSize, cursor: cursor}
|
||||
}
|
||||
|
||||
func (s *Selector) acquireSegmentedCandidates(ctx context.Context, values []account.RoutingCandidate, indexes []int, quotaMode string, tierOrder []account.WebTier, request segmentedSelectorActiveRequest) (*accountLease, error) {
|
||||
func (s *Selector) acquireSegmentedCandidates(ctx context.Context, values []account.RoutingCandidate, indexes []int, quotaMode string, tierOrder []account.WebTier, request segmentedSelectorActiveRequest, materialFailures *credentialMaterialFailureTracker) (*accountLease, error) {
|
||||
startedAt := time.Now()
|
||||
_, _, _, capacityWait := s.routingConfig()
|
||||
waitDeadline := time.Now().Add(capacityWait)
|
||||
@@ -70,7 +70,7 @@ func (s *Selector) acquireSegmentedCandidates(ctx context.Context, values []acco
|
||||
observeSegmentedActive(request.provider, "error", "full_fallback", startedAt, windowsScanned, candidatesScanned)
|
||||
return nil, err
|
||||
}
|
||||
claim, err := s.claimSegmentedPlan(ctx, plan, request.provider, quotaMode, "full_fallback")
|
||||
claim, err := s.claimSegmentedPlan(ctx, plan, request.provider, quotaMode, "full_fallback", materialFailures)
|
||||
if err != nil {
|
||||
observeSegmentedActive(request.provider, "error", "full_fallback", startedAt, windowsScanned, candidatesScanned)
|
||||
return nil, err
|
||||
@@ -100,7 +100,7 @@ func (s *Selector) acquireSegmentedCandidates(ctx context.Context, values []acco
|
||||
return nil, err
|
||||
}
|
||||
stage := segmentedActiveSelectionStage(cohortIndex, windowOffset)
|
||||
claim, err := s.claimSegmentedPlan(ctx, plan, request.provider, quotaMode, stage)
|
||||
claim, err := s.claimSegmentedPlan(ctx, plan, request.provider, quotaMode, stage, materialFailures)
|
||||
if err != nil {
|
||||
observeSegmentedActive(request.provider, "error", "claim", startedAt, windowsScanned, candidatesScanned)
|
||||
return nil, err
|
||||
@@ -129,7 +129,7 @@ func (s *Selector) acquireSegmentedCandidates(ctx context.Context, values []acco
|
||||
observeSegmentedActive(request.provider, "error", "full_fallback", startedAt, windowsScanned, candidatesScanned)
|
||||
return nil, err
|
||||
}
|
||||
claim, err := s.claimSegmentedPlan(ctx, plan, request.provider, quotaMode, "full_fallback")
|
||||
claim, err := s.claimSegmentedPlan(ctx, plan, request.provider, quotaMode, "full_fallback", materialFailures)
|
||||
if err != nil {
|
||||
observeSegmentedActive(request.provider, "error", "full_fallback", startedAt, windowsScanned, candidatesScanned)
|
||||
return nil, err
|
||||
@@ -161,10 +161,10 @@ func (s *Selector) acquireSegmentedCandidates(ctx context.Context, values []acco
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Selector) claimSegmentedPlan(ctx context.Context, plan *candidatePlan, provider account.Provider, quotaMode, stage string) (segmentedClaimResult, error) {
|
||||
func (s *Selector) claimSegmentedPlan(ctx context.Context, plan *candidatePlan, provider account.Provider, quotaMode, stage string, materialFailures *credentialMaterialFailureTracker) (segmentedClaimResult, error) {
|
||||
result := segmentedClaimResult{}
|
||||
for candidate, ok := plan.Next(); ok; candidate, ok = plan.Next() {
|
||||
lease, err := s.claimAccountSlot(ctx, candidate.Credential)
|
||||
lease, err := s.claimAccountSlotTracked(ctx, candidate.Credential, materialFailures)
|
||||
if err != nil {
|
||||
if errors.Is(err, errRoutingCredentialStale) {
|
||||
result.staleClaims++
|
||||
|
||||
@@ -72,6 +72,23 @@ func benchmarkSegmentedSelector(b *testing.B, candidateCount int, enabled, force
|
||||
}
|
||||
}
|
||||
|
||||
func TestSegmentedActiveSkipsCredentialMaterialLoadError(t *testing.T) {
|
||||
limiter := newSegmentedSelectiveLimiter()
|
||||
selector := newSegmentedActiveTestSelector(100, limiter, nil)
|
||||
selector.UpdateSegmentedSelector(true, 100, 8)
|
||||
repo := selector.accounts.(*layeredAccountRepository)
|
||||
repo.materialErrors = map[uint64]error{1: sqliteRoutingLoadError{code: 5}}
|
||||
|
||||
lease, err := selector.Acquire(context.Background(), account.ProviderBuild, 0, "model", "", "", nil, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lease.Release()
|
||||
if lease.Credential.ID != 2 {
|
||||
t.Fatalf("selected account = %d, want 2 after skipping material load error", lease.Credential.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSegmentedActiveReadsOnlyFirstAvailableWindow(t *testing.T) {
|
||||
limiter := newSegmentedSelectiveLimiter()
|
||||
selector := newSegmentedActiveTestSelector(100, limiter, nil)
|
||||
|
||||
@@ -28,6 +28,7 @@ type selectionSession struct {
|
||||
retryAccountID uint64
|
||||
stickyTried bool
|
||||
staleCandidates map[uint64]bool
|
||||
materialFailures credentialMaterialFailureTracker
|
||||
}
|
||||
|
||||
func (s *Selector) beginSelectionSession(ctx context.Context, provider account.Provider, modelRouteID uint64, upstreamModel, quotaMode, affinityKey string, excluded map[uint64]bool, allowQuotaProbe bool) (*selectionSession, error) {
|
||||
@@ -143,7 +144,7 @@ func (session *selectionSession) Acquire(ctx context.Context, excluded map[uint6
|
||||
session.retryAccountID = 0
|
||||
if !session.candidateExcluded(excluded, accountID) {
|
||||
if candidate, ok := routingCandidateByID(session.values, session.normalCandidates, accountID); ok {
|
||||
lease, err := session.selector.claimAccountSlot(ctx, candidate.Credential)
|
||||
lease, err := session.selector.claimAccountSlotTracked(ctx, candidate.Credential, &session.materialFailures)
|
||||
if err != nil {
|
||||
if errors.Is(err, errRoutingCredentialStale) {
|
||||
session.markCandidateStale(accountID)
|
||||
@@ -194,7 +195,7 @@ func (session *selectionSession) acquireQuotaProbe(ctx context.Context, excluded
|
||||
if session.candidateExcluded(excluded, candidate.Credential.ID) {
|
||||
continue
|
||||
}
|
||||
lease, err := session.selector.claimAccountSlot(ctx, candidate.Credential)
|
||||
lease, err := session.selector.claimAccountSlotTracked(ctx, candidate.Credential, &session.materialFailures)
|
||||
if err != nil {
|
||||
if errors.Is(err, errRoutingCredentialStale) {
|
||||
session.markCandidateStale(candidate.Credential.ID)
|
||||
@@ -239,7 +240,7 @@ func (session *selectionSession) acquireNormal(ctx context.Context, excluded map
|
||||
if candidate.Credential.ID != stickyID {
|
||||
continue
|
||||
}
|
||||
lease, err := session.selector.acquirePinnedCapacity(ctx, candidate.Credential)
|
||||
lease, err := session.selector.acquirePinnedCapacity(ctx, candidate.Credential, &session.materialFailures)
|
||||
if err != nil {
|
||||
if errors.Is(err, errRoutingCredentialStale) {
|
||||
session.markCandidateStale(stickyID)
|
||||
@@ -261,7 +262,7 @@ func (session *selectionSession) acquireNormal(ctx context.Context, excluded map
|
||||
indexes := session.unexcludedNormalIndexes(excluded)
|
||||
activeRequest := session.selector.nextSegmentedActiveRequest(session.provider, session.upstreamModel, session.quotaMode, len(indexes))
|
||||
if activeRequest != nil {
|
||||
lease, err := session.selector.acquireSegmentedCandidates(ctx, session.values, indexes, session.quotaMode, session.selector.resolveTierOrder(session.provider, session.upstreamModel, session.quotaMode), *activeRequest)
|
||||
lease, err := session.selector.acquireSegmentedCandidates(ctx, session.values, indexes, session.quotaMode, session.selector.resolveTierOrder(session.provider, session.upstreamModel, session.quotaMode), *activeRequest, &session.materialFailures)
|
||||
if err != nil || lease == nil || session.stickyKey == "" {
|
||||
return lease, err
|
||||
}
|
||||
@@ -285,7 +286,7 @@ func (session *selectionSession) acquireNormal(ctx context.Context, excluded map
|
||||
if session.candidateExcluded(excluded, candidate.Credential.ID) {
|
||||
continue
|
||||
}
|
||||
lease, err := session.selector.claimAccountSlot(ctx, candidate.Credential)
|
||||
lease, err := session.selector.claimAccountSlotTracked(ctx, candidate.Credential, &session.materialFailures)
|
||||
if err != nil {
|
||||
if errors.Is(err, errRoutingCredentialStale) {
|
||||
session.markCandidateStale(candidate.Credential.ID)
|
||||
@@ -326,7 +327,7 @@ func (session *selectionSession) completeNormalLease(ctx context.Context, lease
|
||||
}
|
||||
if boundID != candidate.Credential.ID {
|
||||
if boundCandidate, eligible := routingCandidateByID(session.values, session.normalCandidates, boundID); eligible && !session.candidateExcluded(excluded, boundID) {
|
||||
boundLease, acquireErr := session.selector.claimAccountSlot(ctx, boundCandidate.Credential)
|
||||
boundLease, acquireErr := session.selector.claimAccountSlotTracked(ctx, boundCandidate.Credential, &session.materialFailures)
|
||||
if acquireErr != nil {
|
||||
if errors.Is(acquireErr, errRoutingCredentialStale) {
|
||||
session.markCandidateStale(boundID)
|
||||
|
||||
Reference in new issue
Block a user