mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 08:02:14 +00:00
fix: share Build model entitlement across Super accounts
This commit is contained in:
1 parent
ff1ffb2dde
commit
0779b244b5
5 files changed
+176
-8
No files matched your search
@@ -24,7 +24,8 @@ type quotaBreakdownJSON struct {
|
||||
}
|
||||
|
||||
const (
|
||||
accountPaidBillingPredicate = `EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = provider_accounts.id AND (billing.monthly_limit > 0 OR billing.on_demand_cap > 0 OR billing.on_demand_used > 0 OR billing.prepaid_balance > 0 OR billing.credit_usage_percent > 0))`
|
||||
accountPaidBillingSignals = `(billing.monthly_limit > 0 OR billing.on_demand_cap > 0 OR billing.on_demand_used > 0 OR billing.prepaid_balance > 0 OR billing.credit_usage_percent > 0)`
|
||||
accountPaidBillingPredicate = `EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = provider_accounts.id AND ` + accountPaidBillingSignals + `)`
|
||||
accountFreeSignalPredicate = `(LOWER(TRIM(provider_accounts.observed_model)) LIKE '%-build-free' OR EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = provider_accounts.id AND (billing.is_unified_billing_user = TRUE OR billing.usage_period_type <> '' OR billing.top_up_method <> '' OR billing.billing_period_start <> '' OR (billing.history_json <> '' AND billing.history_json <> '[]' AND billing.history_json <> 'null'))))`
|
||||
accountRecoveryPredicate = `EXISTS (SELECT 1 FROM account_quota_recovery recovery WHERE recovery.account_id = provider_accounts.id AND recovery.status IN ('exhausted', 'probing'))`
|
||||
providerQuotaExhaustedPredicate = `((provider_accounts.provider = 'grok_web' AND ((EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly') AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly' AND quota.remaining > 0)) OR (NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly') AND EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id) AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.remaining > 0)))) OR (provider_accounts.provider = 'grok_console' AND EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id) AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.remaining > 0)))`
|
||||
@@ -234,11 +235,24 @@ func (r *AccountRepository) ListRoutingCandidates(ctx context.Context, provider
|
||||
modelQuotaBlocks[row.AccountID] = account.ModelQuotaBlock{AccountID: row.AccountID, UpstreamModel: row.UpstreamModel, Reason: row.Reason, CooldownUntil: row.CooldownUntil.UTC(), UpdatedAt: row.UpdatedAt.UTC()}
|
||||
}
|
||||
}
|
||||
sharedPaidBuildModel := false
|
||||
if provider == account.ProviderBuild && len(bound) == 0 {
|
||||
for accountID := range supported {
|
||||
if billing, exists := billings[accountID]; exists && billing.IsPaid() {
|
||||
sharedPaidBuildModel = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
result := make([]account.RoutingCandidate, 0, len(values))
|
||||
for _, value := range values {
|
||||
capabilityKnown, supportsModel := known[value.ID], supported[value.ID]
|
||||
if len(bound) > 0 {
|
||||
capabilityKnown, supportsModel = true, true
|
||||
} else if sharedPaidBuildModel {
|
||||
if billing, exists := billings[value.ID]; exists && billing.IsPaid() {
|
||||
capabilityKnown, supportsModel = true, true
|
||||
}
|
||||
}
|
||||
candidate := account.RoutingCandidate{Credential: value, ModelCapabilityKnown: capabilityKnown, SupportsModel: supportsModel}
|
||||
if billing, ok := billings[value.ID]; ok {
|
||||
|
||||
@@ -85,6 +85,105 @@ func TestModelCapabilitiesAggregateAndGateEnabledRoutes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildPaidCapabilitiesAreSharedAcrossActiveSuperAccounts(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database := openTestDatabase(t)
|
||||
accounts := NewAccountRepository(database)
|
||||
models := NewModelRepository(database)
|
||||
|
||||
createAccount := func(name string) account.Credential {
|
||||
t.Helper()
|
||||
value, _, err := accounts.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderBuild, Name: name, SourceKey: name,
|
||||
EncryptedAccessToken: testEncryptedToken, Enabled: true, AuthStatus: account.AuthStatusActive,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return value
|
||||
}
|
||||
observer := createAccount("super-observer")
|
||||
peer := createAccount("super-peer")
|
||||
freeObserver := createAccount("free-observer")
|
||||
freePeer := createAccount("free-peer")
|
||||
now := time.Now().UTC()
|
||||
if err := accounts.SaveBilling(ctx, account.Billing{AccountID: observer.ID, MonthlyLimit: 100, SyncedAt: now}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := accounts.SaveBilling(ctx, account.Billing{AccountID: peer.ID, OnDemandCap: 50, SyncedAt: now}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
const sharedModel = "grok-super-shared"
|
||||
if err := models.UpsertDiscovered(ctx, account.ProviderBuild, []string{sharedModel, "grok-4.5"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for accountID, capabilities := range map[uint64][]string{
|
||||
observer.ID: {sharedModel, "grok-4.5"},
|
||||
peer.ID: {"grok-4.5"},
|
||||
freeObserver.ID: {sharedModel},
|
||||
freePeer.ID: {"grok-4.5"},
|
||||
} {
|
||||
if err := models.ReplaceAccountCapabilities(ctx, accountID, capabilities, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
route, err := models.GetByProviderUpstream(ctx, account.ProviderBuild, sharedModel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
route, err = models.Get(ctx, route.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if route.SupportedAccounts != 3 || route.TotalAccounts != 4 {
|
||||
t.Fatalf("shared route availability = %#v", route)
|
||||
}
|
||||
if _, _, err := models.List(ctx, repository.ModelListQuery{
|
||||
Page: repository.PageQuery{Limit: 20, Sort: repository.SortQuery{Field: "accountSupport", Direction: repository.SortDescending}},
|
||||
}); err != nil {
|
||||
t.Fatalf("sort by shared account support: %v", err)
|
||||
}
|
||||
candidates, err := accounts.ListRoutingCandidates(ctx, account.ProviderBuild, sharedModel, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
byID := make(map[uint64]account.RoutingCandidate, len(candidates))
|
||||
for _, candidate := range candidates {
|
||||
byID[candidate.Credential.ID] = candidate
|
||||
}
|
||||
for _, accountID := range []uint64{observer.ID, peer.ID, freeObserver.ID} {
|
||||
if candidate := byID[accountID]; !candidate.ModelCapabilityKnown || !candidate.SupportsModel {
|
||||
t.Fatalf("account %d should support shared model: %#v", accountID, candidate)
|
||||
}
|
||||
}
|
||||
if candidate := byID[freePeer.ID]; !candidate.ModelCapabilityKnown || candidate.SupportsModel {
|
||||
t.Fatalf("free peer must keep its own capability snapshot: %#v", candidate)
|
||||
}
|
||||
|
||||
observer.Enabled = false
|
||||
if _, err := accounts.Update(ctx, observer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
route, err = models.Get(ctx, route.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if route.SupportedAccounts != 1 || route.TotalAccounts != 3 {
|
||||
t.Fatalf("disabled observer must not grant shared entitlement: %#v", route)
|
||||
}
|
||||
candidates, err = accounts.ListRoutingCandidates(ctx, account.ProviderBuild, sharedModel, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, candidate := range candidates {
|
||||
if candidate.Credential.ID == peer.ID && candidate.SupportsModel {
|
||||
t.Fatalf("paid peer should lose shared capability without an active paid observer: %#v", candidate)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicModelNameResolvesAcrossAvailableProviders(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database := openTestDatabase(t)
|
||||
|
||||
@@ -41,9 +41,33 @@ const availableRoutePredicate = `
|
||||
)
|
||||
`
|
||||
|
||||
const modelSharedPaidBuildSupportSortExpression = `(model_routes.provider = 'grok_build'
|
||||
AND EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = account.id AND ` + accountPaidBillingSignals + `)
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM provider_accounts peer
|
||||
JOIN account_model_capabilities peer_capability ON peer_capability.account_id = peer.id AND peer_capability.upstream_model = model_routes.upstream_model
|
||||
WHERE peer.provider = model_routes.provider
|
||||
AND peer.enabled = TRUE
|
||||
AND peer.auth_status = 'active'
|
||||
AND EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = peer.id AND ` + accountPaidBillingSignals + `)
|
||||
))`
|
||||
|
||||
const modelSharedPaidBuildSupportAvailabilityExpression = `(route.provider = 'grok_build'
|
||||
AND EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = account.id AND ` + accountPaidBillingSignals + `)
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM provider_accounts peer
|
||||
JOIN account_model_capabilities peer_capability ON peer_capability.account_id = peer.id AND peer_capability.upstream_model = route.upstream_model
|
||||
WHERE peer.provider = route.provider
|
||||
AND peer.enabled = TRUE
|
||||
AND peer.auth_status = 'active'
|
||||
AND EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = peer.id AND ` + accountPaidBillingSignals + `)
|
||||
))`
|
||||
|
||||
const (
|
||||
modelProviderPriorityExpression = "CASE model_routes.provider WHEN 'grok_build' THEN 0 WHEN 'grok_web' THEN 1 WHEN 'grok_console' THEN 2 ELSE 3 END"
|
||||
modelSupportSortExpression = `(SELECT COUNT(*) FROM provider_accounts account WHERE account.provider = model_routes.provider AND account.enabled = TRUE AND account.auth_status = 'active' AND (EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id AND binding.account_id = account.id) OR (NOT EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id) AND EXISTS (SELECT 1 FROM account_model_capabilities capability WHERE capability.account_id = account.id AND capability.upstream_model = model_routes.upstream_model))))`
|
||||
modelSupportSortExpression = `(SELECT COUNT(*) FROM provider_accounts account WHERE account.provider = model_routes.provider AND account.enabled = TRUE AND account.auth_status = 'active' AND (EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id AND binding.account_id = account.id) OR (NOT EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id) AND (EXISTS (SELECT 1 FROM account_model_capabilities capability WHERE capability.account_id = account.id AND capability.upstream_model = model_routes.upstream_model) OR ` + modelSharedPaidBuildSupportSortExpression + `))))`
|
||||
modelSyncedSortExpression = `(SELECT MAX(sync.last_success_at) FROM provider_accounts account JOIN account_model_sync_states sync ON sync.account_id = account.id WHERE account.provider = model_routes.provider AND account.enabled = TRUE AND account.auth_status = 'active')`
|
||||
)
|
||||
|
||||
@@ -612,7 +636,7 @@ func (r *ModelRepository) annotateAvailability(ctx context.Context, values []mod
|
||||
SELECT route.id AS route_id,
|
||||
CASE WHEN COUNT(DISTINCT binding.account_id) > 0
|
||||
THEN COUNT(DISTINCT CASE WHEN account.enabled = TRUE AND account.auth_status = ? AND binding.account_id IS NOT NULL THEN account.id END)
|
||||
ELSE COUNT(DISTINCT CASE WHEN account.enabled = TRUE AND account.auth_status = ? AND capability.account_id IS NOT NULL THEN account.id END)
|
||||
ELSE COUNT(DISTINCT CASE WHEN account.enabled = TRUE AND account.auth_status = ? AND (capability.account_id IS NOT NULL OR `+modelSharedPaidBuildSupportAvailabilityExpression+`) THEN account.id END)
|
||||
END AS supported_accounts,
|
||||
CASE WHEN COUNT(DISTINCT binding.account_id) > 0
|
||||
THEN COUNT(DISTINCT CASE WHEN account.enabled = TRUE AND account.auth_status = ? AND binding.account_id IS NOT NULL AND sync.last_success_at IS NOT NULL THEN account.id END)
|
||||
|
||||
@@ -300,14 +300,20 @@ func (a *Adapter) ListModels(ctx context.Context, credential account.Credential)
|
||||
return nil, fmt.Errorf("查询 Build Super 资格: %w", policyErr)
|
||||
}
|
||||
if super {
|
||||
models, status, listErr := a.listModelsAt(ctx, credential, accessToken, a.fallbackBaseURL())
|
||||
if listErr != nil {
|
||||
return nil, listErr
|
||||
}
|
||||
models, xaiStatus, xaiErr := a.listModelsAt(ctx, credential, accessToken, a.fallbackBaseURL())
|
||||
if models != nil {
|
||||
return models, nil
|
||||
}
|
||||
return nil, fmt.Errorf("上游模型接口返回 %d", status)
|
||||
// Super 任一端可用即视为有效。XAI 目录失败时允许退回 Build 目录;
|
||||
// 两端观察到的模型差异由共享 Super entitlement 在路由层统一。
|
||||
models, buildStatus, buildErr := a.listModelsAt(ctx, credential, accessToken, a.primaryBaseURL())
|
||||
if models != nil {
|
||||
return models, nil
|
||||
}
|
||||
if xaiErr != nil || buildErr != nil {
|
||||
return nil, fmt.Errorf("读取 Super 模型目录失败(XAI status=%d: %v;Build status=%d: %v)", xaiStatus, xaiErr, buildStatus, buildErr)
|
||||
}
|
||||
return nil, fmt.Errorf("上游模型接口返回 XAI %d,Build %d", xaiStatus, buildStatus)
|
||||
}
|
||||
|
||||
// Free/Unknown 仅访问 Build,禁止探测 XAI。
|
||||
|
||||
@@ -502,6 +502,31 @@ func TestListModelsSuperUsesUnifiedXAICatalog(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestListModelsSuperAcceptsPrimaryWhenXAICatalogIsForbidden(t *testing.T) {
|
||||
adapter, encrypted := newFallbackTestAdapter(t)
|
||||
marker := &fallbackMarkerStub{}
|
||||
adapter.SetFallbackMarker(marker)
|
||||
var primaryHits, fallbackHits atomic.Int32
|
||||
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
|
||||
if strings.Contains(request.URL.Host, "xai.test") {
|
||||
fallbackHits.Add(1)
|
||||
return jsonResponse(http.StatusForbidden, `{}`, request), nil
|
||||
}
|
||||
primaryHits.Add(1)
|
||||
return jsonResponse(http.StatusOK, `{"data":[{"id":"grok-4.5"}]}`, request), nil
|
||||
})
|
||||
models, err := adapter.ListModels(context.Background(), account.Credential{ID: 15, EncryptedAccessToken: encrypted})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(models) != 1 || models[0] != "grok-4.5" {
|
||||
t.Fatalf("models = %#v", models)
|
||||
}
|
||||
if primaryHits.Load() != 1 || fallbackHits.Load() != 1 || marker.policyCalls.Load() != 1 || marker.calls.Load() != 0 {
|
||||
t.Fatalf("primary=%d fallback=%d policy=%d marks=%d", primaryHits.Load(), fallbackHits.Load(), marker.policyCalls.Load(), marker.calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestListModelsFree403NeverUsesXAI(t *testing.T) {
|
||||
adapter, encrypted := newFallbackTestAdapter(t)
|
||||
marker := &fallbackMarkerStub{denied: true}
|
||||
|
||||
Reference in new issue
Block a user