test(grok): synchronize free-quota refresh tests

This commit is contained in:
lkon committed 2026-11-08 15:14:18 +08:00
1 parent 6b4b37db43
commit b74ed3cda4
2 files changed
+76 -52

No files matched your search

@@ -53,6 +53,45 @@ func (r *grokFreeQuotaUsageRepoStub) GetAccountWindowStatsBatch(_ context.Contex
return result, nil
}
func (r *grokFreeQuotaUsageRepoStub) snapshot() (int, []int64, time.Time) {
r.mu.Lock()
defer r.mu.Unlock()
return r.calls, append([]int64(nil), r.lastIDs...), r.start
}
// These tests own their caches and must not run in parallel when using a shared
// gateway cache. A repository call or cache write can precede the refresh's
// sweep and deferred cleanup; wait for all in-flight markers to disappear.
func waitGrokFreeQuotaRefresh(t *testing.T, cache *sync.Map) {
t.Helper()
root, ok := freeQuotaRefreshInFlight.Load(cache)
if !ok {
return
}
inFlight, ok := root.(*sync.Map)
require.True(t, ok)
require.NotNil(t, inFlight)
require.Eventually(t, func() bool {
idle := true
inFlight.Range(func(_, _ any) bool {
idle = false
return false
})
return idle
}, 2*time.Second, time.Millisecond, "quota refresh must finish before cache cleanup or mutation")
}
func isolateGrokFreeQuotaTestCache(t *testing.T, cache *sync.Map) {
t.Helper()
reset := func() {
waitGrokFreeQuotaRefresh(t, cache)
cache.Clear()
freeQuotaRefreshInFlight.Delete(cache)
}
reset()
t.Cleanup(reset)
}
func grokFreeQuotaTestConfig() *config.Config {
cfg := &config.Config{}
cfg.Gateway.Grok.FreeQuotaSoftGateEnabled = true
@@ -67,9 +106,8 @@ func TestFilterGrokFreeQuotaAccountsOnlyBlocksExplicitFreeOAuth(t *testing.T) {
repo := &grokFreeQuotaUsageRepoStub{stats: map[int64]*usagestats.AccountStats{
1: {Tokens: 475_000}, // 95% of 500k
}}
// Clear shared cache for deterministic unit tests.
openaiGrokFreeQuotaGateCache = sync.Map{}
scheduler := &defaultOpenAIAccountScheduler{service: &OpenAIGatewayService{cfg: grokFreeQuotaTestConfig(), usageLogRepo: repo}}
isolateGrokFreeQuotaTestCache(t, &scheduler.grokFreeQuotaGateCache)
accounts := []Account{
{ID: 1, Platform: PlatformGrok, Type: AccountTypeOAuth, Credentials: map[string]any{"subscription_tier": "FREE"}},
{ID: 2, Platform: PlatformGrok, Type: AccountTypeOAuth, Credentials: map[string]any{"subscription_tier": "PRO"}},
@@ -81,23 +119,21 @@ func TestFilterGrokFreeQuotaAccountsOnlyBlocksExplicitFreeOAuth(t *testing.T) {
filtered := scheduler.filterGrokFreeQuotaAccounts(context.Background(), accounts)
require.Equal(t, []int64{1, 2, 3, 4}, accountIDs(filtered), "miss fails open on hot path")
require.Eventually(t, func() bool {
repo.mu.Lock()
defer repo.mu.Unlock()
return repo.calls >= 1
}, 2*time.Second, 10*time.Millisecond)
waitGrokFreeQuotaRefresh(t, &scheduler.grokFreeQuotaGateCache)
// Second pass: uses refreshed cache and blocks over-gate free OAuth.
filtered = scheduler.filterGrokFreeQuotaAccounts(context.Background(), accounts)
require.Equal(t, []int64{2, 3, 4}, accountIDs(filtered), "paid and unknown fail-open; API-key free marker is not gated")
require.Equal(t, []int64{1}, repo.lastIDs, "paid, unknown, and API-key accounts must not enter the local free-tier query")
require.WithinDuration(t, time.Now().UTC().Add(-24*time.Hour), repo.start, time.Second)
calls, ids, start := repo.snapshot()
require.Equal(t, 1, calls)
require.Equal(t, []int64{1}, ids, "paid, unknown, and API-key accounts must not enter the local free-tier query")
require.WithinDuration(t, time.Now().UTC().Add(-24*time.Hour), start, time.Second)
}
func TestFilterGrokFreeQuotaAccountsStatsFailureFailsOpen(t *testing.T) {
repo := &grokFreeQuotaUsageRepoStub{err: errors.New("usage database unavailable")}
openaiGrokFreeQuotaGateCache = sync.Map{}
scheduler := &defaultOpenAIAccountScheduler{service: &OpenAIGatewayService{cfg: grokFreeQuotaTestConfig(), usageLogRepo: repo}}
isolateGrokFreeQuotaTestCache(t, &scheduler.grokFreeQuotaGateCache)
accounts := []Account{{
ID: 1, Platform: PlatformGrok, Type: AccountTypeOAuth,
Credentials: map[string]any{"subscription_tier": "free"},
@@ -105,15 +141,17 @@ func TestFilterGrokFreeQuotaAccountsStatsFailureFailsOpen(t *testing.T) {
filtered := scheduler.filterGrokFreeQuotaAccounts(context.Background(), accounts)
require.Equal(t, []int64{1}, accountIDs(filtered))
require.Eventually(t, func() bool {
repo.mu.Lock()
defer repo.mu.Unlock()
return repo.calls >= 1
}, 2*time.Second, 10*time.Millisecond)
waitGrokFreeQuotaRefresh(t, &scheduler.grokFreeQuotaGateCache)
cached, ok := scheduler.grokFreeQuotaGateCache.Load(int64(1))
require.True(t, ok, "failed refresh must publish a negative cache entry")
entry, ok := cached.(grokFreeQuotaGateCacheEntry)
require.True(t, ok)
require.False(t, entry.known)
// Negative cache entry keeps subsequent hot-path calls fail-open without thrash.
filtered = scheduler.filterGrokFreeQuotaAccounts(context.Background(), accounts)
require.Equal(t, []int64{1}, accountIDs(filtered))
require.Equal(t, 1, repo.calls)
calls, _, _ := repo.snapshot()
require.Equal(t, 1, calls)
}
func TestFilterGrokFreeQuotaAccountsUnknownTierFailOpen(t *testing.T) {
@@ -121,6 +159,7 @@ func TestFilterGrokFreeQuotaAccountsUnknownTierFailOpen(t *testing.T) {
1: {Tokens: 9_999_999},
}}
scheduler := &defaultOpenAIAccountScheduler{service: &OpenAIGatewayService{cfg: grokFreeQuotaTestConfig(), usageLogRepo: repo}}
isolateGrokFreeQuotaTestCache(t, &scheduler.grokFreeQuotaGateCache)
accounts := []Account{
{ID: 1, Platform: PlatformGrok, Type: AccountTypeOAuth},
{ID: 2, Platform: PlatformGrok, Type: AccountTypeOAuth, Credentials: map[string]any{"subscription_tier": "unknown"}},
@@ -129,15 +168,16 @@ func TestFilterGrokFreeQuotaAccountsUnknownTierFailOpen(t *testing.T) {
filtered := scheduler.filterGrokFreeQuotaAccounts(context.Background(), accounts)
require.Equal(t, []int64{1, 2, 3}, accountIDs(filtered))
require.Zero(t, repo.calls, "unknown/paid tiers must not query free-quota stats")
calls, _, _ := repo.snapshot()
require.Zero(t, calls, "unknown/paid tiers must not query free-quota stats")
}
func TestFilterGrokFreeQuotaAccountsRecoversAfterRollingUsageFalls(t *testing.T) {
repo := &grokFreeQuotaUsageRepoStub{stats: map[int64]*usagestats.AccountStats{
1: {Tokens: 490_000},
}}
openaiGrokFreeQuotaGateCache = sync.Map{}
scheduler := &defaultOpenAIAccountScheduler{service: &OpenAIGatewayService{cfg: grokFreeQuotaTestConfig(), usageLogRepo: repo}}
isolateGrokFreeQuotaTestCache(t, &scheduler.grokFreeQuotaGateCache)
accounts := []Account{{
ID: 1, Platform: PlatformGrok, Type: AccountTypeOAuth,
Credentials: map[string]any{"plan_type": "free"},
@@ -149,6 +189,7 @@ func TestFilterGrokFreeQuotaAccountsRecoversAfterRollingUsageFalls(t *testing.T)
filtered := scheduler.filterGrokFreeQuotaAccounts(context.Background(), accounts)
return len(filtered) == 0
}, 2*time.Second, 10*time.Millisecond)
waitGrokFreeQuotaRefresh(t, &scheduler.grokFreeQuotaGateCache)
repo.mu.Lock()
repo.stats[1] = &usagestats.AccountStats{Tokens: 100_000}
@@ -157,23 +198,22 @@ func TestFilterGrokFreeQuotaAccountsRecoversAfterRollingUsageFalls(t *testing.T)
require.Empty(t, scheduler.filterGrokFreeQuotaAccounts(context.Background(), accounts), "fresh cache keeps the soft-gate hold")
// Expire entry → miss fails open and schedules refresh with recovered usage.
// Clear in-flight markers so a refresh is allowed after we force-expire the entry.
if root, ok := freeQuotaRefreshInFlight.Load(&scheduler.grokFreeQuotaGateCache); ok {
if m, ok := root.(*sync.Map); ok {
m.Delete(int64(1))
}
}
callsBeforeExpire := repo.calls
callsBeforeExpire, _, _ := repo.snapshot()
scheduler.grokFreeQuotaGateCache.Store(int64(1), grokFreeQuotaGateCacheEntry{
tokens: 490_000, checkedAt: time.Now().Add(-2 * time.Minute), known: true, // TTL=60s → stale
})
// Hot path fail-open while refresh is in flight.
require.Equal(t, []int64{1}, accountIDs(scheduler.filterGrokFreeQuotaAccounts(context.Background(), accounts)))
require.Eventually(t, func() bool {
filtered := scheduler.filterGrokFreeQuotaAccounts(context.Background(), accounts)
return len(filtered) == 1 && filtered[0].ID == 1 &&
repo.calls > callsBeforeExpire
}, 2*time.Second, 10*time.Millisecond)
waitGrokFreeQuotaRefresh(t, &scheduler.grokFreeQuotaGateCache)
cached, ok := scheduler.grokFreeQuotaGateCache.Load(int64(1))
require.True(t, ok)
entry, ok := cached.(grokFreeQuotaGateCacheEntry)
require.True(t, ok)
require.True(t, entry.known)
require.Equal(t, int64(100_000), entry.tokens, "recovery must use refreshed usage, not a cache miss")
require.Equal(t, []int64{1}, accountIDs(scheduler.filterGrokFreeQuotaAccounts(context.Background(), accounts)))
calls, _, _ := repo.snapshot()
require.Equal(t, callsBeforeExpire+1, calls)
}
func TestResolveGrokFreeQuotaGateSettingsDefaultsToNinetyFivePercent(t *testing.T) {
@@ -198,7 +238,7 @@ func TestIsExplicitGrokFreeOAuthAccount_OnlyExactFree(t *testing.T) {
func TestOpenAIAccountSchedulerLoadBalanceAppliesGrokFreeQuotaGate(t *testing.T) {
cfg := grokFreeQuotaTestConfig()
cfg.RunMode = config.RunModeSimple
openaiGrokFreeQuotaGateCache = sync.Map{}
isolateGrokFreeQuotaTestCache(t, &openaiGrokFreeQuotaGateCache)
accounts := []Account{
{ID: 1, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, Concurrency: 1, Credentials: map[string]any{"subscription_tier": "free"}},
{ID: 2, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, Concurrency: 1, Credentials: map[string]any{"subscription_tier": "pro"}},
@@ -211,6 +251,7 @@ func TestOpenAIAccountSchedulerLoadBalanceAppliesGrokFreeQuotaGate(t *testing.T)
}},
}
scheduler := &defaultOpenAIAccountScheduler{service: svc, stats: newOpenAIAccountRuntimeStats()}
isolateGrokFreeQuotaTestCache(t, &scheduler.grokFreeQuotaGateCache)
// Warm cache via background refresh so load-balance sees the soft-gate.
_ = scheduler.filterGrokFreeQuotaAccounts(context.Background(), accounts)
@@ -238,8 +279,8 @@ func TestGrokFreeQuotaGateIsSchedulerOnlyAdminPathUnfiltered(t *testing.T) {
repo := &grokFreeQuotaUsageRepoStub{stats: map[int64]*usagestats.AccountStats{
9: {Tokens: 500_000},
}}
openaiGrokFreeQuotaGateCache = sync.Map{}
scheduler := &defaultOpenAIAccountScheduler{service: &OpenAIGatewayService{cfg: grokFreeQuotaTestConfig(), usageLogRepo: repo}}
isolateGrokFreeQuotaTestCache(t, &scheduler.grokFreeQuotaGateCache)
overGate := Account{ID: 9, Platform: PlatformGrok, Type: AccountTypeOAuth, Credentials: map[string]any{"subscription_tier": "FREE"}}
require.Eventually(t, func() bool {
_ = scheduler.filterGrokFreeQuotaAccounts(context.Background(), []Account{overGate})
@@ -284,6 +325,7 @@ func TestFilterGrokFreeQuotaAccountsEvictsDepartedAccounts(t *testing.T) {
1: {Tokens: 1_000},
}}
var cache sync.Map
isolateGrokFreeQuotaTestCache(t, &cache)
// Account 99 was scheduled long ago and no longer appears in any batch. Its
// entry must not survive a run that queries for a different account.
cache.Store(int64(99), grokFreeQuotaGateCacheEntry{tokens: 5, checkedAt: time.Now().UTC().Add(-2 * time.Hour), known: true})
@@ -8,7 +8,6 @@ import (
"io"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
@@ -108,16 +107,7 @@ func TestGetSchedulableAccount_AppliesGrokFreeSoftGate(t *testing.T) {
usageRepo := &grokFreeQuotaUsageRepoStub{stats: map[int64]*usagestats.AccountStats{
account.ID: {Tokens: 480_000}, // above 95% of 500k
}}
// Clear shared gateway free-gate cache so this test is deterministic.
gatewayGrokFreeQuotaGateCache.Range(func(key, _ any) bool {
gatewayGrokFreeQuotaGateCache.Delete(key)
return true
})
if root, ok := freeQuotaRefreshInFlight.Load(&gatewayGrokFreeQuotaGateCache); ok {
if m, ok := root.(*sync.Map); ok {
m.Delete(account.ID)
}
}
isolateGrokFreeQuotaTestCache(t, &gatewayGrokFreeQuotaGateCache)
svc := &GatewayService{
cfg: cfg,
accountRepo: repo,
@@ -155,15 +145,7 @@ func TestOpenAIGetSchedulableAccount_AppliesGrokFreeSoftGate(t *testing.T) {
usageRepo := &grokFreeQuotaUsageRepoStub{stats: map[int64]*usagestats.AccountStats{
account.ID: {Tokens: 480_000},
}}
openaiGrokFreeQuotaGateCache.Range(func(key, _ any) bool {
openaiGrokFreeQuotaGateCache.Delete(key)
return true
})
if root, ok := freeQuotaRefreshInFlight.Load(&openaiGrokFreeQuotaGateCache); ok {
if m, ok := root.(*sync.Map); ok {
m.Delete(account.ID)
}
}
isolateGrokFreeQuotaTestCache(t, &openaiGrokFreeQuotaGateCache)
svc := &OpenAIGatewayService{
cfg: cfg,
accountRepo: repo,