Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions .github/workflows/issue817-quality-quota.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
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_quota_ownership*'
- '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 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
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
3 changes: 2 additions & 1 deletion backend/internal/repository/account_quality.go
Original file line number Diff line number Diff line change
Expand Up @@ -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<NOW())
AND NOT EXISTS (SELECT 1 FROM account_quality_states rest WHERE rest.plan_id=scheduled_test_plans.id
AND COALESCE((pelican_config->'quality'->>'retest_rest_minutes')::int,0)>0
Expand Down
Original file line number Diff line number Diff line change
@@ -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"))
}
9 changes: 7 additions & 2 deletions backend/internal/repository/quality_rule_template_repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
57 changes: 57 additions & 0 deletions backend/internal/repository/quality_template_quota.go
Original file line number Diff line number Diff line change
@@ -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(&current)
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()
}
Loading
Loading