diff --git a/.github/scripts/issue817-race-gate.sh b/.github/scripts/issue817-race-gate.sh new file mode 100644 index 000000000000..6c25cb5633c4 --- /dev/null +++ b/.github/scripts/issue817-race-gate.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +# Remote CI only. Diagnostics never replace the first race regression result. +set -euo pipefail +label="$1" +checkout="$2" +regression="$3" +evidence="$checkout/evidence" +binary="$RUNNER_TEMP/issue817-$label-$GITHUB_RUN_ID.test" +mkdir -p "$evidence" +go version > "$evidence/toolchain.txt" +go env GOOS GOARCH CGO_ENABLED GOEXPERIMENT >> "$evidence/toolchain.txt" +uname -a > "$evidence/kernel.txt" +ldd --version > "$evidence/libc.txt" 2>&1 +printf 'go test -c -race -tags=integration ./internal/repository -o %q\n' "$binary" > "$evidence/command.txt" +printf 'cd %q && %q -test.run %q -test.count=1 -test.v=true -test.timeout=10m\n' "$checkout/backend/internal/repository" "$binary" "$regression" >> "$evidence/command.txt" +if ! (cd "$checkout/backend" && go test -c -race -tags=integration ./internal/repository -o "$binary") > "$evidence/build.log" 2>&1; then + cat "$evidence/build.log" + exit 1 +fi +go version -m "$binary" > "$evidence/binary-modules.txt" +go tool buildid "$binary" > "$evidence/binary-buildid.txt" +sha256sum "$binary" > "$evidence/binary-before.sha256" +ulimit -c 0 +export GOTRACEBACK=crash +set +e +(cd "$checkout/backend/internal/repository" && "$binary" -test.run "$regression" -test.count=1 -test.v=true -test.timeout=10m) > "$evidence/regression.log" 2>&1 +result=$? +set -e +cat "$evidence/regression.log" +printf '%s\n' "$result" > "$evidence/regression-exit.txt" +sha256sum "$binary" > "$evidence/binary-after.sha256" +cmp "$evidence/binary-before.sha256" "$evidence/binary-after.sha256" + +if [ "$result" -eq 139 ]; then + # Live first-signal capture avoids trusting the old core/executable mismatch. + # Keep ASLR enabled as in the uninstrumented invocation. Never print frame + # arguments, locals, the environment, memory dumps or raw core files. + set +e + (cd "$checkout/backend/internal/repository" && timeout --kill-after=5s 90s gdb -nx -batch \ + -iex 'set auto-load off' -iex 'set print frame-arguments none' \ + -ex 'set pagination off' -ex 'set confirm off' \ + -ex 'set disable-randomization off' -ex 'handle SIGSEGV stop print nopass' \ + -ex run -ex 'p $_siginfo' -ex 'info registers pc sp' \ + -ex 'x/8i $pc' -ex 'info sharedlibrary' -ex 'thread apply all bt' \ + --args "$binary" -test.run "$regression" -test.count=1 -test.v=true -test.timeout=60s) > "$evidence/first-signal.txt" 2>&1 + debugger_result=$? + # This still enters the exact TestMain but selects no product tests. It is + # a startup comparison only, and cannot satisfy either RED or GREEN. + (cd "$checkout/backend/internal/repository" && timeout --kill-after=5s 60s "$binary" -test.run '^$' -test.count=1 -test.v=true -test.timeout=45s) > "$evidence/startup-only.log" 2>&1 + startup_result=$? + set -e + printf '%s\n' "$debugger_result" > "$evidence/debugger-exit.txt" + printf '%s\n' "$startup_result" > "$evidence/startup-only-exit.txt" + + # Independent stdlib-only race binary exercises the observed os/exec+timer + # startup path without importing application code. A pass is not exoneration. + cat > "$RUNNER_TEMP/issue817-startup.go" <<'GO' +package main + +import ( + "context" + "fmt" + "os/exec" + "sync" + "time" +) + +func main() { + var workers sync.WaitGroup + for i := 0; i < 4; i++ { + workers.Add(1) + go func() { defer workers.Done(); for j := 0; j < 20; j++ { <-time.After(time.Millisecond) } }() + } + for _, args := range [][]string{{"info"}, {"image", "inspect", "postgres:18.1-alpine3.23"}} { + fmt.Println("stdlib startup before docker", args[0]) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + err := exec.CommandContext(ctx, "docker", args...).Run() + cancel() + fmt.Println("stdlib startup after docker", args[0], "error:", err) + } + workers.Wait() +} +GO + set +e + go build -race -o "$RUNNER_TEMP/issue817-startup" "$RUNNER_TEMP/issue817-startup.go" > "$evidence/stdlib-build.log" 2>&1 + smoke_build=$? + if [ "$smoke_build" -eq 0 ]; then + timeout --kill-after=5s 45s "$RUNNER_TEMP/issue817-startup" > "$evidence/stdlib-startup.log" 2>&1 + printf '%s\n' "$?" > "$evidence/stdlib-startup-exit.txt" + fi + set -e + printf '%s\n' "$smoke_build" > "$evidence/stdlib-build-exit.txt" + sha256sum "$binary" > "$evidence/binary-after-diagnostics.sha256" + cmp "$evidence/binary-before.sha256" "$evidence/binary-after-diagnostics.sha256" +fi +printf 'passed\n' > "$evidence/binary-identity-ok.txt" +# Even a successful debugger/startup comparison cannot turn a crash into GREEN. +exit "$result" diff --git a/.github/scripts/issue817-validate-evidence.sh b/.github/scripts/issue817-validate-evidence.sh new file mode 100644 index 000000000000..1d6a7633f8ac --- /dev/null +++ b/.github/scripts/issue817-validate-evidence.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# Remote CI evidence gate. Expected RED failures never excuse forbidden errors. +set -euo pipefail +behavior="$1" +first_result="$2" +log="$3" +test -r "$log" +if grep -Eq 'build failed|setup failed|undefined:|syntax error:|no tests to run|panic:|--- SKIP:|WARNING: DATA RACE|race detected during execution|Segmentation fault|segmentation fault|core dumped' "$log"; then + echo 'Rejected forbidden error in regression evidence' >&2 + exit 1 +fi +for child in never_run previous_completed_run; do + name="TestIssue817QuotaSkipPreservesPending5xxExecution/$child" + if [ "$behavior" = red ]; then + test "$first_result" -ne 0 + grep -F -- "--- FAIL: $name" "$log" + # Attribute the expected 1/actual 0 probe failure to each child's own + # execution section, rather than accepting one global diagnostic match. + awk -v name="$name" ' + $1 == "===" && $2 == "RUN" { selected = ($3 == name) } + selected && /expected:[[:space:]]*1([[:space:]]|$)/ { expected = 1 } + selected && /actual[[:space:]]*:[[:space:]]*0([[:space:]]|$)/ { actual = 1 } + selected && /pending 5xx signal must execute after quota-skipped cron before acknowledgement/ { diagnostic = 1 } + END { exit !(expected && actual && diagnostic) } + ' "$log" + elif [ "$behavior" = green ]; then + test "$first_result" -eq 0 + grep -F -- "--- PASS: $name" "$log" + else + echo 'Unknown evidence behavior' >&2 + exit 1 + fi +done diff --git a/.github/workflows/issue817-quota-skip-followup.yml b/.github/workflows/issue817-quota-skip-followup.yml new file mode 100644 index 000000000000..1d333b74c6d1 --- /dev/null +++ b/.github/workflows/issue817-quota-skip-followup.yml @@ -0,0 +1,182 @@ +name: Issue817 quota skip pending 5xx + +on: + push: + branches: [fix/issue817-quota-skip-followup-20261113] + pull_request: + paths: + - 'backend/internal/repository/quality_template_quota.go' + - 'backend/internal/repository/quality_quota_5xx_integration_test.go' + - 'backend/internal/repository/integration_harness_test.go' + - 'backend/internal/service/quality_quota_integration_helper.go' + - '.github/scripts/issue817-race-gate.sh' + - '.github/scripts/issue817-validate-evidence.sh' + - '.github/workflows/issue817-quota-skip-followup.yml' + +permissions: + contents: read + +concurrency: + group: issue817-skip-${{ github.event_name }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + pending-5xx: + runs-on: ubuntu-latest + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + behavior: [red, green] + # Provision services outside the race binary: the captured startup SIGSEGV + # occurred in TestMain's Docker subprocess path, before any product test. + 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' + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + path: ${{ matrix.behavior }} + - name: Record exact candidate and baseline blob + working-directory: ${{ matrix.behavior }} + env: + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} + BEHAVIOR: ${{ matrix.behavior }} + 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" = red ]; then + original=c424f8217da12cd4fb8d10aeaf1c4f2592c3f286 + source=backend/internal/repository/quality_template_quota.go + git fetch --no-tags --depth=1 origin "$original" + git rev-parse "$original:$source" | tee evidence/original-blob.txt + # Only the isolated RED checkout receives the old production blob. + git show "$original:$source" > "$source" + fi + - name: Reject contaminated RED evidence before running product regressions + working-directory: ${{ matrix.behavior }} + shell: bash + run: | + set -euo pipefail + cat > evidence/gate-valid-red.log <<'LOG' + === RUN TestIssue817QuotaSkipPreservesPending5xxExecution/never_run + expected: 1 + actual : 0 + Messages: pending 5xx signal must execute after quota-skipped cron before acknowledgement + === RUN TestIssue817QuotaSkipPreservesPending5xxExecution/previous_completed_run + expected: 1 + actual : 0 + Messages: pending 5xx signal must execute after quota-skipped cron before acknowledgement + --- FAIL: TestIssue817QuotaSkipPreservesPending5xxExecution + --- FAIL: TestIssue817QuotaSkipPreservesPending5xxExecution/never_run + --- FAIL: TestIssue817QuotaSkipPreservesPending5xxExecution/previous_completed_run + LOG + validator=.github/scripts/issue817-validate-evidence.sh + bash "$validator" red 1 evidence/gate-valid-red.log + for forbidden in 'WARNING: DATA RACE' 'panic: injected' 'Segmentation fault' '--- SKIP: injected' '[build failed]' 'no tests to run'; do + cp evidence/gate-valid-red.log evidence/gate-contaminated-red.log + printf '%s\n' "$forbidden" >> evidence/gate-contaminated-red.log + if bash "$validator" red 1 evidence/gate-contaminated-red.log; then + echo "Gate wrongly accepted forbidden evidence: $forbidden" >&2 + exit 1 + fi + done + # Both FAIL labels still exist; only the second child's diagnosis is + # missing. A first-child-only global grep would wrongly accept this. + awk '/=== RUN.*previous_completed_run/ { second=1 } second && /Messages:/ { next } { print }' evidence/gate-valid-red.log > evidence/gate-missing-second-diagnostic.log + if bash "$validator" red 1 evidence/gate-missing-second-diagnostic.log; then + echo 'Gate wrongly accepted a missing second-child diagnostic' >&2 + exit 1 + fi + if bash "$validator" red 0 evidence/gate-valid-red.log; then + echo 'Gate wrongly accepted a zero first RED exit' >&2 + exit 1 + fi + echo 'Evidence gate synthetic rejection regressions passed' + - uses: actions/setup-go@v6 + with: + go-version-file: ${{ matrix.behavior }}/backend/go.mod + cache-dependency-path: ${{ matrix.behavior }}/backend/go.sum + - name: Prepare live first-signal startup diagnostics + working-directory: ${{ matrix.behavior }} + shell: bash + run: | + set -euo pipefail + if ! command -v gdb >/dev/null; then + bash .github/scripts/ci-ubuntu-mirrors.sh + sudo apt-get update + sudo apt-get install -y --no-install-recommends gdb + fi + uname -a > evidence/kernel.txt + go version > evidence/toolchain.txt + - name: Real PostgreSQL plan and existing Redis trigger worker + working-directory: ${{ matrix.behavior }} + env: + CI: 'true' + BEHAVIOR: ${{ matrix.behavior }} + shell: bash + run: | + set -euo pipefail + set +e + bash .github/scripts/issue817-race-gate.sh "$BEHAVIOR" "$PWD" '^TestIssue817QuotaSkipPreservesPending5xxExecution$' > evidence/pending-5xx.log 2>&1 + result=$? + set -e + cat evidence/pending-5xx.log + test "$(cat evidence/binary-identity-ok.txt)" = passed + bash .github/scripts/issue817-validate-evidence.sh "$BEHAVIOR" "$result" evidence/pending-5xx.log + - name: Retained exact lease, 401, ownership, manual and trigger contracts + if: matrix.behavior == 'green' + working-directory: green/backend + env: + CI: 'true' + shell: bash + run: | + set -euo pipefail + go test -race -tags=integration ./internal/repository -run '^(TestIssue817QuotaSkipPreserves401AndOwnership|TestIssue817QuotaSkipRetainsActualIsolationOwnership|TestIssue817ManualTriggerIsOneShotAndLeaseFenced|TestQuality5xxClaimKeepsCronAndCoalescesScheduledRun|TestQuality5xxFinishConsumesCrossedCronWithoutOverwritingEdits|TestQualityRetestRestBlocksEveryClaimUntilDeadline)$' -count=1 -v -timeout=10m 2>&1 | tee ../evidence/retained-contracts.log + if grep -Eq 'no tests to run|--- SKIP:|panic:|WARNING: DATA RACE|race detected during execution' ../evidence/retained-contracts.log; then + exit 1 + fi + for required in \ + TestIssue817QuotaSkipPreserves401AndOwnership \ + TestIssue817QuotaSkipRetainsActualIsolationOwnership \ + TestIssue817ManualTriggerIsOneShotAndLeaseFenced \ + TestQuality5xxClaimKeepsCronAndCoalescesScheduledRun \ + TestQuality5xxFinishConsumesCrossedCronWithoutOverwritingEdits \ + TestQualityRetestRestBlocksEveryClaimUntilDeadline; do + grep -F -- "--- PASS: $required (" ../evidence/retained-contracts.log + done + - uses: actions/upload-artifact@v7 + if: always() + with: + name: issue817-skip-${{ matrix.behavior }}-${{ github.event_name }}-${{ github.run_id }} + path: | + ${{ matrix.behavior }}/evidence/ + evidence/ + if-no-files-found: error diff --git a/backend/internal/repository/integration_harness_test.go b/backend/internal/repository/integration_harness_test.go index 1d80bd56c279..e4a12bf3729b 100644 --- a/backend/internal/repository/integration_harness_test.go +++ b/backend/internal/repository/integration_harness_test.go @@ -38,7 +38,7 @@ var ( integrationDB *sql.DB integrationEntClient *dbent.Client integrationRedis *redisclient.Client - // Container-only connection string for tests that need a separate database. + // Isolated test connection string for tests that need a separate database. integrationPostgresDSN string redisNamespaceSeq uint64 @@ -52,46 +52,79 @@ func TestMain(m *testing.M) { os.Exit(1) } - if !dockerIsAvailable(ctx) { - // In CI we expect Docker to be available so integration tests should fail loudly. - if os.Getenv("CI") != "" { - log.Printf("docker is not available (CI=true); failing integration tests") + // CI may provision disposable services before starting the race binary. + // Require both endpoints so a typo cannot silently fall back to Docker. + dsn := strings.TrimSpace(os.Getenv("SUB2API_TEST_POSTGRES_DSN")) + redisURL := strings.TrimSpace(os.Getenv("SUB2API_TEST_REDIS_URL")) + if (dsn == "") != (redisURL == "") { + log.Printf("SUB2API_TEST_POSTGRES_DSN and SUB2API_TEST_REDIS_URL must be set together") + os.Exit(1) + } + var err error + var redisOptions *redisclient.Options + if dsn != "" { + redisOptions, err = redisclient.ParseURL(redisURL) + if err != nil { + log.Printf("invalid SUB2API_TEST_REDIS_URL") os.Exit(1) } - log.Printf("docker is not available; skipping integration tests (start Docker to enable)") - os.Exit(0) - } + log.Printf("using externally provisioned PostgreSQL and Redis test services") + } else { + if !dockerIsAvailable(ctx) { + // In CI we expect Docker to be available so integration tests should fail loudly. + if os.Getenv("CI") != "" { + log.Printf("docker is not available (CI=true); failing integration tests") + os.Exit(1) + } + log.Printf("docker is not available; skipping integration tests (start Docker to enable)") + os.Exit(0) + } - postgresImage := selectDockerImage(ctx, postgresImageTag) - pgContainer, err := tcpostgres.Run( - ctx, - postgresImage, - tcpostgres.WithDatabase("sub2api_test"), - tcpostgres.WithUsername("postgres"), - tcpostgres.WithPassword("postgres"), - tcpostgres.BasicWaitStrategies(), - ) - if err != nil { - log.Printf("failed to start postgres container: %v", err) - os.Exit(1) - } - defer func() { _ = pgContainer.Terminate(ctx) }() + postgresImage := selectDockerImage(ctx, postgresImageTag) + pgContainer, err := tcpostgres.Run( + ctx, + postgresImage, + tcpostgres.WithDatabase("sub2api_test"), + tcpostgres.WithUsername("postgres"), + tcpostgres.WithPassword("postgres"), + tcpostgres.BasicWaitStrategies(), + ) + if err != nil { + log.Printf("failed to start postgres container: %v", err) + os.Exit(1) + } + defer func() { _ = pgContainer.Terminate(ctx) }() - redisImage := os.Getenv("SUB2API_TEST_REDIS_IMAGE") - if redisImage == "" { - redisImage = redisImageTag - } - redisContainer, err := tcredis.Run(ctx, redisImage) - if err != nil { - log.Printf("failed to start redis container: %v", err) - os.Exit(1) - } - defer func() { _ = redisContainer.Terminate(ctx) }() + redisImage := os.Getenv("SUB2API_TEST_REDIS_IMAGE") + if redisImage == "" { + redisImage = redisImageTag + } + redisContainer, err := tcredis.Run(ctx, redisImage) + if err != nil { + log.Printf("failed to start redis container: %v", err) + os.Exit(1) + } + defer func() { _ = redisContainer.Terminate(ctx) }() - dsn, err := pgContainer.ConnectionString(ctx, "sslmode=disable", "TimeZone=UTC") - if err != nil { - log.Printf("failed to get postgres dsn: %v", err) - os.Exit(1) + dsn, err = pgContainer.ConnectionString(ctx, "sslmode=disable", "TimeZone=UTC") + if err != nil { + log.Printf("failed to get postgres dsn: %v", err) + os.Exit(1) + } + redisHost, err := redisContainer.Host(ctx) + if err != nil { + log.Printf("failed to get redis host: %v", err) + os.Exit(1) + } + redisPort, err := redisContainer.MappedPort(ctx, "6379/tcp") + if err != nil { + log.Printf("failed to get redis port: %v", err) + os.Exit(1) + } + redisOptions = &redisclient.Options{ + Addr: fmt.Sprintf("%s:%d", redisHost, redisPort.Int()), + DB: 0, + } } integrationPostgresDSN = dsn @@ -104,26 +137,13 @@ func TestMain(m *testing.M) { log.Printf("failed to apply db migrations: %v", err) os.Exit(1) } + log.Printf("integration PostgreSQL migrations complete") // 创建 ent client 用于集成测试 drv := entsql.OpenDB(dialect.Postgres, integrationDB) integrationEntClient = dbent.NewClient(dbent.Driver(drv)) - redisHost, err := redisContainer.Host(ctx) - if err != nil { - log.Printf("failed to get redis host: %v", err) - os.Exit(1) - } - redisPort, err := redisContainer.MappedPort(ctx, "6379/tcp") - if err != nil { - log.Printf("failed to get redis port: %v", err) - os.Exit(1) - } - - integrationRedis = redisclient.NewClient(&redisclient.Options{ - Addr: fmt.Sprintf("%s:%d", redisHost, redisPort.Int()), - DB: 0, - }) + integrationRedis = redisclient.NewClient(redisOptions) if err := integrationRedis.Ping(ctx).Err(); err != nil { log.Printf("failed to ping redis: %v", err) os.Exit(1) diff --git a/backend/internal/repository/quality_quota_5xx_integration_test.go b/backend/internal/repository/quality_quota_5xx_integration_test.go new file mode 100644 index 000000000000..6eb297b7027b --- /dev/null +++ b/backend/internal/repository/quality_quota_5xx_integration_test.go @@ -0,0 +1,104 @@ +//go:build integration + +package repository + +import ( + "context" + "encoding/json" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/qualityqueue" + "github.com/Wei-Shaw/sub2api/internal/pkg/qualityqueue/queuetest" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/alicebob/miniredis/v2" + "github.com/stretchr/testify/require" +) + +func TestIssue817QuotaSkipPreservesPending5xxExecution(t *testing.T) { + for _, previousRun := range []string{"never_run", "previous_completed_run"} { + t.Run(previousRun, func(t *testing.T) { + ctx := context.Background() + f := newQualityBPSFixture(t, `{}`, &service.QualityPolicy{Action: "disable_scheduling", TriggerOnUpstream5xx: true}) + require.NoError(t, f.plans.FinishPelican(ctx, f.plan.ID, f.until, time.Now())) + now := time.Now().UTC().Truncate(time.Microsecond) + var lastRun *time.Time + if previousRun == "previous_completed_run" { + prior := now.Add(-time.Hour) + lastRun = &prior + } + extra, err := json.Marshal(map[string]any{"codex_5h_used_percent": 100, "codex_usage_updated_at": now.Format(time.RFC3339Nano), "codex_5h_reset_at": now.Add(time.Hour).Format(time.RFC3339Nano)}) + require.NoError(t, err) + _, err = integrationDB.Exec(`UPDATE accounts SET extra=$2::jsonb WHERE id=$1`, f.account, string(extra)) + require.NoError(t, err) + _, err = integrationDB.Exec(`UPDATE scheduled_test_plans SET last_run_at=$2,next_run_at=$3 WHERE id=$1`, f.plan.ID, lastRun, now.Add(-time.Minute)) + require.NoError(t, err) + + templates := NewQualityRuleTemplateRepository(integrationEntClient, integrationDB) + template, err := templates.Create(ctx, &service.QualityRuleTemplate{AccountFilter: service.QualityRuleAccountFilter{Statuses: []string{"active"}}, + ModelID: f.plan.ModelID, CronExpression: f.plan.CronExpression, Enabled: true, MaxResults: f.plan.MaxResults, PelicanConfig: f.plan.PelicanConfig}) + require.NoError(t, err) + t.Cleanup(func() { _, _ = templates.Delete(context.Background(), template.ID) }) + _, err = integrationDB.Exec(`INSERT INTO quality_rule_template_accounts(template_id,account_id,plan_id) VALUES($1,$2,$3)`, template.ID, f.account, f.plan.ID) + require.NoError(t, err) + + redis := miniredis.RunT(t) + client := queuetest.NewClient(redis.Addr()) + t.Cleanup(func() { _ = client.Close() }) + queue := qualityqueue.NewRedis(client) + results := NewScheduledTestResultRepository(integrationDB) + scheduled := service.ProvideScheduledTestService(f.plans, results, templates, nil) + var calls atomic.Int32 + runner := service.NewQuotaTriggerRunnerForTesting(scheduled, NewAccountRepository(integrationEntClient, integrationDB, nil), queue, []string{f.plan.ModelID}, + func(_ context.Context, accountID int64, _ string, cfg *service.PelicanTestConfig) (*service.ScheduledTestResult, error) { + calls.Add(1) + if accountID != f.account { + return nil, service.ErrAccountNotFound + } + return &service.ScheduledTestResult{Status: "success", StartedAt: time.Now(), FinishedAt: time.Now(), PelicanConfig: cfg, + QualityJudgment: &service.QualityJudgment{Verdict: "correct"}}, nil + }) + t.Cleanup(runner.Stop) + + // The failure is pending before a timer claims and skips this plan. + signalAt := now.Add(-time.Second).Truncate(time.Millisecond) + require.NoError(t, queue.Enqueue(ctx, f.account, signalAt)) + plan, err := f.plans.GetByID(ctx, f.plan.ID) + require.NoError(t, err) + require.False(t, plan.ManualQualityRun) + require.False(t, runner.RunQuotaScheduledPlanForTesting(ctx, plan)) + require.Zero(t, calls.Load(), "quota-skipped cron must not execute a probe") + skipped, err := f.plans.GetByID(ctx, f.plan.ID) + require.NoError(t, err) + require.Nil(t, skipped.RunningUntil) + require.True(t, skipped.NextRunAt.After(now), "skip preserves the claimed next cron") + pending, err := queue.Pending(ctx, now.Add(-20*time.Minute)) + require.NoError(t, err) + require.Len(t, pending, 1) + // The provider window recovers before the queued failure is handled. + // A skipped timer still cannot count as evidence covering that failure. + _, err = integrationDB.Exec(`UPDATE accounts SET extra=jsonb_set(extra,'{codex_5h_used_percent}','20') WHERE id=$1`, f.account) + require.NoError(t, err) + + // Run the existing worker, including its real coverage check, claim + // fence, result persistence and Acknowledge. Do not start a cron. + runner.StartQuotaTriggerWorkerForTesting() + require.Eventually(t, func() bool { + pending, err := queue.Pending(ctx, now.Add(-20*time.Minute)) + return err == nil && len(pending) == 0 + }, 5*time.Second, 20*time.Millisecond, "trigger worker must finish and acknowledge its signal") + require.Equal(t, int32(1), calls.Load(), "pending 5xx signal must execute after quota-skipped cron before acknowledgement") + require.Equal(t, lastRun, skipped.LastRunAt, "zero-probe skip must preserve the previous executed round") + stored, err := results.ListByPlanID(ctx, f.plan.ID, 10) + require.NoError(t, err) + require.Len(t, stored, 1) + require.Equal(t, "upstream_5xx", stored[0].PelicanConfig.TriggerSource) + completed, err := f.plans.GetByID(ctx, f.plan.ID) + require.NoError(t, err) + require.NotNil(t, completed.LastRunAt) + require.False(t, completed.LastRunAt.Before(signalAt)) + require.True(t, skipped.NextRunAt.Equal(*completed.NextRunAt), "trigger retains the future cron schedule") + }) + } +} diff --git a/backend/internal/repository/quality_template_quota.go b/backend/internal/repository/quality_template_quota.go index d9d2be20f555..8eaaf8658d44 100644 --- a/backend/internal/repository/quality_template_quota.go +++ b/backend/internal/repository/quality_template_quota.go @@ -49,8 +49,10 @@ func (r *scheduledTestPlanRepository) FinishQuotaSkippedPelican(ctx context.Cont 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 { + // No probe ran: last_run_at must still describe the last executed round. + // Advancing it here would discard an earlier queued upstream 5xx signal. + if _, err = tx.ExecContext(ctx, `UPDATE scheduled_test_plans SET running_until=NULL + WHERE id=$1 AND running_until=$2`, plan.ID, until); err != nil { return err } return tx.Commit() diff --git a/backend/internal/service/quality_quota_integration_helper.go b/backend/internal/service/quality_quota_integration_helper.go new file mode 100644 index 000000000000..d1774c3259c7 --- /dev/null +++ b/backend/internal/service/quality_quota_integration_helper.go @@ -0,0 +1,33 @@ +//go:build integration + +package service + +import ( + "context" + + "github.com/Wei-Shaw/sub2api/internal/pkg/qualityqueue" +) + +// Integration-only bridge to the actual cron execution and trigger worker. +// Only model discovery/execution are replaced; repository, lease, coverage and +// queue acknowledgement paths remain the production implementations. +func NewQuotaTriggerRunnerForTesting(scheduled *ScheduledTestService, accounts AccountRepository, queue qualityqueue.Queue, models []string, + execute func(context.Context, int64, string, *PelicanTestConfig) (*ScheduledTestResult, error), +) *ScheduledTestRunnerService { + scheduled.qualityModels = func(context.Context, int64) ([]string, error) { return models, nil } + return &ScheduledTestRunnerService{ + planRepo: scheduled.planRepo, + scheduledSvc: scheduled, + accountTestSvc: &AccountTestService{accountRepo: accounts}, + runPelican: execute, + qualityTrigger: &quality5xxTrigger{queue: queue}, + } +} + +func (s *ScheduledTestRunnerService) RunQuotaScheduledPlanForTesting(ctx context.Context, plan *ScheduledTestPlan) bool { + return s.runOnePlan(ctx, plan) +} + +func (s *ScheduledTestRunnerService) StartQuotaTriggerWorkerForTesting() { + s.startQualityTriggers() +}