mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 00:01:05 +00:00
Merge pull request #1008 from chenyme/quality-guard-2
fix: quarantine runtime-selected account leases
This commit is contained in:
15 files changed
+473
-36
No files matched your search
@@ -84,17 +84,18 @@ type DegradeNode struct {
|
||||
}
|
||||
|
||||
type DegradeAccount struct {
|
||||
ID uint64
|
||||
Name string
|
||||
Email string
|
||||
Hits int64
|
||||
MaxTPS float64
|
||||
Classes map[string]int64
|
||||
Nodes []string
|
||||
Last time.Time
|
||||
Enabled bool
|
||||
Found bool
|
||||
BFS int
|
||||
ID uint64
|
||||
Name string
|
||||
Email string
|
||||
Hits int64
|
||||
MaxTPS float64
|
||||
Classes map[string]int64
|
||||
Nodes []string
|
||||
Last time.Time
|
||||
Enabled bool
|
||||
Found bool
|
||||
BFS int
|
||||
LeaseCooldownUntil *time.Time
|
||||
}
|
||||
|
||||
type DegradeEventView struct {
|
||||
@@ -212,6 +213,7 @@ func buildDegradeSummary(window string, now time.Time, thresholds DegradeThresho
|
||||
auditdomain.DegradeClassThinking: value.Thinking,
|
||||
},
|
||||
Nodes: value.Nodes, Last: value.Last, Enabled: value.Enabled, Found: value.Found, BFS: value.BuildBotFlagSource,
|
||||
LeaseCooldownUntil: value.LeaseCooldownUntil,
|
||||
})
|
||||
}
|
||||
nodes := make([]DegradeNode, 0, len(data.Nodes))
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
auditdomain "github.com/chenyme/grok2api/backend/internal/domain/audit"
|
||||
egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/persistence/relational"
|
||||
)
|
||||
|
||||
@@ -233,6 +234,56 @@ func TestDegradeSummarySearchesEveryAccountIdentityField(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDegradeSummaryReportsActiveLeaseQuarantineForEnabledAccount(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-lease.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accounts := relational.NewAccountRepository(database)
|
||||
credential, _, err := accounts.UpsertByIdentity(ctx, accountdomain.Credential{
|
||||
Provider: accountdomain.ProviderBuild, Name: "lease-isolated", SourceKey: "lease-isolated",
|
||||
EncryptedAccessToken: "encrypted", AuthStatus: accountdomain.AuthStatusActive, Enabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
node, err := relational.NewEgressRepository(database).CreateEgressNode(ctx, egressdomain.Node{
|
||||
Name: "dynamic", Scope: egressdomain.ScopeBuild, Enabled: true, EncryptedProxyURL: "encrypted",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
cooldownUntil := now.Add(time.Hour)
|
||||
if _, err := accounts.UpsertEgressLeaseBlock(ctx, accountdomain.EgressLeaseBlock{
|
||||
AccountID: credential.ID, NodeID: node.ID, Reason: "hard_tps", Version: "degrade-lease-0001", CooldownUntil: cooldownUntil,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first := int64(100)
|
||||
if err := relational.NewAuditRepository(database).Create(ctx, auditdomain.Record{
|
||||
RequestID: "lease-anomaly", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build",
|
||||
AccountID: &credential.ID, AccountName: credential.Name, EgressNodeName: node.Name,
|
||||
StatusCode: 200, Streaming: true, OutputTokens: 2_000, FirstTokenMS: &first, DurationMS: 1_100, CreatedAt: now.Add(-time.Minute),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := NewService(relational.NewAuditRepository(database), slog.Default(), 8, 4, time.Second)
|
||||
service.now = func() time.Time { return now }
|
||||
summary, err := service.DegradeSummary(ctx, "1h", DegradeThresholds{}, DegradeAccountFilter{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(summary.Accounts) != 1 || !summary.Accounts[0].Enabled || summary.Accounts[0].LeaseCooldownUntil == nil || !summary.Accounts[0].LeaseCooldownUntil.Equal(cooldownUntil) {
|
||||
t.Fatalf("lease-isolated account = %#v", summary.Accounts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDegradeSummaryIncludesQualityDegradedThinkingRetries(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-thinking.db"))
|
||||
|
||||
@@ -4,8 +4,11 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
domain "github.com/chenyme/grok2api/backend/internal/domain/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
"github.com/chenyme/grok2api/backend/internal/repository"
|
||||
)
|
||||
|
||||
@@ -36,6 +39,52 @@ type qualityProberStub struct {
|
||||
input QualityProbeInput
|
||||
}
|
||||
|
||||
type qualityLeaseAccountRepository struct {
|
||||
credential accountdomain.Credential
|
||||
stored accountdomain.EgressLeaseBlock
|
||||
}
|
||||
|
||||
func (r *qualityLeaseAccountRepository) CountProviderAccountsByIDs(context.Context, accountdomain.Provider, []uint64) (int64, error) {
|
||||
return 1, nil
|
||||
}
|
||||
func (r *qualityLeaseAccountRepository) UpdateEgressBindings(context.Context, accountdomain.Provider, []uint64, *uint64, accountdomain.EgressAssignmentMode, time.Time) (int64, error) {
|
||||
return 1, nil
|
||||
}
|
||||
func (r *qualityLeaseAccountRepository) ListEgressAssignments(context.Context, accountdomain.Provider) ([]accountdomain.Credential, error) {
|
||||
return []accountdomain.Credential{r.credential}, nil
|
||||
}
|
||||
func (r *qualityLeaseAccountRepository) ListEgressBindingProviders(context.Context, uint64) ([]accountdomain.Provider, error) {
|
||||
return []accountdomain.Provider{accountdomain.ProviderBuild}, nil
|
||||
}
|
||||
func (r *qualityLeaseAccountRepository) ListEgressSourceBindingProviders(context.Context, uint64) ([]accountdomain.Provider, error) {
|
||||
return []accountdomain.Provider{}, nil
|
||||
}
|
||||
func (r *qualityLeaseAccountRepository) Get(_ context.Context, id uint64) (accountdomain.Credential, error) {
|
||||
if id != r.credential.ID {
|
||||
return accountdomain.Credential{}, repository.ErrNotFound
|
||||
}
|
||||
return r.credential, nil
|
||||
}
|
||||
func (r *qualityLeaseAccountRepository) ListEgressLeaseBlocks(context.Context, int, *accountdomain.EgressLeaseBlockCursor) ([]accountdomain.EgressLeaseBlock, error) {
|
||||
if r.stored.AccountID == 0 {
|
||||
return []accountdomain.EgressLeaseBlock{}, nil
|
||||
}
|
||||
return []accountdomain.EgressLeaseBlock{r.stored}, nil
|
||||
}
|
||||
func (r *qualityLeaseAccountRepository) UpsertEgressLeaseBlock(_ context.Context, value accountdomain.EgressLeaseBlock) (accountdomain.EgressLeaseBlock, error) {
|
||||
r.stored = value
|
||||
return value, nil
|
||||
}
|
||||
func (r *qualityLeaseAccountRepository) DeleteEgressLeaseBlock(context.Context, uint64, uint64, string) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
func (r *qualityLeaseAccountRepository) DeleteEgressLeaseBlocksByNodes(context.Context, []uint64) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
func (r *qualityLeaseAccountRepository) PruneInvalidEgressLeaseBlocks(context.Context, int) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (p *qualityProberStub) ProbeEgressQuality(_ context.Context, nodeID uint64, input QualityProbeInput) (QualityProbeResult, error) {
|
||||
p.nodeID = nodeID
|
||||
p.input = input
|
||||
@@ -100,3 +149,50 @@ func TestProbeQualityScopesThinkingGuardToReasoningBuildModels(t *testing.T) {
|
||||
t.Fatalf("non-reasoning model probe=%#v result=%#v", prober.input, result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQualityLeaseUsesObservedNodeForUnboundAccountButHonorsExplicitBinding(t *testing.T) {
|
||||
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
encryptedProxy, err := cipher.Encrypt("socks5h://Default.{account}:token@resin:2260")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nodes := &qualityProbeRepository{node: domain.Node{
|
||||
ID: 7, Scope: domain.ScopeBuild, Enabled: true, EncryptedProxyURL: encryptedProxy,
|
||||
}}
|
||||
accounts := &qualityLeaseAccountRepository{credential: accountdomain.Credential{
|
||||
ID: 11, Provider: accountdomain.ProviderBuild, Enabled: true, AuthStatus: accountdomain.AuthStatusActive,
|
||||
}}
|
||||
prober := &qualityProberStub{}
|
||||
service := NewService(nodes, cipher, "", accounts)
|
||||
service.SetQualityProber(prober)
|
||||
|
||||
if _, err := service.ProbeQuality(context.Background(), 7, QualityProbeInput{
|
||||
AccountID: 11, ClientKeyID: 3, Model: "grok-test",
|
||||
}); err != nil {
|
||||
t.Fatalf("unbound account recovery probe rejected the observed node: %v", err)
|
||||
}
|
||||
lease, err := service.QuarantineQualityLease(context.Background(), QualityLeaseInput{
|
||||
AccountID: 11, NodeID: 7, Reason: "hard_tps", QuarantineSeconds: 60,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unbound account quarantine rejected the observed node: %v", err)
|
||||
}
|
||||
if lease.AccountID != 11 || lease.NodeID != 7 || accounts.stored.NodeID != 7 {
|
||||
t.Fatalf("stored lease = %#v", lease)
|
||||
}
|
||||
|
||||
accounts.credential.EgressNodeID = 9
|
||||
if _, err := service.ProbeQuality(context.Background(), 7, QualityProbeInput{
|
||||
AccountID: 11, ClientKeyID: 3, Model: "grok-test",
|
||||
}); !errors.Is(err, ErrQualityProbeNoAccount) {
|
||||
t.Fatalf("probe through a node different from the explicit binding returned %v", err)
|
||||
}
|
||||
if _, err := service.QuarantineQualityLease(context.Background(), QualityLeaseInput{
|
||||
AccountID: 11, NodeID: 7, Reason: "hard_tps", QuarantineSeconds: 60,
|
||||
}); !errors.Is(err, ErrQualityLeaseConflict) {
|
||||
t.Fatalf("quarantine on a node different from the explicit binding returned %v", err)
|
||||
}
|
||||
}
|
||||
@@ -202,7 +202,7 @@ func (s *Service) ProbeQuality(ctx context.Context, nodeID uint64, input Quality
|
||||
return QualityProbeResult{}, fmt.Errorf("%w: 账号定向探测仅支持按账号派生代理的节点", ErrInvalidInput)
|
||||
}
|
||||
credential, loadErr := s.qualityLeases.Get(ctx, input.AccountID)
|
||||
if loadErr != nil || credential.Provider != accountdomain.ProviderBuild || !credential.Enabled || credential.AuthStatus != accountdomain.AuthStatusActive || credential.EgressNodeID != nodeID {
|
||||
if loadErr != nil || credential.Provider != accountdomain.ProviderBuild || !credential.Enabled || credential.AuthStatus != accountdomain.AuthStatusActive || !qualityLeaseCredentialMayUseNode(credential, nodeID) {
|
||||
return QualityProbeResult{}, ErrQualityProbeNoAccount
|
||||
}
|
||||
}
|
||||
@@ -333,7 +333,7 @@ func (s *Service) QuarantineQualityLease(ctx context.Context, input QualityLease
|
||||
return accountdomain.EgressLeaseBlock{}, ErrInvalidInput
|
||||
}
|
||||
credential, err := s.qualityLeases.Get(ctx, input.AccountID)
|
||||
if err != nil || credential.Provider != accountdomain.ProviderBuild || !credential.Enabled || credential.AuthStatus != accountdomain.AuthStatusActive || credential.EgressNodeID != input.NodeID {
|
||||
if err != nil || credential.Provider != accountdomain.ProviderBuild || !credential.Enabled || credential.AuthStatus != accountdomain.AuthStatusActive || !qualityLeaseCredentialMayUseNode(credential, input.NodeID) {
|
||||
return accountdomain.EgressLeaseBlock{}, ErrQualityLeaseConflict
|
||||
}
|
||||
version, err := security.NewOpaqueToken(18)
|
||||
@@ -378,6 +378,14 @@ func qualityLeaseReasonAllowed(value string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// An unbound Build account may be assigned an account-derived proxy node by
|
||||
// the runtime pool. In that case the quality audit's node ID is the observed
|
||||
// lease owner. A concrete binding remains authoritative and must never be
|
||||
// quarantined or probed through a different node.
|
||||
func qualityLeaseCredentialMayUseNode(credential accountdomain.Credential, nodeID uint64) bool {
|
||||
return nodeID != 0 && (credential.EgressNodeID == 0 || credential.EgressNodeID == nodeID)
|
||||
}
|
||||
|
||||
func (s *Service) UpdateDefaults(browserUA string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
@@ -917,7 +917,8 @@ func effectiveQuotaMode(candidate account.RoutingCandidate, fallback string) str
|
||||
|
||||
func candidateEgressLeaseCooling(candidate account.RoutingCandidate, credential account.Credential, now time.Time) bool {
|
||||
block := candidate.EgressLeaseBlock
|
||||
return block != nil && block.AccountID == credential.ID && block.NodeID != 0 && credential.EgressNodeID == block.NodeID && now.Before(block.CooldownUntil)
|
||||
return block != nil && block.AccountID == credential.ID && block.NodeID != 0 &&
|
||||
(credential.EgressNodeID == 0 || credential.EgressNodeID == block.NodeID) && now.Before(block.CooldownUntil)
|
||||
}
|
||||
|
||||
// candidateSupportsModel treats a recognized Web catalog entry as an
|
||||
|
||||
@@ -171,6 +171,59 @@ func TestSelectorQualityProbePinsAccountToRequestedEgressNode(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectorCoolsUnboundAccountOnObservedLeaseAndAllowsRecoveryProbe(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "selector-dynamic-egress.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
egressNodes := relational.NewEgressRepository(database)
|
||||
node, err := egressNodes.CreateEgressNode(ctx, egressdomain.Node{
|
||||
Name: "dynamic", Scope: egressdomain.ScopeBuild, Enabled: true, EncryptedProxyURL: "encrypted",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accounts := relational.NewAccountRepository(database)
|
||||
credential, _, err := accounts.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderBuild, Name: "unbound", SourceKey: "unbound", EncryptedAccessToken: "encrypted",
|
||||
Enabled: true, AuthStatus: account.AuthStatusActive, MaxConcurrent: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if credential.EgressNodeID != 0 {
|
||||
t.Fatalf("test account unexpectedly bound to node %d", credential.EgressNodeID)
|
||||
}
|
||||
if _, err := accounts.UpsertEgressLeaseBlock(ctx, account.EgressLeaseBlock{
|
||||
AccountID: credential.ID, NodeID: node.ID, Reason: "hard_tps", Version: "selector-dynamic-0001", CooldownUntil: time.Now().UTC().Add(time.Hour),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
selector := NewSelector(accounts, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), nil, time.Hour, time.Second, time.Minute)
|
||||
if _, err := selector.AcquirePinnedForKey(ctx, account.ProviderBuild, credential.ID, 0, "grok-test", "", true, clientkeydomain.AccountScope{}); err == nil {
|
||||
t.Fatal("ordinary inference ignored the unbound account's active observed lease")
|
||||
} else {
|
||||
var unavailable *SelectionUnavailableError
|
||||
if !errors.As(err, &unavailable) || unavailable.Reason != SelectionCooling {
|
||||
t.Fatalf("ordinary pinned error = %v", err)
|
||||
}
|
||||
}
|
||||
recoveryLease, err := selector.AcquirePinnedForQualityProbe(ctx, account.ProviderBuild, credential.ID, 0, "grok-test", "", clientkeydomain.AccountScope{})
|
||||
if err != nil {
|
||||
t.Fatalf("quality recovery did not bypass the observed lease block: %v", err)
|
||||
}
|
||||
defer recoveryLease.Release()
|
||||
if recoveryLease.Credential.ID != credential.ID || recoveryLease.Credential.EgressNodeID != 0 {
|
||||
t.Fatalf("quality recovery lease = %#v", recoveryLease.Credential)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectorQualityProbeBorrowsHealthyAccountForUnavailableNode(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "selector-egress-fallback.db"))
|
||||
|
||||
@@ -1235,7 +1235,10 @@ attemptLoop:
|
||||
err = &SelectionUnavailableError{Reason: SelectionNoAccounts}
|
||||
} else {
|
||||
lease, err = s.selector.AcquirePinnedForQualityProbe(ctx, route.Provider, input.ForcedAccountID, route.ID, route.UpstreamModel, quotaMode, accountScope)
|
||||
if err == nil && lease.Credential.EgressNodeID != input.ForcedEgressNodeID {
|
||||
// An unbound account can still have reached the observed node through
|
||||
// runtime pool selection. The Provider request below carries the forced
|
||||
// node explicitly; only a conflicting concrete binding is invalid.
|
||||
if err == nil && lease.Credential.EgressNodeID != 0 && lease.Credential.EgressNodeID != input.ForcedEgressNodeID {
|
||||
lease.Release()
|
||||
lease = nil
|
||||
err = &SelectionUnavailableError{Reason: SelectionNoAccounts}
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
|
||||
accountapp "github.com/chenyme/grok2api/backend/internal/application/account"
|
||||
clientkeyapp "github.com/chenyme/grok2api/backend/internal/application/clientkey"
|
||||
egressapp "github.com/chenyme/grok2api/backend/internal/application/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/audit"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/clientkey"
|
||||
@@ -448,6 +449,90 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestQualityProbeForcesObservedNodeForUnboundAccountAndRejectsConflictingBinding(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "quality-probe-unbound.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accountRepo := relational.NewAccountRepository(database)
|
||||
modelRepo := relational.NewModelRepository(database)
|
||||
auditRepo := relational.NewAuditRepository(database)
|
||||
keyRepo := relational.NewClientKeyRepository(database)
|
||||
nodes := relational.NewEgressRepository(database)
|
||||
observedNode, err := nodes.CreateEgressNode(ctx, egressdomain.Node{
|
||||
Name: "observed", Scope: egressdomain.ScopeBuild, Enabled: true, EncryptedProxyURL: "encrypted-observed",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
otherNode, err := nodes.CreateEgressNode(ctx, egressdomain.Node{
|
||||
Name: "other", Scope: egressdomain.ScopeBuild, Enabled: true, EncryptedProxyURL: "encrypted-other",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unbound, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderBuild, Name: "unbound", SourceKey: "quality-unbound", EncryptedAccessToken: "encrypted",
|
||||
ExpiresAt: time.Now().Add(time.Hour), Enabled: true, AuthStatus: account.AuthStatusActive, MaxConcurrent: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
boundElsewhere, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderBuild, Name: "bound-elsewhere", SourceKey: "quality-bound", EncryptedAccessToken: "encrypted",
|
||||
ExpiresAt: time.Now().Add(time.Hour), Enabled: true, AuthStatus: account.AuthStatusActive, MaxConcurrent: 1, EgressNodeID: otherNode.ID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := modelRepo.UpsertDiscovered(ctx, account.ProviderBuild, []string{"grok-test"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, accountID := range []uint64{unbound.ID, boundElsewhere.ID} {
|
||||
if err := modelRepo.ReplaceAccountCapabilities(ctx, accountID, []string{"grok-test"}, time.Now().UTC()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
key, err := keyRepo.Create(ctx, clientkey.Key{
|
||||
Name: "quality-probe", Prefix: "quality", SecretHash: strings.Repeat("7", 64), EncryptedSecret: "encrypted",
|
||||
Enabled: true, RPMLimit: 60, MaxConcurrent: 4,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
adapter := &forcedQualityProbeAdapter{}
|
||||
registry := provider.NewRegistry(adapter)
|
||||
sticky := memory.NewStickyStore()
|
||||
accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil)
|
||||
selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute)
|
||||
service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(keyRepo, nil, nil, 60, 4, nil), registry, selector, nil, 1)
|
||||
|
||||
result, err := service.ProbeEgressQuality(ctx, observedNode.ID, egressapp.QualityProbeInput{
|
||||
AccountID: unbound.ID, ClientKeyID: key.ID, Model: "grok-test", Prompt: "probe", Expected: "ok", MatchMode: "contains", MaxOutputTokens: 16,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unbound account did not reach the observed node: %v", err)
|
||||
}
|
||||
if !result.ExpectedMatched || adapter.Attempts() != 1 || adapter.LastAccountID() != unbound.ID || adapter.LastForcedNodeID() != observedNode.ID {
|
||||
t.Fatalf("probe result=%#v attempts=%d account=%d forcedNode=%d", result, adapter.Attempts(), adapter.LastAccountID(), adapter.LastForcedNodeID())
|
||||
}
|
||||
|
||||
_, err = service.ProbeEgressQuality(ctx, observedNode.ID, egressapp.QualityProbeInput{
|
||||
AccountID: boundElsewhere.ID, ClientKeyID: key.ID, Model: "grok-test", Prompt: "probe", Expected: "ok", MatchMode: "contains", MaxOutputTokens: 16,
|
||||
})
|
||||
if !errors.Is(err, egressapp.ErrQualityProbeNoAccount) {
|
||||
t.Fatalf("conflicting explicit binding returned %v", err)
|
||||
}
|
||||
if adapter.Attempts() != 1 {
|
||||
t.Fatalf("conflicting binding reached upstream; attempts=%d", adapter.Attempts())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayBuildResponseHeaderTimeoutDoesNotSwitchAccounts(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "gateway-build-header-timeout.db"))
|
||||
@@ -3899,6 +3984,52 @@ type scriptedBuildResponse struct {
|
||||
header http.Header
|
||||
}
|
||||
|
||||
type forcedQualityProbeAdapter struct {
|
||||
mu sync.Mutex
|
||||
attempts int
|
||||
accountID uint64
|
||||
forcedNodeID uint64
|
||||
}
|
||||
|
||||
func (a *forcedQualityProbeAdapter) Provider() account.Provider { return account.ProviderBuild }
|
||||
func (a *forcedQualityProbeAdapter) Definition() provider.Definition {
|
||||
definition := testConversationDefinition(account.ProviderBuild)
|
||||
definition.Credential.Refresh = false
|
||||
return definition
|
||||
}
|
||||
func (a *forcedQualityProbeAdapter) ForwardResponse(_ context.Context, request provider.ResponseResourceRequest) (*provider.Response, error) {
|
||||
a.mu.Lock()
|
||||
a.attempts++
|
||||
a.accountID = request.Credential.ID
|
||||
a.forcedNodeID = request.ForcedEgressNodeID
|
||||
a.mu.Unlock()
|
||||
body := strings.Join([]string{
|
||||
`data: {"id":"quality-response","model":"grok-test","choices":[{"delta":{"content":"ok"}}]}`,
|
||||
`data: {"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`,
|
||||
`data: [DONE]`,
|
||||
"",
|
||||
}, "\n")
|
||||
return &provider.Response{
|
||||
StatusCode: http.StatusOK, Status: "200 OK", Header: http.Header{"Content-Type": {"text/event-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
}, nil
|
||||
}
|
||||
func (a *forcedQualityProbeAdapter) Attempts() int {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.attempts
|
||||
}
|
||||
func (a *forcedQualityProbeAdapter) LastAccountID() uint64 {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.accountID
|
||||
}
|
||||
func (a *forcedQualityProbeAdapter) LastForcedNodeID() uint64 {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.forcedNodeID
|
||||
}
|
||||
|
||||
type barePermissionEgressAdapter struct {
|
||||
providerValue account.Provider
|
||||
attempts atomic.Int64
|
||||
|
||||
@@ -73,6 +73,65 @@ func TestEgressLeaseBlockRoutesOnlyMatchingActiveBindingAndUsesCAS(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEgressLeaseBlockRoutesUnboundAccountUsingObservedLeaseNode(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "egress-dynamic-lease.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accounts := NewAccountRepository(database)
|
||||
nodes := NewEgressRepository(database)
|
||||
node := createHealthyEgressNode(t, ctx, nodes, egressOperationsCipher(t), "dynamic-lease", 0)
|
||||
laterNode := createHealthyEgressNode(t, ctx, nodes, egressOperationsCipher(t), "dynamic-lease-later", 0)
|
||||
credential := createEgressOperationsAccount(t, ctx, accounts, "dynamic-lease-account")
|
||||
if credential.EgressNodeID != 0 {
|
||||
t.Fatalf("test account unexpectedly bound to node %d", credential.EgressNodeID)
|
||||
}
|
||||
|
||||
base := time.Now().UTC()
|
||||
stored, err := accounts.UpsertEgressLeaseBlock(ctx, account.EgressLeaseBlock{
|
||||
AccountID: credential.ID, NodeID: node.ID, Reason: "hard_tps", Version: "dynamic-lease-0001", CooldownUntil: base.Add(time.Hour),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unbound account lease quarantine failed: %v", err)
|
||||
}
|
||||
if stored.AccountID != credential.ID || stored.NodeID != node.ID {
|
||||
t.Fatalf("stored dynamic lease = %#v", stored)
|
||||
}
|
||||
if _, err := accounts.UpsertEgressLeaseBlock(ctx, account.EgressLeaseBlock{
|
||||
AccountID: credential.ID, NodeID: laterNode.ID, Reason: "hard_tps", Version: "dynamic-lease-0002", CooldownUntil: base.Add(2 * time.Hour),
|
||||
}); err != nil {
|
||||
t.Fatalf("second observed lease quarantine failed: %v", err)
|
||||
}
|
||||
candidates, err := accounts.ListRoutingCandidates(ctx, account.ProviderBuild, 0, "grok-test", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(candidates) != 1 || candidates[0].EgressLeaseBlock == nil || candidates[0].EgressLeaseBlock.NodeID != laterNode.ID {
|
||||
t.Fatalf("dynamic lease was not loaded for routing: %#v", candidates)
|
||||
}
|
||||
|
||||
credential.Name = "dynamic-lease-account-refreshed"
|
||||
if _, err := accounts.Update(ctx, credential); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
leases, err := accounts.ListEgressLeaseBlocks(ctx, 10, nil)
|
||||
if err != nil || len(leases) != 2 {
|
||||
t.Fatalf("ordinary account refresh removed dynamic lease: leases=%#v err=%v", leases, err)
|
||||
}
|
||||
if _, err := accounts.UpdateEgressBindings(ctx, account.ProviderBuild, []uint64{credential.ID}, &node.ID, account.EgressAssignmentManual, base); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
leases, err = accounts.ListEgressLeaseBlocks(ctx, 10, nil)
|
||||
if err != nil || len(leases) != 1 || leases[0].NodeID != node.ID {
|
||||
t.Fatalf("explicit binding did not remove leases observed on other nodes: leases=%#v err=%v", leases, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpiredEgressLeaseBlockIsReconciledButNotRouted(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "expired-egress-lease.db"))
|
||||
|
||||
@@ -525,12 +525,16 @@ func (r *AccountRepository) getRoutingEgressLeaseBlocks(ctx context.Context, pro
|
||||
Table("account_egress_lease_blocks AS block").
|
||||
Select("block.*").
|
||||
Joins("JOIN provider_accounts AS account ON account.id = block.account_id").
|
||||
Where("account.provider = ? AND account.enabled = ? AND account.auth_status = ? AND account.egress_node_id = block.node_id AND block.cooldown_until > ?", provider, true, account.AuthStatusActive, now.UTC()).
|
||||
Where("account.provider = ? AND account.enabled = ? AND account.auth_status = ? AND (account.egress_node_id IS NULL OR account.egress_node_id = block.node_id) AND block.cooldown_until > ?", provider, true, account.AuthStatusActive, now.UTC()).
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
result[row.AccountID] = egressLeaseBlockFromModel(row)
|
||||
block := egressLeaseBlockFromModel(row)
|
||||
current, exists := result[row.AccountID]
|
||||
if !exists || block.CooldownUntil.After(current.CooldownUntil) {
|
||||
result[row.AccountID] = block
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -2267,7 +2271,7 @@ func (r *AccountRepository) ListEgressLeaseBlocks(ctx context.Context, limit int
|
||||
Table("account_egress_lease_blocks AS block").Select("block.*").
|
||||
Joins("JOIN provider_accounts AS account ON account.id = block.account_id").
|
||||
Joins("JOIN egress_nodes AS node ON node.id = block.node_id").
|
||||
Where("account.provider = ? AND account.enabled = ? AND account.auth_status = ? AND account.egress_node_id = block.node_id AND node.enabled = ? AND node.scope = ?", account.ProviderBuild, true, account.AuthStatusActive, true, "grok_build").
|
||||
Where("account.provider = ? AND account.enabled = ? AND account.auth_status = ? AND (account.egress_node_id IS NULL OR account.egress_node_id = block.node_id) AND node.enabled = ? AND node.scope = ?", account.ProviderBuild, true, account.AuthStatusActive, true, "grok_build").
|
||||
Order("block.cooldown_until ASC, block.account_id ASC, block.node_id ASC").Limit(limit)
|
||||
if after != nil {
|
||||
cursorTime := after.CooldownUntil.UTC()
|
||||
@@ -2291,7 +2295,10 @@ func deleteInvalidEgressLeaseBlocksForAccount(tx *gorm.DB, row accountModel) (in
|
||||
return 0, nil
|
||||
}
|
||||
query := tx.Where("account_id = ?", row.ID)
|
||||
if row.Enabled && account.AuthStatus(row.AuthStatus) == account.AuthStatusActive && row.EgressNodeID != nil {
|
||||
if row.Enabled && account.AuthStatus(row.AuthStatus) == account.AuthStatusActive {
|
||||
if row.EgressNodeID == nil {
|
||||
return 0, nil
|
||||
}
|
||||
query = query.Where("node_id <> ?", *row.EgressNodeID)
|
||||
}
|
||||
result := query.Delete(&accountEgressLeaseBlockModel{})
|
||||
@@ -2307,7 +2314,7 @@ func (r *AccountRepository) PruneInvalidEgressLeaseBlocks(ctx context.Context, l
|
||||
Table("account_egress_lease_blocks AS block").Select("block.*").
|
||||
Joins("LEFT JOIN provider_accounts AS account ON account.id = block.account_id").
|
||||
Joins("LEFT JOIN egress_nodes AS node ON node.id = block.node_id").
|
||||
Where("account.id IS NULL OR account.provider <> ? OR account.enabled <> ? OR account.auth_status <> ? OR account.egress_node_id IS NULL OR account.egress_node_id <> block.node_id OR node.id IS NULL OR node.enabled <> ? OR node.scope <> ?", account.ProviderBuild, true, account.AuthStatusActive, true, "grok_build").
|
||||
Where("account.id IS NULL OR account.provider <> ? OR account.enabled <> ? OR account.auth_status <> ? OR (account.egress_node_id IS NOT NULL AND account.egress_node_id <> block.node_id) OR node.id IS NULL OR node.enabled <> ? OR node.scope <> ?", account.ProviderBuild, true, account.AuthStatusActive, true, "grok_build").
|
||||
Order("block.cooldown_until ASC, block.account_id ASC, block.node_id ASC").Limit(limit).Find(&rows).Error
|
||||
if err != nil || len(rows) == 0 {
|
||||
return 0, err
|
||||
@@ -2345,9 +2352,10 @@ func (r *AccountRepository) DeleteEgressLeaseBlocksByNodes(ctx context.Context,
|
||||
return result.RowsAffected, result.Error
|
||||
}
|
||||
|
||||
// UpsertEgressLeaseBlock atomically verifies that the Build account is still
|
||||
// bound to the requested node. A shorter concurrent hold cannot replace a
|
||||
// longer one or rotate its CAS version.
|
||||
// UpsertEgressLeaseBlock atomically verifies that the Build account may still
|
||||
// use the observed node. Unbound accounts can receive a runtime-selected
|
||||
// account-derived proxy; explicit bindings remain authoritative. A shorter
|
||||
// concurrent hold cannot replace a longer one or rotate its CAS version.
|
||||
func (r *AccountRepository) UpsertEgressLeaseBlock(ctx context.Context, value account.EgressLeaseBlock) (account.EgressLeaseBlock, error) {
|
||||
value.Reason = strings.TrimSpace(value.Reason)
|
||||
value.Version = strings.TrimSpace(value.Version)
|
||||
@@ -2363,7 +2371,7 @@ func (r *AccountRepository) UpsertEgressLeaseBlock(ctx context.Context, value ac
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Select("id", "provider", "enabled", "auth_status", "egress_node_id").First(&owner, value.AccountID).Error; err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
if account.Provider(owner.Provider) != account.ProviderBuild || !owner.Enabled || account.AuthStatus(owner.AuthStatus) != account.AuthStatusActive || owner.EgressNodeID == nil || *owner.EgressNodeID != value.NodeID {
|
||||
if account.Provider(owner.Provider) != account.ProviderBuild || !owner.Enabled || account.AuthStatus(owner.AuthStatus) != account.AuthStatusActive || (owner.EgressNodeID != nil && *owner.EgressNodeID != value.NodeID) {
|
||||
return repository.ErrConflict
|
||||
}
|
||||
var existing accountEgressLeaseBlockModel
|
||||
|
||||
@@ -738,6 +738,11 @@ type degradeAccountRow struct {
|
||||
BuildBotFlagSource int `gorm:"column:build_bot_flag_source"`
|
||||
}
|
||||
|
||||
type degradeAccountLeaseRow struct {
|
||||
AccountID uint64 `gorm:"column:account_id"`
|
||||
CooldownUntil degradeTimestamp `gorm:"column:cooldown_until"`
|
||||
}
|
||||
|
||||
type degradeTimestamp time.Time
|
||||
|
||||
func (value *degradeTimestamp) Scan(input any) error {
|
||||
@@ -874,6 +879,20 @@ func (r *AuditRepository) SummarizeDegrade(ctx context.Context, input repository
|
||||
accountsByID[row.ID] = &result.Accounts[len(result.Accounts)-1]
|
||||
}
|
||||
if len(accountIDs) > 0 {
|
||||
var leaseRows []degradeAccountLeaseRow
|
||||
if err := tx.Table("account_egress_lease_blocks").
|
||||
Select("account_id, MAX(cooldown_until) AS cooldown_until").
|
||||
Where("account_id IN ? AND cooldown_until > ?", accountIDs, input.End).
|
||||
Group("account_id").Scan(&leaseRows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, row := range leaseRows {
|
||||
if account := accountsByID[row.AccountID]; account != nil {
|
||||
cooldownUntil := time.Time(row.CooldownUntil).UTC()
|
||||
account.LeaseCooldownUntil = &cooldownUntil
|
||||
}
|
||||
}
|
||||
|
||||
var nodeRows []degradeAccountNodeRow
|
||||
if err := tx.Table("(?) AS d", classified).
|
||||
Select("d.account_id, COALESCE(NULLIF(d.egress_node_name, ''), '?') AS name").
|
||||
|
||||
@@ -80,6 +80,7 @@ type DegradeAccount struct {
|
||||
Enabled bool
|
||||
Found bool
|
||||
BuildBotFlagSource int
|
||||
LeaseCooldownUntil *time.Time
|
||||
Nodes []string
|
||||
}
|
||||
|
||||
|
||||
@@ -369,7 +369,7 @@ func (h *Handler) degradeAccounts(c *gin.Context) {
|
||||
accounts = append(accounts, degradeAccountResponse{
|
||||
ID: strconv.FormatUint(account.ID, 10), Name: account.Name, Email: account.Email, Hits: account.Hits,
|
||||
MaxTPS: account.MaxTPS, Classes: account.Classes, Nodes: account.Nodes, Last: account.Last,
|
||||
Enabled: account.Enabled, Found: account.Found, BFS: account.BFS,
|
||||
Enabled: account.Enabled, Found: account.Found, BFS: account.BFS, LeaseCooldownUntil: account.LeaseCooldownUntil,
|
||||
})
|
||||
}
|
||||
events := make([]degradeEventResponse, 0, len(result.Events))
|
||||
@@ -442,17 +442,18 @@ type degradeTotalsResponse struct {
|
||||
}
|
||||
|
||||
type degradeAccountResponse struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Hits int64 `json:"hits"`
|
||||
MaxTPS float64 `json:"maxTPS"`
|
||||
Classes map[string]int64 `json:"classes"`
|
||||
Nodes []string `json:"nodes"`
|
||||
Last time.Time `json:"last"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Found bool `json:"found"`
|
||||
BFS int `json:"bfs"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Hits int64 `json:"hits"`
|
||||
MaxTPS float64 `json:"maxTPS"`
|
||||
Classes map[string]int64 `json:"classes"`
|
||||
Nodes []string `json:"nodes"`
|
||||
Last time.Time `json:"last"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Found bool `json:"found"`
|
||||
BFS int `json:"bfs"`
|
||||
LeaseCooldownUntil *time.Time `json:"leaseQuarantinedUntil,omitempty"`
|
||||
}
|
||||
|
||||
type degradeEventResponse struct {
|
||||
|
||||
@@ -166,6 +166,8 @@ export function DegradeAccountsPanel({ softTPS, hardTPS, failClosed, minGenMs }:
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{!account.found
|
||||
? <Badge variant="outline" className="whitespace-nowrap text-muted-foreground">{t("qualityGuard.degrade.deletedStatus")}</Badge>
|
||||
: account.leaseQuarantinedUntil
|
||||
? <Badge variant="outline" className="whitespace-nowrap border-amber-500/40 text-amber-700 dark:text-amber-400">{t("qualityGuard.leaseUntil", { time: formatCompactDateTime(account.leaseQuarantinedUntil, i18n.language) })}</Badge>
|
||||
: account.enabled
|
||||
? <Badge variant="outline" className="whitespace-nowrap text-destructive">{t("qualityGuard.degrade.scheduling")}</Badge>
|
||||
: <Badge variant="outline" className="whitespace-nowrap text-emerald-600 dark:text-emerald-400">{t("qualityGuard.degrade.disabledStatus")}</Badge>}
|
||||
|
||||
@@ -248,6 +248,7 @@ export type DegradeAccountDTO = {
|
||||
enabled: boolean;
|
||||
found: boolean;
|
||||
bfs: number;
|
||||
leaseQuarantinedUntil?: string;
|
||||
};
|
||||
|
||||
export type DegradeEventDTO = {
|
||||
@@ -287,6 +288,7 @@ const decodeDegradeSummary = createObjectDecoder<DegradeSummaryDTO>("degrade acc
|
||||
accounts: isArrayOf(hasShape({
|
||||
id: isString, name: isString, email: isString, hits: isNumber, maxTPS: isNumber,
|
||||
classes: isObject, nodes: isArrayOf(isString), last: isString, enabled: isBoolean, found: isBoolean, bfs: isNumber,
|
||||
leaseQuarantinedUntil: isOptional(isString),
|
||||
})),
|
||||
accountPage: hasShape({ page: isNumber, pageSize: isNumber, total: isNumber, hasMore: isBoolean }),
|
||||
events: isArrayOf(hasShape({
|
||||
|
||||
Reference in new issue
Block a user