From c462b2c484175bbf56731533c8e421f1c8a3fc4e Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 08:51:19 +0800 Subject: [PATCH 1/7] =?UTF-8?q?fix:=20=E9=A2=9D=E5=BA=A6=E8=B7=B3=E8=BF=87?= =?UTF-8?q?=E4=BF=9D=E7=95=99=E5=AE=9E=E9=99=85=E6=89=A7=E8=A1=8C=E6=97=B6?= =?UTF-8?q?=E9=97=B4=E4=B8=8E=E5=BE=85=E5=A4=84=E7=90=865xx=E4=BF=A1?= =?UTF-8?q?=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (cherry picked from commit af3f0da94920bdf67909eb0a6e8a3cca9560dc4c) --- .../quality_quota_5xx_integration_test.go | 104 ++++++++++++++++++ .../repository/quality_template_quota.go | 6 +- .../quality_quota_integration_helper.go | 33 ++++++ 3 files changed, 141 insertions(+), 2 deletions(-) create mode 100644 backend/internal/repository/quality_quota_5xx_integration_test.go create mode 100644 backend/internal/service/quality_quota_integration_helper.go 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() +} From 7ba84c20aed5f4faa91dc59ede06f82ef46bb1b2 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 08:52:11 +0800 Subject: [PATCH 2/7] =?UTF-8?q?ci:=20=E7=94=A8=E9=9A=94=E7=A6=BB=E6=97=A7?= =?UTF-8?q?=E7=94=9F=E4=BA=A7=E4=B8=8E=E7=9C=9F=E5=AE=9E=E8=A7=A6=E5=8F=91?= =?UTF-8?q?=E9=98=9F=E5=88=97=E9=AA=8C=E8=AF=81=E9=A2=9D=E5=BA=A6=E8=B7=B3?= =?UTF-8?q?=E8=BF=87P2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../issue817-quota-skip-followup.yml | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 .github/workflows/issue817-quota-skip-followup.yml diff --git a/.github/workflows/issue817-quota-skip-followup.yml b/.github/workflows/issue817-quota-skip-followup.yml new file mode 100644 index 000000000000..481ffc490e1d --- /dev/null +++ b/.github/workflows/issue817-quota-skip-followup.yml @@ -0,0 +1,95 @@ +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/service/quality_quota_integration_helper.go' + - '.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] + 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 + - uses: actions/setup-go@v6 + with: + go-version-file: ${{ matrix.behavior }}/backend/go.mod + cache-dependency-path: ${{ matrix.behavior }}/backend/go.sum + - 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 + (cd backend && go test -race -tags=integration ./internal/repository -run '^TestIssue817QuotaSkipPreservesPending5xxExecution$' -count=1 -v -timeout=10m) > evidence/pending-5xx.log 2>&1 + result=$? + set -e + cat evidence/pending-5xx.log + ! grep -Eq 'build failed|setup failed|undefined:|syntax error:|no tests to run|panic:|--- SKIP:' evidence/pending-5xx.log + if [ "$BEHAVIOR" = red ]; then + test "$result" -ne 0 + grep -F -- '--- FAIL: TestIssue817QuotaSkipPreservesPending5xxExecution/never_run' evidence/pending-5xx.log + grep -F -- '--- FAIL: TestIssue817QuotaSkipPreservesPending5xxExecution/previous_completed_run' evidence/pending-5xx.log + grep -F -- 'pending 5xx signal must execute after quota-skipped cron before acknowledgement' evidence/pending-5xx.log + else + test "$result" -eq 0 + grep -F -- '--- PASS: TestIssue817QuotaSkipPreservesPending5xxExecution/never_run' evidence/pending-5xx.log + grep -F -- '--- PASS: TestIssue817QuotaSkipPreservesPending5xxExecution/previous_completed_run' evidence/pending-5xx.log + fi + - 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|TestQualityRetestRestBlocksEveryClaimUntilDeadline)$' -count=1 -v -timeout=10m 2>&1 | tee ../evidence/retained-contracts.log + ! grep -Eq 'no tests to run|--- SKIP:' ../evidence/retained-contracts.log + - uses: actions/upload-artifact@v7 + if: always() + with: + name: issue817-skip-${{ matrix.behavior }}-${{ github.event_name }}-${{ github.run_id }} + path: ${{ matrix.behavior }}/evidence/ + if-no-files-found: error From f85c1dcd58d1319cd4768b355f1f6701cddd5698 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 09:00:16 +0800 Subject: [PATCH 3/7] =?UTF-8?q?ci:=20=E4=B8=BA=E7=9C=9F=E5=AE=9E=E9=A2=9D?= =?UTF-8?q?=E5=BA=A6=E8=A7=A6=E5=8F=91=E5=9B=9E=E5=BD=92=E4=BF=9D=E7=95=99?= =?UTF-8?q?=E8=BF=9C=E7=A8=8B=E5=90=AF=E5=8A=A8=E5=B4=A9=E6=BA=83=E5=A0=86?= =?UTF-8?q?=E6=A0=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../workflows/issue817-quota-skip-followup.yml | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/.github/workflows/issue817-quota-skip-followup.yml b/.github/workflows/issue817-quota-skip-followup.yml index 481ffc490e1d..b0a444affcfb 100644 --- a/.github/workflows/issue817-quota-skip-followup.yml +++ b/.github/workflows/issue817-quota-skip-followup.yml @@ -53,6 +53,18 @@ jobs: with: go-version-file: ${{ matrix.behavior }}/backend/go.mod cache-dependency-path: ${{ matrix.behavior }}/backend/go.sum + - name: Prepare existing sanitized startup crash 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: @@ -62,7 +74,7 @@ jobs: run: | set -euo pipefail set +e - (cd backend && go test -race -tags=integration ./internal/repository -run '^TestIssue817QuotaSkipPreservesPending5xxExecution$' -count=1 -v -timeout=10m) > evidence/pending-5xx.log 2>&1 + bash .github/scripts/oauth-degradation-integration-race.sh "issue817-$BEHAVIOR" "$PWD" '^TestIssue817QuotaSkipPreservesPending5xxExecution$' 10m > evidence/pending-5xx.log 2>&1 result=$? set -e cat evidence/pending-5xx.log @@ -91,5 +103,7 @@ jobs: if: always() with: name: issue817-skip-${{ matrix.behavior }}-${{ github.event_name }}-${{ github.run_id }} - path: ${{ matrix.behavior }}/evidence/ + path: | + ${{ matrix.behavior }}/evidence/ + evidence/ if-no-files-found: error From 4f051105efa10695cd38d5d7e1dbb8637ecb810b Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 13:18:40 +0800 Subject: [PATCH 4/7] =?UTF-8?q?ci:=20=E5=9B=BA=E5=AE=9Arace=E4=BA=8C?= =?UTF-8?q?=E8=BF=9B=E5=88=B6=E5=B9=B6=E6=8D=95=E8=8E=B7=E9=A2=9D=E5=BA=A6?= =?UTF-8?q?=E5=9B=9E=E5=BD=92=E5=90=AF=E5=8A=A8=E9=A6=96=E6=AC=A1=E4=BF=A1?= =?UTF-8?q?=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/issue817-race-gate.sh | 96 +++++++++++++++++++ .../issue817-quota-skip-followup.yml | 7 +- 2 files changed, 100 insertions(+), 3 deletions(-) create mode 100644 .github/scripts/issue817-race-gate.sh diff --git a/.github/scripts/issue817-race-gate.sh b/.github/scripts/issue817-race-gate.sh new file mode 100644 index 000000000000..a3ab3b400a98 --- /dev/null +++ b/.github/scripts/issue817-race-gate.sh @@ -0,0 +1,96 @@ +#!/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" +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 +# Even a successful debugger/startup comparison cannot turn a crash into GREEN. +exit "$result" diff --git a/.github/workflows/issue817-quota-skip-followup.yml b/.github/workflows/issue817-quota-skip-followup.yml index b0a444affcfb..e24f729fb5b7 100644 --- a/.github/workflows/issue817-quota-skip-followup.yml +++ b/.github/workflows/issue817-quota-skip-followup.yml @@ -8,6 +8,7 @@ on: - 'backend/internal/repository/quality_template_quota.go' - 'backend/internal/repository/quality_quota_5xx_integration_test.go' - 'backend/internal/service/quality_quota_integration_helper.go' + - '.github/scripts/issue817-race-gate.sh' - '.github/workflows/issue817-quota-skip-followup.yml' permissions: @@ -53,7 +54,7 @@ jobs: with: go-version-file: ${{ matrix.behavior }}/backend/go.mod cache-dependency-path: ${{ matrix.behavior }}/backend/go.sum - - name: Prepare existing sanitized startup crash diagnostics + - name: Prepare live first-signal startup diagnostics working-directory: ${{ matrix.behavior }} shell: bash run: | @@ -74,11 +75,11 @@ jobs: run: | set -euo pipefail set +e - bash .github/scripts/oauth-degradation-integration-race.sh "issue817-$BEHAVIOR" "$PWD" '^TestIssue817QuotaSkipPreservesPending5xxExecution$' 10m > evidence/pending-5xx.log 2>&1 + bash .github/scripts/issue817-race-gate.sh "$BEHAVIOR" "$PWD" '^TestIssue817QuotaSkipPreservesPending5xxExecution$' > evidence/pending-5xx.log 2>&1 result=$? set -e cat evidence/pending-5xx.log - ! grep -Eq 'build failed|setup failed|undefined:|syntax error:|no tests to run|panic:|--- SKIP:' evidence/pending-5xx.log + ! grep -Eq 'build failed|setup failed|undefined:|syntax error:|no tests to run|panic:|--- SKIP:|WARNING: DATA RACE|race detected during execution|Segmentation fault|core dumped' evidence/pending-5xx.log if [ "$BEHAVIOR" = red ]; then test "$result" -ne 0 grep -F -- '--- FAIL: TestIssue817QuotaSkipPreservesPending5xxExecution/never_run' evidence/pending-5xx.log From cc91a8d2bd6b965aa39191a2aa47061a251038e7 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 13:19:43 +0800 Subject: [PATCH 5/7] =?UTF-8?q?ci:=20=E5=B0=86race=E4=BA=8C=E8=BF=9B?= =?UTF-8?q?=E5=88=B6=E8=BA=AB=E4=BB=BD=E6=A0=A1=E9=AA=8C=E8=AE=BE=E4=B8=BA?= =?UTF-8?q?=E6=98=BE=E5=BC=8F=E5=BF=85=E9=9C=80=E9=97=A8=E6=A7=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/issue817-race-gate.sh | 2 ++ .github/workflows/issue817-quota-skip-followup.yml | 1 + 2 files changed, 3 insertions(+) diff --git a/.github/scripts/issue817-race-gate.sh b/.github/scripts/issue817-race-gate.sh index a3ab3b400a98..6c25cb5633c4 100644 --- a/.github/scripts/issue817-race-gate.sh +++ b/.github/scripts/issue817-race-gate.sh @@ -12,6 +12,7 @@ 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 @@ -92,5 +93,6 @@ GO 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/workflows/issue817-quota-skip-followup.yml b/.github/workflows/issue817-quota-skip-followup.yml index e24f729fb5b7..aeb847c28a30 100644 --- a/.github/workflows/issue817-quota-skip-followup.yml +++ b/.github/workflows/issue817-quota-skip-followup.yml @@ -79,6 +79,7 @@ jobs: result=$? set -e cat evidence/pending-5xx.log + test "$(cat evidence/binary-identity-ok.txt)" = passed ! grep -Eq 'build failed|setup failed|undefined:|syntax error:|no tests to run|panic:|--- SKIP:|WARNING: DATA RACE|race detected during execution|Segmentation fault|core dumped' evidence/pending-5xx.log if [ "$BEHAVIOR" = red ]; then test "$result" -ne 0 From 6e66361e2d8e1134bf622f27fe2ac314b15a9d43 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 13:28:00 +0800 Subject: [PATCH 6/7] =?UTF-8?q?ci:=20=E6=98=BE=E5=BC=8F=E6=8B=92=E7=BB=9D?= =?UTF-8?q?=E6=B1=A1=E6=9F=93RED=E8=AF=81=E6=8D=AE=E5=B9=B6=E9=80=90?= =?UTF-8?q?=E5=AD=90=E4=BE=8B=E6=A0=B8=E9=AA=8C=E5=A4=B1=E8=B4=A5=E5=BD=92?= =?UTF-8?q?=E5=9B=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/issue817-validate-evidence.sh | 33 +++++++++++ .../issue817-quota-skip-followup.yml | 59 +++++++++++++++---- 2 files changed, 79 insertions(+), 13 deletions(-) create mode 100644 .github/scripts/issue817-validate-evidence.sh 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 index aeb847c28a30..38d261775d7b 100644 --- a/.github/workflows/issue817-quota-skip-followup.yml +++ b/.github/workflows/issue817-quota-skip-followup.yml @@ -9,6 +9,7 @@ on: - 'backend/internal/repository/quality_quota_5xx_integration_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: @@ -50,6 +51,46 @@ jobs: # 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 @@ -80,17 +121,7 @@ jobs: set -e cat evidence/pending-5xx.log test "$(cat evidence/binary-identity-ok.txt)" = passed - ! grep -Eq 'build failed|setup failed|undefined:|syntax error:|no tests to run|panic:|--- SKIP:|WARNING: DATA RACE|race detected during execution|Segmentation fault|core dumped' evidence/pending-5xx.log - if [ "$BEHAVIOR" = red ]; then - test "$result" -ne 0 - grep -F -- '--- FAIL: TestIssue817QuotaSkipPreservesPending5xxExecution/never_run' evidence/pending-5xx.log - grep -F -- '--- FAIL: TestIssue817QuotaSkipPreservesPending5xxExecution/previous_completed_run' evidence/pending-5xx.log - grep -F -- 'pending 5xx signal must execute after quota-skipped cron before acknowledgement' evidence/pending-5xx.log - else - test "$result" -eq 0 - grep -F -- '--- PASS: TestIssue817QuotaSkipPreservesPending5xxExecution/never_run' evidence/pending-5xx.log - grep -F -- '--- PASS: TestIssue817QuotaSkipPreservesPending5xxExecution/previous_completed_run' evidence/pending-5xx.log - fi + 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 @@ -99,8 +130,10 @@ jobs: shell: bash run: | set -euo pipefail - go test -race -tags=integration ./internal/repository -run '^(TestIssue817QuotaSkipPreserves401AndOwnership|TestIssue817QuotaSkipRetainsActualIsolationOwnership|TestIssue817ManualTriggerIsOneShotAndLeaseFenced|TestQuality5xxClaimKeepsCronAndCoalescesScheduledRun|TestQualityRetestRestBlocksEveryClaimUntilDeadline)$' -count=1 -v -timeout=10m 2>&1 | tee ../evidence/retained-contracts.log - ! grep -Eq 'no tests to run|--- SKIP:' ../evidence/retained-contracts.log + 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 - uses: actions/upload-artifact@v7 if: always() with: From 1ec135aa46375cc8f94ceaeb667fd521dacf58c9 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 16:52:33 +0800 Subject: [PATCH 7/7] test: provision quota regression services before race startup --- .../issue817-quota-skip-followup.yml | 38 ++++++ .../repository/integration_harness_test.go | 122 ++++++++++-------- 2 files changed, 109 insertions(+), 51 deletions(-) diff --git a/.github/workflows/issue817-quota-skip-followup.yml b/.github/workflows/issue817-quota-skip-followup.yml index 38d261775d7b..1d333b74c6d1 100644 --- a/.github/workflows/issue817-quota-skip-followup.yml +++ b/.github/workflows/issue817-quota-skip-followup.yml @@ -7,6 +7,7 @@ on: 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' @@ -27,6 +28,34 @@ jobs: 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: @@ -134,6 +163,15 @@ jobs: 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: 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)