From f1733c2bf4391deb32df2be2f913a87007071a32 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 00:32:47 +0800 Subject: [PATCH 1/3] =?UTF-8?q?fix:=20=E8=B4=A8=E9=87=8F=E5=88=86=E7=BB=84?= =?UTF-8?q?=E6=AD=A3=E5=B8=B8=E8=B4=A6=E5=8F=B7=E5=AE=9A=E6=97=B6=E6=A3=80?= =?UTF-8?q?=E6=B5=8B=E8=B7=B3=E8=BF=87=E5=B7=B2=E7=9F=A5=E8=80=97=E5=B0=BD?= =?UTF-8?q?=E9=A2=9D=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/issue817-quality-quota.yml | 108 ++++++++++ .../internal/repository/account_quality.go | 3 +- .../repository/quality_rule_template_repo.go | 9 +- .../repository/quality_template_quota.go | 57 +++++ ...quality_template_quota_integration_test.go | 163 ++++++++++++++ .../repository/scheduled_test_repo.go | 9 +- backend/internal/service/pelican_scheduled.go | 19 ++ .../internal/service/quality_quota_filter.go | 104 +++++++++ .../service/quality_quota_filter_test.go | 200 ++++++++++++++++++ .../internal/service/quality_rule_template.go | 2 + .../service/quality_rule_template_test.go | 11 + .../internal/service/scheduled_test_port.go | 2 + 12 files changed, 683 insertions(+), 4 deletions(-) create mode 100644 .github/workflows/issue817-quality-quota.yml create mode 100644 backend/internal/repository/quality_template_quota.go create mode 100644 backend/internal/repository/quality_template_quota_integration_test.go create mode 100644 backend/internal/service/quality_quota_filter.go create mode 100644 backend/internal/service/quality_quota_filter_test.go diff --git a/.github/workflows/issue817-quality-quota.yml b/.github/workflows/issue817-quality-quota.yml new file mode 100644 index 000000000000..13c44703ed73 --- /dev/null +++ b/.github/workflows/issue817-quality-quota.yml @@ -0,0 +1,108 @@ +name: Issue817 quality quota regressions + +on: + push: + branches: [fix/issue817-quality-exhausted-filter] + pull_request: + paths: + - 'backend/internal/service/quality_quota*' + - 'backend/internal/service/quality_rule_template*' + - 'backend/internal/service/pelican_scheduled.go' + - 'backend/internal/service/scheduled_test_port.go' + - 'backend/internal/repository/quality_template_quota*' + - 'backend/internal/repository/quality_rule_template_repo.go' + - 'backend/internal/repository/account_quality.go' + - 'backend/internal/repository/scheduled_test_repo.go' + - '.github/workflows/issue817-quality-quota.yml' + +permissions: + contents: read + +concurrency: + group: issue817-${{ github.event_name }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + regressions: + runs-on: ubuntu-latest + timeout-minutes: 35 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + - name: Record and assert actual head + env: + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} + run: | + mkdir -p evidence + git rev-parse HEAD | tee evidence/head.txt + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Record source formatting diff for static follow-up + shell: bash + run: | + gofmt -d backend/internal/service/quality_quota_filter*.go backend/internal/service/scheduled_test_port.go backend/internal/repository/quality_template_quota*.go > evidence/format.diff + cat evidence/format.diff + - name: Original runner must fail the unchanged execution regression + shell: bash + run: | + set -euo pipefail + source=backend/internal/service/pelican_scheduled.go + cp "$source" "$RUNNER_TEMP/issue817-runner.go" + trap 'cp "$RUNNER_TEMP/issue817-runner.go" "$source"' EXIT + original=9837bfbfc845027a61b86cec1460785e869c4e54 + git fetch --no-tags --depth=1 origin "$original" + git show "$original:$source" > "$source" + set +e + (cd backend && go test -tags=unit ./internal/service -run '^TestIssue817RunnerRechecksQuotaAfterClaim$' -count=1 -v) > evidence/red-runner.log 2>&1 + result=$? + set -e + cat evidence/red-runner.log + test "$result" -ne 0 + ! grep -Eq 'build failed|setup failed|undefined:|syntax error:|no tests to run|panic:|--- SKIP:' evidence/red-runner.log + grep -F -- '--- FAIL: TestIssue817RunnerRechecksQuotaAfterClaim/normal_only_five_hour' evidence/red-runner.log + grep -F -- '--- FAIL: TestIssue817RunnerRechecksQuotaAfterClaim/normal_only_weekly' evidence/red-runner.log + - name: Current service race regressions and retained quality safeguards + shell: bash + working-directory: backend + run: | + set -euo pipefail + go test -race -tags=unit ./internal/service -run '^(TestIssue817|TestQuality|TestPelicanSchedule)' -count=1 -v -timeout=10m 2>&1 | tee ../evidence/green-service.log + ! grep -Eq 'no tests to run|--- SKIP:' ../evidence/green-service.log + - name: Original candidate selection must fail unchanged PostgreSQL regression + shell: bash + env: + CI: 'true' + run: | + set -euo pipefail + source=backend/internal/repository/quality_rule_template_repo.go + cp "$source" "$RUNNER_TEMP/issue817-template.go" + trap 'cp "$RUNNER_TEMP/issue817-template.go" "$source"' EXIT + git show "9837bfbfc845027a61b86cec1460785e869c4e54:$source" > "$source" + set +e + (cd backend && go test -tags=integration ./internal/repository -run '^TestIssue817TemplateCandidateQuotaAndRecovery$' -count=1 -v -timeout=10m) > evidence/red-candidates.log 2>&1 + result=$? + set -e + cat evidence/red-candidates.log + test "$result" -ne 0 + ! grep -Eq 'build failed|setup failed|undefined:|syntax error:|no tests to run|panic:|--- SKIP:' evidence/red-candidates.log + grep -F -- '--- FAIL: TestIssue817TemplateCandidateQuotaAndRecovery' evidence/red-candidates.log + grep -F -- 'normal-only candidates must exclude known 5h and weekly exhaustion' evidence/red-candidates.log + - name: Current PostgreSQL candidates, triggers, 401, ownership and leases + working-directory: backend + shell: bash + env: + CI: 'true' + run: | + set -euo pipefail + go test -tags=integration ./internal/repository -run '^(TestIssue817|TestQualityRuleTemplate|TestQualityRetestRest|TestQualityOAuth401|TestQualityOwnership|TestQualityIsolation|TestQualityEnableBPS)' -count=1 -v -timeout=15m 2>&1 | tee ../evidence/green-postgres.log + ! grep -Eq 'no tests to run|--- SKIP:' ../evidence/green-postgres.log + - uses: actions/upload-artifact@v7 + if: always() + with: + name: issue817-${{ github.event_name }}-${{ github.run_id }} + path: evidence/ + if-no-files-found: error diff --git a/backend/internal/repository/account_quality.go b/backend/internal/repository/account_quality.go index 8705bb3fd487..5917c1747be4 100644 --- a/backend/internal/repository/account_quality.go +++ b/backend/internal/repository/account_quality.go @@ -22,7 +22,8 @@ func (r *scheduledTestPlanRepository) ListQualityPlans(ctx context.Context) ([]* return scanPlans(rows, true) } func (r *scheduledTestPlanRepository) TriggerQuality(ctx context.Context, id int64) error { - result, err := r.db.ExecContext(ctx, `UPDATE scheduled_test_plans SET next_run_at=NOW(), updated_at=NOW() + result, err := r.db.ExecContext(ctx, `UPDATE scheduled_test_plans SET next_run_at=NOW(), updated_at=NOW(), + pelican_config=jsonb_set(pelican_config, '{_manual_quality_run}', 'true'::jsonb) WHERE id=$1 AND enabled AND pelican_config->'quality' IS NOT NULL AND (running_until IS NULL OR running_until'quality'->>'retest_rest_minutes')::int,0)>0 diff --git a/backend/internal/repository/quality_rule_template_repo.go b/backend/internal/repository/quality_rule_template_repo.go index 5139f4d9cb08..39d4c687cf0e 100644 --- a/backend/internal/repository/quality_rule_template_repo.go +++ b/backend/internal/repository/quality_rule_template_repo.go @@ -188,18 +188,23 @@ func (r *qualityRuleTemplateRepository) Delete(ctx context.Context, id int64) (p } // MatchingAccounts reuses the admin account list predicates so the selector's count and the -// accounts a group rule covers always agree. +// accounts a group rule covers agree on native status. Normal-only rules also +// exclude known exhausted OAuth snapshots without changing the admin list. func (r *qualityRuleTemplateRepository) MatchingAccounts(ctx context.Context, filter service.QualityRuleAccountFilter) ([]service.QualityTemplateAccount, error) { accounts := &accountRepository{client: r.client} rows, err := accounts.accountListFilteredQuery("", filter.Type, strings.Join(filter.Statuses, ","), filter.Search, service.QualityTemplateGroupID(filter), ""). Order(dbent.Asc(dbaccount.FieldID)). - Select(dbaccount.FieldID, dbaccount.FieldPlatform, dbaccount.FieldType, dbaccount.FieldExtra). + Select(dbaccount.FieldID, dbaccount.FieldPlatform, dbaccount.FieldType, dbaccount.FieldExtra, dbaccount.FieldCredentials, dbaccount.FieldRateLimitResetAt). All(ctx) if err != nil { return nil, err } out := make([]service.QualityTemplateAccount, 0, len(rows)) + now := time.Now() for _, row := range rows { + if !service.QualityTemplateQuotaAvailable(filter, accountEntityToService(row), now) { + continue + } out = append(out, service.QualityTemplateAccount{ID: row.ID, Platform: row.Platform, Type: row.Type, Extra: row.Extra}) } return out, nil diff --git a/backend/internal/repository/quality_template_quota.go b/backend/internal/repository/quality_template_quota.go new file mode 100644 index 000000000000..d9d2be20f555 --- /dev/null +++ b/backend/internal/repository/quality_template_quota.go @@ -0,0 +1,57 @@ +package repository + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" +) + +func (r *qualityRuleTemplateRepository) ForPlan(ctx context.Context, planID int64) (*service.QualityRuleTemplate, error) { + var filter []byte + err := r.db.QueryRowContext(ctx, `SELECT t.account_filter FROM quality_rule_templates t + JOIN quality_rule_template_accounts link ON link.template_id=t.id WHERE link.plan_id=$1`, planID).Scan(&filter) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + if err != nil { + return nil, err + } + t := &service.QualityRuleTemplate{} + if err := json.Unmarshal(filter, &t.AccountFilter); err != nil { + return nil, err + } + return t, nil +} + +var _ service.QualityQuotaSkipRepository = (*scheduledTestPlanRepository)(nil) + +func (r *scheduledTestPlanRepository) FinishQuotaSkippedPelican(ctx context.Context, plan *service.ScheduledTestPlan, until, finished time.Time) error { + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + var current bool + err = tx.QueryRowContext(ctx, `SELECT COALESCE(running_until=$2,false) FROM scheduled_test_plans WHERE id=$1 FOR UPDATE`, plan.ID, until).Scan(¤t) + if errors.Is(err, sql.ErrNoRows) { + return nil + } + if err != nil || !current { + return err + } + // Undo only this unexecuted ledger claim. Keep the completed round and its + // failures/revocation evidence; no 401 was observed during a quota skip. + if _, err = tx.ExecContext(ctx, `UPDATE quality_oauth_401_streaks + SET claimed_until=COALESCE(last_round_until,claimed_until) WHERE plan_id=$1 AND claimed_until=$2`, plan.ID, until); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, `UPDATE scheduled_test_plans SET running_until=NULL,last_run_at=$3 + WHERE id=$1 AND running_until=$2`, plan.ID, until, finished); err != nil { + return err + } + return tx.Commit() +} diff --git a/backend/internal/repository/quality_template_quota_integration_test.go b/backend/internal/repository/quality_template_quota_integration_test.go new file mode 100644 index 000000000000..f8f25b83bd09 --- /dev/null +++ b/backend/internal/repository/quality_template_quota_integration_test.go @@ -0,0 +1,163 @@ +//go:build integration + +package repository + +import ( + "context" + "encoding/json" + "fmt" + "strconv" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestIssue817TemplateCandidateQuotaAndRecovery(t *testing.T) { + ctx := context.Background() + var group int64 + require.NoError(t, integrationDB.QueryRow(`INSERT INTO groups(name,platform) VALUES($1,'openai') RETURNING id`, fmt.Sprintf("issue817-%d", time.Now().UnixNano())).Scan(&group)) + var ids []int64 + t.Cleanup(func() { + _, _ = integrationDB.Exec(`DELETE FROM quality_rule_templates WHERE account_filter->>'group'=$1`, strconv.FormatInt(group, 10)) + for _, id := range ids { + _, _ = integrationDB.Exec(`DELETE FROM scheduled_test_plans WHERE account_id=$1`, id) + _, _ = integrationDB.Exec(`DELETE FROM scheduler_outbox WHERE account_id=$1`, id) + _, _ = integrationDB.Exec(`DELETE FROM account_groups WHERE account_id=$1`, id) + _, _ = integrationDB.Exec(`DELETE FROM accounts WHERE id=$1`, id) + } + _, _ = integrationDB.Exec(`DELETE FROM groups WHERE id=$1`, group) + }) + add := func(platform, kind, extra string) int64 { + var id int64 + require.NoError(t, integrationDB.QueryRow(`INSERT INTO accounts(name,platform,type,status,schedulable,extra) + VALUES('issue817-fixture',$1,$2,'active',true,$3::jsonb) RETURNING id`, platform, kind, extra).Scan(&id)) + ids = append(ids, id) + _, err := integrationDB.Exec(`INSERT INTO account_groups(account_id,group_id,priority) VALUES($1,$2,1)`, id, group) + require.NoError(t, err) + return id + } + now := time.Now() + snapshot := func(window string, used float64, observed, reset time.Time) string { + extra := map[string]any{"codex_usage_updated_at": observed.Format(time.RFC3339Nano), "codex_" + window + "_used_percent": used} + if !reset.IsZero() { + extra["codex_"+window+"_reset_at"] = reset.Format(time.RFC3339Nano) + } + data, err := json.Marshal(extra) + require.NoError(t, err) + return string(data) + } + five := add("openai", "oauth", snapshot("5h", 100, now, now.Add(time.Hour))) + week := add("openai", "oauth", snapshot("7d", 100, now, now.Add(time.Hour))) + healthy := add("openai", "oauth", snapshot("5h", 99, now, now.Add(time.Hour))) + unknown := add("openai", "oauth", `{}`) + stale := add("openai", "oauth", snapshot("7d", 100, now.Add(-3*time.Hour), time.Time{})) + recovered := add("openai", "oauth", snapshot("5h", 100, now, now.Add(-time.Minute))) + apiKey := add("openai", "apikey", snapshot("7d", 100, now, now.Add(time.Hour))) + unrelated := add("anthropic", "oauth", snapshot("7d", 100, now, now.Add(time.Hour))) + templates := NewQualityRuleTemplateRepository(integrationEntClient, integrationDB) + filter := service.QualityRuleAccountFilter{Group: strconv.FormatInt(group, 10), Statuses: []string{"active"}} + matchingIDs := func(filter service.QualityRuleAccountFilter) []int64 { + rows, err := templates.MatchingAccounts(ctx, filter) + require.NoError(t, err) + out := make([]int64, 0, len(rows)) + for _, row := range rows { + out = append(out, row.ID) + } + return out + } + require.ElementsMatch(t, []int64{healthy, unknown, stale, recovered, apiKey, unrelated}, matchingIDs(filter), "normal-only candidates must exclude known 5h and weekly exhaustion") + filter.Statuses = []string{"active", "rate_limited"} + require.ElementsMatch(t, ids, matchingIDs(filter), "explicit other statuses retain probe intent") + filter.Statuses = nil + require.ElementsMatch(t, ids, matchingIDs(filter)) + filter.Statuses = []string{"active"} + _, err := integrationDB.Exec(`UPDATE accounts SET extra=jsonb_set(extra,'{codex_5h_reset_at}',to_jsonb($2::text)) WHERE id=$1`, five, now.Add(-time.Minute).Format(time.RFC3339Nano)) + require.NoError(t, err) + require.Contains(t, matchingIDs(filter), five, "window rollover makes the account a candidate again") + require.NotContains(t, matchingIDs(filter), week) + + // Exercise the persisted link, rather than copying a filter into plan JSON. + template, err := templates.Create(ctx, &service.QualityRuleTemplate{AccountFilter: filter, ModelID: "fixture-model", CronExpression: "*/5 * * * *", Enabled: true, MaxResults: 50, + PelicanConfig: &service.PelicanTestConfig{Prompt: "fixture", ReasoningEffort: "medium", ParallelCount: 1, Quality: &service.QualityPolicy{Action: service.QualityActionObserveOnly}}}) + require.NoError(t, err) + next := time.Now().Add(time.Minute) + plan, err := templates.CreateLinkedPlan(ctx, template, &service.ScheduledTestPlan{AccountID: healthy, ModelID: template.ModelID, CronExpression: template.CronExpression, Enabled: true, MaxResults: 50, NextRunAt: &next, PelicanConfig: template.PelicanConfig}) + require.NoError(t, err) + owner, err := templates.ForPlan(ctx, plan.ID) + require.NoError(t, err) + require.Equal(t, filter, owner.AccountFilter) + template.AccountFilter.Statuses = []string{"rate_limited"} + _, err = templates.Update(ctx, template) + require.NoError(t, err) + owner, err = templates.ForPlan(ctx, plan.ID) + require.NoError(t, err) + require.Equal(t, []string{"rate_limited"}, owner.AccountFilter.Statuses, "execution uses the current selection") + _, err = templates.Delete(ctx, template.ID) + require.NoError(t, err) + owner, err = templates.ForPlan(ctx, plan.ID) + require.NoError(t, err) + require.Nil(t, owner, "detached rules retain independent behavior") +} + +func TestIssue817ManualTriggerIsOneShotAndLeaseFenced(t *testing.T) { + f := newQualityBPSFixture(t, `{}`, &service.QualityPolicy{Action: "disable_scheduling", AutoRestore: true}) + ctx := context.Background() + require.NoError(t, f.plans.FinishPelican(ctx, f.plan.ID, f.until, time.Now())) + stale, err := f.plans.GetByID(ctx, f.plan.ID) + require.NoError(t, err) + require.False(t, stale.ManualQualityRun) + require.NoError(t, f.plans.TriggerQuality(ctx, f.plan.ID)) + manual, err := f.plans.GetByID(ctx, f.plan.ID) + require.NoError(t, err) + require.True(t, manual.ManualQualityRun) + data, err := json.Marshal(manual) + require.NoError(t, err) + require.NotContains(t, string(data), "_manual_quality_run", "marker must not become a public configuration field") + now := time.Now().Add(time.Second).Truncate(time.Microsecond) + until := now.Add(15 * time.Minute) + claimed, err := f.plans.ClaimPelican(ctx, stale, now, until, now.Add(time.Hour)) + require.NoError(t, err) + require.False(t, claimed, "old selection cannot consume a new manual trigger") + current, err := f.plans.GetByID(ctx, f.plan.ID) + require.NoError(t, err) + require.True(t, current.ManualQualityRun) + claimed, err = f.plans.ClaimPelican(ctx, manual, now, until, now.Add(time.Hour)) + require.NoError(t, err) + require.True(t, claimed) + require.True(t, manual.ManualQualityRun, "claimed run keeps its explicit intent") + current, err = f.plans.GetByID(ctx, f.plan.ID) + require.NoError(t, err) + require.False(t, current.ManualQualityRun, "next automatic round cannot inherit the bypass") + require.Error(t, f.plans.TriggerQuality(ctx, f.plan.ID), "manual runs cannot bypass the active lease") + require.NoError(t, f.plans.FinishPelican(ctx, f.plan.ID, until, time.Now())) +} + +func TestIssue817QuotaSkipPreserves401AndOwnership(t *testing.T) { + f := oauth401Fixture(t, 6) + ctx := context.Background() + require.False(t, oauth401Complete(t, f, oauth401Evidence())) + require.Equal(t, 1, oauth401Failures(t, f)) + oauth401Next(t, f) + var before []byte + require.NoError(t, integrationDB.QueryRow(`SELECT COALESCE((SELECT state FROM account_quality_states WHERE plan_id=$1),'{}'::jsonb)`, f.plan.ID).Scan(&before)) + // A stale worker must not release a newer lease or touch its streak. + repo := f.plans.(service.QualityQuotaSkipRepository) + require.NoError(t, repo.FinishQuotaSkippedPelican(ctx, f.plan, f.until.Add(-time.Minute), time.Now())) + current, err := f.plans.GetByID(ctx, f.plan.ID) + require.NoError(t, err) + require.NotNil(t, current.RunningUntil) + require.NoError(t, repo.FinishQuotaSkippedPelican(ctx, f.plan, f.until, time.Now())) + current, err = f.plans.GetByID(ctx, f.plan.ID) + require.NoError(t, err) + require.Nil(t, current.RunningUntil) + require.Equal(t, 1, oauth401Failures(t, f)) + var after []byte + require.NoError(t, integrationDB.QueryRow(`SELECT COALESCE((SELECT state FROM account_quality_states WHERE plan_id=$1),'{}'::jsonb)`, f.plan.ID).Scan(&after)) + require.JSONEq(t, string(before), string(after)) + oauth401ClaimDue(t, f) + require.Equal(t, 1, oauth401Failures(t, f), "unexecuted quota skip must not reset the prior 401 streak") + require.False(t, oauth401Complete(t, f, oauth401Evidence())) + require.Equal(t, 2, oauth401Failures(t, f)) +} diff --git a/backend/internal/repository/scheduled_test_repo.go b/backend/internal/repository/scheduled_test_repo.go index 3ccba6bbb66b..4ed854cc5748 100644 --- a/backend/internal/repository/scheduled_test_repo.go +++ b/backend/internal/repository/scheduled_test_repo.go @@ -329,6 +329,13 @@ func scanPlan(row scannable, withAccountName ...bool) (*service.ScheduledTestPla if err := json.Unmarshal(config, &p.PelicanConfig); err != nil { return nil, err } + var internal struct { + ManualQualityRun bool `json:"_manual_quality_run"` + } + if err := json.Unmarshal(config, &internal); err != nil { + return nil, err + } + p.ManualQualityRun = internal.ManualQualityRun } return p, nil } @@ -368,7 +375,7 @@ func (r *scheduledTestPlanRepository) ClaimPelican(ctx context.Context, plan *se return false, nil } result, err := tx.ExecContext(ctx, `UPDATE scheduled_test_plans - SET running_until = $3, next_run_at = $4 + SET running_until = $3, next_run_at = $4, pelican_config = pelican_config - '_manual_quality_run' WHERE id = $1 AND enabled = true AND (next_run_at <= $2 OR ($7 AND pelican_config->'quality'->>'trigger_on_upstream_5xx'='true')) AND (NOT $7 OR (pelican_config->'quality'->>'trigger_on_upstream_5xx'='true' diff --git a/backend/internal/service/pelican_scheduled.go b/backend/internal/service/pelican_scheduled.go index 8e4c69609de7..06bdbdc84c3f 100644 --- a/backend/internal/service/pelican_scheduled.go +++ b/backend/internal/service/pelican_scheduled.go @@ -126,6 +126,25 @@ func (s *ScheduledTestRunnerService) runPelicanPlan(ctx context.Context, plan *S if err != nil || !claimed { return false } + // Re-read quota after claiming: the account may have exhausted its quota + // since template selection or ListDue. Do not turn a skipped run into a + // quality verdict, or disturb ownership used by later recovery rounds. + available, quotaErr := s.qualityTemplateQuotaAvailable(ctx, plan) + if quotaErr != nil || !available { + logger.LegacyPrintf("service.scheduled_test_runner", "pelican plan=%d account=%d skipped: template quota unavailable", plan.ID, plan.AccountID) + finishCtx, stop := context.WithTimeout(context.Background(), 30*time.Second) + defer stop() + var finishErr error + if repo, ok := s.planRepo.(QualityQuotaSkipRepository); ok { + finishErr = repo.FinishQuotaSkippedPelican(finishCtx, plan, until, time.Now()) + } else { + finishErr = s.planRepo.FinishPelican(finishCtx, plan.ID, until, time.Now()) + } + if finishErr != nil { + logger.LegacyPrintf("service.scheduled_test_runner", "pelican plan=%d finish failed: %v", plan.ID, finishErr) + } + return false + } // Result-only metadata must not mutate the stored rule or shared plan config. snapshot := *plan.PelicanConfig if snapshot.PromptMode == PelicanPromptModeRandom { diff --git a/backend/internal/service/quality_quota_filter.go b/backend/internal/service/quality_quota_filter.go new file mode 100644 index 000000000000..c5db251d6268 --- /dev/null +++ b/backend/internal/service/quality_quota_filter.go @@ -0,0 +1,104 @@ +package service + +import ( + "context" + "fmt" + "math" + "strconv" + "time" +) + +// QualityTemplateQuotaAvailable refines the normal-only template selection with +// known OAuth quota availability. Explicit other statuses (and all statuses) +// preserve their existing probe/recovery intent. It never probes the provider. +func QualityTemplateQuotaAvailable(filter QualityRuleAccountFilter, account *Account, now time.Time) bool { + if len(filter.Statuses) != 1 || filter.Statuses[0] != StatusActive || account == nil || !account.IsOpenAIOAuth() { + return true + } + if account.RateLimitResetAt != nil && now.Before(*account.RateLimitResetAt) { + return false + } + if !openAICodexSnapshotIdentityTrusted(account) { + return true + } + // Unlike a persisted cooldown, an undated/invalid observation cannot prove + // exhaustion. Reuse scheduling's reset and stale-window handling below. + for _, window := range []string{"5h", "7d"} { + extra := qualityQuotaWindowObservation(account.Extra, window, now) + used, known := resolveOpenAIQuotaUtilization(extra, window, now) + if known && !math.IsNaN(used) && !math.IsInf(used, 0) && used >= 1 { + return false + } + } + return true +} + +// Coalesced snapshots retain each field's original time. A newer 5h packet +// must not refresh old weekly exhaustion or slide its relative reset forward. +func qualityQuotaWindowObservation(extra map[string]any, window string, now time.Time) map[string]any { + prefix := "codex_" + window + "_" + observed := func(key string) (time.Time, bool) { + if raw, exists := extra[CodexUsageFieldVersionsKey]; exists { + fields, ok := raw.(map[string]any) + if !ok { + return time.Time{}, false + } + stamp, err := strconv.ParseInt(fmt.Sprint(fields[key]), 10, 64) + if err != nil || stamp <= 0 { + return time.Time{}, false + } + at := time.Unix(0, stamp) + return at, !at.After(now) + } + at, err := parseTime(fmt.Sprint(extra["codex_usage_updated_at"])) + return at, err == nil && !at.After(now) + } + at, ok := observed(prefix + "used_percent") + if !ok { + return nil + } + out := map[string]any{prefix + "used_percent": extra[prefix+"used_percent"], "codex_usage_updated_at": at.Format(time.RFC3339Nano)} + if raw, exists := extra[prefix+"reset_at"]; exists { + reset, err := parseTime(fmt.Sprint(raw)) + if err != nil { + return nil + } + out[prefix+"reset_at"] = reset.Format(time.RFC3339Nano) + } else if raw, exists := extra[prefix+"reset_after_seconds"]; exists { + resetObserved, valid := observed(prefix + "reset_after_seconds") + seconds, err := strconv.ParseInt(fmt.Sprint(raw), 10, 64) + if !valid || err != nil || seconds < 0 || seconds > int64((7*24*time.Hour)/time.Second) { + return nil + } + out[prefix+"reset_at"] = resetObserved.Add(time.Duration(seconds) * time.Second).Format(time.RFC3339Nano) + } + return out +} + +func (s *ScheduledTestRunnerService) qualityTemplateQuotaAvailable(ctx context.Context, plan *ScheduledTestPlan) (bool, error) { + // Explicit runs and upstream-error protection retain their existing semantics. + if plan.PelicanConfig == nil || plan.PelicanConfig.Quality == nil || plan.ManualQualityRun || plan.TriggerSource != "" || s.scheduledSvc == nil || s.scheduledSvc.templateRepo == nil { + return true, nil + } + template, err := s.scheduledSvc.templateRepo.ForPlan(ctx, plan.ID) + if err != nil || template == nil { + return err == nil, err + } + if len(template.AccountFilter.Statuses) != 1 || template.AccountFilter.Statuses[0] != StatusActive { + return true, nil + } + if s.accountTestSvc == nil || s.accountTestSvc.accountRepo == nil { + return false, fmt.Errorf("quality template account lookup unavailable") + } + account, err := s.accountTestSvc.accountRepo.GetByID(ctx, plan.AccountID) + if err != nil { + return false, err + } + return account != nil && QualityTemplateQuotaAvailable(template.AccountFilter, account, time.Now()), nil +} + +// A quota skip is not an interrupted quality round: preserve the 401 streak +// captured by ClaimPelican while releasing exactly the lease we acquired. +type QualityQuotaSkipRepository interface { + FinishQuotaSkippedPelican(context.Context, *ScheduledTestPlan, time.Time, time.Time) error +} diff --git a/backend/internal/service/quality_quota_filter_test.go b/backend/internal/service/quality_quota_filter_test.go new file mode 100644 index 000000000000..e0653cfc55ac --- /dev/null +++ b/backend/internal/service/quality_quota_filter_test.go @@ -0,0 +1,200 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "math" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func issue817Account(now time.Time) *Account { + return &Account{ID: 42, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, + Extra: map[string]any{"codex_usage_updated_at": now.Format(time.RFC3339Nano), "codex_5h_used_percent": 20.0, "codex_7d_used_percent": 30.0}} +} + +func TestIssue817QuotaEvidence(t *testing.T) { + now := time.Date(2026, 11, 12, 12, 0, 0, 0, time.UTC) + for _, tc := range []struct { + name string + change func(*Account) + want bool + }{ + {"available", func(*Account) {}, true}, + {"five_hour_exhausted", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0 }, false}, + {"weekly_exhausted", func(a *Account) { a.Extra["codex_7d_used_percent"] = 100.0 }, false}, + {"over_100", func(a *Account) { a.Extra["codex_7d_used_percent"] = 101.0 }, false}, + {"unknown", func(a *Account) { a.Extra = nil }, true}, + {"undated", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; delete(a.Extra, "codex_usage_updated_at") }, true}, + {"invalid_date", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Extra["codex_usage_updated_at"] = "unknown" }, true}, + {"future_date", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Extra["codex_usage_updated_at"] = now.Add(time.Hour).Format(time.RFC3339) }, true}, + {"stale_without_reset", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Extra["codex_usage_updated_at"] = now.Add(-3 * time.Hour).Format(time.RFC3339) }, true}, + {"old_but_current_week", func(a *Account) { a.Extra["codex_7d_used_percent"] = 100.0; a.Extra["codex_usage_updated_at"] = now.Add(-3 * time.Hour).Format(time.RFC3339); a.Extra["codex_7d_reset_at"] = now.Add(time.Hour).Format(time.RFC3339) }, false}, + {"five_hour_reset", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Extra["codex_5h_reset_at"] = now.Format(time.RFC3339) }, true}, + {"weekly_reset", func(a *Account) { a.Extra["codex_7d_used_percent"] = 100.0; a.Extra["codex_7d_reset_at"] = now.Add(-time.Second).Format(time.RFC3339) }, true}, + {"relative_reset", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Extra["codex_usage_updated_at"] = now.Add(-time.Hour).Format(time.RFC3339); a.Extra["codex_5h_reset_after_seconds"] = 3600 }, true}, + {"nan", func(a *Account) { a.Extra["codex_5h_used_percent"] = math.NaN() }, true}, + {"infinite", func(a *Account) { a.Extra["codex_5h_used_percent"] = math.Inf(1) }, true}, + {"bad_percent", func(a *Account) { a.Extra["codex_5h_used_percent"] = "unknown" }, true}, + {"other_platform", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Platform = PlatformAnthropic }, true}, + {"api_key", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Type = AccountTypeAPIKey }, true}, + {"other_identity", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Credentials = map[string]any{"chatgpt_account_id": "fixture-a"}; a.Extra["chatgpt_account_id"] = "fixture-b" }, true}, + {"live_429", func(a *Account) { reset := now.Add(time.Minute); a.RateLimitResetAt = &reset; a.Extra = nil }, false}, + {"expired_429", func(a *Account) { reset := now; a.RateLimitResetAt = &reset }, true}, + {"auto_pause_disabled_still_exhausted", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Extra["auto_pause_5h_disabled"] = true }, false}, + {"below_full_even_with_lower_pause_threshold", func(a *Account) { a.Extra["codex_5h_used_percent"] = 99.0; a.Extra["auto_pause_5h_threshold"] = 50 }, true}, + } { + t.Run(tc.name, func(t *testing.T) { + a := issue817Account(now) + tc.change(a) + require.Equal(t, tc.want, QualityTemplateQuotaAvailable(QualityRuleAccountFilter{Statuses: []string{StatusActive}}, a, now)) + }) + } + for _, statuses := range [][]string{nil, {"rate_limited"}, {"active", "rate_limited"}, {"active", "error"}, {"temp_unschedulable"}, {"unschedulable"}, {"inactive"}} { + a := issue817Account(now) + a.Extra["codex_5h_used_percent"] = 100.0 + require.True(t, QualityTemplateQuotaAvailable(QualityRuleAccountFilter{Statuses: statuses}, a, now), "explicit status selection %v", statuses) + } +} + +func TestIssue817CoalescedQuotaObservationsKeepFieldTimes(t *testing.T) { + now := time.Now() + a := issue817Account(now) + a.Extra["codex_7d_used_percent"] = 100.0 + a.Extra[CodexUsageFieldVersionsKey] = map[string]any{ + "codex_5h_used_percent": now.UnixNano(), + "codex_7d_used_percent": now.Add(-3 * time.Hour).UnixNano(), + } + filter := QualityRuleAccountFilter{Statuses: []string{"active"}} + require.True(t, QualityTemplateQuotaAvailable(filter, a, now), "new 5h observation must not refresh stale weekly exhaustion") + a.Extra["codex_7d_reset_after_seconds"] = 3600 + a.Extra[CodexUsageFieldVersionsKey].(map[string]any)["codex_7d_reset_after_seconds"] = now.Add(-3 * time.Hour).UnixNano() + require.True(t, QualityTemplateQuotaAvailable(filter, a, now), "relative reset must use its original field observation") + a.Extra["codex_7d_reset_at"] = now.Add(time.Hour).Format(time.RFC3339Nano) + require.False(t, QualityTemplateQuotaAvailable(filter, a, now), "known current window retains exhaustion until reset") + delete(a.Extra[CodexUsageFieldVersionsKey].(map[string]any), "codex_7d_used_percent") + require.True(t, QualityTemplateQuotaAvailable(filter, a, now), "missing version in versioned observations is unknown") +} + +type issue817Templates struct { + QualityRuleTemplateRepository + template *QualityRuleTemplate + err error +} + +func (r *issue817Templates) ForPlan(context.Context, int64) (*QualityRuleTemplate, error) { + return r.template, r.err +} + +type issue817Claims struct { + qualityPlanRepo + afterClaim func() + lease time.Time + finishedAt time.Time + next time.Time +} + +func (r *issue817Claims) ClaimPelican(ctx context.Context, p *ScheduledTestPlan, now, until, next time.Time) (bool, error) { + claimed, err := r.qualityPlanRepo.ClaimPelican(ctx, p, now, until, next) + if claimed { + r.lease, r.next = until, next + if r.afterClaim != nil { + r.afterClaim() + } + } + return claimed, err +} + +func (r *issue817Claims) FinishPelican(ctx context.Context, id int64, until, finished time.Time) error { + r.finishedAt = until + return r.qualityPlanRepo.FinishPelican(ctx, id, until, finished) +} + +func TestIssue817RunnerRechecksQuotaAfterClaim(t *testing.T) { + for _, tc := range []struct { + name string + statuses []string + manual bool + unlinked bool + lookupErr bool + wantRun bool + }{ + {"normal_only_five_hour", []string{"active"}, false, false, false, false}, + {"normal_only_weekly", []string{"active"}, false, false, false, false}, + {"normal_only_429", []string{"active"}, false, false, false, false}, + {"explicit_rate_limited", []string{"active", "rate_limited"}, false, false, false, true}, + {"explicit_other_status", []string{"temp_unschedulable"}, false, false, false, true}, + {"all_statuses", nil, false, false, false, true}, + {"manual_run", []string{"active"}, true, false, false, true}, + {"independent_rule", []string{"active"}, false, true, false, true}, + {"template_lookup_failed", []string{"active"}, false, false, true, false}, + {"quota_recovers", []string{"active"}, false, false, false, true}, + {"owned_quality_penalty", []string{"active"}, false, false, false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + a := issue817Account(time.Now()) + plans := &issue817Claims{} + plans.afterClaim = func() { + // The selection snapshot was usable. Change only after acquiring + // the persisted execution lease to expose the original race. + a.Extra["codex_5h_used_percent"] = 100.0 + if tc.name == "normal_only_weekly" { + a.Extra["codex_5h_used_percent"], a.Extra["codex_7d_used_percent"] = 20.0, 100.0 + } + if tc.name == "normal_only_429" { + reset := time.Now().Add(time.Hour) + a.RateLimitResetAt = &reset + a.Extra = nil + } + if tc.name == "quota_recovers" { + a.Extra["codex_5h_reset_at"] = time.Now().Add(-time.Second).Format(time.RFC3339) + } + if tc.name == "owned_quality_penalty" { + a.Extra["codex_5h_used_percent"] = 20.0 + a.Schedulable = false + cooldown := time.Now().Add(time.Hour) + a.TempUnschedulableUntil = &cooldown + } + } + templates := &issue817Templates{template: &QualityRuleTemplate{AccountFilter: QualityRuleAccountFilter{Statuses: tc.statuses}}} + if tc.unlinked { + templates.template = nil + } + if tc.lookupErr { + templates.err = errors.New("fixture storage unavailable") + } + results := &pelicanResults{} + svc := NewScheduledTestService(plans, results) + svc.templateRepo = templates + svc.qualityModels = func(context.Context, int64) ([]string, error) { return []string{"gpt-6-astra"}, nil } + runner := &ScheduledTestRunnerService{planRepo: plans, scheduledSvc: svc, accountTestSvc: &AccountTestService{accountRepo: &qualitySupportAccounts{account: a}}} + calls := 0 + runner.runPelican = func(_ context.Context, _ int64, _ string, cfg *PelicanTestConfig) (*ScheduledTestResult, error) { + calls++ + return &ScheduledTestResult{Status: "success", ResponseText: "21", PelicanConfig: cfg, QualityJudgment: &QualityJudgment{Verdict: "correct"}}, nil + } + plan := pelicanPlan() + plan.ManualQualityRun = tc.manual + plan.PelicanConfig.QuestionKind = "candy" + plan.PelicanConfig.ParallelCount = 1 + plan.PelicanConfig.Quality = &QualityPolicy{ExpectedAnswer: "21", Action: "disable_scheduling"} + started := time.Now() + require.Equal(t, tc.wantRun, runner.runOnePlan(context.Background(), plan)) + require.True(t, plans.finished, "even a skipped round must release its lease") + require.Equal(t, plans.lease, plans.finishedAt, "finish must use the claimed lease") + require.True(t, plans.next.After(started), "skip keeps the advanced schedule") + if tc.wantRun { + require.Equal(t, 1, calls) + require.Len(t, results.results, 1) + } else { + require.Zero(t, calls, "exhausted automatic round must not call upstream") + require.Empty(t, results.results, "no fabricated quality sample") + require.Empty(t, plans.outcomes, "no quality penalty or restoration") + } + }) + } +} diff --git a/backend/internal/service/quality_rule_template.go b/backend/internal/service/quality_rule_template.go index 4ae99d2aebca..fbc086cb30e5 100644 --- a/backend/internal/service/quality_rule_template.go +++ b/backend/internal/service/quality_rule_template.go @@ -71,6 +71,8 @@ type QualityRuleTemplateRepository interface { CreatePreset(ctx context.Context, preset *QualityRulePreset) (*QualityRulePreset, error) List(ctx context.Context) ([]*QualityRuleTemplate, error) Get(ctx context.Context, id int64) (*QualityRuleTemplate, error) + // ForPlan returns the current owning template, or nil for an independent plan. + ForPlan(ctx context.Context, planID int64) (*QualityRuleTemplate, error) Create(ctx context.Context, template *QualityRuleTemplate) (*QualityRuleTemplate, error) Update(ctx context.Context, template *QualityRuleTemplate) (*QualityRuleTemplate, error) // Delete removes the template and returns the rules it had created that still exist. diff --git a/backend/internal/service/quality_rule_template_test.go b/backend/internal/service/quality_rule_template_test.go index ff10a54345c7..50b6a7edbbee 100644 --- a/backend/internal/service/quality_rule_template_test.go +++ b/backend/internal/service/quality_rule_template_test.go @@ -116,6 +116,17 @@ func (r *fakeTemplateRepo) Get(_ context.Context, id int64) (*QualityRuleTemplat return r.snapshot(t), nil } +func (r *fakeTemplateRepo) ForPlan(ctx context.Context, planID int64) (*QualityRuleTemplate, error) { + for id, links := range r.links { + for _, linkedPlan := range links { + if linkedPlan == planID { + return r.Get(ctx, id) + } + } + } + return nil, nil +} + func (r *fakeTemplateRepo) Create(ctx context.Context, t *QualityRuleTemplate) (*QualityRuleTemplate, error) { r.nextID++ stored := *t diff --git a/backend/internal/service/scheduled_test_port.go b/backend/internal/service/scheduled_test_port.go index 9f1a0e3f2f31..7d2786d23a3a 100644 --- a/backend/internal/service/scheduled_test_port.go +++ b/backend/internal/service/scheduled_test_port.go @@ -37,6 +37,8 @@ type PelicanTestConfig struct { // ScheduledTestPlan represents a scheduled test plan domain model. type ScheduledTestPlan struct { + // Populated only from the repository's one-shot manual trigger marker. + ManualQualityRun bool `json:"-"` QualityBatchEvaluated bool `json:"-"` QualityBatchModels map[string]string `json:"-"` // Request-only: importing configuration preserves this target's ownership. From cb9db7e88bd715f3a8a3d0dd2e880b5074f23194 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 00:36:00 +0800 Subject: [PATCH 2/3] =?UTF-8?q?test:=20=E9=AA=8C=E8=AF=81=E9=A2=9D?= =?UTF-8?q?=E5=BA=A6=E8=B7=B3=E8=BF=87=E4=BF=9D=E7=95=99=E5=AE=9E=E9=99=85?= =?UTF-8?q?=E9=9A=94=E7=A6=BB=E5=BD=92=E5=B1=9E=E5=8F=8A=E6=81=A2=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/issue817-quality-quota.yml | 3 +- ...uality_quota_ownership_integration_test.go | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 backend/internal/repository/quality_quota_ownership_integration_test.go diff --git a/.github/workflows/issue817-quality-quota.yml b/.github/workflows/issue817-quality-quota.yml index 13c44703ed73..280a33e8e264 100644 --- a/.github/workflows/issue817-quality-quota.yml +++ b/.github/workflows/issue817-quality-quota.yml @@ -10,6 +10,7 @@ on: - 'backend/internal/service/pelican_scheduled.go' - 'backend/internal/service/scheduled_test_port.go' - 'backend/internal/repository/quality_template_quota*' + - 'backend/internal/repository/quality_quota_ownership*' - 'backend/internal/repository/quality_rule_template_repo.go' - 'backend/internal/repository/account_quality.go' - 'backend/internal/repository/scheduled_test_repo.go' @@ -44,7 +45,7 @@ jobs: - name: Record source formatting diff for static follow-up shell: bash run: | - gofmt -d backend/internal/service/quality_quota_filter*.go backend/internal/service/scheduled_test_port.go backend/internal/repository/quality_template_quota*.go > evidence/format.diff + gofmt -d backend/internal/service/quality_quota_filter*.go backend/internal/service/scheduled_test_port.go backend/internal/repository/quality_template_quota*.go backend/internal/repository/quality_quota_ownership*.go > evidence/format.diff cat evidence/format.diff - name: Original runner must fail the unchanged execution regression shell: bash diff --git a/backend/internal/repository/quality_quota_ownership_integration_test.go b/backend/internal/repository/quality_quota_ownership_integration_test.go new file mode 100644 index 000000000000..dd39a7d49586 --- /dev/null +++ b/backend/internal/repository/quality_quota_ownership_integration_test.go @@ -0,0 +1,33 @@ +//go:build integration + +package repository + +import ( + "context" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestIssue817QuotaSkipRetainsActualIsolationOwnership(t *testing.T) { + f, _, _ := newQualityIsolationFixture(t) + require.Equal(t, "models_isolated", isolationRound(f, "failed", "passed")) + ctx := context.Background() + require.NoError(t, f.plans.FinishPelican(ctx, f.plan.ID, f.until, time.Now())) + f.claim() + var stateBefore, accountBefore []byte + require.NoError(t, integrationDB.QueryRow(`SELECT state FROM account_quality_states WHERE plan_id=$1`, f.plan.ID).Scan(&stateBefore)) + require.NotEqual(t, "{}", string(stateBefore)) + require.NoError(t, integrationDB.QueryRow(`SELECT to_jsonb(a) FROM accounts a WHERE id=$1`, f.account).Scan(&accountBefore)) + require.NoError(t, f.plans.(service.QualityQuotaSkipRepository).FinishQuotaSkippedPelican(ctx, f.plan, f.until, time.Now())) + var stateAfter, accountAfter []byte + require.NoError(t, integrationDB.QueryRow(`SELECT state FROM account_quality_states WHERE plan_id=$1`, f.plan.ID).Scan(&stateAfter)) + require.NoError(t, integrationDB.QueryRow(`SELECT to_jsonb(a) FROM accounts a WHERE id=$1`, f.account).Scan(&accountAfter)) + require.JSONEq(t, string(stateBefore), string(stateAfter), "quota skip must retain actual model isolation ownership") + require.JSONEq(t, string(accountBefore), string(accountAfter), "skip cannot mutate the penalized account") + // The same ownership can still restore after quota recovery. + f.claim() + require.Equal(t, "restored", isolationRound(f, "passed", "passed")) +} From ff0558f24d152f2fc235f5e4c236db2939a37619 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 00:39:21 +0800 Subject: [PATCH 3/3] =?UTF-8?q?style:=20=E5=B1=95=E5=BC=80=E9=A2=9D?= =?UTF-8?q?=E5=BA=A6=E8=BE=B9=E7=95=8C=E5=9B=9E=E5=BD=92=E4=BE=BF=E4=BA=8E?= =?UTF-8?q?=E5=AE=A1=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/quality_quota_filter_test.go | 89 ++++++++++++++----- 1 file changed, 69 insertions(+), 20 deletions(-) diff --git a/backend/internal/service/quality_quota_filter_test.go b/backend/internal/service/quality_quota_filter_test.go index e0653cfc55ac..89a8822f1a05 100644 --- a/backend/internal/service/quality_quota_filter_test.go +++ b/backend/internal/service/quality_quota_filter_test.go @@ -29,24 +29,73 @@ func TestIssue817QuotaEvidence(t *testing.T) { {"weekly_exhausted", func(a *Account) { a.Extra["codex_7d_used_percent"] = 100.0 }, false}, {"over_100", func(a *Account) { a.Extra["codex_7d_used_percent"] = 101.0 }, false}, {"unknown", func(a *Account) { a.Extra = nil }, true}, - {"undated", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; delete(a.Extra, "codex_usage_updated_at") }, true}, - {"invalid_date", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Extra["codex_usage_updated_at"] = "unknown" }, true}, - {"future_date", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Extra["codex_usage_updated_at"] = now.Add(time.Hour).Format(time.RFC3339) }, true}, - {"stale_without_reset", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Extra["codex_usage_updated_at"] = now.Add(-3 * time.Hour).Format(time.RFC3339) }, true}, - {"old_but_current_week", func(a *Account) { a.Extra["codex_7d_used_percent"] = 100.0; a.Extra["codex_usage_updated_at"] = now.Add(-3 * time.Hour).Format(time.RFC3339); a.Extra["codex_7d_reset_at"] = now.Add(time.Hour).Format(time.RFC3339) }, false}, - {"five_hour_reset", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Extra["codex_5h_reset_at"] = now.Format(time.RFC3339) }, true}, - {"weekly_reset", func(a *Account) { a.Extra["codex_7d_used_percent"] = 100.0; a.Extra["codex_7d_reset_at"] = now.Add(-time.Second).Format(time.RFC3339) }, true}, - {"relative_reset", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Extra["codex_usage_updated_at"] = now.Add(-time.Hour).Format(time.RFC3339); a.Extra["codex_5h_reset_after_seconds"] = 3600 }, true}, + {"undated", func(a *Account) { + a.Extra["codex_5h_used_percent"] = 100.0 + delete(a.Extra, "codex_usage_updated_at") + }, true}, + {"invalid_date", func(a *Account) { + a.Extra["codex_5h_used_percent"] = 100.0 + a.Extra["codex_usage_updated_at"] = "unknown" + }, true}, + {"future_date", func(a *Account) { + a.Extra["codex_5h_used_percent"] = 100.0 + a.Extra["codex_usage_updated_at"] = now.Add(time.Hour).Format(time.RFC3339) + }, true}, + {"stale_without_reset", func(a *Account) { + a.Extra["codex_5h_used_percent"] = 100.0 + a.Extra["codex_usage_updated_at"] = now.Add(-3 * time.Hour).Format(time.RFC3339) + }, true}, + {"old_but_current_week", func(a *Account) { + a.Extra["codex_7d_used_percent"] = 100.0 + a.Extra["codex_usage_updated_at"] = now.Add(-3 * time.Hour).Format(time.RFC3339) + a.Extra["codex_7d_reset_at"] = now.Add(time.Hour).Format(time.RFC3339) + }, false}, + {"five_hour_reset", func(a *Account) { + a.Extra["codex_5h_used_percent"] = 100.0 + a.Extra["codex_5h_reset_at"] = now.Format(time.RFC3339) + }, true}, + {"weekly_reset", func(a *Account) { + a.Extra["codex_7d_used_percent"] = 100.0 + a.Extra["codex_7d_reset_at"] = now.Add(-time.Second).Format(time.RFC3339) + }, true}, + {"relative_reset", func(a *Account) { + a.Extra["codex_5h_used_percent"] = 100.0 + a.Extra["codex_usage_updated_at"] = now.Add(-time.Hour).Format(time.RFC3339) + a.Extra["codex_5h_reset_after_seconds"] = 3600 + }, true}, {"nan", func(a *Account) { a.Extra["codex_5h_used_percent"] = math.NaN() }, true}, {"infinite", func(a *Account) { a.Extra["codex_5h_used_percent"] = math.Inf(1) }, true}, {"bad_percent", func(a *Account) { a.Extra["codex_5h_used_percent"] = "unknown" }, true}, - {"other_platform", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Platform = PlatformAnthropic }, true}, - {"api_key", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Type = AccountTypeAPIKey }, true}, - {"other_identity", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Credentials = map[string]any{"chatgpt_account_id": "fixture-a"}; a.Extra["chatgpt_account_id"] = "fixture-b" }, true}, - {"live_429", func(a *Account) { reset := now.Add(time.Minute); a.RateLimitResetAt = &reset; a.Extra = nil }, false}, - {"expired_429", func(a *Account) { reset := now; a.RateLimitResetAt = &reset }, true}, - {"auto_pause_disabled_still_exhausted", func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0; a.Extra["auto_pause_5h_disabled"] = true }, false}, - {"below_full_even_with_lower_pause_threshold", func(a *Account) { a.Extra["codex_5h_used_percent"] = 99.0; a.Extra["auto_pause_5h_threshold"] = 50 }, true}, + {"other_platform", func(a *Account) { + a.Extra["codex_5h_used_percent"] = 100.0 + a.Platform = PlatformAnthropic + }, true}, + {"api_key", func(a *Account) { + a.Extra["codex_5h_used_percent"] = 100.0 + a.Type = AccountTypeAPIKey + }, true}, + {"other_identity", func(a *Account) { + a.Extra["codex_5h_used_percent"] = 100.0 + a.Credentials = map[string]any{"chatgpt_account_id": "fixture-a"} + a.Extra["chatgpt_account_id"] = "fixture-b" + }, true}, + {"live_429", func(a *Account) { + reset := now.Add(time.Minute) + a.RateLimitResetAt = &reset + a.Extra = nil + }, false}, + {"expired_429", func(a *Account) { + reset := now + a.RateLimitResetAt = &reset + }, true}, + {"auto_pause_disabled_still_exhausted", func(a *Account) { + a.Extra["codex_5h_used_percent"] = 100.0 + a.Extra["auto_pause_5h_disabled"] = true + }, false}, + {"below_full_even_with_lower_pause_threshold", func(a *Account) { + a.Extra["codex_5h_used_percent"] = 99.0 + a.Extra["auto_pause_5h_threshold"] = 50 + }, true}, } { t.Run(tc.name, func(t *testing.T) { a := issue817Account(now) @@ -116,12 +165,12 @@ func (r *issue817Claims) FinishPelican(ctx context.Context, id int64, until, fin func TestIssue817RunnerRechecksQuotaAfterClaim(t *testing.T) { for _, tc := range []struct { - name string - statuses []string - manual bool - unlinked bool + name string + statuses []string + manual bool + unlinked bool lookupErr bool - wantRun bool + wantRun bool }{ {"normal_only_five_hour", []string{"active"}, false, false, false, false}, {"normal_only_weekly", []string{"active"}, false, false, false, false},