diff --git a/.github/workflows/issue817-grok-persistence.yml b/.github/workflows/issue817-grok-persistence.yml new file mode 100644 index 000000000000..6294b14f542a --- /dev/null +++ b/.github/workflows/issue817-grok-persistence.yml @@ -0,0 +1,238 @@ +name: Issue817 Grok persistence recovery + +on: + workflow_dispatch: + pull_request: + paths: + - 'backend/internal/service/account_test_service.go' + - 'backend/internal/service/grok_scheduled_test_recovery.go' + - 'backend/internal/service/grok_rate_limit_history.go' + - 'backend/internal/service/grok_rate_limit_history_test.go' + - 'backend/internal/service/scheduled_test_runner_service.go' + - 'backend/internal/service/scheduled_test_port.go' + - 'backend/internal/service/ratelimit_service.go' + - 'backend/internal/service/quality_quota_integration_helper.go' + - 'backend/internal/service/openai_gateway_grok.go' + - 'backend/internal/service/scheduled_test_service.go' + - 'backend/internal/service/grok_token_provider.go' + - 'backend/internal/pkg/xai/**' + - 'backend/internal/repository/account_repo.go' + - 'backend/internal/repository/account_repo_integration_test.go' + - 'backend/internal/repository/scheduler_cache.go' + - 'backend/internal/repository/scheduled_test_repo.go' + - 'backend/internal/repository/integration_harness_test.go' + - 'backend/go.mod' + - 'backend/go.sum' + - 'backend/internal/repository/grok_scheduled_persistence_integration_test.go' + - '.github/workflows/issue817-grok-persistence.yml' + - '.github/scripts/issue817-race-gate.sh' + +permissions: + contents: read + +concurrency: + group: issue817-grok-${{ github.event_name }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + grok-persistence: + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + behavior: [red, negative_red, backoff_red, edit_red, green] + services: + postgres: + image: postgres:18.1-alpine3.23 + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: sub2api_test + ports: ['5432:5432'] + options: >- + --health-cmd "pg_isready -U postgres -d sub2api_test" + --health-interval 5s --health-timeout 5s --health-retries 12 + redis: + image: redis:8.4-alpine + ports: ['6379:6379'] + options: >- + --health-cmd "redis-cli ping" + --health-interval 5s --health-timeout 5s --health-retries 12 + env: + SUB2API_TEST_POSTGRES_DSN: 'host=127.0.0.1 port=5432 dbname=sub2api_test user=postgres password=postgres sslmode=disable TimeZone=UTC' + SUB2API_TEST_REDIS_URL: 'redis://127.0.0.1:6379/0' + BEHAVIOR: ${{ matrix.behavior }} + CI: 'true' + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + - name: Pin candidate and old observer source + env: + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} + shell: bash + run: | + set -euo pipefail + mkdir -p evidence + git rev-parse HEAD | tee evidence/head.txt + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + if [ "$BEHAVIOR" != green ]; then + if [ "$BEHAVIOR" = red ]; then + original=45ebcb708867dd61caae10435d19d2df17cd41f3 + source=backend/internal/service/account_test_service.go + elif [ "$BEHAVIOR" = negative_red ]; then + original=e9e2d4ac9a18f9eeab510cfb2c4213e6041455d6 + source=backend/internal/repository/account_repo.go + elif [ "$BEHAVIOR" = backoff_red ]; then + original=48ae8cfef14dab52e90e5103057dc65f5d601dea + source=backend/internal/repository/account_repo.go + else + original=0e2b93a9c99f329748fc43f3f4f625a17c253db0 + source=backend/internal/repository/account_repo.go + fi + expected_blob="$(git rev-parse "$original:$source")" + printf '%s %s %s\n' "$original" "$source" "$expected_blob" > evidence/original-blob.txt + git show "$original:$source" > "$source" + test "$(git hash-object "$source")" = "$expected_blob" + git diff --stat > evidence/red-source-diff.txt + else + git diff --exit-code + fi + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Compile production packages without test tags + shell: bash + run: | + set -euo pipefail + (cd backend && go build ./internal/service ./internal/repository) > evidence/production-build.log 2>&1 + cat evidence/production-build.log + - name: Same oracle old observer RED and current GREEN + shell: bash + run: | + set -euo pipefail + pattern='^TestIssue817GrokScheduledRecoveryRequiresSavedResult$/(headerless_create|available_create)$' + children=(headerless_create available_create) + parent=TestIssue817GrokScheduledRecoveryRequiresSavedResult + diagnostic='Grok observer must keep the observed limit until result Create succeeds' + if [ "$BEHAVIOR" = negative_red ]; then + pattern='^TestIssue817GrokScheduledRecoveryRequiresSavedResult$/negative_(shorter_429|equal_429|exhausted_200)_auto_(off|on)_(saved|prune)$' + children=() + diagnostic='actual negative observation must survive deferred positive recovery' + fi + if [ "$BEHAVIOR" = green ]; then + pattern='^(TestIssue817GrokScheduledRecoveryRequiresSavedResult|TestIssue817GrokManualRecoveryRemainsImmediate|TestIssue817GrokNegativePreservesAdaptiveCooldown)$' + children+=(headerless_saved available_saved headerless_prune available_prune auto_recover_off_create auto_recover_off_saved 429_create 429_saved exhausted_200_create exhausted_200_saved failed_stream_create failed_stream_saved newer_generation owned_pause_and_model) + fi + if [ "$BEHAVIOR" = green ] || [ "$BEHAVIOR" = negative_red ]; then + for negative in shorter_429 equal_429 later_429 exhausted_200; do + for auto in off on; do + for fault in saved create prune; do + if [ "$BEHAVIOR" = green ] || { [ "$negative" != later_429 ] && [ "$fault" != create ]; }; then + children+=("negative_${negative}_auto_${auto}_${fault}") + fi + done + done + done + fi + if [ "$BEHAVIOR" = backoff_red ]; then + parent=TestIssue817GrokNegativePreservesAdaptiveCooldown + pattern='^TestIssue817GrokNegativePreservesAdaptiveCooldown$/(forty_minutes|thirty_minutes_exact|thirty_minutes_below)$' + diagnostic='actual negative must preserve the exact adaptive cooldown tier after expiry' + children=() + for tier in forty_minutes thirty_minutes_exact thirty_minutes_below; do + for negative in shorter_429 equal_429 exhausted_200; do + children+=("$tier/$negative") + done + done + fi + if [ "$BEHAVIOR" = edit_red ]; then + parent=TestIssue817GrokNegativePreservesAdaptiveCooldown + pattern='^TestIssue817GrokNegativePreservesAdaptiveCooldown$/(forty_minutes|thirty_minutes_exact|ten_minutes_exact)$' + diagnostic='stale configuration edit must preserve the latest negative generation and history' + children=() + for tier in forty_minutes thirty_minutes_exact ten_minutes_exact; do + for negative in shorter_429 equal_429 exhausted_200; do + children+=("$tier/$negative") + done + done + fi + set +e + bash .github/scripts/issue817-race-gate.sh "$BEHAVIOR" "$PWD" "$pattern" > evidence/grok-gate.log 2>&1 + result=$? + set -e + cat evidence/grok-gate.log + test "$(cat evidence/binary-identity-ok.txt)" = passed + if grep -Eiq 'no tests to run|--- SKIP:|panic:|WARNING: DATA RACE|race detected during execution|segmentation fault|SIGSEGV|\[build failed\]|setup failed' evidence/grok-gate.log; then + exit 1 + fi + if [ "$BEHAVIOR" != green ]; then + test "$result" -eq 1 + for child in "${children[@]}"; do + grep -F -- "--- FAIL: $parent/$child (" evidence/grok-gate.log + # Each child must reach its own named business assertion. + awk -v parent="$parent" -v child="$child" -v diagnostic="$diagnostic" ' + $0 ~ "=== RUN.*" parent "/" child "$" { active=1; next } + active && /=== RUN/ { active=0 } + active && index($0,diagnostic) { found=1 } + END { exit !found } + ' evidence/grok-gate.log + done + else + test "$result" -eq 0 + for child in "${children[@]}"; do + grep -F -- "--- PASS: TestIssue817GrokScheduledRecoveryRequiresSavedResult/$child (" evidence/grok-gate.log + done + grep -F -- '--- PASS: TestIssue817GrokManualRecoveryRemainsImmediate (' evidence/grok-gate.log + for mode in default text; do + grep -F -- "--- PASS: TestIssue817GrokManualRecoveryRemainsImmediate/$mode (" evidence/grok-gate.log + done + for tier in forty_minutes thirty_minutes_exact thirty_minutes_below ten_minutes_exact ten_minutes_below; do + for negative in shorter_429 equal_429 exhausted_200; do + grep -F -- "--- PASS: TestIssue817GrokNegativePreservesAdaptiveCooldown/$tier/$negative (" evidence/grok-gate.log + done + done + fi + - name: Retain merged SaveResult and quota contracts + if: matrix.behavior == 'green' + shell: bash + run: | + set -euo pipefail + pattern='^(TestIssue817SaveResultFailureDoesNotAcknowledge|TestIssue817ConnectivitySaveFailureDoesNotCompleteOrRecover|TestIssue817QuotaSkipPreservesPending5xxExecution)$' + (cd backend && go test -race -tags=integration ./internal/repository -run "$pattern" -count=1 -v -timeout=10m) > evidence/retained.log 2>&1 + cat evidence/retained.log + if grep -Eiq 'no tests to run|--- SKIP:|panic:|WARNING: DATA RACE|race detected during execution|SIGSEGV|\[build failed\]' evidence/retained.log; then + exit 1 + fi + for name in TestIssue817SaveResultFailureDoesNotAcknowledge TestIssue817ConnectivitySaveFailureDoesNotCompleteOrRecover TestIssue817QuotaSkipPreservesPending5xxExecution; do + grep -F -- "--- PASS: $name (" evidence/retained.log + done + pattern='^TestAccountRepoSuite$/(TestSetRateLimitedIfLaterDoesNotShortenReset|TestClearRateLimitIfObservedProtectsRearmed429Generation|TestGrokNegativeObservationAdvancesGenerationWithoutShorteningReset|TestGrokConfigurationEditRuntimeBoundary)$' + (cd backend && go test -race -tags=integration ./internal/repository -run "$pattern" -count=1 -v -timeout=10m) > evidence/generation-contracts.log 2>&1 + cat evidence/generation-contracts.log + if grep -Eiq 'no tests to run|--- SKIP:|panic:|WARNING: DATA RACE|race detected during execution|SIGSEGV|\[build failed\]' evidence/generation-contracts.log; then + exit 1 + fi + for name in TestSetRateLimitedIfLaterDoesNotShortenReset TestClearRateLimitIfObservedProtectsRearmed429Generation TestGrokNegativeObservationAdvancesGenerationWithoutShorteningReset TestGrokConfigurationEditRuntimeBoundary; do + grep -F -- "--- PASS: TestAccountRepoSuite/$name (" evidence/generation-contracts.log + done + for name in grok_oauth grok_apikey other_oauth; do + grep -F -- "--- PASS: TestAccountRepoSuite/TestGrokConfigurationEditRuntimeBoundary/$name (" evidence/generation-contracts.log + done + (cd backend && go test -race -tags=unit ./internal/service -run '^TestGrokAdaptiveCooldownRequiresMatchingHistory$' -count=1 -v -timeout=10m) > evidence/history-controls.log 2>&1 + cat evidence/history-controls.log + if grep -Eiq 'no tests to run|--- SKIP:|panic:|WARNING: DATA RACE|race detected during execution|SIGSEGV|\[build failed\]' evidence/history-controls.log; then + exit 1 + fi + for name in matching old_generation old_reset invalid_duration overflow zero legacy; do + grep -F -- "--- PASS: TestGrokAdaptiveCooldownRequiresMatchingHistory/$name (" evidence/history-controls.log + done + - uses: actions/upload-artifact@v7 + if: always() + with: + name: issue817-grok-${{ matrix.behavior }}-${{ github.run_id }} + path: evidence/ + if-no-files-found: error diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 5373657a330b..0ee0a834e8a5 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -635,6 +635,10 @@ func (r *accountRepository) updateAccount( account.Schedulable = updated.Schedulable account.Status = updated.Status account.ErrorMessage = derefString(updated.ErrorMessage) + if account.IsGrokOAuth() && !service.AccountPlatformChanging(ctx) { + account.RateLimitedAt = updated.RateLimitedAt + account.RateLimitResetAt = updated.RateLimitResetAt + } // 普通账号编辑(如 model_mapping / credentials)也需要立即刷新单账号快照, // 否则网关在 outbox worker 延迟或异常时仍可能读到旧配置。 if contextTx == nil { @@ -716,15 +720,21 @@ func (r *accountRepository) updateLockedAccount( } else { builder.ClearExpiresAt() } - if account.RateLimitedAt != nil { - builder.SetRateLimitedAt(*account.RateLimitedAt) - } else { - builder.ClearRateLimitedAt() - } - if account.RateLimitResetAt != nil { - builder.SetRateLimitResetAt(*account.RateLimitResetAt) - } else { - builder.ClearRateLimitResetAt() + // Ordinary Grok OAuth configuration edits do not own runtime generations. + // The row is locked and its history was merged above; leave the matching + // timestamps in that row intact. Explicit runtime setters/clears and platform + // transitions retain their separate write paths. + if !account.IsGrokOAuth() || service.AccountPlatformChanging(ctx) { + if account.RateLimitedAt != nil { + builder.SetRateLimitedAt(*account.RateLimitedAt) + } else { + builder.ClearRateLimitedAt() + } + if account.RateLimitResetAt != nil { + builder.SetRateLimitResetAt(*account.RateLimitResetAt) + } else { + builder.ClearRateLimitResetAt() + } } if account.OverloadUntil != nil { builder.SetOverloadUntil(*account.OverloadUntil) @@ -1079,7 +1089,7 @@ func lockAndMergeAccountProbeExtra( // The fork already reads the complete extra object under this row lock for // ticket, quality and admission ownership. Use that same snapshot for Grok // managed state, preserving the other owners and the query contract. - for _, key := range []string{"grok_observed_models", service.UpstreamModelMetadataExtraKey, service.UpstreamModelSyncExtraKey} { + for _, key := range []string{"grok_observed_models", service.GrokRateLimitHistoryExtraKey, service.UpstreamModelMetadataExtraKey, service.UpstreamModelSyncExtraKey} { delete(extra, key) if value, ok := currentExtra[key]; ok && value != nil { if extra == nil { @@ -2845,20 +2855,44 @@ func (r *accountRepository) SetRateLimited(ctx context.Context, id int64, resetA // SetRateLimitedIfLater atomically extends an account-level rate limit. Grok // requests may finish concurrently, so an older response must not overwrite a -// later reset boundary observed by another request or instance. +// later reset boundary observed by another request or instance. Every Grok OAuth +// negative also advances the recovery generation, even without extending reset. func (r *accountRepository) SetRateLimitedIfLater(ctx context.Context, id int64, resetAt time.Time) error { + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.SetRateLimitedIfLater(ctx, id, resetAt) + } now := time.Now() - updated, err := r.client.Account.Update(). - Where( - dbaccount.IDEQ(id), - dbaccount.Or( - dbaccount.RateLimitResetAtIsNil(), - dbaccount.RateLimitResetAtLT(resetAt), - ), - ). - SetRateLimitedAt(now). - SetRateLimitResetAt(resetAt). - Save(ctx) + // One row update serializes observations across replicas. Using only a Go + // clock could repeat a timestamp; advance at least one PostgreSQL microsecond + // beyond the locked generation so a deferred positive can never match it. + // Keep adaptive cooldown duration separate from the recovery generation. + // Lock before deriving either value, and bind history to the exact new pair + // so an external clear/re-arm cannot inherit another cooldown's evidence. + result, err := r.client.ExecContext(ctx, `WITH observed AS MATERIALIZED ( + SELECT id,platform,type,rate_limited_at,rate_limit_reset_at,extra FROM accounts + WHERE id=$1 AND deleted_at IS NULL AND + (rate_limit_reset_at IS NULL OR rate_limit_reset_at<$2 OR (platform='grok' AND type='oauth')) FOR UPDATE + ), next AS MATERIALIZED ( + SELECT *,CASE WHEN platform='grok' AND type='oauth' + THEN GREATEST(clock_timestamp(),rate_limited_at+interval '1 microsecond') ELSE $3 END AS generation, + GREATEST(rate_limit_reset_at,$2::timestamptz) AS boundary FROM observed + ) UPDATE accounts a SET rate_limited_at=n.generation,rate_limit_reset_at=n.boundary,updated_at=$3, + extra=CASE WHEN n.platform='grok' AND n.type='oauth' THEN + jsonb_set(COALESCE(n.extra,'{}'::jsonb),ARRAY[$4]::text[],jsonb_build_object( + 'generation_us',((extract(epoch FROM n.generation)*1000000)::bigint)::text, + 'reset_us',((extract(epoch FROM n.boundary)*1000000)::bigint)::text, + 'cooldown_us',CASE WHEN n.rate_limited_at IS NOT NULL AND n.rate_limit_reset_at>=$2 THEN + CASE WHEN n.extra->$4->>'generation_us'=((extract(epoch FROM n.rate_limited_at)*1000000)::bigint)::text + AND n.extra->$4->>'reset_us'=((extract(epoch FROM n.rate_limit_reset_at)*1000000)::bigint)::text + AND n.extra->$4->>'cooldown_us' ~ '^[1-9][0-9]{0,15}$' + THEN n.extra->$4->>'cooldown_us' + ELSE ((extract(epoch FROM (n.rate_limit_reset_at-n.rate_limited_at))*1000000)::bigint)::text END + ELSE ((extract(epoch FROM (n.boundary-n.generation))*1000000)::bigint)::text END),true) + ELSE n.extra END FROM next n WHERE a.id=n.id`, id, resetAt, now, service.GrokRateLimitHistoryExtraKey) + if err != nil { + return err + } + updated, err := result.RowsAffected() if err != nil { return err } diff --git a/backend/internal/repository/account_repo_integration_test.go b/backend/internal/repository/account_repo_integration_test.go index a629cb2a125c..4803078bc2a5 100644 --- a/backend/internal/repository/account_repo_integration_test.go +++ b/backend/internal/repository/account_repo_integration_test.go @@ -905,12 +905,17 @@ func (s *AccountRepoSuite) TestSetRateLimitedIfLaterDoesNotShortenReset() { s.repo.schedulerCache = cacheRecorder s.Require().NoError(s.repo.SetRateLimitedIfLater(s.ctx, account.ID, later)) + before, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + s.Require().NotNil(before.RateLimitedAt) s.Require().NoError(s.repo.SetRateLimitedIfLater(s.ctx, account.ID, earlier)) got, err := s.repo.GetByID(s.ctx, account.ID) s.Require().NoError(err) s.Require().NotNil(got.RateLimitResetAt) s.Require().WithinDuration(later, *got.RateLimitResetAt, time.Second) + s.Require().NotNil(got.RateLimitedAt) + s.Require().True(before.RateLimitedAt.Equal(*got.RateLimitedAt), "non-Grok shorter observations retain the existing no-op behavior") s.Require().Len(cacheRecorder.setAccounts, 2) s.Require().NotNil(cacheRecorder.setAccounts[1].RateLimitResetAt) s.Require().WithinDuration(later, *cacheRecorder.setAccounts[1].RateLimitResetAt, time.Second) @@ -966,6 +971,76 @@ func (s *AccountRepoSuite) TestClearRateLimitIfObservedProtectsRearmed429Generat s.Require().WithinDuration(rearmedReset, *retyped.RateLimitResetAt, time.Second) } +func (s *AccountRepoSuite) TestGrokNegativeObservationAdvancesGenerationWithoutShorteningReset() { + account := mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "grok-negative-generation", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth, + }) + reset := time.Now().Add(time.Hour).UTC().Truncate(time.Microsecond) + // A future observed timestamp forces strict advancement independent of + // clock precision/skew. Two repository instances share only the database. + observed := time.Now().Add(time.Minute).UTC().Truncate(time.Microsecond) + _, err := s.client.Account.UpdateOneID(account.ID).SetRateLimitedAt(observed).SetRateLimitResetAt(reset).Save(s.ctx) + s.Require().NoError(err) + other := newAccountRepositoryWithSQL(s.client, s.repo.sql, nil) + for _, candidate := range []time.Time{reset.Add(-time.Minute), reset} { + s.Require().NoError(other.SetRateLimitedIfLater(s.ctx, account.ID, candidate)) + current, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + s.Require().NotNil(current.RateLimitedAt) + s.Require().NotNil(current.RateLimitResetAt) + s.Require().True(current.RateLimitedAt.After(observed), "Grok negative must advance even with equal/shorter reset and a future prior clock") + s.Require().True(reset.Equal(*current.RateLimitResetAt)) + cleared, err := s.repo.ClearRateLimitIfObserved(s.ctx, account.ID, observed, reset) + s.Require().NoError(err) + s.Require().False(cleared) + observed = *current.RateLimitedAt + } +} + +func (s *AccountRepoSuite) TestGrokConfigurationEditRuntimeBoundary() { + for _, tc := range []struct { + name string + platform string + kind string + }{ + {name: "grok_oauth", platform: service.PlatformGrok, kind: service.AccountTypeOAuth}, + {name: "grok_apikey", platform: service.PlatformGrok, kind: service.AccountTypeAPIKey}, + {name: "other_oauth", platform: service.PlatformAnthropic, kind: service.AccountTypeOAuth}, + } { + s.Run(tc.name, func() { + account := mustCreateAccount(s.T(), s.client, &service.Account{Name: tc.name, Platform: tc.platform, Type: tc.kind}) + account, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + reset := time.Now().Add(time.Hour).UTC().Truncate(time.Microsecond) + s.Require().NoError(s.repo.SetRateLimited(s.ctx, account.ID, reset)) + current, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + account.Name = "configuration only" + s.Require().NoError(s.repo.Update(s.ctx, account)) + stored, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + if tc.platform == service.PlatformGrok && tc.kind == service.AccountTypeOAuth { + s.Require().NotNil(stored.RateLimitedAt) + s.Require().True(current.RateLimitedAt.Equal(*stored.RateLimitedAt)) + s.Require().True(reset.Equal(*stored.RateLimitResetAt)) + // An explicitly validated platform transition retains its caller + // write semantics rather than inheriting the old Grok runtime. + stored.Platform = service.PlatformAnthropic + stored.Type = service.AccountTypeAPIKey + stored.RateLimitedAt, stored.RateLimitResetAt = nil, nil + s.Require().NoError(s.repo.Update(service.WithAccountPlatformChange(s.ctx), stored)) + stored, err = s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + s.Require().Nil(stored.RateLimitedAt) + s.Require().Nil(stored.RateLimitResetAt) + } else { + s.Require().Nil(stored.RateLimitedAt, "non-Grok OAuth edit semantics remain unchanged") + s.Require().Nil(stored.RateLimitResetAt) + } + }) + } +} + func (s *AccountRepoSuite) TestClearRateLimit() { account := mustCreateAccount(s.T(), s.client, &service.Account{Name: "acc-clear"}) until := time.Now().Add(1 * time.Hour) diff --git a/backend/internal/repository/grok_scheduled_persistence_integration_test.go b/backend/internal/repository/grok_scheduled_persistence_integration_test.go new file mode 100644 index 000000000000..d822c4dd5544 --- /dev/null +++ b/backend/internal/repository/grok_scheduled_persistence_integration_test.go @@ -0,0 +1,474 @@ +//go:build integration + +package repository + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "net/url" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// Replace only the remote endpoint, keeping real HTTP, SSE parsing, observer, +// repository CAS and result insertion. No provider or OAuth refresh is called. +type issue817GrokHTTP struct { + service.HTTPUpstream + client *http.Client + target *url.URL + negative bool +} + +func (u *issue817GrokHTTP) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + local := req.Clone(req.Context()) + endpoint := *req.URL + endpoint.Scheme, endpoint.Host = u.target.Scheme, u.target.Host + local.URL = &endpoint + if u.negative { + local.Header.Set("X-Issue817-Negative", "true") + } + return u.client.Do(local) +} + +type issue817GrokResults struct { + service.ScheduledTestResultRepository + beforeCreate func() + failCreate bool + failPrune bool +} + +func (r *issue817GrokResults) Create(ctx context.Context, result *service.ScheduledTestResult) (*service.ScheduledTestResult, error) { + r.beforeCreate() + if r.failCreate { + return nil, errors.New("issue817 Grok injected Create failure") + } + return r.ScheduledTestResultRepository.Create(ctx, result) +} + +func (r *issue817GrokResults) PruneOldResults(ctx context.Context, planID int64, keep int) error { + if r.failPrune { + return errors.New("issue817 Grok injected prune failure") + } + return r.ScheduledTestResultRepository.PruneOldResults(ctx, planID, keep) +} + +func TestIssue817GrokScheduledRecoveryRequiresSavedResult(t *testing.T) { + type scenario struct { + name string + response string + fault string + autoRecover bool + newer bool + owned bool + negative string + } + cases := []scenario{ + {name: "headerless_create", response: "headerless", fault: "create", autoRecover: true}, + {name: "available_create", response: "available", fault: "create", autoRecover: true}, + {name: "headerless_saved", response: "headerless", autoRecover: true}, + {name: "available_saved", response: "available", autoRecover: true}, + {name: "headerless_prune", response: "headerless", fault: "prune", autoRecover: true}, + {name: "available_prune", response: "available", fault: "prune", autoRecover: true}, + {name: "auto_recover_off_create", response: "available", fault: "create"}, + {name: "auto_recover_off_saved", response: "available"}, + {name: "429_create", response: "429", fault: "create", autoRecover: true}, + {name: "429_saved", response: "429", autoRecover: true}, + {name: "exhausted_200_create", response: "exhausted", fault: "create", autoRecover: true}, + {name: "exhausted_200_saved", response: "exhausted", autoRecover: true}, + {name: "failed_stream_create", response: "failed_stream", fault: "create", autoRecover: true}, + {name: "failed_stream_saved", response: "failed_stream", autoRecover: true}, + {name: "newer_generation", response: "available", autoRecover: true, newer: true}, + {name: "owned_pause_and_model", response: "available", autoRecover: true, owned: true}, + } + for _, negative := range []string{"shorter_429", "equal_429", "later_429", "exhausted_200"} { + for _, auto := range []bool{false, true} { + mode := "auto_off" + if auto { + mode = "auto_on" + } + for _, fault := range []string{"saved", "create", "prune"} { + cases = append(cases, scenario{name: "negative_" + negative + "_" + mode + "_" + fault, + response: "available", negative: negative, autoRecover: auto, fault: fault, owned: true}) + } + } + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + accounts := NewAccountRepository(integrationEntClient, integrationDB, nil) + plans := NewScheduledTestPlanRepository(integrationDB) + now := time.Now().UTC().Truncate(time.Microsecond) + limitedAt, resetAt := now.Add(-time.Minute), now.Add(10*time.Minute) + credentials, err := json.Marshal(map[string]any{"access_token": "offline-access", "refresh_token": "offline-refresh", "expires_at": now.Add(time.Hour).Format(time.RFC3339)}) + require.NoError(t, err) + var accountID int64 + require.NoError(t, integrationDB.QueryRow(`INSERT INTO accounts(name,platform,type,status,schedulable,credentials,rate_limited_at,rate_limit_reset_at) + VALUES('issue817 Grok offline','grok','oauth','active',true,$1::jsonb,$2,$3) RETURNING id`, string(credentials), limitedAt, resetAt).Scan(&accountID)) + t.Cleanup(func() { + _, _ = integrationDB.Exec(`DELETE FROM scheduler_outbox WHERE account_id=$1`, accountID) + _, _ = integrationDB.Exec(`DELETE FROM accounts WHERE id=$1`, accountID) + }) + due, previous := now.Add(-time.Minute), now.Add(-time.Hour) + plan, err := plans.Create(ctx, &service.ScheduledTestPlan{AccountID: accountID, ModelID: "grok-4.5", CronExpression: "0 * * * *", Enabled: true, MaxResults: 10, AutoRecover: tc.autoRecover, NextRunAt: &due}) + require.NoError(t, err) + _, err = integrationDB.Exec(`UPDATE scheduled_test_plans SET last_run_at=$2 WHERE id=$1`, plan.ID, previous) + require.NoError(t, err) + if tc.owned { + require.NoError(t, accounts.SetTempUnschedulable(ctx, accountID, now.Add(time.Hour), "quality_rule:817")) + require.NoError(t, accounts.SetModelRateLimit(ctx, accountID, "grok-heavy", now.Add(time.Hour), "quality_rule:817")) + } + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + if r.URL.Path != "/v1/responses" || r.Method != http.MethodPost { + http.Error(w, "unexpected offline route", http.StatusBadRequest) + return + } + w.Header().Set("Content-Type", "text/event-stream") + if r.Header.Get("X-Issue817-Negative") == "true" { + reset := resetAt + switch tc.negative { + case "shorter_429": + reset = now.Add(time.Minute) + w.Header().Set("Retry-After", "60") + case "later_429": + reset = resetAt.Add(time.Hour) + } + w.Header().Set("X-Ratelimit-Limit-Requests", "10") + w.Header().Set("X-Ratelimit-Remaining-Requests", "0") + w.Header().Set("X-Ratelimit-Reset-Requests", reset.Format(time.RFC3339Nano)) + if tc.negative != "exhausted_200" { + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(`{"error":{"message":"actual concurrent negative"}}`)) + return + } + _, _ = w.Write([]byte("data: {\"type\":\"response.completed\"}\n\n")) + return + } + if tc.response == "available" || tc.response == "exhausted" { + w.Header().Set("X-Ratelimit-Limit-Requests", "10") + remaining := "9" + if tc.response == "exhausted" { + remaining = "0" + } + w.Header().Set("X-Ratelimit-Remaining-Requests", remaining) + w.Header().Set("X-Ratelimit-Reset-Requests", "3600") + } + if tc.response == "429" { + w.Header().Set("Retry-After", "3600") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(`{"error":{"message":"rate limited"}}`)) + return + } + if tc.response == "failed_stream" { + _, _ = w.Write([]byte("data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"message\":\"offline stream failed\"}}}\n\n")) + return + } + _, _ = w.Write([]byte("data: {\"type\":\"response.output_text.delta\",\"delta\":\"ok\"}\n\ndata: {\"type\":\"response.completed\"}\n\n")) + })) + t.Cleanup(server.Close) + target, err := url.Parse(server.URL) + require.NoError(t, err) + results := &issue817GrokResults{ScheduledTestResultRepository: NewScheduledTestResultRepository(integrationDB), failCreate: tc.fault == "create", failPrune: tc.fault == "prune"} + var negativeExecutor *service.AccountTestService + var negativeLimitedAt, negativeResetAt time.Time + results.beforeCreate = func() { + require.Equal(t, int32(1), calls.Load(), "real HTTP must reach the observer before Create") + account, err := accounts.GetByID(ctx, accountID) + require.NoError(t, err) + require.NotNil(t, account.RateLimitedAt, "Grok observer must keep the observed limit until result Create succeeds") + require.NotNil(t, account.RateLimitResetAt) + if tc.response != "429" && tc.response != "exhausted" { + require.True(t, limitedAt.Equal(*account.RateLimitedAt)) + require.True(t, resetAt.Equal(*account.RateLimitResetAt)) + } else { + require.True(t, account.RateLimitResetAt.After(resetAt), "negative quota observation must persist before Create") + } + if tc.response == "available" || tc.response == "exhausted" { + require.NotNil(t, account.Extra["grok_usage_snapshot"], "quota observation remains enabled") + } + if tc.newer { + // Clear/re-arm with a shorter reset: both timestamps fence stale success. + limitedAt, resetAt = now.Add(time.Second), now.Add(5*time.Minute) + _, err = integrationDB.Exec(`UPDATE accounts SET rate_limited_at=$2,rate_limit_reset_at=$3 WHERE id=$1`, accountID, limitedAt, resetAt) + require.NoError(t, err) + } + if tc.negative != "" { + // A second executor/repository performs an actual negative HTTP + // observation while the scheduled positive is awaiting Create. + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/offline/concurrent-test", nil) + negativeErr := negativeExecutor.TestAccountConnection(c, accountID, "grok-4.5", "", service.AccountTestModeDefault) + if tc.negative == "exhausted_200" { + require.NoError(t, negativeErr) + } else { + require.ErrorContains(t, negativeErr, "429") + } + negative, err := accounts.GetByID(ctx, accountID) + require.NoError(t, err) + require.NotNil(t, negative.RateLimitedAt) + require.NotNil(t, negative.RateLimitResetAt) + negativeLimitedAt, negativeResetAt = *negative.RateLimitedAt, *negative.RateLimitResetAt + if tc.negative == "later_429" { + require.True(t, negativeResetAt.After(resetAt)) + } else { + require.True(t, resetAt.Equal(negativeResetAt), "negative observation must not shorten the existing reset") + } + } + } + scheduled := service.ProvideScheduledTestService(plans, results, nil, nil) + runner, _ := service.NewGrokConnectivityRunnerForTesting(scheduled, accounts, &issue817GrokHTTP{client: server.Client(), target: target}) + _, negativeExecutor = service.NewGrokConnectivityRunnerForTesting(scheduled, NewAccountRepository(integrationEntClient, integrationDB, nil), + &issue817GrokHTTP{client: server.Client(), target: target, negative: true}) + require.Equal(t, tc.fault != "create", runner.RunQuotaScheduledPlanForTesting(ctx, plan)) + expectedCalls := int32(1) + if tc.negative != "" { + expectedCalls++ + } + require.Equal(t, expectedCalls, calls.Load(), "only the planned probe and explicit negative may run") + account, err := accounts.GetByID(ctx, accountID) + require.NoError(t, err) + positive := tc.response == "headerless" || tc.response == "available" + if tc.negative != "" { + require.NotNil(t, account.RateLimitedAt, "actual negative observation must survive deferred positive recovery") + require.NotNil(t, account.RateLimitResetAt) + require.True(t, negativeLimitedAt.Equal(*account.RateLimitedAt)) + require.True(t, negativeResetAt.Equal(*account.RateLimitResetAt)) + require.True(t, negativeLimitedAt.After(limitedAt), "every actual negative must advance the recovery generation") + } else if positive && tc.fault != "create" && !tc.newer { + require.Nil(t, account.RateLimitedAt) + require.Nil(t, account.RateLimitResetAt) + } else { + require.NotNil(t, account.RateLimitedAt) + require.NotNil(t, account.RateLimitResetAt) + if tc.response != "429" && tc.response != "exhausted" { + require.True(t, limitedAt.Equal(*account.RateLimitedAt)) + require.True(t, resetAt.Equal(*account.RateLimitResetAt)) + } + } + if tc.owned { + require.NotNil(t, account.TempUnschedulableUntil) + require.Equal(t, "quality_rule:817", account.TempUnschedulableReason) + var owner string + require.NoError(t, integrationDB.QueryRow(`SELECT extra->'model_rate_limits'->'grok-heavy'->>'reason' FROM accounts WHERE id=$1`, accountID).Scan(&owner)) + require.Equal(t, "quality_rule:817", owner) + } + stored, err := results.ListByPlanID(ctx, plan.ID, 10) + require.NoError(t, err) + current, err := plans.GetByID(ctx, plan.ID) + require.NoError(t, err) + if tc.fault == "create" { + require.Empty(t, stored) + require.True(t, previous.Equal(*current.LastRunAt)) + require.True(t, due.Equal(*current.NextRunAt)) + } else { + require.Len(t, stored, 1) + expectedStatus := "success" + if tc.response == "429" || tc.response == "failed_stream" { + expectedStatus = "failed" + } + require.Equal(t, expectedStatus, stored[0].Status) + encoded, err := json.Marshal(stored[0]) + require.NoError(t, err) + require.NotContains(t, string(encoded), "grokRecovery", "runtime recovery evidence is not an API/history field") + require.True(t, current.LastRunAt.After(previous)) + } + }) + } +} + +func TestIssue817GrokManualRecoveryRemainsImmediate(t *testing.T) { + // The same real transport and observer retain default/manual recovery; no + // scheduled context or SaveResult gate is injected into the admin path. + for _, mode := range []string{service.AccountTestModeDefault, service.AccountTestModeGrokText} { + t.Run(mode, func(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC().Truncate(time.Microsecond) + var id int64 + credentials, err := json.Marshal(map[string]any{"access_token": "offline-access", "refresh_token": "offline-refresh", "expires_at": now.Add(time.Hour).Format(time.RFC3339)}) + require.NoError(t, err) + require.NoError(t, integrationDB.QueryRow(`INSERT INTO accounts(name,platform,type,status,schedulable,credentials,rate_limited_at,rate_limit_reset_at) + VALUES('issue817 manual','grok','oauth','active',true,$1::jsonb,$2,$3) RETURNING id`, string(credentials), now.Add(-time.Minute), now.Add(time.Hour)).Scan(&id)) + t.Cleanup(func() { + _, _ = integrationDB.Exec(`DELETE FROM scheduler_outbox WHERE account_id=$1`, id) + _, _ = integrationDB.Exec(`DELETE FROM accounts WHERE id=$1`, id) + }) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte("data: {\"type\":\"response.completed\"}\n\n")) + })) + t.Cleanup(server.Close) + target, err := url.Parse(server.URL) + require.NoError(t, err) + accounts := NewAccountRepository(integrationEntClient, integrationDB, nil) + scheduled := service.NewScheduledTestService(NewScheduledTestPlanRepository(integrationDB), NewScheduledTestResultRepository(integrationDB)) + _, executor := service.NewGrokConnectivityRunnerForTesting(scheduled, accounts, &issue817GrokHTTP{client: server.Client(), target: target}) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/offline/admin/test", nil) + require.NoError(t, executor.TestAccountConnection(c, id, "grok-4.5", "", mode)) + account, err := accounts.GetByID(ctx, id) + require.NoError(t, err) + require.Nil(t, account.RateLimitedAt) + require.Nil(t, account.RateLimitResetAt) + }) + } +} + +func TestIssue817GrokNegativePreservesAdaptiveCooldown(t *testing.T) { + for _, tc := range []struct { + name string + previous time.Duration + next time.Duration + }{ + {name: "forty_minutes", previous: 40 * time.Minute, next: time.Hour}, + {name: "thirty_minutes_exact", previous: 30 * time.Minute, next: time.Hour}, + {name: "thirty_minutes_below", previous: 30*time.Minute - time.Microsecond, next: 30 * time.Minute}, + {name: "ten_minutes_exact", previous: 10 * time.Minute, next: 30 * time.Minute}, + {name: "ten_minutes_below", previous: 10*time.Minute - time.Microsecond, next: 10 * time.Minute}, + } { + for _, negative := range []string{"shorter_429", "equal_429", "exhausted_200"} { + t.Run(tc.name+"/"+negative, func(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC().Truncate(time.Microsecond) + reset := now.Add(5 * time.Minute) + started := reset.Add(-tc.previous) + credentials, err := json.Marshal(map[string]any{"access_token": "offline-access", "refresh_token": "offline-refresh", "expires_at": now.Add(time.Hour).Format(time.RFC3339)}) + require.NoError(t, err) + var id int64 + require.NoError(t, integrationDB.QueryRow(`INSERT INTO accounts(name,platform,type,status,schedulable,credentials,rate_limited_at,rate_limit_reset_at) + VALUES('issue817 backoff','grok','oauth','active',true,$1::jsonb,$2,$3) RETURNING id`, string(credentials), started, reset).Scan(&id)) + t.Cleanup(func() { + _, _ = integrationDB.Exec(`DELETE FROM scheduler_outbox WHERE account_id=$1`, id) + _, _ = integrationDB.Exec(`DELETE FROM accounts WHERE id=$1`, id) + }) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + boundary := reset + if negative == "shorter_429" { + boundary = now.Add(time.Minute) + w.Header().Set("Retry-After", "60") + } + w.Header().Set("X-Ratelimit-Limit-Requests", "10") + w.Header().Set("X-Ratelimit-Remaining-Requests", "0") + w.Header().Set("X-Ratelimit-Reset-Requests", boundary.Format(time.RFC3339Nano)) + if negative != "exhausted_200" { + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(`{"error":{"message":"offline negative backoff observation"}}`)) + return + } + _, _ = w.Write([]byte("data: {\"type\":\"response.completed\"}\n\n")) + })) + t.Cleanup(server.Close) + target, err := url.Parse(server.URL) + require.NoError(t, err) + accounts := NewAccountRepository(integrationEntClient, integrationDB, nil) + scheduled := service.NewScheduledTestService(NewScheduledTestPlanRepository(integrationDB), NewScheduledTestResultRepository(integrationDB)) + _, executor := service.NewGrokConnectivityRunnerForTesting(scheduled, accounts, &issue817GrokHTTP{client: server.Client(), target: target}) + previousGeneration := started + var staleEdit *service.Account + var staleBillingEdit *service.Account + for observation := range 2 { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/offline/backoff-test", nil) + err = executor.TestAccountConnection(c, id, "grok-4.5", "", service.AccountTestModeDefault) + if negative == "exhausted_200" { + require.NoError(t, err) + } else { + require.ErrorContains(t, err, "429") + } + account, err := accounts.GetByID(ctx, id) + require.NoError(t, err) + require.NotNil(t, account.RateLimitedAt) + require.NotNil(t, account.RateLimitResetAt) + require.True(t, account.RateLimitedAt.After(previousGeneration)) + require.True(t, reset.Equal(*account.RateLimitResetAt)) + afterExpiry := reset.Add(time.Second) + next, limited := service.GrokRepeated429ResetForTesting(account, afterExpiry) + require.True(t, limited) + require.True(t, afterExpiry.Add(tc.next).Equal(next), "actual negative must preserve the exact adaptive cooldown tier after expiry") + previousGeneration = *account.RateLimitedAt + if observation == 0 { + // An actual name edit reads G1 before the next HTTP negative + // commits G2. Saving this snapshot must not resurrect G1. + staleEdit = account + billingSnapshot := *account + staleBillingEdit = &billingSnapshot + } + } + account, err := accounts.GetByID(ctx, id) + require.NoError(t, err) + generation := *account.RateLimitedAt + history := account.Extra[service.GrokRateLimitHistoryExtraKey] + staleGeneration := *staleEdit.RateLimitedAt + staleEdit.Name = "stale name edit after G2" + require.NoError(t, accounts.Update(ctx, staleEdit)) + account, err = accounts.GetByID(ctx, id) + require.NoError(t, err) + require.NotNil(t, account.RateLimitedAt) + require.NotNil(t, account.RateLimitResetAt) + require.True(t, generation.Equal(*account.RateLimitedAt), "stale configuration edit must preserve the latest negative generation and history") + require.Equal(t, "stale name edit after G2", account.Name) + require.True(t, reset.Equal(*account.RateLimitResetAt)) + require.Equal(t, history, account.Extra[service.GrokRateLimitHistoryExtraKey]) + require.True(t, generation.Equal(*staleEdit.RateLimitedAt), "the returned edit snapshot must reflect the committed generation") + cleared, err := accounts.(*accountRepository).ClearRateLimitIfObserved(ctx, id, staleGeneration, reset) + require.NoError(t, err) + require.False(t, cleared, "a positive that observed G1 cannot clear G2 after a name edit") + // The admin path normally uses the billing-settings capability. + staleBillingEdit.Name = "stale billing-settings name edit" + require.NoError(t, accounts.(service.AccountBillingSettingsRepository).UpdateWithAccountBillingSettings(ctx, staleBillingEdit, nil, nil, nil)) + account, err = accounts.GetByID(ctx, id) + require.NoError(t, err) + require.True(t, generation.Equal(*account.RateLimitedAt)) + require.Equal(t, history, account.Extra[service.GrokRateLimitHistoryExtraKey]) + afterEditExpiry := reset.Add(time.Second) + afterEditNext, limited := service.GrokRepeated429ResetForTesting(account, afterEditExpiry) + require.True(t, limited) + require.True(t, afterEditExpiry.Add(tc.next).Equal(afterEditNext), "stale configuration edit must preserve the adaptive cooldown tier after expiry") + // The scheduler projection and an ordinary account edit must retain + // the history bound to the current recovery generation. + account.Extra = filterSchedulerExtra(account.Extra) + afterExpiry := reset.Add(time.Second) + next, _ := service.GrokRepeated429ResetForTesting(account, afterExpiry) + require.True(t, afterExpiry.Add(tc.next).Equal(next)) + delete(account.Extra, service.GrokRateLimitHistoryExtraKey) + require.NoError(t, accounts.Update(ctx, account)) + account, err = accounts.GetByID(ctx, id) + require.NoError(t, err) + next, _ = service.GrokRepeated429ResetForTesting(account, afterExpiry) + require.True(t, afterExpiry.Add(tc.next).Equal(next)) + // Reset extension starts a new window, so old tier evidence must + // not leak into that window or survive a clear/re-arm generation. + newBoundary := reset.Add(time.Minute) + require.NoError(t, accounts.(*accountRepository).SetRateLimitedIfLater(ctx, id, newBoundary)) + account, err = accounts.GetByID(ctx, id) + require.NoError(t, err) + next, _ = service.GrokRepeated429ResetForTesting(account, newBoundary.Add(time.Second)) + require.True(t, newBoundary.Add(time.Second+10*time.Minute).Equal(next)) + beforeClear := account + require.NoError(t, accounts.ClearRateLimit(ctx, id)) + require.NoError(t, accounts.Update(ctx, beforeClear)) + account, err = accounts.GetByID(ctx, id) + require.NoError(t, err) + require.Nil(t, account.RateLimitedAt, "an ordinary stale edit cannot undo an explicit clear") + require.Nil(t, account.RateLimitResetAt) + require.NoError(t, accounts.(*accountRepository).SetRateLimitedIfLater(ctx, id, reset)) + account, err = accounts.GetByID(ctx, id) + require.NoError(t, err) + rearmedGeneration := *account.RateLimitedAt + require.NoError(t, accounts.Update(ctx, beforeClear)) + account, err = accounts.GetByID(ctx, id) + require.NoError(t, err) + require.True(t, rearmedGeneration.Equal(*account.RateLimitedAt), "an ordinary stale edit cannot undo an explicit re-arm") + next, _ = service.GrokRepeated429ResetForTesting(account, afterExpiry) + require.True(t, afterExpiry.Add(10*time.Minute).Equal(next)) + }) + } + } +} diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index e5b6bd3f8148..75c80dbdeea2 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -1752,6 +1752,7 @@ func filterSchedulerExtra(extra map[string]any) map[string]any { service.UpstreamBillingProbeExtraKey, service.GrokMediaEligibleExtraKey, "grok_billing_snapshot", + service.GrokRateLimitHistoryExtraKey, } filtered := make(map[string]any) for _, key := range keys { diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index 371380d03101..08d803e13881 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -1437,6 +1437,9 @@ func (s *AccountTestService) observeGrokTestResponse(ctx context.Context, accoun if resp == nil { return } + if recovery, ok := ctx.Value(grokTestRecoveryContextKey{}).(*grokTestRecovery); ok && account.IsGrokOAuth() { + recovery.observed = true + } now := time.Now() // Error bodies carry Grok's free-usage, billing, and content-policy // classifications when quota headers are absent. Read only non-success @@ -1470,10 +1473,10 @@ func (s *AccountTestService) observeGrokTestResponse(ctx context.Context, accoun if limited && !skipAccountState { persistGrokRateLimit(ctx, s.accountRepo, account, resetAt) } else if isSuccessfulGrokRateLimitRecovery(account, snapshot) { - clearGrokRateLimitAfterRecovery(ctx, s.accountRepo, account) + s.recoverGrokTestRateLimit(ctx, account) } } else if s.accountRepo != nil && isSuccessfulGrokRateLimitRecovery(account, &xai.QuotaSnapshot{StatusCode: resp.StatusCode}) { - clearGrokRateLimitAfterRecovery(ctx, s.accountRepo, account) + s.recoverGrokTestRateLimit(ctx, account) } if s.accountRepo == nil || len(responseBody) == 0 { if resp.StatusCode == http.StatusPaymentRequired && s.accountRepo != nil { @@ -3763,10 +3766,12 @@ func (s *AccountTestService) sendErrorAndEnd(c *gin.Context, errorMsg string) er return fmt.Errorf("%s", errorMsg) } -// RunTestBackground executes an account test in-memory (no real HTTP client), -// capturing SSE output via httptest.NewRecorder, then parses the result. +// RunTestBackground captures an account test's SSE in memory, then parses the +// result. Grok recovery evidence is returned for the runner to apply after save. func (s *AccountTestService) RunTestBackground(ctx context.Context, accountID int64, modelID string) (*ScheduledTestResult, error) { startedAt := time.Now() + recovery := &grokTestRecovery{} + ctx = context.WithValue(ctx, grokTestRecoveryContextKey{}, recovery) w := httptest.NewRecorder() ginCtx, _ := gin.CreateTestContext(w) @@ -3788,6 +3793,7 @@ func (s *AccountTestService) RunTestBackground(ctx context.Context, accountID in } return &ScheduledTestResult{ + grokRecovery: recovery, Status: status, ResponseText: responseText, ErrorMessage: errMsg, diff --git a/backend/internal/service/grok_rate_limit_history.go b/backend/internal/service/grok_rate_limit_history.go new file mode 100644 index 000000000000..9b4355a06604 --- /dev/null +++ b/backend/internal/service/grok_rate_limit_history.go @@ -0,0 +1,29 @@ +package service + +import ( + "strconv" + "time" +) + +const GrokRateLimitHistoryExtraKey = "grok_rate_limit_history" + +// Recovery generations may advance while the cooldown boundary stays fixed. +// Use the separately retained duration only for that exact generation/boundary; +// legacy rows and external clears/re-arms retain their existing interpretation. +func grokHistoricalCooldown(account *Account) time.Duration { + legacy := account.RateLimitResetAt.Sub(*account.RateLimitedAt) + history, ok := account.Extra[GrokRateLimitHistoryExtraKey].(map[string]any) + if !ok || history["generation_us"] != strconv.FormatInt(account.RateLimitedAt.UnixMicro(), 10) || + history["reset_us"] != strconv.FormatInt(account.RateLimitResetAt.UnixMicro(), 10) { + return legacy + } + raw, ok := history["cooldown_us"].(string) + if !ok { + return legacy + } + micros, err := strconv.ParseInt(raw, 10, 64) + if err != nil || micros <= 0 || micros > int64((1<<63-1)/time.Microsecond) { + return legacy + } + return time.Duration(micros) * time.Microsecond +} diff --git a/backend/internal/service/grok_rate_limit_history_test.go b/backend/internal/service/grok_rate_limit_history_test.go new file mode 100644 index 000000000000..d0c9f666224a --- /dev/null +++ b/backend/internal/service/grok_rate_limit_history_test.go @@ -0,0 +1,47 @@ +//go:build unit + +package service + +import ( + "net/http" + "strconv" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" + "github.com/stretchr/testify/require" +) + +func TestGrokAdaptiveCooldownRequiresMatchingHistory(t *testing.T) { + now := time.Now().UTC().Truncate(time.Microsecond) + reset, generation := now.Add(-time.Second), now.Add(-5*time.Minute) + for _, tc := range []struct { + name string + edit func(map[string]any) + want time.Duration + }{ + {name: "matching", want: time.Hour}, + {name: "old_generation", edit: func(h map[string]any) { h["generation_us"] = "1" }, want: 10 * time.Minute}, + {name: "old_reset", edit: func(h map[string]any) { h["reset_us"] = "1" }, want: 10 * time.Minute}, + {name: "invalid_duration", edit: func(h map[string]any) { h["cooldown_us"] = "invalid" }, want: 10 * time.Minute}, + {name: "overflow", edit: func(h map[string]any) { h["cooldown_us"] = "9223372036854775807" }, want: 10 * time.Minute}, + {name: "zero", edit: func(h map[string]any) { h["cooldown_us"] = "0" }, want: 10 * time.Minute}, + {name: "legacy", edit: func(h map[string]any) { clear(h) }, want: 10 * time.Minute}, + } { + t.Run(tc.name, func(t *testing.T) { + history := map[string]any{"generation_us": strconv.FormatInt(generation.UnixMicro(), 10), + "reset_us": strconv.FormatInt(reset.UnixMicro(), 10), "cooldown_us": strconv.FormatInt((40*time.Minute).Microseconds(), 10)} + if tc.edit != nil { + tc.edit(history) + } + account := &Account{Platform: PlatformGrok, Type: AccountTypeOAuth, RateLimitedAt: &generation, + RateLimitResetAt: &reset, Extra: map[string]any{GrokRateLimitHistoryExtraKey: history}} + retryAfter := 60 + next, limited := grokRateLimitResetAtForAccount(account, &xai.QuotaSnapshot{ + StatusCode: http.StatusTooManyRequests, RetryAfterSeconds: &retryAfter, UpdatedAt: now.Format(time.RFC3339Nano), + }, now) + require.True(t, limited) + require.True(t, now.Add(tc.want).Equal(next)) + }) + } +} diff --git a/backend/internal/service/grok_scheduled_test_recovery.go b/backend/internal/service/grok_scheduled_test_recovery.go new file mode 100644 index 000000000000..fc05dfeadc82 --- /dev/null +++ b/backend/internal/service/grok_scheduled_test_recovery.go @@ -0,0 +1,32 @@ +package service + +import "context" + +type grokTestRecoveryContextKey struct{} + +// Background connectivity tests may observe quota immediately, but positive +// recovery belongs after result insertion. This is attempt-local evidence, not +// a durable continuation or permission to replay a probe after a failed save. +type grokTestRecovery struct { + observed bool + account *Account +} + +func (s *AccountTestService) recoverGrokTestRateLimit(ctx context.Context, account *Account) { + if account == nil || account.RateLimitedAt == nil || account.RateLimitResetAt == nil { + return + } + if recovery, ok := ctx.Value(grokTestRecoveryContextKey{}).(*grokTestRecovery); ok { + // Copy the observed generation, never a later re-read or mutable pointer. + limitedAt, resetAt := *account.RateLimitedAt, *account.RateLimitResetAt + recovery.account = &Account{ID: account.ID, RateLimitedAt: &limitedAt, RateLimitResetAt: &resetAt} + return + } + clearGrokRateLimitAfterRecovery(ctx, s.accountRepo, account) +} + +func (r *grokTestRecovery) complete(ctx context.Context, accounts AccountRepository) { + if r != nil && r.account != nil { + clearGrokRateLimitAfterRecovery(ctx, accounts, r.account) + } +} diff --git a/backend/internal/service/openai_gateway_grok.go b/backend/internal/service/openai_gateway_grok.go index f0aca6e158f7..cfd76611712c 100644 --- a/backend/internal/service/openai_gateway_grok.go +++ b/backend/internal/service/openai_gateway_grok.go @@ -1808,7 +1808,7 @@ func grokRateLimitResetAtForAccount(account *Account, snapshot *xai.QuotaSnapsho if previousResetAt.After(now) || now.Sub(previousResetAt) > grokRateLimitBackoffQuietPeriod { return resetAt, true } - previousCooldown := previousResetAt.Sub(*account.RateLimitedAt) + previousCooldown := grokHistoricalCooldown(account) if previousCooldown <= 0 { return resetAt, true } diff --git a/backend/internal/service/quality_quota_integration_helper.go b/backend/internal/service/quality_quota_integration_helper.go index d0d9db760326..99de7c13e839 100644 --- a/backend/internal/service/quality_quota_integration_helper.go +++ b/backend/internal/service/quality_quota_integration_helper.go @@ -4,8 +4,12 @@ package service import ( "context" + "net/http" + "time" + "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/pkg/qualityqueue" + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" ) // Integration-only bridge to the actual cron execution and trigger worker. @@ -46,3 +50,21 @@ func NewConnectivityRunnerForTesting(scheduled *ScheduledTestService, accounts A rateLimitSvc: NewRateLimitService(accounts, nil, nil, nil, nil), } } + +// Exercise the actual Grok transport/observer/background parser with an offline +// HTTPUpstream. No alternate execution or recovery implementation is installed. +func NewGrokConnectivityRunnerForTesting(scheduled *ScheduledTestService, accounts AccountRepository, upstream HTTPUpstream) (*ScheduledTestRunnerService, *AccountTestService) { + runner := NewConnectivityRunnerForTesting(scheduled, accounts) + runner.accountTestSvc.httpUpstream = upstream + runner.accountTestSvc.grokTokenProvider = NewGrokTokenProvider(accounts, nil) + runner.accountTestSvc.cfg = &config.Config{} + return runner, runner.accountTestSvc +} + +// Exercise the production adaptive policy at a logical instant after expiry. +func GrokRepeated429ResetForTesting(account *Account, now time.Time) (time.Time, bool) { + retryAfter := 60 + return grokRateLimitResetAtForAccount(account, &xai.QuotaSnapshot{ + StatusCode: http.StatusTooManyRequests, RetryAfterSeconds: &retryAfter, UpdatedAt: now.Format(time.RFC3339Nano), + }, now) +} diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index 493046314ccf..9810d369ab01 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -66,6 +66,9 @@ type SuccessfulTestRecoveryResult struct { type AccountRecoveryOptions struct { InvalidateToken bool preserveGrokScopedBlocks bool + // Scheduled Grok tests recover only the observed rate-limit generation after + // saving. The generic callback must not clear newer or separately owned state. + preserveGrokRuntimeState bool } type geminiUsageCacheEntry struct { @@ -2456,7 +2459,7 @@ func (s *RateLimitService) RecoverAccountState(ctx context.Context, accountID in hasScopedGrokState := account.IsGrok() && !options.preserveGrokScopedBlocks && (hasGrokModelQuotaBlockForAccount(account.ID) || hasGrokTeamModelRateLimitForAccount(account)) - if hasRecoverableRuntimeState(account) || hasScopedGrokState { + if (hasRecoverableRuntimeState(account) || hasScopedGrokState) && (!account.IsGrok() || !options.preserveGrokRuntimeState) { if err := s.clearRateLimit(ctx, accountID, options.preserveGrokScopedBlocks && account.IsGrok()); err != nil { return nil, err } diff --git a/backend/internal/service/scheduled_test_port.go b/backend/internal/service/scheduled_test_port.go index d4f45972ce72..376379168c19 100644 --- a/backend/internal/service/scheduled_test_port.go +++ b/backend/internal/service/scheduled_test_port.go @@ -68,6 +68,9 @@ type ScheduledTestPlan struct { // ScheduledTestResult represents a single test execution result. type ScheduledTestResult struct { + // Attempt-local Grok recovery evidence; never accepted from or stored in JSON. + grokRecovery *grokTestRecovery + // Runtime-only; set solely from an actual own-credential OAuth HTTP 401. DirectOAuth401 bool `json:"-"` DirectOAuthRevoked401 bool `json:"-"` diff --git a/backend/internal/service/scheduled_test_runner_service.go b/backend/internal/service/scheduled_test_runner_service.go index 7b9899f1b3cc..2a27b14d328e 100644 --- a/backend/internal/service/scheduled_test_runner_service.go +++ b/backend/internal/service/scheduled_test_runner_service.go @@ -200,10 +200,13 @@ func (s *ScheduledTestRunnerService) runOnePlan(ctx context.Context, plan *Sched if !saved { return false } + if result.Status == "success" { + result.grokRecovery.complete(ctx, s.accountTestSvc.accountRepo) + } // Auto-recover account if test succeeded and auto_recover is enabled. if result.Status == "success" && plan.AutoRecover { - s.tryRecoverAccount(ctx, plan.AccountID, plan.ID) + s.tryRecoverAccount(ctx, plan.AccountID, plan.ID, result.grokRecovery) } nextRun, err := computeNextRun(plan.CronExpression, time.Now()) @@ -219,12 +222,17 @@ func (s *ScheduledTestRunnerService) runOnePlan(ctx context.Context, plan *Sched } // tryRecoverAccount attempts to recover an account from recoverable runtime state. -func (s *ScheduledTestRunnerService) tryRecoverAccount(ctx context.Context, accountID int64, planID int64) { +func (s *ScheduledTestRunnerService) tryRecoverAccount(ctx context.Context, accountID int64, planID int64, grokRecovery ...*grokTestRecovery) { if s.rateLimitSvc == nil { return } - recovery, err := s.rateLimitSvc.RecoverAccountAfterSuccessfulTest(ctx, accountID) + // Grok's observer owns the generation-fenced recovery. Broad recovery here + // would clear a newer 429 or an exhausted-200 observation after saving. + recovery, err := s.rateLimitSvc.RecoverAccountState(ctx, accountID, AccountRecoveryOptions{ + preserveGrokScopedBlocks: true, + preserveGrokRuntimeState: len(grokRecovery) > 0 && grokRecovery[0] != nil && grokRecovery[0].observed, + }) if err != nil { logger.LegacyPrintf("service.scheduled_test_runner", "[ScheduledTestRunner] plan=%d auto-recover failed: %v", planID, err) return