From 780a7edf7a9616b6a9deef274e2bcaf8d57b0a00 Mon Sep 17 00:00:00 2001 From: Jiawei Date: Sat, 21 Nov 2026 23:09:35 +0800 Subject: [PATCH] Report verified pre-commit test regressions to Patchwork Rebuild both filtered reports from their raw DejaGnu sums under the same allowlist and verify the eight expected target configurations. Publish a warning for incomplete comparisons or first observations and retain verified failures alongside coverage gaps. --- .../workflows/generate-precommit-summary.yaml | 317 +++++++----------- .github/workflows/pre-pull-request.yaml | 2 + configure-scripts/precommit-matrix.json | 58 ++++ docs/precommit-maintenance-runbook.md | 12 + riscv-gnu-toolchain | 2 +- scripts/precommit_result.py | 125 +++++++ scripts/prepare_test_comparison.py | 228 +++++++++++++ tests/test_precommit_result.py | 100 ++++++ tests/test_prepare_test_comparison.py | 190 +++++++++++ tests/test_workflow_recovery.py | 56 ++-- 10 files changed, 868 insertions(+), 222 deletions(-) create mode 100644 configure-scripts/precommit-matrix.json create mode 100644 scripts/precommit_result.py create mode 100644 scripts/prepare_test_comparison.py create mode 100644 tests/test_precommit_result.py create mode 100644 tests/test_prepare_test_comparison.py diff --git a/.github/workflows/generate-precommit-summary.yaml b/.github/workflows/generate-precommit-summary.yaml index 07f660d..f4bb731 100644 --- a/.github/workflows/generate-precommit-summary.yaml +++ b/.github/workflows/generate-precommit-summary.yaml @@ -48,6 +48,8 @@ jobs: if: ${{ always() && inputs.build_only != 'true' }} # ensure comparison always runs even on error runs-on: ubuntu-24.04 environment: production + env: + RESULT_SUFFIX: ${{ github.run_attempt > 1 && format('-attempt-{0}', github.run_attempt) || '' }} permissions: actions: read contents: read @@ -63,142 +65,78 @@ jobs: with: free_up_space: false - - name: Create directories - run: | - mkdir current_logs - mkdir temp - mkdir summaries - - - name: Set up Python - uses: actions/setup-python@v5 + - uses: actions/setup-python@v5 with: python-version: "3.11" - - name: Install Python dependencies - run: | - pip install -r ../requirements.txt --break-system-packages - - - name: Download baseline sum files + - name: Collect post-commit baseline sums env: - POSTCOMMIT_TOKEN: ${{ secrets.RISE_CI_READ_TOKEN }} - run: | - if [ -z "${POSTCOMMIT_TOKEN}" ]; then - echo "::error::RISE_CI_READ_TOKEN is required to read baseline artifacts from ${POSTCOMMIT_REPOSITORY}." - exit 1 - fi - # Download linux - python ./scripts/download_artifact.py -name gcc-linux-rv64gcv-lp64d-${{ inputs.baseline_hash }}-multilib-sum-files -repo "${POSTCOMMIT_REPOSITORY}" -token "${POSTCOMMIT_TOKEN}" -outdir ./temp - python ./scripts/download_artifact.py -name gcc-linux-rv64gc_zba_zbb_zbc_zbs-lp64d-${{ inputs.baseline_hash }}-non-multilib-sum-files -repo "${POSTCOMMIT_REPOSITORY}" -token "${POSTCOMMIT_TOKEN}" -outdir ./temp - python ./scripts/download_artifact.py -name gcc-linux-rv32gc_zba_zbb_zbc_zbs-ilp32d-${{ inputs.baseline_hash }}-non-multilib-sum-files -repo "${POSTCOMMIT_REPOSITORY}" -token "${POSTCOMMIT_TOKEN}" -outdir ./temp - # Download newlib - python ./scripts/download_artifact.py -name gcc-newlib-rv64gcv-lp64d-${{ inputs.baseline_hash }}-multilib-sum-files -repo "${POSTCOMMIT_REPOSITORY}" -token "${POSTCOMMIT_TOKEN}" -outdir ./temp - python ./scripts/download_artifact.py -name gcc-newlib-rv64gc-lp64d-${{ inputs.baseline_hash }}-non-multilib-sum-files -repo "${POSTCOMMIT_REPOSITORY}" -token "${POSTCOMMIT_TOKEN}" -outdir ./temp - python ./scripts/download_artifact.py -name gcc-newlib-rv32gc-ilp32d-${{ inputs.baseline_hash }}-non-multilib-sum-files -repo "${POSTCOMMIT_REPOSITORY}" -token "${POSTCOMMIT_TOKEN}" -outdir ./temp - python ./scripts/download_artifact.py -name gcc-newlib-rv64imc_zba_zbb_zbc_zbs-lp64d-${{ inputs.baseline_hash }}-multilib-sum-files -repo "${POSTCOMMIT_REPOSITORY}" -token "${POSTCOMMIT_TOKEN}" -outdir ./temp - - - name: Replace allowlist - run: | - rm -rf test/ - cp -r ../test/ . - - - name: Extract and parse baseline results - run: | - mkdir -p previous_logs - for file in $(find ./temp -name "*.zip"); do - unzip $file - if grep -q "linux" <<< $file; then - PARSE_EXISTING_REPORT="./scripts/testsuite-filter gcc glibc test/allowlist `find sum_files -name *.sum |paste -sd "," -`" - else - PARSE_EXISTING_REPORT="./scripts/testsuite-filter gcc newlib test/allowlist `find sum_files -name *.sum |paste -sd "," -`" - fi - ZIP_NAME=${file##*/} - FILE_NAME=${ZIP_NAME%%-multilib*} - echo $FILE_NAME - $PARSE_EXISTING_REPORT | tee "previous_logs/$FILE_NAME-multilib-report.log" - rm -rf sum_files - done - ls previous_logs + GH_TOKEN: ${{ secrets.RISE_CI_READ_TOKEN }} + BASELINE: ${{ inputs.baseline_hash }} + run: python ../scripts/prepare_test_comparison.py collect baseline "$BASELINE" --repo "$POSTCOMMIT_REPOSITORY" - - name: Separate multilib results - run: | - python scripts/separate_multilib_results.py -indir previous_logs -outdir previous_logs - ls previous_logs - continue-on-error: true - - # Download all current workflow artifacts + - name: Collect patch sums from this run + env: + GH_TOKEN: ${{ github.token }} + CANDIDATE: ${{ inputs.patch_applied_gcchash }} + run: python ../scripts/prepare_test_comparison.py collect candidate "$CANDIDATE" --repo "$GITHUB_REPOSITORY" --run-id "$GITHUB_RUN_ID" - - name: Print API usage info + - name: Compare matching boards with the pre-commit allowlist + env: + BASELINE: ${{ inputs.baseline_hash }} + CANDIDATE: ${{ inputs.patch_applied_gcchash }} run: | - curl \ - -H "Accept: application/vnd.github+json" \ - -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ - https://api.github.com/rate_limit - - - name: Download All targets - uses: ./.github/actions/download-all-comparison-artifacts + mkdir -p summaries + python ../scripts/prepare_test_comparison.py filter baseline "$BASELINE" + python ../scripts/prepare_test_comparison.py filter candidate "$CANDIDATE" + python scripts/compare_all_artifacts.py -hash "$CANDIDATE" --baseline-hash "$BASELINE" + python scripts/precommit_evidence.py --baseline "$BASELINE" --candidate "$CANDIDATE" \ + --matrix ../configure-scripts/precommit-matrix.json --baseline-sums baseline-sums --candidate-sums candidate-sums + + - name: Archive comparison evidence + id: evidence + uses: actions/upload-artifact@v4 with: - gcchash: ${{ inputs.patch_applied_gcchash }} - token: ${{ secrets.GITHUB_TOKEN }} - repo: ${{ env.PRECOMMIT_REPOSITORY }} + name: ${{ inputs.patch_applied_gcchash }}-comparison-evidence${{ env.RESULT_SUFFIX }} + path: riscv-gnu-toolchain/evidence/ + if-no-files-found: error + retention-days: 90 - - name: Print API usage info - run: | - curl \ - -H "Accept: application/vnd.github+json" \ - -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ - https://api.github.com/rate_limit + - name: Install build status dependencies + run: python -m pip install -r ../requirements.txt - - name: Separate multilib logs + - name: Read build results env: - GCC_HASH: ${{ inputs.patch_applied_gcchash }} - run: | - if ! python scripts/separate_multilib_results.py -indir current_logs -outdir current_logs; then - echo "multilib|Could not parse testsuite report" >> current_logs/failed_testsuite.txt - fi - rv32_log="current_logs/gcc-newlib-rv32imc_zba_zbb_zbc_zbs-ilp32-$GCC_HASH" - if [[ -f "$rv32_log-non-multilib-report.log" ]]; then - mv "$rv32_log-non-multilib-report.log" "$rv32_log-multilib-report.log" - fi - - - name: Compare artifacts - run: | - ls current_logs - python ./scripts/compare_all_artifacts.py -hash ${{ inputs.patch_applied_gcchash }} - - - name: Search for build failures - run: | - python scripts/update_issue_status.py -token ${{ secrets.GITHUB_TOKEN }} -comment ${{ inputs.build_comment_id }} -repo "${PRECOMMIT_REPOSITORY}" -failure -baseline ${{ inputs.baseline_hash }} - ls current_logs - continue-on-error: true - - - name: Remove testsuite failures on build-only - if: ${{ inputs.build_only == 'true' }} + GH_TOKEN: ${{ github.token }} + COMMENT_ID: ${{ inputs.build_comment_id }} + BASELINE: ${{ inputs.baseline_hash }} run: | - rm current_logs/failed_testsuite.txt - continue-on-error: true + python scripts/update_issue_status.py -token "$GH_TOKEN" -comment "$COMMENT_ID" -repo "$PRECOMMIT_REPOSITORY" -failure -baseline "$BASELINE" - name: Upload compare summaries + id: summaries + if: ${{ !cancelled() }} uses: actions/upload-artifact@v4 with: - name: ${{ inputs.patch_applied_gcchash }}-summaries - path: | - riscv-gnu-toolchain/summaries + name: ${{ inputs.patch_applied_gcchash }}-summaries${{ env.RESULT_SUFFIX }} + path: riscv-gnu-toolchain/summaries retention-days: 90 - name: Upload current log failures + id: current + if: ${{ !cancelled() }} uses: actions/upload-artifact@v4 with: - name: ${{ inputs.patch_applied_gcchash }}-current-logs - path: | - riscv-gnu-toolchain/current_logs + name: ${{ inputs.patch_applied_gcchash }}-current-logs${{ env.RESULT_SUFFIX }} + path: riscv-gnu-toolchain/current_logs retention-days: 90 - name: Upload baseline results + if: ${{ !cancelled() }} uses: actions/upload-artifact@v4 with: - name: ${{ inputs.patch_applied_gcchash }}-previous-logs - path: | - riscv-gnu-toolchain/previous_logs + name: ${{ inputs.patch_applied_gcchash }}-previous-logs${{ env.RESULT_SUFFIX }} + path: riscv-gnu-toolchain/previous_logs retention-days: 90 # Compare build warnings @@ -299,9 +237,12 @@ jobs: outputs: baseline_hash: ${{ inputs.baseline_hash }} + evidence_artifact_id: ${{ steps.evidence.outputs.artifact-id }} + summaries_artifact_id: ${{ steps.summaries.outputs.artifact-id }} + current_logs_artifact_id: ${{ steps.current.outputs.artifact-id }} generate-issues: - if: ${{ always() && inputs.build_only != 'true' }} # ensure generate issues always runs even on error + if: ${{ !cancelled() && inputs.build_only != 'true' }} needs: [compare-artifacts] runs-on: ubuntu-24.04 permissions: @@ -329,31 +270,44 @@ jobs: pip install -r ../requirements.txt --break-system-packages - name: Download summaries artifact + id: summaries + if: needs.compare-artifacts.outputs.summaries_artifact_id != '' + continue-on-error: true uses: actions/download-artifact@v4 with: - name: ${{ inputs.patch_applied_gcchash }}-summaries + artifact-ids: ${{ needs.compare-artifacts.outputs.summaries_artifact_id }} + merge-multiple: true path: ./riscv-gnu-toolchain/summaries - name: Download current logs artifact + id: current + if: needs.compare-artifacts.outputs.current_logs_artifact_id != '' + continue-on-error: true uses: actions/download-artifact@v4 with: - name: ${{ inputs.patch_applied_gcchash }}-current-logs + artifact-ids: ${{ needs.compare-artifacts.outputs.current_logs_artifact_id }} + merge-multiple: true path: ./riscv-gnu-toolchain/current_logs - - name: Download previous logs artifact + - name: Download verified comparison + id: evidence + if: needs.compare-artifacts.outputs.evidence_artifact_id != '' + continue-on-error: true uses: actions/download-artifact@v4 with: - name: ${{ inputs.patch_applied_gcchash }}-previous-logs - path: ./riscv-gnu-toolchain/previous_logs + artifact-ids: ${{ needs.compare-artifacts.outputs.evidence_artifact_id }} + merge-multiple: true + path: ./riscv-gnu-toolchain/evidence - name: Link testsuite logs from this run + continue-on-error: true env: GH_TOKEN: ${{ github.token }} GCC_HASH: ${{ inputs.patch_applied_gcchash }} run: | + : > debug-links.md gh api --paginate "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/artifacts?per_page=100" \ --jq '.artifacts[] | select(.expired == false) | [.name, .id] | @tsv' > run-artifacts.tsv - : > debug-links.md for target in linux-rv64gc_zba_zbb_zbc_zbs-lp64d linux-rv64gcv-lp64d newlib-rv64gcv-lp64d; do name="gcc-$target-$GCC_HASH-multilib-debug-output.log" id=$(awk -F '\t' -v name="$name" '$1 == name {print $2; exit}' run-artifacts.tsv) @@ -363,37 +317,33 @@ jobs: fi done - - name: Print API usage info - run: | - curl \ - -H "Accept: application/vnd.github+json" \ - -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ - https://api.github.com/rate_limit + - name: Aggregate filtered results + id: aggregate + if: steps.summaries.outcome == 'success' && steps.current.outcome == 'success' + continue-on-error: true + env: + GCC_HASH: ${{ inputs.patch_applied_gcchash }} + PATCH_NAME: ${{ inputs.patch_name }} + run: python ./scripts/aggregate.py -chash "$GCC_HASH" -patch "$PATCH_NAME" -o temp_comment.md - - name: Aggregate information - run: | - python ./scripts/aggregate.py \ - -chash ${{ inputs.patch_applied_gcchash }} \ - -patch ${{ inputs.patch_name }} \ - -o temp_comment.md - echo "## Testsuite Status" > comment.md - tail -n+5 temp_comment.md >> comment.md - cat comment.md - - - name: Print API usage info - run: | - curl \ - -H "Accept: application/vnd.github+json" \ - -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ - https://api.github.com/rate_limit + - name: Determine testsuite verdict + id: verdict + env: + COMPARISON_JOB: ${{ needs.compare-artifacts.result }} + AGGREGATE_STEP: ${{ steps.aggregate.outcome }} + EVIDENCE_STEP: ${{ steps.evidence.outcome }} + run: python ../scripts/precommit_result.py - name: Trim comment length # reduce the number of lines in final comment so github always creates comment + env: + ADDITIONAL_INFO: ${{ inputs.additional_info }} + EVIDENCE_ID: ${{ needs.compare-artifacts.outputs.evidence_artifact_id }} run: | # Max comment length is 65536. Allocate 1536 for extra statements head -c 64000 comment.md > trimmed_comment.md FILE_SIZE=$(stat -c%s "comment.md") if [ $FILE_SIZE -gt 64000 ]; then - printf "\n\`\`\`\nComment text has been trimmed. Please check logs for the untrimmed comment." >> trimmed_comment.md; + printf "\n\`\`\`\nComment text has been trimmed. The run artifacts contain the full comparison.\n" >> trimmed_comment.md # Max gist bytes are 1048576. Allocate 576 for extra statements ONE_MB_IN_BYTES=1048000 if [ $FILE_SIZE -gt $ONE_MB_IN_BYTES ]; then @@ -405,16 +355,21 @@ jobs: fi fi printf "\n### Testsuite download links\n\n" >> trimmed_comment.md + if [[ "$EVIDENCE_ID" =~ ^[0-9]+$ ]]; then + printf '[Complete comparison evidence](%s/%s/actions/runs/%s/artifacts/%s)\n\n' "$GITHUB_SERVER_URL" "$GITHUB_REPOSITORY" "$GITHUB_RUN_ID" "$EVIDENCE_ID" >> trimmed_comment.md + fi printf "Please check the Additional Information Build Targets section to see which testsuite log to look at. If you cannot download the artifacts or get a 404 error, you may need to sign in to github first.\n\n" >> trimmed_comment.md - cat debug-links.md >> trimmed_comment.md + if [[ -f debug-links.md ]]; then cat debug-links.md >> trimmed_comment.md; fi echo "" >> trimmed_comment.md - printf "\n[Additional information](${{ inputs.additional_info }})\n" >> trimmed_comment.md - cat trimmed_comment.md + printf '\n[Additional information](%s)\n' "$ADDITIONAL_INFO" >> trimmed_comment.md - name: Create Unresolved Errors Comment Gist + env: + GIST_TOKEN: ${{ secrets.GIST_TOKEN }} + GIST_TITLE: ${{ inputs.issue_num }}_${{ inputs.patch_name }}_${{ inputs.patch_applied_gcchash }}_summary.md run: | if [ -e "trimmed_comment_gist.md" ]; then - python3 ./scripts/create_gist.py --token ${{ secrets.GIST_TOKEN }} --input trimmed_comment_gist.md --output comment_gist_url.txt --title ${{ inputs.issue_num }}_${{ inputs.patch_name }}_${{ inputs.patch_applied_gcchash }}_summary.md + python3 ./scripts/create_gist.py --token "$GIST_TOKEN" --input trimmed_comment_gist.md --output comment_gist_url.txt --title "$GIST_TITLE" printf "\nGist URL: $(cat comment_gist_url.txt)" >> trimmed_comment.md fi continue-on-error: true @@ -429,52 +384,24 @@ jobs: body-path: riscv-gnu-toolchain/trimmed_comment.md edit-mode: replace - - name: Output issue labels - id: issue-labels - run: | - export LABELS=$(cat labels.txt) - echo "issue_labels=$LABELS" >> $GITHUB_OUTPUT - - - name: Add New regressions Label to Issue - if: ${{ contains(steps.issue-labels.outputs.issue_labels, 'new-regressions') }} - uses: actions/github-script@v7 - with: - script: | - github.rest.issues.addLabels({ - issue_number: ${{ inputs.issue_num }}, - owner: context.repo.owner, - repo: context.repo.repo, - labels: ['new-regressions'] - }) - - - name: Add Resolved regressions Label to Issue - if: ${{ contains(steps.issue-labels.outputs.issue_labels, 'resolved-regressions') }} - uses: actions/github-script@v7 - with: - script: | - github.rest.issues.addLabels({ - issue_number: ${{ inputs.issue_num }}, - owner: context.repo.owner, - repo: context.repo.repo, - labels: ['resolved-regressions'] - }) - - - name: Add incomplete result labels - if: ${{ contains(steps.issue-labels.outputs.issue_labels, 'testsuite-failure') || contains(steps.issue-labels.outputs.issue_labels, 'invalid') }} + - name: Reconcile testsuite labels uses: actions/github-script@v7 env: - RESULT_LABELS: ${{ steps.issue-labels.outputs.issue_labels }} + ISSUE_NUMBER: ${{ inputs.issue_num }} + RESULT_LABELS: ${{ steps.verdict.outputs.labels }} with: script: | - const labels = process.env.RESULT_LABELS.split(',').filter( - label => ['testsuite-failure', 'invalid'].includes(label) - ); - await github.rest.issues.addLabels({ - issue_number: ${{ inputs.issue_num }}, - owner: context.repo.owner, - repo: context.repo.repo, - labels - }); + const params = {...context.repo, issue_number: Number(process.env.ISSUE_NUMBER)}; + const wanted = new Set(process.env.RESULT_LABELS.split(',').filter(Boolean)); + const current = new Set((await github.paginate(github.rest.issues.listLabelsOnIssue, params)).map(label => label.name)); + const additions = [...wanted].filter(label => !current.has(label)); + if (additions.length) await github.rest.issues.addLabels({...params, labels: additions}); + const managed = ['new-regressions', 'resolved-regressions', 'invalid', 'testsuite-failure']; + // The build reporter also manages build-failure. Keep its evidence on an incomplete rerun. + if (!wanted.has('invalid')) managed.push('build-failure'); + for (const name of managed) { + if (current.has(name) && !wanted.has(name)) await github.rest.issues.removeLabel({...params, name}); + } # Adds comment which links issue to PR - name: Link Staging PR @@ -489,14 +416,12 @@ jobs: body: 'Pull request: ${{ github.event.pull_request.html_url }}' }) - - name: Report Failure - if: ${{ github.workflow != 'Staging' && (contains(steps.issue-labels.outputs.issue_labels, 'build-failure') || contains(steps.issue-labels.outputs.issue_labels, 'testsuite-failure') || contains(steps.issue-labels.outputs.issue_labels, 'new-regressions') || contains(steps.issue-labels.outputs.issue_labels, 'invalid')) }} - id: report-failure - run: | - python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid "$PATCH_ID" -desc 'Testing failed' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.test_comment_id }}' -state 'fail' -context 'test' -token '${{ secrets.PATCHWORK_API }}' - - - name: Report Success - if: ${{ github.workflow != 'Staging' && steps.report-failure.outcome == 'skipped' }} - id: report-success + - name: Publish testsuite verdict + if: ${{ !cancelled() && github.workflow != 'Staging' && steps.test-report.outcome == 'success' && steps.verdict.outcome == 'success' }} + env: + STATE: ${{ steps.verdict.outputs.state }} + DESCRIPTION: ${{ steps.verdict.outputs.description }} + PATCHWORK_TOKEN: ${{ secrets.PATCHWORK_API }} + TEST_REPORT: ${{ inputs.issue_num }}#issuecomment-${{ inputs.test_comment_id }} run: | - python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid "$PATCH_ID" -desc 'Testing passed' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.test_comment_id }}' -state 'success' -context 'test' -token '${{ secrets.PATCHWORK_API }}' + python scripts/post_check_to_patchworks.py -event "$GITHUB_EVENT_NAME" -repo "$PRECOMMIT_REPOSITORY" -pid "$PATCH_ID" -desc "$DESCRIPTION" -iid "$TEST_REPORT" -state "$STATE" -context test -token "$PATCHWORK_TOKEN" diff --git a/.github/workflows/pre-pull-request.yaml b/.github/workflows/pre-pull-request.yaml index 64ff435..edf44bd 100644 --- a/.github/workflows/pre-pull-request.yaml +++ b/.github/workflows/pre-pull-request.yaml @@ -13,6 +13,8 @@ jobs: runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 + with: + submodules: true - name: Set up Python uses: actions/setup-python@v5 diff --git a/configure-scripts/precommit-matrix.json b/configure-scripts/precommit-matrix.json new file mode 100644 index 0000000..834c54f --- /dev/null +++ b/configure-scripts/precommit-matrix.json @@ -0,0 +1,58 @@ +[ + { + "mode": "linux", + "arch": "rv32gcv", + "abi": "ilp32d", + "baseline": "gcc-linux-rv64gcv-lp64d-{sha}-multilib-sum-files", + "candidate": "gcc-linux-rv64gcv-lp64d-{sha}-multilib-sum-files" + }, + { + "mode": "linux", + "arch": "rv64gcv", + "abi": "lp64d", + "baseline": "gcc-linux-rv64gcv-lp64d-{sha}-multilib-sum-files", + "candidate": "gcc-linux-rv64gcv-lp64d-{sha}-multilib-sum-files" + }, + { + "mode": "linux", + "arch": "rv32gc_zba_zbb_zbc_zbs", + "abi": "ilp32d", + "baseline": "gcc-linux-rv32gc_zba_zbb_zbc_zbs-ilp32d-{sha}-non-multilib-sum-files", + "candidate": "gcc-linux-rv64gc_zba_zbb_zbc_zbs-lp64d-{sha}-multilib-sum-files" + }, + { + "mode": "linux", + "arch": "rv64gc_zba_zbb_zbc_zbs", + "abi": "lp64d", + "baseline": "gcc-linux-rv64gc_zba_zbb_zbc_zbs-lp64d-{sha}-non-multilib-sum-files", + "candidate": "gcc-linux-rv64gc_zba_zbb_zbc_zbs-lp64d-{sha}-multilib-sum-files" + }, + { + "mode": "newlib", + "arch": "rv32imc_zba_zbb_zbc_zbs", + "abi": "ilp32", + "baseline": "gcc-newlib-rv64imc_zba_zbb_zbc_zbs-lp64d-{sha}-multilib-sum-files", + "candidate": "gcc-newlib-rv64gcv-lp64d-{sha}-multilib-sum-files" + }, + { + "mode": "newlib", + "arch": "rv32gc", + "abi": "ilp32d", + "baseline": "gcc-newlib-rv32gc-ilp32d-{sha}-non-multilib-sum-files", + "candidate": "gcc-newlib-rv64gcv-lp64d-{sha}-multilib-sum-files" + }, + { + "mode": "newlib", + "arch": "rv64gc", + "abi": "lp64d", + "baseline": "gcc-newlib-rv64gc-lp64d-{sha}-non-multilib-sum-files", + "candidate": "gcc-newlib-rv64gcv-lp64d-{sha}-multilib-sum-files" + }, + { + "mode": "newlib", + "arch": "rv64gcv", + "abi": "lp64d", + "baseline": "gcc-newlib-rv64gcv-lp64d-{sha}-multilib-sum-files", + "candidate": "gcc-newlib-rv64gcv-lp64d-{sha}-multilib-sum-files" + } +] diff --git a/docs/precommit-maintenance-runbook.md b/docs/precommit-maintenance-runbook.md index 255fc71..1dd58c5 100644 --- a/docs/precommit-maintenance-runbook.md +++ b/docs/precommit-maintenance-runbook.md @@ -62,6 +62,18 @@ as passing tests. ## Failure Triage +Read the testsuite comment and its linked comparison evidence before assigning +a failure to the patch. The Patchwork `test` check uses the following outcomes. + +| State | Meaning | +| --- | --- | +| `fail` | The raw DejaGnu results show at least one matching subtest changing from PASS to FAIL. The comment identifies any incomplete targets separately. | +| `warning` | Results need review. A test may be newly observed, a build may have failed, or a comparable baseline or testsuite result may be missing. | +| `success` | The expected matrix was compared and has no verified regression or new result awaiting review. Known failures may still be present in both runs. | + +Use the build check for the affected target to diagnose a build failure. Track +reproducible GCC defects in the status issue or upstream bug tracker. + - Apply failures: check series order and prerequisites. Distinguish a patch that no longer applies to trunk from an artifact/download failure. - Build or testsuite failures: compare with the exact post-commit baseline and diff --git a/riscv-gnu-toolchain b/riscv-gnu-toolchain index 92b995f..ebf4aba 160000 --- a/riscv-gnu-toolchain +++ b/riscv-gnu-toolchain @@ -1 +1 @@ -Subproject commit 92b995f8ac464c3f6efba5332450fbcd479af97f +Subproject commit ebf4abafab24a73610a13dbe46a1eca50c5f109a diff --git a/scripts/precommit_result.py b/scripts/precommit_result.py new file mode 100644 index 0000000..093363b --- /dev/null +++ b/scripts/precommit_result.py @@ -0,0 +1,125 @@ +"""Render the pre-commit issue and Patchwork verdict from the comparison job.""" + +import json +import os +from pathlib import Path + + +def read_evidence(directory): + result = json.loads((directory / "verdict.json").read_text()) + if not isinstance(result, dict) or type(result.get("complete")) is not bool: + raise ValueError("missing coverage decision") + for key in ("confirmed", "unverified"): + if type(result.get(key)) is not int or result[key] < 0: + raise ValueError("invalid result count") + details = (directory / "evidence.md").read_text().strip() + if not details: + raise ValueError("missing comparison details") + return result, details + + +def render(root, comparison_ok, aggregate_ok, evidence_ok): + labels = set() + details = [] + incomplete = not comparison_ok + if not comparison_ok: + details.append("The comparison job did not finish successfully.") + + legacy = "" + if aggregate_ok: + try: + _, separator, legacy = ( + (root / "temp_comment.md").read_text().partition("\n---\n") + ) + if not separator or not legacy.strip(): + raise ValueError("empty aggregate report") + labels = set((root / "labels.txt").read_text().strip().split(",")) & { + "new-regressions", + "resolved-regressions", + "build-failure", + "testsuite-failure", + "invalid", + } + except (OSError, ValueError): + aggregate_ok = False + legacy = "" + if not aggregate_ok: + incomplete = True + details.append("The filtered comparison report is unavailable.") + if labels & {"build-failure", "testsuite-failure", "invalid"}: + incomplete = True + + confirmed = unverified = 0 + if evidence_ok: + try: + verdict, evidence = read_evidence(root / "evidence") + confirmed, unverified = verdict["confirmed"], verdict["unverified"] + incomplete |= not verdict["complete"] + details.append(evidence) + except (OSError, ValueError): + evidence_ok = False + if not evidence_ok: + incomplete = True + details.append("The verified comparison report is unavailable.") + + if "new-regressions" in labels: + labels.remove("new-regressions") + if evidence_ok and not (confirmed or unverified): + incomplete = True + details.append( + "The filtered report lists new observations that could not be " + "matched to the raw comparison." + ) + if incomplete: + labels.add("invalid") + if confirmed: + labels.add("new-regressions") + state = "fail" + transition = "transition" if confirmed == 1 else "transitions" + description = f"{confirmed} verified PASS to FAIL {transition}" + if incomplete: + description += " with incomplete coverage" + elif incomplete: + state = "warning" + description = "Testsuite comparison incomplete" + if "build-failure" in labels: + description += " after a build failure" + elif unverified: + state = "warning" + description = "Newly observed test results need review" + else: + state = "success" + description = "Complete testsuite comparison found no new regressions" + + if legacy: + # The shared aggregate includes cases with no comparable prior outcome. + legacy = legacy.replace("|New Failures|gcc|", "|Newly observed results|gcc|") + legacy = legacy.replace( + "\n## New Failures Across All Affected Targets", + "\n## Newly observed results across affected targets", + ).replace( + "\n## Architecture Specific New Failures", + "\n## Newly observed results by architecture", + ) + details.append(legacy.strip()) + (root / "comment.md").write_text( + "\n\n".join(["## Testsuite Status", f"**{description}.**", *details]) + "\n" + ) + return state, description, ",".join(sorted(labels)) + + +if __name__ == "__main__": + state, description, labels = render( + Path.cwd(), + os.environ["COMPARISON_JOB"] == "success", + os.environ["AGGREGATE_STEP"] == "success", + os.environ["EVIDENCE_STEP"] == "success", + ) + with open(os.environ["GITHUB_OUTPUT"], "a") as output: + print( + f"state={state}", + f"description={description}", + f"labels={labels}", + sep="\n", + file=output, + ) diff --git a/scripts/prepare_test_comparison.py b/scripts/prepare_test_comparison.py new file mode 100644 index 0000000..33f8b22 --- /dev/null +++ b/scripts/prepare_test_comparison.py @@ -0,0 +1,228 @@ +"""Collect the raw CI evidence and filter both sides using the pre-commit allowlist.""" + +import argparse +from collections import defaultdict +import json +from pathlib import Path +import re +import shutil +import subprocess +import sys +from tempfile import TemporaryDirectory, TemporaryFile +from time import sleep +from urllib.parse import urlencode +from zipfile import BadZipFile, ZipFile +import zlib + + +ROOT = Path(__file__).resolve().parents[1] +MATRIX = ROOT / "configure-scripts/precommit-matrix.json" +TOOLS = ("gcc", "g++", "gfortran") +MAX_ARCHIVE = 256 * 1024**2 +MAX_SUM = 512 * 1024**2 + + +def artifact_groups(matrix, role, revision): + groups = defaultdict(set) + for row in matrix: + name = row[role].format(sha=revision) + groups[name].add((row["arch"], row["abi"])) + return groups + + +def extract_sums(bundle, directory, prefix): + """Copy only the expected regular .sum names, regardless of other ZIP members.""" + found = False + for tool in TOOLS: + name = f"{tool}.sum" + members = [item for item in bundle.infolist() if item.filename == prefix + name] + if not members: + continue + if len(members) != 1 or members[0].file_size > MAX_SUM: + raise ValueError(f"Ambiguous or oversized {name}") + with bundle.open(members[0]) as source, (directory / name).open("wb") as output: + shutil.copyfileobj(source, output) + found = True + if not found: + raise ValueError("The archive contains no GCC language summaries") + + +def unpack_archive(path, directory, name, baseline): + with ZipFile(path) as outer: + if not baseline: + extract_sums(outer, directory, "") + return + # Post-commit uploads a named ZIP, pre-commit uploads the .sum files directly. + inner_name = name + ".zip" + members = [item for item in outer.infolist() if item.filename == inner_name] + if len(members) != 1 or members[0].file_size > MAX_ARCHIVE: + raise ValueError("Missing, ambiguous or oversized post-commit archive") + with TemporaryFile() as inner: + with outer.open(members[0]) as source: + shutil.copyfileobj(source, inner) + with ZipFile(inner) as bundle: + extract_sums(bundle, directory, "sum_files/") + + +def gh_api(args, output=subprocess.PIPE): + for attempt in range(2): + try: + return subprocess.run( + ["gh", "api", *args], + stdout=output, + stderr=subprocess.PIPE, + check=True, + timeout=300, + ).stdout + except (OSError, subprocess.SubprocessError) as err: + # gh diagnostics can include a signed download URL. + transient = isinstance(err, subprocess.TimeoutExpired) or re.search( + rb"timeout|timed out|connection reset|unexpected EOF|HTTP 5\d\d", + getattr(err, "stderr", None) or b"", + re.IGNORECASE, + ) + if attempt or not transient: + raise ValueError("GitHub Actions artifact request failed") from err + if output != subprocess.PIPE: + output.seek(0) + output.truncate() + sleep(1) + + +def collect(name, repo, run_id, storage): + endpoint = f"repos/{repo}/actions" + query = urlencode({"name": name, "per_page": 100}) + scope = f"/runs/{run_id}" if run_id else "" + lines = gh_api( + [ + f"{endpoint}{scope}/artifacts?{query}", + "--paginate", + "--jq", + ".artifacts[] | @json", + ] + ) + records = [json.loads(line) for line in lines.splitlines()] + matches = [ + row for row in records if row["name"] == name and row["expired"] is False + ] + if len(matches) != 1: + raise ValueError("Expected one unexpired artifact matching this build") + record = matches[0] + origin = run_id or record["workflow_run"]["id"] + if not (0 < record["size_in_bytes"] <= MAX_ARCHIVE): + raise ValueError("Empty or oversized Actions artifact") + with TemporaryDirectory(dir=storage) as tmp: + tmp = Path(tmp) + with (tmp / "archive.zip").open("wb") as output: + gh_api([f"{endpoint}/artifacts/{record['id']}/zip"], output) + extracted = tmp / "result" + extracted.mkdir() + unpack_archive(tmp / "archive.zip", extracted, name, baseline=run_id is None) + (extracted / "source.json").write_text( + json.dumps({"id": record["id"], "run_id": int(origin), "repository": repo}) + ) + extracted.rename(storage / name) + + +def prepare_reports(groups, storage, destination, revision, toolchain): + # Import the splitter from the toolchain gitlink used by this workflow. + sys.path.insert(0, str(toolchain / "scripts")) + from separate_multilib_results import read_report, split_report_name + + for name, targets in groups.items(): + directory = storage / name + sums = [ + directory / f"{tool}.sum" + for tool in TOOLS + if (directory / f"{tool}.sum").is_file() + ] + if not sums: + continue # The evidence check requires every target in MATRIX. + mode = name.split("-")[1] + with TemporaryDirectory() as temp: + filtered = Path(temp) / "report.log" + with filtered.open("wb") as output: + rc = subprocess.run( + [ + sys.executable, + toolchain / "scripts/testsuite-filter", + "gcc", + "glibc" if mode == "linux" else mode, + ROOT / "test/allowlist", + ",".join(map(str, sums)), + ], + stdout=output, + stderr=subprocess.PIPE, + ) + # testsuite-filter exits 1 both for unexpected results and for a crash. + try: + if rc.returncode not in (0, 1) or rc.stderr: + raise ValueError("testsuite-filter did not complete") + for board, report in read_report(filtered).items(): + if (board.arch, board.abi) in targets: + output = destination / split_report_name(mode, revision, board) + with output.open("x") as f: + f.write(report.text) + except (OSError, ValueError) as err: + record_problem( + name, + f"Could not prepare {storage.name} report ({err})", + ) + + +def record_problem(name, reason): + # The aggregate reads one artifact|message record per line. + reason = " ".join(reason.replace("|", "/").splitlines())[:500] + with Path("current_logs/failed_testsuite.txt").open("a") as problems: + problems.write(f"{name}|{reason}\n") + print(f"{name}: {reason}", file=sys.stderr) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("operation", choices=["collect", "filter"]) + parser.add_argument("role", choices=["baseline", "candidate"]) + parser.add_argument("revision") + parser.add_argument("--repo") + parser.add_argument("--run-id", type=int) + args = parser.parse_args() + if not re.fullmatch(r"[0-9a-f]{40}", args.revision): + parser.error("expected a full GCC SHA") + if args.operation == "collect" and ( + not args.repo or (args.role == "candidate") != bool(args.run_id) + ): + parser.error( + "specify a repository for each collection and a workflow run ID for the candidate" + ) + groups = artifact_groups(json.loads(MATRIX.read_text()), args.role, args.revision) + storage = Path(f"{args.role}-sums") + storage.mkdir(exist_ok=True) + Path("current_logs").mkdir(exist_ok=True) + if args.operation == "filter": + destination = Path( + "previous_logs" if args.role == "baseline" else "current_logs" + ) + destination.mkdir(exist_ok=True) + prepare_reports(groups, storage, destination, args.revision, Path.cwd()) + return + if any(storage.iterdir()): + parser.error(f"{storage} contains results from an earlier collection") + for name in groups: + try: + collect(name, args.repo, args.run_id, storage) + except ( + ValueError, + OSError, + KeyError, + TypeError, + BadZipFile, + RuntimeError, + EOFError, + zlib.error, + ) as err: + reason = str(err) if type(err) is ValueError else type(err).__name__ + record_problem(name, f"{args.role} artifact unavailable ({reason})") + + +if __name__ == "__main__": + main() diff --git a/tests/test_precommit_result.py b/tests/test_precommit_result.py new file mode 100644 index 0000000..44cc3f6 --- /dev/null +++ b/tests/test_precommit_result.py @@ -0,0 +1,100 @@ +import json +from pathlib import Path +import sys +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) +from precommit_result import render + + +class ResultTests(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + (self.root / "evidence").mkdir() + (self.root / "evidence/evidence.md").write_text("Evidence rows") + (self.root / "temp_comment.md").write_text( + "---\ntitle: Patch status\n---\n\n# Summary\n|New Failures|gcc|g++|\n" + ) + (self.root / "labels.txt").write_text("") + self.set_verdict() + + def set_verdict(self, confirmed=0, unverified=0, complete=True): + (self.root / "evidence/verdict.json").write_text( + json.dumps( + dict(confirmed=confirmed, unverified=unverified, complete=complete) + ) + ) + + def test_complete_known_failures_are_success(self): + (self.root / "labels.txt").write_text("resolved-regressions") + state, _, labels = render(self.root, True, True, True) + self.assertEqual(state, "success") + self.assertEqual(labels, "resolved-regressions") + + def test_unverified_observation_is_visible_and_warns(self): + self.set_verdict(unverified=1) + (self.root / "labels.txt").write_text("new-regressions") + state, _, labels = render(self.root, True, True, True) + self.assertEqual((state, labels), ("warning", "")) + body = (self.root / "comment.md").read_text() + self.assertIn("Evidence rows", body) + self.assertIn("Newly observed results|gcc|", body) + self.assertNotIn("|New Failures|", body) + + def test_unexplained_difference_between_filtered_and_raw_reports(self): + (self.root / "labels.txt").write_text("new-regressions") + state, _, labels = render(self.root, True, True, True) + self.assertEqual((state, labels), ("warning", "invalid")) + self.assertIn("could not be matched", (self.root / "comment.md").read_text()) + + def test_confirmed_result_survives_partial_matrix(self): + self.set_verdict(confirmed=2, complete=False) + (self.root / "labels.txt").write_text("build-failure") + state, description, labels = render(self.root, False, True, True) + self.assertEqual(state, "fail") + self.assertIn("incomplete coverage", description) + self.assertEqual(labels, "build-failure,invalid,new-regressions") + + def test_incomplete_inputs_never_report_success(self): + for flags in ((False, True, True), (True, False, True), (True, True, False)): + with self.subTest(flags=flags): + state, _, labels = render(self.root, *flags) + self.assertEqual((state, labels), ("warning", "invalid")) + self.set_verdict(complete=False) + self.assertEqual(render(self.root, True, True, True)[0], "warning") + + def test_build_failure_is_distinguished_from_regression(self): + (self.root / "labels.txt").write_text("build-failure") + state, description, labels = render(self.root, True, True, True) + self.assertEqual(state, "warning") + self.assertIn("build failure", description) + self.assertEqual(labels, "build-failure,invalid") + + def test_missing_or_malformed_evidence(self): + p = self.root / "evidence/verdict.json" + p.unlink() + self.assertEqual(render(self.root, True, True, True)[0], "warning") + for raw in ( + "{}", + "not JSON", + '{"confirmed":true,"unverified":0,"complete":true}', + ): + with self.subTest(raw=raw): + p.write_text(raw) + self.assertEqual(render(self.root, True, True, True)[0], "warning") + + def test_missing_aggregate_preserves_verified_rows(self): + self.set_verdict(confirmed=1) + (self.root / "temp_comment.md").unlink() + state, _, labels = render(self.root, True, True, True) + self.assertEqual((state, labels), ("fail", "invalid,new-regressions")) + self.assertIn("Evidence rows", (self.root / "comment.md").read_text()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_prepare_test_comparison.py b/tests/test_prepare_test_comparison.py new file mode 100644 index 0000000..c1cc670 --- /dev/null +++ b/tests/test_prepare_test_comparison.py @@ -0,0 +1,190 @@ +"""Check the mapping from raw Actions artifacts to the configured CI builds.""" + +import io +import json +from pathlib import Path +import re +import sys +import tempfile +import unittest +from unittest.mock import patch +from zipfile import ZipFile + + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) +import prepare_test_comparison as prep + + +def archive(files): + data = io.BytesIO() + with ZipFile(data, "w") as bundle: + for name, contents in files.items(): + bundle.writestr(name, contents) + return data.getvalue() + + +class ComparisonInputs(unittest.TestCase): + def test_matrix_covers_configured_patch_boards(self): + matrix = json.loads(prep.MATRIX.read_text()) + groups = prep.artifact_groups(matrix, "candidate", "a" * 40) + self.assertEqual(len(groups), 3) + self.assertEqual(sum(map(len, groups.values())), len(matrix)) + self.assertEqual(len(prep.artifact_groups(matrix, "baseline", "a" * 40)), 7) + for name, targets in groups.items(): + _, mode, arch, abi, *_ = name.split("-") + script = arch + "-" + abi + if mode == "newlib": + script += "-reduced-multilib-set" + configure = (ROOT / "configure-scripts" / script).read_text() + specs = re.search(r'--with-multilib-generator="([^"]+)"', configure)[1] + expected = { + tuple(spec.removesuffix("--").split("-")) for spec in specs.split(";") + } + self.assertEqual(targets, expected) + + def test_collects_only_sums_from_the_selected_producer(self): + name = "gcc-linux-rv64gcv-lp64d-" + "a" * 40 + "-multilib-sum-files" + for run in [None, 42]: + prefix = "sum_files/" if run is None else "" + sums = archive({prefix + "gcc.sum": b"PASS: test\n", "../unexpected": b"x"}) + outer = archive({name + ".zip": sums}) if run is None else sums + record = dict( + id=2, + workflow_run=dict(id=42), + name=name, + expired=False, + size_in_bytes=len(outer), + ) + with self.subTest(run=run), tempfile.TemporaryDirectory() as tmp: + storage = Path(tmp) + + def api(args, output=None): + if output is None: + scope = "/runs/42/artifacts?" if run else "/actions/artifacts?" + self.assertIn(scope, args[0]) + return json.dumps(record).encode() + self.assertTrue(args[0].endswith("/artifacts/2/zip")) + output.write(outer) + + with patch.object(prep, "gh_api", side_effect=api): + prep.collect(name, "rise/repo", run, storage) + dest = storage / name + self.assertEqual( + sorted(p.name for p in dest.iterdir()), ["gcc.sum", "source.json"] + ) + self.assertEqual( + json.loads((dest / "source.json").read_text()), + dict(repository="rise/repo", id=2, run_id=42), + ) + self.assertFalse((storage / "unexpected").exists()) + + def test_expired_ambiguous_and_unreadable_sources_are_not_promoted(self): + name = "test-sum-files" + record = dict( + id=2, workflow_run=dict(id=42), name=name, expired=False, size_in_bytes=1 + ) + with tempfile.TemporaryDirectory() as tmp: + dest = Path(tmp) + for rows in ([dict(record, expired=True)], [record, record], []): + with self.subTest(rows=rows), patch.object( + prep, + "gh_api", + return_value=b"\n".join(json.dumps(r).encode() for r in rows), + ): + with self.assertRaises(ValueError): + prep.collect(name, "rise/repo", None, dest) + self.assertEqual(list(dest.iterdir()), []) + + def missing(args, output=None): + if output is None: + return json.dumps(record).encode() + output.write(archive({"ignored.zip": b"other run"})) + + with patch.object(prep, "gh_api", side_effect=missing), self.assertRaises( + ValueError + ): + prep.collect(name, "rise/repo", None, dest) + self.assertEqual(list(dest.iterdir()), []) + + +@unittest.skipUnless( + (ROOT / "riscv-gnu-toolchain/scripts").is_dir(), + "initialize the toolchain submodule to run the integration test", +) +class PinnedToolchainComparison(unittest.TestCase): + def test_first_failure_on_clean_board_survives_partial_matrix(self): + import subprocess + from precommit_result import render + + matrix = json.loads(prep.MATRIX.read_text()) + row = next( + r for r in matrix if r["mode"] == "newlib" and r["arch"] == "rv64gcv" + ) + baseline = "a" * 40 + candidate = "b" * 40 + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "scripts").symlink_to( + ROOT / "riscv-gnu-toolchain/scripts", target_is_directory=True + ) + (root / "summaries").mkdir() + + def run_script(script, *args): + subprocess.run( + [sys.executable, "-B", script, *args], + cwd=root, + check=True, + stdout=subprocess.DEVNULL, + ) + + for role, revision in (("baseline", baseline), ("candidate", candidate)): + source = root / f"{role}-sums" / row[role].format(sha=revision) + source.mkdir(parents=True) + for language in ("gcc", "g++"): + failed = language == "gcc" and role == "candidate" + (source / f"{language}.sum").write_text( + "Target is riscv64-unknown-elf\n" + "Running target riscv-sim/-march=rv64gcv/-mabi=lp64d/-mcmodel=medlow\n" + "Running /build/gcc/testsuite/gcc.dg/dg.exp ...\n" + "PASS: gcc.dg/control.c -O2 execution test\n" + f"{'FAIL' if failed else 'PASS'}: gcc.dg/first.c -O2 execution test\n" + f"\t\t=== {language} Summary ===\n" + f"# of expected passes\t{1 if failed else 2}\n" + f"# of unexpected failures\t{int(failed)}\n" + ) + run_script(prep.__file__, "filter", role, revision) + + run_script( + "scripts/compare_all_artifacts.py", + "-hash", + candidate, + "--baseline-hash", + baseline, + ) + run_script( + "scripts/precommit_evidence.py", + "--baseline", + baseline, + "--candidate", + candidate, + "--matrix", + prep.MATRIX, + "--baseline-sums", + "baseline-sums", + "--candidate-sums", + "candidate-sums", + ) + run_script( + "scripts/aggregate.py", "-chash", candidate, "-o", "temp_comment.md" + ) + self.assertEqual( + json.loads((root / "evidence/verdict.json").read_text()), + {"complete": False, "confirmed": 1, "unverified": 0}, + ) + state, _, labels = render(root, True, True, True) + self.assertEqual(state, "fail") + self.assertIn("new-regressions", labels.split(",")) + self.assertIn( + "gcc.dg/first.c -O2 execution test", (root / "comment.md").read_text() + ) diff --git a/tests/test_workflow_recovery.py b/tests/test_workflow_recovery.py index d4269d6..8db2351 100644 --- a/tests/test_workflow_recovery.py +++ b/tests/test_workflow_recovery.py @@ -183,31 +183,37 @@ def test_manual_override_consumes_extracted_metadata(self): self.assertEqual(result.returncode, 0, result.stderr) self.assertIn("patch_id=12345", output.read_text()) - def test_invalid_summary_cannot_report_success(self): - block = named_step( - WORKFLOWS / "generate-precommit-summary.yaml", "Report Failure" - ) - expression = condition(block) - for labels in ("invalid", "resolved-regressions,invalid", "testsuite-failure"): - with self.subTest(labels=labels): - self.assertTrue( - evaluate( - expression, - { - "github.workflow": "Patchworks", - "steps.issue-labels.outputs.issue_labels": labels, - }, - ) - ) - self.assertFalse( - evaluate( - expression, - { - "github.workflow": "Patchworks", - "steps.issue-labels.outputs.issue_labels": "resolved-regressions", - }, - ) - ) + def test_final_patchwork_state_comes_from_published_verdict(self): + workflow = WORKFLOWS / "generate-precommit-summary.yaml" + block = named_step(workflow, "Publish testsuite verdict") + self.assertIn("STATE: ${{ steps.verdict.outputs.state }}", block) + self.assertIn('-state "$STATE"', block) + expr = condition(block) + values = { + "github.workflow": "Patchworks", + "steps.test-report.outcome": "success", + "steps.verdict.outcome": "success", + } + self.assertTrue(evaluate(expr, values)) + for key, value in ( + ("github.workflow", "Staging"), + ("steps.test-report.outcome", "failure"), + ("steps.verdict.outcome", "skipped"), + ): + self.assertFalse(evaluate(expr, {**values, key: value})) + + def test_summary_uses_comparison_job_artifact_ids(self): + workflow = WORKFLOWS / "generate-precommit-summary.yaml" + for name, key in ( + ("Download summaries artifact", "summaries"), + ("Download current logs artifact", "current_logs"), + ("Download verified comparison", "evidence"), + ): + output = f"needs.compare-artifacts.outputs.{key}_artifact_id" + block = named_step(workflow, name) + self.assertIn("artifact-ids: ${{ " + output + " }}", block) + self.assertIn(f"if: {output} != ''", block) + self.assertIn("merge-multiple: true", block) def test_empty_patch_selection_skips_build_setup(self): for workflow in ("patchworks.yaml", "downtime-runner.yaml"):