diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml index 42563fb..b285e16 100644 --- a/.github/actionlint.yaml +++ b/.github/actionlint.yaml @@ -1,3 +1,4 @@ self-hosted-runner: labels: - rise-gcc-ci + - rise-precommit-regression-07 diff --git a/.github/actions/common/download-comparison-artifacts/action.yaml b/.github/actions/common/download-comparison-artifacts/action.yaml index 47bfdbc..0ec6d4c 100644 --- a/.github/actions/common/download-comparison-artifacts/action.yaml +++ b/.github/actions/common/download-comparison-artifacts/action.yaml @@ -1,10 +1,8 @@ name: "Download Comparison Artifacts" -description: "Downloads artifacts needed for run comparison" +description: "Collect one testsuite report from the current workflow run" inputs: report-artifact-name: required: true - binary-artifact-name: - required: true github-token: required: true repo: @@ -13,44 +11,22 @@ inputs: runs: using: "composite" steps: - - name: Download report from this workflow - if: ${{ !cancelled() }} - uses: actions/download-artifact@v4 - with: - name: ${{ inputs.report-artifact-name }} - path: ./riscv-gnu-toolchain/current_logs - continue-on-error: true - - - name: Download report from another workflow - if: ${{ !cancelled() && hashFiles(format('./riscv-gnu-toolchain/current_logs/{0}', inputs.report-artifact-name)) == '' }} - shell: bash - run: | - cd riscv-gnu-toolchain - python ./scripts/download_artifact.py -name ${{ inputs.report-artifact-name }} -repo ${{ inputs.repo }} -token ${{ inputs.github-token }} -outdir current_logs - continue-on-error: true - - - name: Download rv32 non-multilib binary - if: ${{ !cancelled() && hashFiles(format('./riscv-gnu-toolchain/current_logs/{0}', inputs.report-artifact-name)) == '' }} - id: same-workflow-binary - uses: actions/download-artifact@v4 - with: - name: ${{ inputs.binary-artifact-name }} - path: ./riscv-gnu-toolchain/temp - continue-on-error: true - - - name: Download binary from another workflow - if: ${{ !cancelled() && hashFiles(format('./riscv-gnu-toolchain/current_logs/{0}', inputs.report-artifact-name)) == '' && steps.same-workflow-binary.outcome == 'failure' }} - shell: bash - run: | - cd riscv-gnu-toolchain - python ./scripts/download_artifact.py -name ${{ inputs.binary-artifact-name }} -repo ${{ inputs.repo }} -token ${{ inputs.github-token }} -outdir temp - continue-on-error: true - - - name: Record missing testsuite report - if: ${{ !cancelled() && hashFiles(format('./riscv-gnu-toolchain/current_logs/{0}', inputs.report-artifact-name)) == '' }} + - name: Collect the expected report from this run shell: bash env: - REPORT_ARTIFACT_NAME: ${{ inputs.report-artifact-name }} + GH_TOKEN: ${{ inputs.github-token }} + REPOSITORY: ${{ inputs.repo }} + REPORT_NAME: ${{ inputs.report-artifact-name }} run: | + directory=$(mktemp -d) + gh api --paginate "repos/$REPOSITORY/actions/runs/$GITHUB_RUN_ID/artifacts?per_page=100" \ + --jq '.artifacts[] | select(.expired == false and .size_in_bytes <= 268435456) | [.name, .id] | @tsv' > "$directory/artifacts.tsv" + artifact_id=$(awk -F '\t' -v name="$REPORT_NAME" '$1 == name {print $2; exit}' "$directory/artifacts.tsv") + if [[ "$artifact_id" =~ ^[0-9]+$ ]]; then + gh api "repos/$REPOSITORY/actions/artifacts/$artifact_id/zip" > "$directory/report.zip" + if python scripts/collect_testsuite_report.py "$directory/report.zip" "$REPORT_NAME" riscv-gnu-toolchain/current_logs; then + exit 0 + fi + fi mkdir -p riscv-gnu-toolchain/current_logs - printf '%s|Testsuite report artifact could not be downloaded\n' "$REPORT_ARTIFACT_NAME" >> riscv-gnu-toolchain/current_logs/failed_testsuite.txt + printf '%s|Testsuite report missing or invalid in this run\n' "$REPORT_NAME" >> riscv-gnu-toolchain/current_logs/failed_testsuite.txt diff --git a/.github/actions/download-all-comparison-artifacts/action.yaml b/.github/actions/download-all-comparison-artifacts/action.yaml index 84b42e7..9fb2cf6 100644 --- a/.github/actions/download-all-comparison-artifacts/action.yaml +++ b/.github/actions/download-all-comparison-artifacts/action.yaml @@ -16,7 +16,6 @@ runs: uses: ./.github/actions/common/download-comparison-artifacts with: report-artifact-name: gcc-linux-rv64gc_zba_zbb_zbc_zbs-lp64d-${{ inputs.gcchash }}-multilib-report.log - binary-artifact-name: gcc-linux-rv64gc_zba_zbb_zbc_zbs-lp64d-${{ inputs.gcchash }}-multilib github-token: ${{ inputs.token }} repo: ${{ inputs.repo }} @@ -24,7 +23,6 @@ runs: uses: ./.github/actions/common/download-comparison-artifacts with: report-artifact-name: gcc-linux-rv64gcv-lp64d-${{ inputs.gcchash }}-multilib-report.log - binary-artifact-name: gcc-linux-rv64gcv-lp64d-${{ inputs.gcchash }}-multilib github-token: ${{ inputs.token }} repo: ${{ inputs.repo }} @@ -32,7 +30,6 @@ runs: uses: ./.github/actions/common/download-comparison-artifacts with: report-artifact-name: gcc-newlib-rv64gcv-lp64d-${{ inputs.gcchash }}-multilib-report.log - binary-artifact-name: gcc-newlib-rv64gcv-lp64d-${{ inputs.gcchash }}-multilib github-token: ${{ inputs.token }} repo: ${{ inputs.repo }} diff --git a/.github/actions/report-build-complete-status/action.yaml b/.github/actions/report-build-complete-status/action.yaml index c3622df..423d074 100644 --- a/.github/actions/report-build-complete-status/action.yaml +++ b/.github/actions/report-build-complete-status/action.yaml @@ -4,6 +4,9 @@ inputs: build_status: description: 'Build status' required: true + patch_id: + description: 'Patchwork ID from trusted discovery metadata' + required: true patch_name: description: 'Name of patch' required: true @@ -56,15 +59,23 @@ runs: python scripts/update_issue_status.py -token ${{ inputs.github_token }} -state 'Success' -comment ${{ inputs.build_comment_id }} -target ${{ inputs.target }} -check 'Build GCC' -repo '${{ inputs.repository }}' -baseline $HASH printf "\n[Additional information](${{ inputs.additional_info }})\n" >> comment.md + - name: Read build log previews + id: preview + if: ${{ inputs.build_status == 'failure' && inputs.gist_token != '' }} + shell: bash + env: + GH_TOKEN: ${{ inputs.github_token }} + LOG_NAME: ${{ inputs.build_log_name }} + run: python3 scripts/build_log_preview.py "$LOG_NAME" "$RUNNER_TEMP/build-preview" + continue-on-error: true + - name: Build combined stdout/stderr gist - if: ${{ inputs.build_status == 'failure' }} + if: ${{ steps.preview.outcome == 'success' }} id: tail-gist-url shell: bash working-directory: riscv-gnu-toolchain run: | - ONE_MB_IN_BYTES=1048000 - tail -c $ONE_MB_IN_BYTES build/${{ inputs.build_log_name }}.log >> gist.md - python3 ./scripts/create_gist.py --token ${{ inputs.gist_token }} --input gist.md --output gist_url.txt --title ${{ inputs.issue_num }}_${{ inputs.patch_name }}_${{ inputs.build_log_name }}.log + python3 ./scripts/create_gist.py --token ${{ inputs.gist_token }} --input "$RUNNER_TEMP/build-preview/stdout.txt" --output gist_url.txt --title ${{ inputs.issue_num }}_${{ inputs.patch_name }}_${{ inputs.build_log_name }}.log GIST_URL=$(cat gist_url.txt) echo "gist url: $GIST_URL" RAW_GIST_URL=$GIST_URL/raw/${{ inputs.issue_num }}_${{ inputs.patch_name }}_${{ inputs.build_log_name }}.log @@ -73,14 +84,12 @@ runs: continue-on-error: true - name: Build stderr report gist - if: ${{ inputs.build_status == 'failure' }} + if: ${{ steps.preview.outcome == 'success' }} id: stderr-gist-url shell: bash working-directory: riscv-gnu-toolchain run: | - ONE_MB_IN_BYTES=1048000 - tail -c $ONE_MB_IN_BYTES build/${{ inputs.build_log_name }}-stderr.log >> gist.md - python3 ./scripts/create_gist.py --token ${{ inputs.gist_token }} --input gist.md --output gist_url.txt --title ${{ inputs.issue_num }}_${{ inputs.patch_name }}_${{ inputs.build_log_name }}-stderr.log + python3 ./scripts/create_gist.py --token ${{ inputs.gist_token }} --input "$RUNNER_TEMP/build-preview/stderr.txt" --output gist_url.txt --title ${{ inputs.issue_num }}_${{ inputs.patch_name }}_${{ inputs.build_log_name }}-stderr.log GIST_URL=$(cat gist_url.txt) echo "gist url: $GIST_URL" RAW_GIST_URL=$GIST_URL/raw/${{ inputs.issue_num }}_${{ inputs.patch_name }}_${{ inputs.build_log_name }}-stderr.log @@ -92,9 +101,16 @@ runs: if: ${{ inputs.build_status == 'failure' }} shell: bash working-directory: riscv-gnu-toolchain + env: + LOG_NAME: ${{ inputs.build_log_name }} + STDOUT_URL: ${{ steps.tail-gist-url.outputs.gist_url }} + STDERR_URL: ${{ steps.stderr-gist-url.outputs.gist_url }} run: | if [ '${{ inputs.build_only }}' == 'true' ]; then export HASH=${{ inputs.tot_hash }}; else export HASH=${{ inputs.baseline_hash }}; fi - python scripts/update_issue_status.py -token ${{ inputs.github_token }} -state 'Build failure. Please check the ${{ inputs.build_log_name }} artifact. [Tail Preview (1MB)](${{ steps.tail-gist-url.outputs.gist_url }}), [Stderr preview](${{ steps.stderr-gist-url.outputs.gist_url }})' -comment ${{ inputs.build_comment_id }} -target ${{ inputs.target }} -check 'Build GCC' -repo '${{ inputs.repository }}' -baseline $HASH + state="Build failure. See the $LOG_NAME artifact in [this run]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID)." + if [[ -n "$STDOUT_URL" ]]; then state+=" [Tail preview]($STDOUT_URL)"; fi + if [[ -n "$STDERR_URL" ]]; then state+=" [Stderr preview]($STDERR_URL)"; fi + python scripts/update_issue_status.py -token ${{ inputs.github_token }} -state "$state" -comment ${{ inputs.build_comment_id }} -target ${{ inputs.target }} -check 'Build GCC' -repo '${{ inputs.repository }}' -baseline $HASH printf "\n[Additional information](${{ inputs.additional_info }})\n" >> comment.md - name: Update build complete report comment @@ -121,11 +137,11 @@ runs: shell: bash working-directory: riscv-gnu-toolchain run: | - python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo '${{ inputs.repository }}' -pid $(tail -n 1 patches/${{ inputs.patch_name }}) -desc 'Build failed' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.build_comment_id }}' -state 'fail' -context 'build--${{ inputs.target }}' -token '${{ inputs.patchwork_token }}' + python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo '${{ inputs.repository }}' -pid '${{ inputs.patch_id }}' -desc 'Build failed' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.build_comment_id }}' -state 'fail' -context 'build--${{ inputs.target }}' -token '${{ inputs.patchwork_token }}' - name: Report build success if: ${{ inputs.build_status == 'success' && github.workflow != 'Staging' }} shell: bash working-directory: riscv-gnu-toolchain run: | - python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo '${{ inputs.repository }}' -pid $(tail -n 1 patches/${{ inputs.patch_name }}) -desc 'Build passed' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.build_comment_id }}' -state 'success' -context 'build--${{ inputs.target }}' -token '${{ inputs.patchwork_token }}' + python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo '${{ inputs.repository }}' -pid '${{ inputs.patch_id }}' -desc 'Build passed' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.build_comment_id }}' -state 'success' -context 'build--${{ inputs.target }}' -token '${{ inputs.patchwork_token }}' diff --git a/.github/workflows/call-patchworks-api.yaml b/.github/workflows/call-patchworks-api.yaml index fd255da..e47110b 100644 --- a/.github/workflows/call-patchworks-api.yaml +++ b/.github/workflows/call-patchworks-api.yaml @@ -33,7 +33,6 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - cache: "pip" - name: Install Python dependencies run: | @@ -123,7 +122,6 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - cache: "pip" - name: Install Python dependencies run: | @@ -155,7 +153,6 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - cache: "pip" - name: Install Python dependencies run: | @@ -186,7 +183,6 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - cache: "pip" - name: Install Python dependencies run: | diff --git a/.github/workflows/downtime-runner.yaml b/.github/workflows/downtime-runner.yaml index 9f38888..ef8e780 100644 --- a/.github/workflows/downtime-runner.yaml +++ b/.github/workflows/downtime-runner.yaml @@ -33,7 +33,6 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - cache: "pip" - name: Install Python dependencies run: | @@ -101,7 +100,6 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - cache: "pip" - name: Install Python dependencies run: | @@ -141,7 +139,7 @@ jobs: id: list_patches run: | if [ -f ./artifact_names.txt ]; then - export PATCHLIST="$(cat artifact_names.txt)" + PATCHLIST=$(python ../scripts/patch_matrix.py) else export PATCHLIST='[]' fi @@ -166,12 +164,12 @@ jobs: retention-days: 90 outputs: - list_of_patch_names: ${{ steps.list_patches.outputs.patch_list }} + patch_targets: ${{ steps.list_patches.outputs.patch_list }} end_date: ${{ steps.timestamps.outputs.end_date }} init-submodules: needs: [check_last_runner, fetch_patches] - if: ${{ needs.fetch_patches.outputs.list_of_patch_names != '[]' }} + if: ${{ needs.fetch_patches.outputs.patch_targets != '[]' }} uses: ./.github/workflows/init-submodules.yaml secrets: inherit @@ -179,7 +177,7 @@ jobs: needs: [check_last_runner, fetch_patches, init-submodules, patch_matrix] # Empty queues intentionally skip the downstream jobs. Failed or cancelled # processing must retain the old checkpoint so the next scan can retry it. - if: ${{ !cancelled() && needs.check_last_runner.result == 'success' && needs.fetch_patches.result == 'success' && (needs.fetch_patches.outputs.list_of_patch_names == '[]' || (needs.init-submodules.result == 'success' && needs.patch_matrix.result == 'success')) }} + if: ${{ !cancelled() && needs.check_last_runner.result == 'success' && needs.fetch_patches.result == 'success' && (needs.fetch_patches.outputs.patch_targets == '[]' || (needs.init-submodules.result == 'success' && needs.patch_matrix.result == 'success')) }} runs-on: ubuntu-24.04 permissions: contents: read @@ -204,7 +202,7 @@ jobs: strategy: fail-fast: false matrix: - patch_name: ${{ fromJSON(needs.fetch_patches.outputs.list_of_patch_names) }} + include: ${{ fromJSON(needs.fetch_patches.outputs.patch_targets) }} uses: ./.github/workflows/run-checks.yaml permissions: actions: read @@ -212,6 +210,7 @@ jobs: issues: write with: patch_name: ${{ matrix.patch_name }} + patch_id: ${{ matrix.patch_id }} baseline_hash: ${{ needs.init-submodules.outputs.baseline_hash }} tot_hash: ${{ needs.init-submodules.outputs.tot_hash }} secrets: inherit diff --git a/.github/workflows/generate-precommit-summary.yaml b/.github/workflows/generate-precommit-summary.yaml index 371f13e..07f660d 100644 --- a/.github/workflows/generate-precommit-summary.yaml +++ b/.github/workflows/generate-precommit-summary.yaml @@ -3,6 +3,9 @@ name: Generate-Summary on: workflow_call: inputs: + patch_id: + required: true + type: string patch_name: required: true type: string @@ -33,9 +36,12 @@ on: env: PRECOMMIT_REPOSITORY: ${{ github.repository }} + PATCH_ID: ${{ inputs.patch_id }} POSTCOMMIT_REPOSITORY: riseproject-dev/gcc-postcommit-ci - POSTCOMMIT_TOKEN: ${{ secrets.RISE_CI_READ_TOKEN }} - PATCHWORK_REPORTING_ENABLED: ${{ vars.PATCHWORK_REPORTING_ENABLED }} + PATCHWORK_REPORTING_ENABLED: >- + ${{ (vars.PATCHWORK_REPORTING_ENABLED == 'true' || + (github.workflow == 'Patchworks' && github.event_name == 'workflow_dispatch' && + github.sha == vars.PATCHWORK_REPORTING_ENABLED)) && 'true' || 'false' }} jobs: compare-artifacts: @@ -67,13 +73,14 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - cache: "pip" - name: Install Python dependencies run: | pip install -r ../requirements.txt --break-system-packages - name: Download baseline sum files + 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}." @@ -141,20 +148,17 @@ jobs: -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ https://api.github.com/rate_limit - - name: Extract artifacts - run: | - ls ./temp/ - mkdir -p current_logs - for f in $(ls ./temp/*report.zip); do - unzip $f -d ./current_logs || true - done - ls current_logs - - name: Separate multilib logs + env: + GCC_HASH: ${{ inputs.patch_applied_gcchash }} run: | - python scripts/separate_multilib_results.py -indir current_logs -outdir current_logs - mv current_logs/gcc-newlib-rv32imc_zba_zbb_zbc_zbs-ilp32-${{ inputs.patch_applied_gcchash }}-non-multilib-report.log current_logs/gcc-newlib-rv32imc_zba_zbb_zbc_zbs-ilp32-${{ inputs.patch_applied_gcchash }}-multilib-report.log - continue-on-error: true + 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: | @@ -198,12 +202,6 @@ jobs: retention-days: 90 # Compare build warnings - - name: Download patches artifact - uses: actions/download-artifact@v4 - with: - name: ${{ inputs.patch_name }}-downloaded-patches - path: ./riscv-gnu-toolchain/patches - ################################################################################ # remove build log comparison stuff while we disable build-only runners # ################################################################################ @@ -223,7 +221,7 @@ jobs: # echo "build_warnings_directory=$(readlink -f ./build_warnings/)" >> $GITHUB_OUTPUT # echo "new_build_warnings_path=$(readlink -f ./build_warnings/new_build_warnings.md)" >> $GITHUB_OUTPUT # echo "resolved_build_warnings_path=$(readlink -f ./build_warnings/resolved_build_warnings.md)" >> $GITHUB_OUTPUT - # echo "patch_hash=$(tail -n 1 patches/${{ inputs.patch_name }})" >> $GITHUB_OUTPUT + # echo "patch_hash=$PATCH_ID" >> $GITHUB_OUTPUT # # begin downloading current workflow build logs @@ -325,7 +323,6 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - cache: "pip" - name: Install Python dependencies run: | @@ -349,33 +346,22 @@ jobs: name: ${{ inputs.patch_applied_gcchash }}-previous-logs path: ./riscv-gnu-toolchain/previous_logs - # debug logs - - name: Download linux rv64 bitmanip debug url artifact - uses: actions/download-artifact@v4 - with: - name: gcc-linux-rv64gc_zba_zbb_zbc_zbs-lp64d-${{ inputs.patch_applied_gcchash }}-multilib-debug-url.md - path: ./riscv-gnu-toolchain/ - continue-on-error: true - - - name: Download linux rv64 vector debug url artifact - uses: actions/download-artifact@v4 - with: - name: gcc-linux-rv64gcv-lp64d-${{ inputs.patch_applied_gcchash }}-multilib-debug-url.md - path: ./riscv-gnu-toolchain/ - continue-on-error: true - - - name: Download newlib rv64 vector debug url artifact - uses: actions/download-artifact@v4 - with: - name: gcc-newlib-rv64gcv-lp64d-${{ inputs.patch_applied_gcchash }}-multilib-debug-url.md - path: ./riscv-gnu-toolchain - continue-on-error: true - - - name: Download patches artifact - uses: actions/download-artifact@v4 - with: - name: ${{ inputs.patch_name }}-downloaded-patches - path: ./riscv-gnu-toolchain/patches + - name: Link testsuite logs from this run + env: + GH_TOKEN: ${{ github.token }} + GCC_HASH: ${{ inputs.patch_applied_gcchash }} + run: | + 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) + if [[ "$id" =~ ^[0-9]+$ ]]; then + printf '%s testsuite logs: [zip](%s/%s/actions/runs/%s/artifacts/%s)\n' \ + "$target" "$GITHUB_SERVER_URL" "$GITHUB_REPOSITORY" "$GITHUB_RUN_ID" "$id" >> debug-links.md + fi + done - name: Print API usage info run: | @@ -420,7 +406,7 @@ jobs: fi printf "\n### Testsuite download links\n\n" >> trimmed_comment.md 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 gcc-*.md >> trimmed_comment.md + cat debug-links.md >> trimmed_comment.md echo "" >> trimmed_comment.md printf "\n[Additional information](${{ inputs.additional_info }})\n" >> trimmed_comment.md cat trimmed_comment.md @@ -507,10 +493,10 @@ jobs: 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 $(tail -n 1 ./patches/${{ inputs.patch_name }}) -desc 'Testing failed' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.test_comment_id }}' -state 'fail' -context 'test' -token '${{ secrets.PATCHWORK_API }}' + 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 run: | - python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid $(tail -n 1 ./patches/${{ inputs.patch_name }}) -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 'Testing passed' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.test_comment_id }}' -state 'success' -context 'test' -token '${{ secrets.PATCHWORK_API }}' diff --git a/.github/workflows/init-submodules.yaml b/.github/workflows/init-submodules.yaml index d557225..1d6c3af 100644 --- a/.github/workflows/init-submodules.yaml +++ b/.github/workflows/init-submodules.yaml @@ -24,7 +24,6 @@ permissions: env: POSTCOMMIT_REPOSITORY: riseproject-dev/gcc-postcommit-ci - POSTCOMMIT_TOKEN: ${{ secrets.RISE_CI_READ_TOKEN }} jobs: init-submodules: @@ -43,19 +42,19 @@ jobs: - name: Determine baseline id: baseline-hash + env: + REQUESTED_BASELINE: ${{ inputs.baseline_hash }} + POSTCOMMIT_TOKEN: ${{ secrets.RISE_CI_READ_TOKEN }} run: | - if [ '${{ inputs.baseline_hash }}' == '' ] ; then - if [ -z "${POSTCOMMIT_TOKEN}" ]; then - echo "::error::RISE_CI_READ_TOKEN is required to read baseline issues from ${POSTCOMMIT_REPOSITORY}." - exit 1 - fi - python ./scripts/get_baseline_hash.py -repo "${POSTCOMMIT_REPOSITORY}" -token "${POSTCOMMIT_TOKEN}" - export BASELINE_HASH=$(cat baseline.txt) + if [[ -n "$REQUESTED_BASELINE" ]]; then + baseline=$REQUESTED_BASELINE else - export BASELINE_HASH=${{ inputs.baseline_hash }} + : "${POSTCOMMIT_TOKEN:?RISE_CI_READ_TOKEN is required to read baseline issues}" + python ./scripts/get_baseline_hash.py -repo "$POSTCOMMIT_REPOSITORY" -token "$POSTCOMMIT_TOKEN" + baseline=$(cat baseline.txt) fi - echo $BASELINE_HASH - echo "baseline_hash=$BASELINE_HASH" >> $GITHUB_OUTPUT + [[ "$baseline" =~ ^[0-9a-fA-F]{7,40}$ ]] + echo "baseline_hash=$baseline" >> "$GITHUB_OUTPUT" - name: Retrieve cache id: retrieve-cache @@ -70,7 +69,7 @@ jobs: riscv-gnu-toolchain/glibc riscv-gnu-toolchain/newlib riscv-gnu-toolchain/qemu - key: submodules-archive-17 # Invalidate cached source URLs after the mirror switch + key: precommit-hosted-sources-v1 # New namespace after isolating patch workers from Actions caches - name: Synchronize submodule URLs run: git submodule sync --recursive @@ -103,16 +102,23 @@ jobs: - name: Determine tip-of-tree hash working-directory: riscv-gnu-toolchain/gcc id: tot-hash + env: + REQUESTED_TIP: ${{ inputs.tot_hash }} run: | - if [ '${{ inputs.tot_hash }}' != '' ]; then git checkout ${{ inputs.tot_hash }}; fi - export TOT_HASH=$(git rev-parse HEAD) - echo $TOT_HASH - echo "tot_hash=$TOT_HASH" >> $GITHUB_OUTPUT + if [[ -n "$REQUESTED_TIP" ]]; then + [[ "$REQUESTED_TIP" =~ ^[0-9a-fA-F]{7,40}$ ]] + git checkout --detach "$REQUESTED_TIP" + fi + echo "tot_hash=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" - name: Checkout baseline GCC hash working-directory: riscv-gnu-toolchain/gcc + id: checkout-baseline + env: + BASELINE: ${{ steps.baseline-hash.outputs.baseline_hash }} run: | - git checkout ${{ steps.baseline-hash.outputs.baseline_hash }} + git checkout --detach "$BASELINE" + echo "baseline_hash=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" - name: Cache submodules if: steps.retrieve-cache.outputs.cache-hit != 'true' @@ -127,23 +133,21 @@ jobs: riscv-gnu-toolchain/glibc riscv-gnu-toolchain/newlib riscv-gnu-toolchain/qemu - key: submodules-archive-17 + key: precommit-hosted-sources-v1 - - name: Make cache zip + - name: Archive sources for this run run: | zip -r cache.zip .git binutils dejagnu gcc gdb glibc newlib qemu - # Use artifact rather than cache since cache downloads are flaky/hang. - # Artifacts are reliable but ~30 min slower to set up. - # Setup is done on one runner, so this isn't a show stopper. - - name: Upload git cache + # All patch workers in this run can reuse the hosted source checkout. + - name: Upload source archive uses: actions/upload-artifact@v4 with: - name: gcc-sources-${{ steps.baseline-hash.outputs.baseline_hash }} + name: gcc-sources-${{ steps.checkout-baseline.outputs.baseline_hash }} path: | riscv-gnu-toolchain/cache.zip retention-days: 5 outputs: - baseline_hash: ${{ steps.baseline-hash.outputs.baseline_hash }} + baseline_hash: ${{ steps.checkout-baseline.outputs.baseline_hash }} tot_hash: ${{ steps.tot-hash.outputs.tot_hash }} diff --git a/.github/workflows/issue-closer.yaml b/.github/workflows/issue-closer.yaml index 3c1b80e..6f64702 100644 --- a/.github/workflows/issue-closer.yaml +++ b/.github/workflows/issue-closer.yaml @@ -30,7 +30,6 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - cache: "pip" - name: Install Python dependencies run: | diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml index 36678aa..0f7e32f 100644 --- a/.github/workflows/lint.yaml +++ b/.github/workflows/lint.yaml @@ -3,6 +3,9 @@ name: Lint on: workflow_call: inputs: + patch_id: + required: true + type: string patch_name: required: true type: string @@ -21,7 +24,11 @@ on: env: PRECOMMIT_REPOSITORY: ${{ github.repository }} - PATCHWORK_REPORTING_ENABLED: ${{ vars.PATCHWORK_REPORTING_ENABLED }} + PATCH_ID: ${{ inputs.patch_id }} + PATCHWORK_REPORTING_ENABLED: >- + ${{ (vars.PATCHWORK_REPORTING_ENABLED == 'true' || + (github.workflow == 'Patchworks' && github.event_name == 'workflow_dispatch' && + github.sha == vars.PATCHWORK_REPORTING_ENABLED)) && 'true' || 'false' }} jobs: lint: @@ -42,17 +49,14 @@ jobs: with: free_up_space: false - - name: Restore submodules from cache - run: | - gh run download --repo ${{ github.repository }} "${{ github.run_id }}" --name "gcc-sources-${{ inputs.baseline_hash }}" - env: - GH_TOKEN: ${{ github.token }} - - - name: Restore submodules - run: | - rm -rf .git binutils dejagnu gcc gdb glibc newlib qemu - unzip cache.zip - rm -rf cache.zip + - name: Checkout GCC lint tools at the selected baseline + uses: actions/checkout@v4 + with: + repository: gcc-mirror/gcc + ref: ${{ inputs.baseline_hash }} + path: gcc-lint-tools + sparse-checkout: contrib + persist-credentials: false - name: Download patches artifact uses: actions/download-artifact@v4 @@ -67,16 +71,17 @@ jobs: - name: Report start linter if: ${{ github.workflow != 'Staging' }} run: | - python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid $(tail -n 1 patches/${{ inputs.patch_name }}) -desc 'Lint starting' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.lint_comment_id }}' -state 'pending' -context 'lint' -token '${{ secrets.PATCHWORK_API }}' + python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid "$PATCH_ID" -desc 'Lint starting' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.lint_comment_id }}' -state 'pending' -context 'lint' -token '${{ secrets.PATCHWORK_API }}' # Only lint the last patch in the series since that's where the warning will be displayed - name: Lint patch id: lint run: | - let patches_and_metadata_count=$(ls -1 patches | wc -l) - let patches_count=$((patches_and_metadata_count / 2)) - let patch_num=$(printf "%04d" $patches_count) - python ./gcc/contrib/check_GNU_style.py "./patches/$(printf '%04d' $patches_count)-patch.patch" 2>&1 | tee "lint_results.txt" + # download_patches.sh numbers mboxes in series order. + shopt -s nullglob + patches=(patches/*-patch.patch) + ((${#patches[@]} > 0)) + python ../gcc-lint-tools/contrib/check_GNU_style.py "${patches[-1]}" > lint_results.txt 2>&1 if (($(cat lint_results.txt | wc -l) > 0)); then echo "lint_failed=true" >> $GITHUB_OUTPUT else @@ -123,7 +128,7 @@ jobs: - name: Report linter warning if: ${{ steps.lint.outputs.lint_failed == 'true' && github.workflow != 'Staging' }} run: | - python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid $(tail -n 1 patches/${{ inputs.patch_name }}) -desc 'Lint failed' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.lint_comment_id }}' -state 'warning' -context 'lint' -token '${{ secrets.PATCHWORK_API }}' + python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid "$PATCH_ID" -desc 'Lint failed' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.lint_comment_id }}' -state 'warning' -context 'lint' -token '${{ secrets.PATCHWORK_API }}' - name: Make lint passed comment if: ${{ steps.lint.outputs.lint_failed == 'false' }} @@ -145,4 +150,4 @@ jobs: - name: Report linter success if: ${{ steps.lint.outputs.lint_failed == 'false' && github.workflow != 'Staging' }} run: | - python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid $(tail -n 1 patches/${{ inputs.patch_name }}) -desc 'Lint passed' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.lint_comment_id }}' -state 'success' -context 'lint' -token '${{ secrets.PATCHWORK_API }}' + python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid "$PATCH_ID" -desc 'Lint passed' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.lint_comment_id }}' -state 'success' -context 'lint' -token '${{ secrets.PATCHWORK_API }}' diff --git a/.github/workflows/patchworks.yaml b/.github/workflows/patchworks.yaml index 939dea8..852e8ba 100644 --- a/.github/workflows/patchworks.yaml +++ b/.github/workflows/patchworks.yaml @@ -71,7 +71,6 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - cache: "pip" - name: Install Python dependencies run: python -m pip install -r ../requirements.txt @@ -125,7 +124,7 @@ jobs: - name: List patch artifacts id: list_patches run: | - export PATCHLIST="$(cat artifact_names.txt)" + PATCHLIST=$(python ../scripts/patch_matrix.py) echo "patch_list=$PATCHLIST" >> $GITHUB_OUTPUT - name: Upload patch urls @@ -147,11 +146,11 @@ jobs: retention-days: 90 outputs: - list_of_patch_names: ${{ steps.list_patches.outputs.patch_list }} + patch_targets: ${{ steps.list_patches.outputs.patch_list }} init-submodules: needs: [fetch_patches] - if: ${{ needs.fetch_patches.outputs.list_of_patch_names != '[]' }} + if: ${{ needs.fetch_patches.outputs.patch_targets != '[]' }} uses: ./.github/workflows/init-submodules.yaml with: baseline_hash: ${{ inputs.baseline_gcc_hash }} @@ -163,7 +162,7 @@ jobs: strategy: fail-fast: false matrix: - patch_name: ${{ fromJSON(needs.fetch_patches.outputs.list_of_patch_names) }} + include: ${{ fromJSON(needs.fetch_patches.outputs.patch_targets) }} uses: ./.github/workflows/run-checks.yaml permissions: actions: read @@ -171,6 +170,7 @@ jobs: issues: write with: patch_name: ${{ matrix.patch_name }} + patch_id: ${{ matrix.patch_id }} baseline_hash: ${{ needs.init-submodules.outputs.baseline_hash }} tot_hash: ${{ needs.init-submodules.outputs.tot_hash }} original_patch_issue_num: ${{ inputs.original_patch_issue_num }} diff --git a/.github/workflows/regression-worker.yaml b/.github/workflows/regression-worker.yaml new file mode 100644 index 0000000..c07a80a --- /dev/null +++ b/.github/workflows/regression-worker.yaml @@ -0,0 +1,369 @@ +name: Build and test patch + +on: + workflow_call: + inputs: + patch_name: + required: true + type: string + patch_id: + required: true + type: string + mode: + required: true + type: string + target: + required: true + type: string + baseline_hash: + required: true + type: string + patch_applied_gcchash: + required: true + type: string + multilib: + required: true + type: string + build_only: + required: true + type: string + run_on_self_hosted: + required: true + type: boolean + tot_hash: + required: true + type: string + outputs: + build_status: + description: "Outcome of the build step, including setup and artifact upload" + value: ${{ inputs.run_on_self_hosted && jobs.run-on-self-hosted.outputs.build_status || jobs.build.outputs.build_status }} + test_status: + description: "Outcome of the requested testsuite or its timeout retry" + value: ${{ (inputs.run_on_self_hosted && jobs.run-on-self-hosted.outputs.test_status == 'success' || !inputs.run_on_self_hosted && (jobs.test.outputs.test_status == 'success' || jobs.rerun-timeouts.outputs.test_status == 'success')) && 'success' || 'failure' }} + +permissions: + actions: read + contents: read + +jobs: + build: + runs-on: ubuntu-24.04 + if: ${{ !inputs.run_on_self_hosted }} + defaults: + run: + working-directory: riscv-gnu-toolchain + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Setup env + uses: ./.github/actions/common/setup-env + with: + free_up_space: true + + - name: Restore submodules from cache + run: | + gh run download --repo ${{ github.repository }} "${{ github.run_id }}" --name "gcc-sources-${{ inputs.baseline_hash }}" + env: + GH_TOKEN: ${{ github.token }} + + - name: Restore submodules + run: | + rm -rf .git binutils dejagnu gcc gdb glibc newlib qemu + unzip cache.zip + rm -rf cache.zip + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Install Python dependencies + run: | + pip install -r ../requirements.txt --break-system-packages + + - name: Extract and apply patches + uses: ./.github/actions/extract-apply-patches-trunk-or-baseline + with: + patch_name: ${{ inputs.patch_name }} + baseline_hash: ${{ inputs.baseline_hash }} + build_only: ${{ inputs.build_only }} + tot_hash: ${{ inputs.tot_hash }} + + - name: Build gcc + id: build-status + uses: ./.github/actions/common/build-target + with: + multilib_target_string: ${{ inputs.target }} + build_log_name: ${{ inputs.patch_id }}-${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }}-build-log + upload_stage2_artifacts: 'true' + mode: ${{ inputs.mode }} + target: ${{ inputs.target }} + gcchash: ${{ inputs.patch_applied_gcchash }} + multilib: ${{ inputs.multilib }} + + outputs: + build_status: ${{ steps.build-status.outcome }} + + test: + runs-on: ubuntu-24.04 + needs: [build] + # Skip linux multilib + if: ${{ inputs.build_only == 'false' && !inputs.run_on_self_hosted }} + defaults: + run: + working-directory: riscv-gnu-toolchain + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + # Everything is moved onto self-hosted runners except for rv64gc build only + - name: Error if enter + run: | + exit 1 + + - name: Setup env + uses: ./.github/actions/common/setup-env + with: + free_up_space: true + + - name: Restore submodules from cache + run: | + gh run download --repo ${{ github.repository }} "${{ github.run_id }}" --name "gcc-sources-${{ inputs.baseline_hash }}" + env: + GH_TOKEN: ${{ github.token }} + + - name: Restore submodules + run: | + rm -rf .git binutils dejagnu gcc gdb glibc newlib qemu + unzip cache.zip + rm -rf cache.zip + + - name: Extract and apply patches + uses: ./.github/actions/extract-apply-patches-trunk-or-baseline + with: + patch_name: ${{ inputs.patch_name }} + baseline_hash: ${{ inputs.baseline_hash }} + build_only: ${{ inputs.build_only }} + tot_hash: ${{ inputs.tot_hash }} + + - name: Prepare toolchain dependencies + uses: ./.github/actions/common/setup-dependencies + + # There is only one github target now which is rv64gc build only + - name: Configure + run: | + mkdir build + cd build + TARGET_TUPLE=($(echo ${{ inputs.target }} | tr "-" "\n")) + ../../configure-scripts/${TARGET_TUPLE[0]}-${TARGET_TUPLE[1]} + sed -i "s/ --user / --user --break-system-packages /g" Makefile + + - name: Restore Stage2 Artifacts + uses: ./.github/actions/common/restore-stage-2 + with: + mode: ${{ inputs.mode }} + target: ${{ inputs.target }} + gcchash: ${{ inputs.patch_applied_gcchash }} + multilib: ${{ inputs.multilib }} + + - name: Replace allowlist + run: | + rm -rf test/ + cp -r ../test/ . + + - name: Run Testsuite + id: testsuite + uses: ./.github/actions/common/run-testsuite + with: + mode: ${{ inputs.mode }} + target: ${{ inputs.target }} + gcchash: ${{ inputs.patch_applied_gcchash }} + multilib: ${{ inputs.multilib }} + + outputs: + test_status: ${{ steps.testsuite.outcome }} + + # The self-hosted environment does not have the same path setup as the hosted runners + # We need to rebuild since restoring the artifact won't work + # (the new path will break the existing build). + rerun-timeouts: + runs-on: [self-hosted, linux, x64, rise-precommit-regression-07] + needs: [build, test] + if: ${{ failure() && needs.build.outputs.build_status == 'success' && !inputs.run_on_self_hosted }} + timeout-minutes: 1440 # 24 hours + defaults: + run: + working-directory: riscv-gnu-toolchain + steps: + - name: Cleanup build folder + working-directory: ./ + run: | + ls -la ./ + rm -rf ./* || true + rm -rf ./.??* || true + ls -la ./ + + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Setup env + uses: ./.github/actions/common/setup-env + with: + free_up_space: false + + - name: Restore submodules from cache + run: | + gh run download --repo ${{ github.repository }} "${{ github.run_id }}" --name "gcc-sources-${{ inputs.baseline_hash }}" + env: + GH_TOKEN: ${{ github.token }} + + - name: Restore submodules + run: | + rm -rf .git binutils dejagnu gcc gdb glibc newlib qemu + unzip cache.zip + rm -rf cache.zip + + - name: Install Python dependencies + run: python -m pip install -r ../requirements.txt --break-system-packages + + - name: Extract and apply patches + uses: ./.github/actions/extract-apply-patches-trunk-or-baseline + with: + patch_name: ${{ inputs.patch_name }} + baseline_hash: ${{ inputs.baseline_hash }} + build_only: ${{ inputs.build_only }} + tot_hash: ${{ inputs.tot_hash }} + + - name: Prepare toolchain dependencies + uses: ./.github/actions/common/setup-dependencies + + # There is only one github target now which is rv64gc build only + - name: Configure + run: | + mkdir build + cd build + TARGET_TUPLE=($(echo ${{ inputs.target }} | tr "-" "\n")) + ../../configure-scripts/${TARGET_TUPLE[0]}-${TARGET_TUPLE[1]} + sed -i "s/ --user / --user --break-system-packages /g" Makefile + + - name: Build + run: | + cd build + make ${{ inputs.mode }} -j32 + + - name: Replace allowlist + run: | + rm -rf test/ + cp -r ../test/ . + + - name: Run Testsuite + id: testsuite + if: ${{ inputs.build_only == 'false' }} + uses: ./.github/actions/common/run-testsuite + with: + mode: ${{ inputs.mode }} + target: ${{ inputs.target }} + gcchash: ${{ inputs.patch_applied_gcchash }} + multilib: ${{ inputs.multilib }} + + outputs: + test_status: ${{ steps.testsuite.outcome }} + + # The self-hosted environment does not have the same path setup as the hosted runners + # We need to rebuild since restoring the artifact won't work + # (the new path will break the existing build). + run-on-self-hosted: + runs-on: [self-hosted, linux, x64, rise-precommit-regression-07] + if: ${{ inputs.run_on_self_hosted }} + timeout-minutes: 1440 # 24 hours + defaults: + run: + working-directory: riscv-gnu-toolchain + steps: + - name: Cleanup build folder + working-directory: ./ + run: | + ls -la ./ + rm -rf ./* || true + rm -rf ./.??* || true + ls -la ./ + + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Setup env + uses: ./.github/actions/common/setup-env + with: + free_up_space: false + + - name: Restore submodules from cache + run: | + gh run download --repo ${{ github.repository }} "${{ github.run_id }}" --name "gcc-sources-${{ inputs.baseline_hash }}" + env: + GH_TOKEN: ${{ github.token }} + + - name: Restore submodules + run: | + rm -rf .git binutils dejagnu gcc gdb glibc newlib qemu + unzip cache.zip + rm -rf cache.zip + + - name: Install Python dependencies + run: | + pip install -r ../requirements.txt --break-system-packages + + - name: Extract and apply patches + uses: ./.github/actions/extract-apply-patches-trunk-or-baseline + with: + patch_name: ${{ inputs.patch_name }} + baseline_hash: ${{ inputs.baseline_hash }} + build_only: ${{ inputs.build_only }} + tot_hash: ${{ inputs.tot_hash }} + + - name: Get target string + id: target-string + run: | + if [ '${{ inputs.mode }}' == 'newlib' ] && [ '${{ inputs.target }}' == 'rv64gcv-lp64d' ]; + then + echo "target_string=rv64gcv-lp64d-reduced-multilib-set" >> $GITHUB_OUTPUT + else + echo "target_string=${{ inputs.target }}" >> $GITHUB_OUTPUT + fi + + # Don't upload stage 2 artifacts on self-hosted runners + # in interest of resources + - name: Build gcc + id: build-gcc-status + uses: ./.github/actions/common/build-target + with: + multilib_target_string: ${{ steps.target-string.outputs.target_string }} + build_log_name: ${{ inputs.patch_id }}-${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }}-build-log + upload_stage2_artifacts: 'false' + mode: ${{ inputs.mode }} + target: ${{ inputs.target }} + gcchash: ${{ inputs.patch_applied_gcchash }} + multilib: ${{ inputs.multilib }} + + - name: Replace allowlist + run: | + rm -rf test/ + cp -r ../test/ . + + - name: Run Testsuite + id: testsuite + if: ${{ inputs.build_only == 'false' }} + uses: ./.github/actions/common/run-testsuite + with: + mode: ${{ inputs.mode }} + target: ${{ inputs.target }} + gcchash: ${{ inputs.patch_applied_gcchash }} + multilib: ${{ inputs.multilib }} + + outputs: + build_status: ${{ steps.build-gcc-status.outcome }} + test_status: ${{ steps.testsuite.outcome }} diff --git a/.github/workflows/run-checks.yaml b/.github/workflows/run-checks.yaml index 25cfe45..1963a4e 100644 --- a/.github/workflows/run-checks.yaml +++ b/.github/workflows/run-checks.yaml @@ -3,6 +3,9 @@ name: Run checks on: workflow_call: inputs: + patch_id: + required: true + type: string patch_name: required: true type: string @@ -18,8 +21,12 @@ on: env: PRECOMMIT_REPOSITORY: ${{ github.repository }} + PATCH_ID: ${{ inputs.patch_id }} POSTCOMMIT_REPOSITORY: riseproject-dev/gcc-postcommit-ci - PATCHWORK_REPORTING_ENABLED: ${{ vars.PATCHWORK_REPORTING_ENABLED }} + PATCHWORK_REPORTING_ENABLED: >- + ${{ (vars.PATCHWORK_REPORTING_ENABLED == 'true' || + (github.workflow == 'Patchworks' && github.event_name == 'workflow_dispatch' && + github.sha == vars.PATCHWORK_REPORTING_ENABLED)) && 'true' || 'false' }} jobs: download_patches: @@ -55,17 +62,11 @@ jobs: cp patchworks_metadata/${{ inputs.patch_name }} patches/ continue-on-error: true - # patchwork.sourceware.org has been rather flakey lately with regards - # to downloading the patches. when it does, wget will fail on the - # scripts/download_patches.sh step and should not move the patch from the - # patchworks_metadata folder. Retry downloading the patches from - # ozlabs - - name: Try different server to download patches from + - name: Retry downloading the selected patches from Sourceware if: ${{ steps.patch-download.outcome == 'failure' }} run: | rm -rf patches mkdir patches - sed -i 's/patchwork.sourceware.org/patchwork.ozlabs.org/g' patch_urls/${{ inputs.patch_name }} scripts/download_patches.sh -p ${{ inputs.patch_name }} cp patchworks_metadata/${{ inputs.patch_name }} patches/ @@ -108,7 +109,7 @@ jobs: printf "## Patch information\n" >> issue.md head -n 3 patches/${{ inputs.patch_name }} >> issue.md # Issue closer depends on patch id - printf "Patch id: %d\n" $(tail -n 1 patches/${{ inputs.patch_name }}) >> issue.md + printf "Patch id: %d\n" "$PATCH_ID" >> issue.md printf "## Build Targets\n" >> issue.md printf "Some targets are built as multilibs. If a build target ends with \`multilib\`, please refer to the table below to see all the targets within that multilib.\n" >> issue.md printf "|Target name|\`-march\` string|\n" >> issue.md @@ -203,6 +204,7 @@ jobs: issues: write with: patch_name: ${{ inputs.patch_name }} + patch_id: ${{ inputs.patch_id }} issue_num: ${{ needs.create-issue.outputs.issue_num }} lint_comment_id: ${{ needs.create-issue.outputs.lint_comment_id }} additional_info: ${{ needs.create-issue.outputs.additional_info }} @@ -224,17 +226,15 @@ jobs: with: free_up_space: false - - name: Restore submodules from cache - run: | - gh run download --repo ${{ github.repository }} "${{ github.run_id }}" --name "gcc-sources-${{ inputs.baseline_hash }}" - env: - GH_TOKEN: ${{ github.token }} - - - name: Restore submodules - run: | - rm -rf .git binutils dejagnu gcc gdb glibc newlib qemu - unzip cache.zip - rm -rf cache.zip + - name: Checkout the baseline from GCC + uses: actions/checkout@v4 + with: + repository: gcc-mirror/gcc + ref: ${{ inputs.baseline_hash }} + path: riscv-gnu-toolchain/gcc + persist-credentials: false + filter: blob:none + fetch-depth: 0 - name: Download patches artifact uses: actions/download-artifact@v4 @@ -242,10 +242,15 @@ jobs: name: ${{ inputs.patch_name }}-downloaded-patches path: ./riscv-gnu-toolchain/patches - - name: Checkout gcc hash + - name: Check the selected GCC revisions + env: + BASELINE: ${{ inputs.baseline_hash }} + TIP: ${{ inputs.tot_hash }} run: | cd gcc - git checkout ${{ inputs.baseline_hash }} + [[ "$BASELINE" =~ ^[0-9a-f]{7,40}$ && "$TIP" =~ ^[0-9a-f]{40}$ ]] + test "$(git rev-parse HEAD)" = "$(git rev-parse "$BASELINE^{commit}")" + git cat-file -e "$TIP^{commit}" - name: Apply patches to baseline id: apply-baseline @@ -346,17 +351,17 @@ jobs: - name: Report patch failed to apply to tip of tree if: ${{ steps.apply-baseline.outputs.apply_baseline == 'true' && steps.apply-tip-of-tree.outputs.apply_tot == 'false' && github.workflow != 'Staging' }} run: | - python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid $(tail -n 1 patches/${{ inputs.patch_name }}) -desc 'Patch failed to apply to tip of tree.' -iid '${{ needs.create-issue.outputs.issue_num }}#issuecomment-${{ needs.create-issue.outputs.apply_comment_id }}' -state 'warning' -context 'apply-patch' -token '${{ secrets.PATCHWORK_API }}' + python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid "$PATCH_ID" -desc 'Patch failed to apply to tip of tree.' -iid '${{ needs.create-issue.outputs.issue_num }}#issuecomment-${{ needs.create-issue.outputs.apply_comment_id }}' -state 'warning' -context 'apply-patch' -token '${{ secrets.PATCHWORK_API }}' - name: Report patch applied to tip of tree successfully if: ${{ steps.apply-tip-of-tree.outputs.apply_tot == 'true' && github.workflow != 'Staging' }} run: | - python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid $(tail -n 1 patches/${{ inputs.patch_name }}) -desc 'Patch applied' -iid '${{ needs.create-issue.outputs.issue_num }}#issuecomment-${{ needs.create-issue.outputs.apply_comment_id }}' -state 'success' -context 'apply-patch' -token '${{ secrets.PATCHWORK_API }}' + python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid "$PATCH_ID" -desc 'Patch applied' -iid '${{ needs.create-issue.outputs.issue_num }}#issuecomment-${{ needs.create-issue.outputs.apply_comment_id }}' -state 'success' -context 'apply-patch' -token '${{ secrets.PATCHWORK_API }}' - name: Report patch failed to apply anywhere if: ${{ steps.apply-failure.outputs.apply_failure == 'true' && github.workflow != 'Staging' }} run: | - python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid $(tail -n 1 patches/${{ inputs.patch_name }}) -desc 'Patch failed to apply' -iid '${{ needs.create-issue.outputs.issue_num }}#issuecomment-${{ needs.create-issue.outputs.apply_comment_id }}' -state 'fail' -context 'apply-patch' -token '${{ secrets.PATCHWORK_API }}' + python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid "$PATCH_ID" -desc 'Patch failed to apply' -iid '${{ needs.create-issue.outputs.issue_num }}#issuecomment-${{ needs.create-issue.outputs.apply_comment_id }}' -state 'fail' -context 'apply-patch' -token '${{ secrets.PATCHWORK_API }}' - name: Add apply-failure label if patch failed to apply anywhere if: ${{ steps.apply-failure.outputs.apply_failure == 'true' }} @@ -457,7 +462,7 @@ jobs: - name: Report test warning on build only if: ${{ needs.apply.outputs.build_only == 'true' && github.workflow != 'Staging' }} run: | - python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid $(tail -n 1 patches/${{ inputs.patch_name }}) -desc 'Testing skipped' -iid '${{ needs.create-issue.outputs.issue_num }}#issuecomment-${{ steps.test-comment.outputs.comment-id }}' -state 'warning' -context 'test' -token '${{ secrets.PATCHWORK_API }}' + python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid "$PATCH_ID" -desc 'Testing skipped' -iid '${{ needs.create-issue.outputs.issue_num }}#issuecomment-${{ steps.test-comment.outputs.comment-id }}' -state 'warning' -context 'test' -token '${{ secrets.PATCHWORK_API }}' # If the patch does not apply to baseline, we need to run the build warning # comparisons against tip of tree and not the baseline hash. @@ -524,6 +529,7 @@ jobs: issues: write with: patch_name: ${{ inputs.patch_name }} + patch_id: ${{ inputs.patch_id }} mode: ${{ matrix.mode }} target: ${{ matrix.target }} baseline_hash: ${{ inputs.baseline_hash }} @@ -536,7 +542,9 @@ jobs: run_on_self_hosted: true tot_hash: ${{ inputs.tot_hash }} additional_info: ${{ needs.create-issue.outputs.additional_info }} - secrets: inherit + secrets: + PATCHWORK_API: ${{ secrets.PATCHWORK_API }} + GIST_TOKEN: ${{ secrets.GIST_TOKEN }} creg-sh: # Vector self hosted runners multilib build needs: [download_patches, create-issue, apply, initialize-build-test-comments] @@ -554,6 +562,7 @@ jobs: issues: write with: patch_name: ${{ inputs.patch_name }} + patch_id: ${{ inputs.patch_id }} mode: ${{ matrix.mode }} target: ${{ matrix.target }} baseline_hash: ${{ inputs.baseline_hash }} @@ -566,7 +575,9 @@ jobs: run_on_self_hosted: true tot_hash: ${{ inputs.tot_hash }} additional_info: ${{ needs.create-issue.outputs.additional_info }} - secrets: inherit + secrets: + PATCHWORK_API: ${{ secrets.PATCHWORK_API }} + GIST_TOKEN: ${{ secrets.GIST_TOKEN }} summarize: if: ${{ !cancelled() && needs.apply.outputs.apply_failure == 'false' }} # Generate github issues even when some (or all) targets fail to build. Ignore apply failures since there are no artifacts expected. @@ -578,6 +589,7 @@ jobs: uses: ./.github/workflows/generate-precommit-summary.yaml with: patch_name: ${{ inputs.patch_name }} + patch_id: ${{ inputs.patch_id }} baseline_hash: ${{ inputs.baseline_hash }} patch_applied_gcchash: ${{ needs.apply.outputs.patch_applied_gcchash }} build_only: ${{ needs.apply.outputs.build_only }} diff --git a/.github/workflows/staging.yaml b/.github/workflows/staging.yaml index 7354e75..8f6de51 100644 --- a/.github/workflows/staging.yaml +++ b/.github/workflows/staging.yaml @@ -84,25 +84,18 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - cache: "pip" - name: Install Python dependencies run: python -m pip install -r ../requirements.txt - - name: Install dependencies - run: sudo apt install zip -y - - name: Get patch data id: data - run: | - python scripts/get_staging_patch.py -repo "${PRECOMMIT_REPOSITORY}" -token ${{ secrets.GITHUB_TOKEN }} - echo "timestamp=$(cat timestamp.txt)" >> $GITHUB_OUTPUT - echo "baseline_hash=$(cat baseline_hash.txt)" >> $GITHUB_OUTPUT - echo "tot_hash=$(cat tot_hash.txt)" >> $GITHUB_OUTPUT - echo "patch_id=$(cat patch_id.txt)" >> $GITHUB_OUTPUT - echo "issue_num=$(cat issue_num.txt)" >> $GITHUB_OUTPUT + env: + GH_TOKEN: ${{ github.token }} + run: python ../scripts/staging_replay.py outputs: + found: ${{ steps.data.outputs.found }} timestamp: ${{ steps.data.outputs.timestamp }} baseline_gcc_hash: ${{ steps.data.outputs.baseline_hash }} tip_of_tree_hash: ${{ steps.data.outputs.tot_hash }} @@ -111,7 +104,7 @@ jobs: run-workflow: needs: [get-patch-info] - if: ${{ github.event_name == 'pull_request' }} + if: ${{ github.event_name == 'pull_request' && needs.get-patch-info.outputs.found == 'true' }} uses: ./.github/workflows/patchworks.yaml permissions: actions: read diff --git a/.github/workflows/test-regression.yaml b/.github/workflows/test-regression.yaml index 810d67a..5f58cd8 100644 --- a/.github/workflows/test-regression.yaml +++ b/.github/workflows/test-regression.yaml @@ -2,10 +2,18 @@ name: Test-Regression on: workflow_call: + secrets: + PATCHWORK_API: + required: false + GIST_TOKEN: + required: false inputs: patch_name: required: true type: string + patch_id: + required: true + type: string mode: required: true type: string @@ -46,435 +54,119 @@ on: permissions: actions: read contents: read - issues: write env: PRECOMMIT_REPOSITORY: ${{ github.repository }} - PATCHWORK_REPORTING_ENABLED: ${{ vars.PATCHWORK_REPORTING_ENABLED }} + PATCHWORK_REPORTING_ENABLED: >- + ${{ (vars.PATCHWORK_REPORTING_ENABLED == 'true' || + (github.workflow == 'Patchworks' && github.event_name == 'workflow_dispatch' && + github.sha == vars.PATCHWORK_REPORTING_ENABLED)) && 'true' || 'false' }} jobs: - build: + report-queued: runs-on: ubuntu-24.04 environment: production - if: ${{ !inputs.run_on_self_hosted }} - defaults: - run: - working-directory: riscv-gnu-toolchain + permissions: + contents: read + issues: write steps: - uses: actions/checkout@v4 - - - name: Setup env - uses: ./.github/actions/common/setup-env with: - free_up_space: true + submodules: true + persist-credentials: false - - name: Restore submodules from cache - run: | - gh run download --repo ${{ github.repository }} "${{ github.run_id }}" --name "gcc-sources-${{ inputs.baseline_hash }}" + - name: Validate the Patchwork target env: - GH_TOKEN: ${{ github.token }} + PATCH_ID: ${{ inputs.patch_id }} + run: '[[ "$PATCH_ID" =~ ^[0-9]+$ ]]' - - name: Restore submodules - run: | - rm -rf .git binutils dejagnu gcc gdb glibc newlib qemu - unzip cache.zip - rm -rf cache.zip - - - name: Set up Python - uses: actions/setup-python@v5 + - uses: actions/setup-python@v5 with: python-version: "3.11" - cache: "pip" - - - name: Install Python dependencies - run: | - pip install -r ../requirements.txt --break-system-packages - - - name: Extract and apply patches - uses: ./.github/actions/extract-apply-patches-trunk-or-baseline - with: - patch_name: ${{ inputs.patch_name }} - baseline_hash: ${{ inputs.baseline_hash }} - build_only: ${{ inputs.build_only }} - tot_hash: ${{ inputs.tot_hash }} - - - name: Build pending comment - run: | - if [ '${{ inputs.build_only }}' == 'true' ]; then - python scripts/update_issue_status.py -token ${{ secrets.GITHUB_TOKEN }} -state 'Pending' -comment ${{ inputs.build_comment_id }} -target ${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }} -check 'Build GCC' -repo "${PRECOMMIT_REPOSITORY}" -baseline ${{ inputs.tot_hash }} - else - python scripts/update_issue_status.py -token ${{ secrets.GITHUB_TOKEN }} -state 'Pending' -comment ${{ inputs.build_comment_id }} -target ${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }} -check 'Build GCC' -repo "${PRECOMMIT_REPOSITORY}" -baseline ${{ inputs.baseline_hash }} - fi - printf "\n[Additional information](${{ inputs.additional_info }})\n" >> comment.md - - - name: Update build pending report comment - uses: ./.github/actions/update-comment - with: - comment_id: ${{ inputs.build_comment_id }} - file_path: riscv-gnu-toolchain/comment.md - token: ${{ secrets.GITHUB_TOKEN }} - - - name: Report build - if: ${{ github.workflow != 'Staging' }} - run: | - python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid $(tail -n 1 patches/${{ inputs.patch_name }}) -desc 'Build started' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.build_comment_id }}' -state 'pending' -context 'build--${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }}' -token '${{ secrets.PATCHWORK_API }}' - - - name: Make log name - id: build-log - run: | - export BUILD_LOG_NAME=$(tail -n 1 patches/${{ inputs.patch_name }})-${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }}-build-log - echo "build_log_name=$BUILD_LOG_NAME" >> $GITHUB_OUTPUT - - - name: Build gcc - id: build-status - uses: ./.github/actions/common/build-target - with: - multilib_target_string: ${{ inputs.target }} - build_log_name: ${{ steps.build-log.outputs.build_log_name }} - upload_stage2_artifacts: 'true' - mode: ${{ inputs.mode }} - target: ${{ inputs.target }} - gcchash: ${{ inputs.patch_applied_gcchash }} - multilib: ${{ inputs.multilib }} - - - name: Report build completion status - if: ${{ always() }} - uses: ./.github/actions/report-build-complete-status - with: - build_status: ${{ steps.build-status.outputs.build_status }} - patch_name: ${{ inputs.patch_name }} - build_log_name: ${{ steps.build-log.outputs.build_log_name }} - target: ${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }} - baseline_hash: ${{ inputs.baseline_hash }} - tot_hash: ${{ inputs.tot_hash }} - build_only: ${{ inputs.build_only }} - issue_num: ${{ inputs.issue_num }} - build_comment_id: ${{ inputs.build_comment_id }} - additional_info: ${{ inputs.additional_info }} - github_token: ${{ secrets.GITHUB_TOKEN }} - gist_token: ${{ secrets.GIST_TOKEN }} - patchwork_token: ${{ secrets.PATCHWORK_API }} - repository: ${{ env.PRECOMMIT_REPOSITORY }} - outputs: - build_status: ${{ steps.build-status.outputs.build_status }} + - run: python -m pip install --no-cache-dir -r requirements.txt - test: - runs-on: ubuntu-24.04 - environment: production - needs: [build] - # Skip linux multilib - if: ${{ inputs.build_only == 'false' && !inputs.run_on_self_hosted }} - defaults: - run: + - name: Mark build queued working-directory: riscv-gnu-toolchain - steps: - - uses: actions/checkout@v4 - - # Everything is moved onto self-hosted runners except for rv64gc build only - - name: Error if enter - run: | - exit 1 - - - name: Setup env - uses: ./.github/actions/common/setup-env - with: - free_up_space: true - - - name: Restore submodules from cache - run: | - gh run download --repo ${{ github.repository }} "${{ github.run_id }}" --name "gcc-sources-${{ inputs.baseline_hash }}" env: GH_TOKEN: ${{ github.token }} - - - name: Restore submodules + COMMENT_ID: ${{ inputs.build_comment_id }} + TARGET: ${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }} + GCC_HASH: ${{ inputs.build_only == 'true' && inputs.tot_hash || inputs.baseline_hash }} + INFO_URL: ${{ inputs.additional_info }} run: | - rm -rf .git binutils dejagnu gcc gdb glibc newlib qemu - unzip cache.zip - rm -rf cache.zip + python scripts/update_issue_status.py -token "$GH_TOKEN" -state 'Queued' -comment "$COMMENT_ID" -target "$TARGET" -check 'Build GCC' -repo "$GITHUB_REPOSITORY" -baseline "$GCC_HASH" + printf '\n[Additional information](%s)\n' "$INFO_URL" >> comment.md - - name: Extract and apply patches - uses: ./.github/actions/extract-apply-patches-trunk-or-baseline + - uses: ./.github/actions/update-comment with: - patch_name: ${{ inputs.patch_name }} - baseline_hash: ${{ inputs.baseline_hash }} - build_only: ${{ inputs.build_only }} - tot_hash: ${{ inputs.tot_hash }} - - - name: Build test pending report - run: | - python scripts/update_issue_status.py -token ${{ secrets.GITHUB_TOKEN }} -state 'Pending' -comment ${{ inputs.test_comment_id }} -target ${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }} -check 'Testsuite' -repo "${PRECOMMIT_REPOSITORY}" -baseline ${{ inputs.baseline_hash }} - printf "\n[Additional information](${{ inputs.additional_info }})\n" >> comment.md - - - name: Update test pending report comment - uses: ./.github/actions/update-comment - with: - comment_id: ${{ inputs.test_comment_id }} + comment_id: ${{ inputs.build_comment_id }} file_path: riscv-gnu-toolchain/comment.md - token: ${{ secrets.GITHUB_TOKEN }} + token: ${{ github.token }} - - name: Report testing + - name: Report queued Patchwork checks if: ${{ github.workflow != 'Staging' }} - run: | - python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid $(tail -n 1 patches/${{ inputs.patch_name }}) -desc 'Testing started' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.test_comment_id }}' -state 'pending' -context 'test' -token '${{ secrets.PATCHWORK_API }}' - - - name: Prepare toolchain dependencies - uses: ./.github/actions/common/setup-dependencies - - # There is only one github target now which is rv64gc build only - - name: Configure - run: | - mkdir build - cd build - TARGET_TUPLE=($(echo ${{ inputs.target }} | tr "-" "\n")) - ../../configure-scripts/${TARGET_TUPLE[0]}-${TARGET_TUPLE[1]} - sed -i "s/ --user / --user --break-system-packages /g" Makefile - - - name: Restore Stage2 Artifacts - uses: ./.github/actions/common/restore-stage-2 - with: - mode: ${{ inputs.mode }} - target: ${{ inputs.target }} - gcchash: ${{ inputs.patch_applied_gcchash }} - multilib: ${{ inputs.multilib }} - - - name: Replace allowlist - run: | - rm -rf test/ - cp -r ../test/ . - - - name: Run Testsuite - uses: ./.github/actions/common/run-testsuite - with: - mode: ${{ inputs.mode }} - target: ${{ inputs.target }} - gcchash: ${{ inputs.patch_applied_gcchash }} - multilib: ${{ inputs.multilib }} - - - name: Build test complete report - run: | - python scripts/update_issue_status.py -token ${{ secrets.GITHUB_TOKEN }} -state 'Complete. Full report will be displayed once all targets are complete' -comment ${{ inputs.test_comment_id }} -target ${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }} -check 'Testsuite' -repo "${PRECOMMIT_REPOSITORY}" -baseline ${{ inputs.baseline_hash }} - printf "\n[Additional information](${{ inputs.additional_info }})\n" >> comment.md - - - name: Update test complete report comment - uses: ./.github/actions/update-comment - with: - comment_id: ${{ inputs.test_comment_id }} - file_path: riscv-gnu-toolchain/comment.md - token: ${{ secrets.GITHUB_TOKEN }} - - # The self-hosted environment does not have the same path setup as the hosted runners - # We need to rebuild since restoring the artifact won't work - # (the new path will break the existing build). - rerun-timeouts: - runs-on: [self-hosted, linux, x64, rise-gcc-ci] - environment: production - needs: [build, test] - if: ${{ failure() && needs.build.outputs.build_status == 'success' && !inputs.run_on_self_hosted }} - timeout-minutes: 1440 # 24 hours - defaults: - run: working-directory: riscv-gnu-toolchain - steps: - - name: Cleanup build folder - working-directory: ./ - run: | - ls -la ./ - rm -rf ./* || true - rm -rf ./.??* || true - ls -la ./ - - - uses: actions/checkout@v4 - - - name: Setup env - uses: ./.github/actions/common/setup-env - with: - free_up_space: false - - - name: Restore submodules from cache - run: | - gh run download --repo ${{ github.repository }} "${{ github.run_id }}" --name "gcc-sources-${{ inputs.baseline_hash }}" env: - GH_TOKEN: ${{ github.token }} - - - name: Restore submodules - run: | - rm -rf .git binutils dejagnu gcc gdb glibc newlib qemu - unzip cache.zip - rm -rf cache.zip - - - name: Install Python dependencies - run: python -m pip install -r ../requirements.txt --break-system-packages - - - name: Extract and apply patches - uses: ./.github/actions/extract-apply-patches-trunk-or-baseline - with: - patch_name: ${{ inputs.patch_name }} - baseline_hash: ${{ inputs.baseline_hash }} - build_only: ${{ inputs.build_only }} - tot_hash: ${{ inputs.tot_hash }} - - - name: Prepare toolchain dependencies - uses: ./.github/actions/common/setup-dependencies - - # There is only one github target now which is rv64gc build only - - name: Configure - run: | - mkdir build - cd build - TARGET_TUPLE=($(echo ${{ inputs.target }} | tr "-" "\n")) - ../../configure-scripts/${TARGET_TUPLE[0]}-${TARGET_TUPLE[1]} - sed -i "s/ --user / --user --break-system-packages /g" Makefile - - - name: Build - run: | - cd build - make ${{ inputs.mode }} -j32 - - - name: Replace allowlist - run: | - rm -rf test/ - cp -r ../test/ . - - - name: Run Testsuite - if: ${{ inputs.build_only == 'false' }} - uses: ./.github/actions/common/run-testsuite - with: - mode: ${{ inputs.mode }} - target: ${{ inputs.target }} - gcchash: ${{ inputs.patch_applied_gcchash }} - multilib: ${{ inputs.multilib }} - - - name: Build test complete report - if: ${{ inputs.build_only == 'false' }} - run: | - python scripts/update_issue_status.py -token ${{ secrets.GITHUB_TOKEN }} -state 'Complete. Full report will be displayed once all targets are complete' -comment ${{ inputs.test_comment_id }} -target ${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }} -check 'Testsuite' -repo "${PRECOMMIT_REPOSITORY}" -baseline ${{ inputs.baseline_hash }} - printf "\n[Additional information](${{ inputs.additional_info }})\n" >> comment.md - - - name: Update test complete report comment - if: ${{ inputs.build_only == 'false' }} - uses: ./.github/actions/update-comment - with: - comment_id: ${{ inputs.test_comment_id }} - file_path: riscv-gnu-toolchain/comment.md - token: ${{ secrets.GITHUB_TOKEN }} + PATCHWORK_TOKEN: ${{ secrets.PATCHWORK_API }} + PATCH_ID: ${{ inputs.patch_id }} + TARGET: ${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }} + BUILD_ISSUE: ${{ inputs.issue_num }}#issuecomment-${{ inputs.build_comment_id }} + TEST_ISSUE: ${{ inputs.issue_num }}#issuecomment-${{ inputs.test_comment_id }} + BUILD_ONLY: ${{ inputs.build_only }} + run: | + python scripts/post_check_to_patchworks.py -event "$GITHUB_EVENT_NAME" -repo "$GITHUB_REPOSITORY" -pid "$PATCH_ID" -desc 'Build queued' -iid "$BUILD_ISSUE" -state pending -context "build--$TARGET" -token "$PATCHWORK_TOKEN" + if [[ "$BUILD_ONLY" == false ]]; then + python scripts/post_check_to_patchworks.py -event "$GITHUB_EVENT_NAME" -repo "$GITHUB_REPOSITORY" -pid "$PATCH_ID" -desc 'Testsuite queued' -iid "$TEST_ISSUE" -state pending -context test -token "$PATCHWORK_TOKEN" + fi - # The self-hosted environment does not have the same path setup as the hosted runners - # We need to rebuild since restoring the artifact won't work - # (the new path will break the existing build). - run-on-self-hosted: - runs-on: [self-hosted, linux, x64, rise-gcc-ci] + execute: + needs: [report-queued] + uses: ./.github/workflows/regression-worker.yaml + cache-mode: none + permissions: + actions: read + contents: read + with: + patch_name: ${{ inputs.patch_name }} + patch_id: ${{ inputs.patch_id }} + mode: ${{ inputs.mode }} + target: ${{ inputs.target }} + baseline_hash: ${{ inputs.baseline_hash }} + patch_applied_gcchash: ${{ inputs.patch_applied_gcchash }} + multilib: ${{ inputs.multilib }} + build_only: ${{ inputs.build_only }} + run_on_self_hosted: ${{ inputs.run_on_self_hosted }} + tot_hash: ${{ inputs.tot_hash }} + + report-complete: + needs: [report-queued, execute] + if: ${{ !cancelled() && needs.report-queued.result == 'success' }} + runs-on: ubuntu-24.04 environment: production - if: ${{ inputs.run_on_self_hosted }} - timeout-minutes: 1440 # 24 hours - defaults: - run: - working-directory: riscv-gnu-toolchain + permissions: + actions: read + contents: read + issues: write steps: - - name: Cleanup build folder - working-directory: ./ - run: | - ls -la ./ - rm -rf ./* || true - rm -rf ./.??* || true - ls -la ./ - - uses: actions/checkout@v4 - - - name: Setup env - uses: ./.github/actions/common/setup-env - with: - free_up_space: false - - - name: Restore submodules from cache - run: | - gh run download --repo ${{ github.repository }} "${{ github.run_id }}" --name "gcc-sources-${{ inputs.baseline_hash }}" - env: - GH_TOKEN: ${{ github.token }} - - - name: Restore submodules - run: | - rm -rf .git binutils dejagnu gcc gdb glibc newlib qemu - unzip cache.zip - rm -rf cache.zip - - - name: Install Python dependencies - run: | - pip install -r ../requirements.txt --break-system-packages - - - name: Extract and apply patches - uses: ./.github/actions/extract-apply-patches-trunk-or-baseline with: - patch_name: ${{ inputs.patch_name }} - baseline_hash: ${{ inputs.baseline_hash }} - build_only: ${{ inputs.build_only }} - tot_hash: ${{ inputs.tot_hash }} - - - name: Update build pending issue - run: | - if [ '${{ inputs.build_only }}' == 'true' ]; then - python scripts/update_issue_status.py -token ${{ secrets.GITHUB_TOKEN }} -state 'Pending' -comment ${{ inputs.build_comment_id }} -target ${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }} -check 'Build GCC' -repo "${PRECOMMIT_REPOSITORY}" -baseline ${{ inputs.tot_hash }} - else - python scripts/update_issue_status.py -token ${{ secrets.GITHUB_TOKEN }} -state 'Pending' -comment ${{ inputs.build_comment_id }} -target ${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }} -check 'Build GCC' -repo "${PRECOMMIT_REPOSITORY}" -baseline ${{ inputs.baseline_hash }} - fi - printf "\n[Additional information](${{ inputs.additional_info }})\n" >> comment.md + submodules: true + persist-credentials: false - - name: Update build pending report comment - uses: ./.github/actions/update-comment + - uses: actions/setup-python@v5 with: - comment_id: ${{ inputs.build_comment_id }} - file_path: riscv-gnu-toolchain/comment.md - token: ${{ secrets.GITHUB_TOKEN }} - - - name: Report build - if: ${{ github.workflow != 'Staging' }} - run: | - python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid $(tail -n 1 patches/${{ inputs.patch_name }}) -desc 'Build started' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.build_comment_id }}' -state 'pending' -context 'build--${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }}' -token '${{ secrets.PATCHWORK_API }}' - - - name: Make log name - id: build-log - run: | - export BUILD_LOG_NAME=$(tail -n 1 patches/${{ inputs.patch_name }})-${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }}-build-log - echo "build_log_name=$BUILD_LOG_NAME" >> $GITHUB_OUTPUT - - - name: Get target string - id: target-string - run: | - if [ '${{ inputs.mode }}' == 'newlib' ] && [ '${{ inputs.target }}' == 'rv64gcv-lp64d' ]; - then - echo "target_string=rv64gcv-lp64d-reduced-multilib-set" >> $GITHUB_OUTPUT - else - echo "target_string=${{ inputs.target }}" >> $GITHUB_OUTPUT - fi + python-version: "3.11" - # Don't upload stage 2 artifacts on self-hosted runners - # in interest of resources - - name: Build gcc - id: build-gcc-status - uses: ./.github/actions/common/build-target - with: - multilib_target_string: ${{ steps.target-string.outputs.target_string }} - build_log_name: ${{ steps.build-log.outputs.build_log_name }} - upload_stage2_artifacts: 'false' - mode: ${{ inputs.mode }} - target: ${{ inputs.target }} - gcchash: ${{ inputs.patch_applied_gcchash }} - multilib: ${{ inputs.multilib }} - - - name: Get build status - if: ${{ always() }} - id: build-status - run: | - export BUILD_STATUS=${{steps.build-gcc-status.outputs.build_status }} - echo "build_status=$BUILD_STATUS" >> $GITHUB_OUTPUT + - run: python -m pip install --no-cache-dir -r requirements.txt - name: Report build completion status - if: ${{ always() }} uses: ./.github/actions/report-build-complete-status with: - build_status: ${{ steps.build-status.outputs.build_status }} + build_status: ${{ needs.execute.outputs.build_status == 'success' && 'success' || 'failure' }} + patch_id: ${{ inputs.patch_id }} patch_name: ${{ inputs.patch_name }} - build_log_name: ${{ steps.build-log.outputs.build_log_name }} + build_log_name: ${{ inputs.patch_id }}-${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }}-build-log target: ${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }} baseline_hash: ${{ inputs.baseline_hash }} tot_hash: ${{ inputs.tot_hash }} @@ -482,54 +174,33 @@ jobs: issue_num: ${{ inputs.issue_num }} build_comment_id: ${{ inputs.build_comment_id }} additional_info: ${{ inputs.additional_info }} - github_token: ${{ secrets.GITHUB_TOKEN }} + github_token: ${{ github.token }} gist_token: ${{ secrets.GIST_TOKEN }} patchwork_token: ${{ secrets.PATCHWORK_API }} - repository: ${{ env.PRECOMMIT_REPOSITORY }} - - - name: Build test starting report - if: ${{ inputs.build_only == 'false' }} - run: | - python scripts/update_issue_status.py -token ${{ secrets.GITHUB_TOKEN }} -state 'Pending' -comment ${{ inputs.test_comment_id }} -target ${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }} -check 'Testsuite' -repo "${PRECOMMIT_REPOSITORY}" -baseline ${{ inputs.baseline_hash }} - printf "\n[Additional information](${{ inputs.additional_info }})\n" >> comment.md - - - name: Update test pending report comment - if: ${{ inputs.build_only == 'false' }} - uses: ./.github/actions/update-comment - with: - comment_id: ${{ inputs.test_comment_id }} - file_path: riscv-gnu-toolchain/comment.md - token: ${{ secrets.GITHUB_TOKEN }} - - - name: Report testing - if: ${{ inputs.build_only == 'false' && github.workflow != 'Staging' }} - run: | - python scripts/post_check_to_patchworks.py -event ${{ github.event_name }} -repo "${PRECOMMIT_REPOSITORY}" -pid $(tail -n 1 patches/${{ inputs.patch_name }}) -desc 'Testing started' -iid '${{ inputs.issue_num }}#issuecomment-${{ inputs.test_comment_id }}' -state 'pending' -context 'test' -token '${{ secrets.PATCHWORK_API }}' + repository: ${{ github.repository }} - - name: Replace allowlist - run: | - rm -rf test/ - cp -r ../test/ . - - - name: Run Testsuite - if: ${{ inputs.build_only == 'false' }} - uses: ./.github/actions/common/run-testsuite - with: - mode: ${{ inputs.mode }} - target: ${{ inputs.target }} - gcchash: ${{ inputs.patch_applied_gcchash }} - multilib: ${{ inputs.multilib }} - - - name: Build test complete report + - name: Record testsuite completion if: ${{ inputs.build_only == 'false' }} - run: | - python scripts/update_issue_status.py -token ${{ secrets.GITHUB_TOKEN }} -state 'Complete. Full report will be displayed once all targets are complete' -comment ${{ inputs.test_comment_id }} -target ${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }} -check 'Testsuite' -repo "${PRECOMMIT_REPOSITORY}" -baseline ${{ inputs.baseline_hash }} - printf "\n[Additional information](${{ inputs.additional_info }})\n" >> comment.md + working-directory: riscv-gnu-toolchain + env: + GH_TOKEN: ${{ github.token }} + COMMENT_ID: ${{ inputs.test_comment_id }} + TARGET: ${{ inputs.mode }}-${{ inputs.target }}-${{ inputs.multilib }} + GCC_HASH: ${{ inputs.baseline_hash }} + INFO_URL: ${{ inputs.additional_info }} + TEST_SUCCEEDED: ${{ needs.execute.outputs.test_status == 'success' }} + run: | + if [[ "$TEST_SUCCEEDED" == true ]]; then + state='Complete. Full report will be displayed once all targets are complete' + else + state='Testsuite did not complete. See the Actions run for details.' + fi + python scripts/update_issue_status.py -token "$GH_TOKEN" -state "$state" -comment "$COMMENT_ID" -target "$TARGET" -check Testsuite -repo "$GITHUB_REPOSITORY" -baseline "$GCC_HASH" + printf '\n[Additional information](%s)\n' "$INFO_URL" >> comment.md - - name: Update test complete report comment + - uses: ./.github/actions/update-comment if: ${{ inputs.build_only == 'false' }} - uses: ./.github/actions/update-comment with: comment_id: ${{ inputs.test_comment_id }} file_path: riscv-gnu-toolchain/comment.md - token: ${{ secrets.GITHUB_TOKEN }} + token: ${{ github.token }} diff --git a/docs/precommit-maintenance-runbook.md b/docs/precommit-maintenance-runbook.md index abe011c..255fc71 100644 --- a/docs/precommit-maintenance-runbook.md +++ b/docs/precommit-maintenance-runbook.md @@ -29,7 +29,7 @@ and Patchwork checks. Out-of-scope IDs produce an empty build queue. ## Shadow And Production Modes -Keep `PATCHWORK_REPORTING_ENABLED` unset or different from `true` during shadow +Keep `PATCHWORK_REPORTING_ENABLED` unset or set to `false` during shadow testing. GitHub issues, artifacts, builds, and comparisons still run, but no Patchwork check may be written. Logs must explicitly say that reporting was skipped. @@ -44,6 +44,13 @@ Before enabling writes: - run one real patch in shadow mode and compare it with the legacy result; - restrict manual result overrides to designated repository maintainers. +To validate publication before enabling all schedules, set the repository variable +`PATCHWORK_REPORTING_ENABLED` to the full 40-character SHA of the reviewed +workflow revision, then dispatch `Patchworks` at that revision. Only a manual +`Patchworks` run with that exact SHA may publish in this mode. Verify the RISE +check and its target URL on the selected patch before switching the variable to +`true` for normal production reporting or `false` to stop writes. + Set `PATCHWORK_REPORTING_ENABLED=true` only after those checks. A missing token, non-2xx Patchwork response, unexpected username, or legacy `toolchain-ci-rivos-` context is a production failure, not a warning to ignore. @@ -82,7 +89,7 @@ recovery run therefore needs attention even if some patch issues look complete. Patch polling and staging metadata lookup run on `ubuntu-24.04`; they do not wait behind self-hosted builds or require a `ping` runner. Long builds require -`self-hosted`, `linux`, `x64`, and `rise-gcc-ci`, with a registration available to +`self-hosted`, `linux`, `x64`, and `rise-precommit-regression-07`, with a registration available to this repository. Each build/test job uses 32 parallel workers. Provision dependencies using the maintenance account before starting the @@ -91,7 +98,10 @@ They erase their own Actions workspace and execute incoming patch code, so use an isolated, disposable execution environment with a separate workspace from post-commit. A runner group controls routing; it does not provide execution isolation. Keep the polling/reporting credentials out of the patch execution -environment when deploying the runner. +environment when deploying the runner. The reusable `regression-worker.yaml` +workflow receives read-only Actions and repository access. GitHub-hosted jobs +in `test-regression.yaml` publish queued and completed checks. A failed build +links its Actions run even when its optional log preview is unavailable. ## Dependency Updates @@ -99,7 +109,8 @@ Merge shared toolchain changes first. For changes confined to pre-commit patch selection, update the pre-commit gitlink to the published toolchain revision. For changes that affect baseline comparability, update post-commit and wait for a new valid baseline before updating pre-commit. When source submodules change, -bump the corresponding `submodules-archive-` restore/save keys. +bump the `precommit-hosted-sources-` restore/save key in the hosted source job. +Patch workers receive the prepared `gcc-sources-` artifact for their run. ## Incident Stop Controls diff --git a/docs/rise-precommit-cutover.md b/docs/rise-precommit-cutover.md index a01b466..7846c6a 100644 --- a/docs/rise-precommit-cutover.md +++ b/docs/rise-precommit-cutover.md @@ -40,7 +40,7 @@ The normal data flow is: | --- | --- | --- | --- | --- | | `PATCHWORK_API` | Repository or organization secret | GCC Patchwork check write access for a RISE-managed service account | Post Patchwork check results | Production cutover | | `PATCHWORK_CHECK_USERNAME` | Repository variable | Patchwork username, not a token | Identifies checks written by the RISE account during recovery scans | Shadow validation | -| `PATCHWORK_REPORTING_ENABLED` | Repository variable | Set to `true` only after shadow results are verified | Enables Patchwork writes; any other value skips writes | Shadow testing can run while unset | +| `PATCHWORK_REPORTING_ENABLED` | Repository variable | `false` for shadow, a reviewed full commit SHA for a manual pilot, or `true` for production | Enables reporting for the selected mode | Shadow testing can run while unset | | `PATCHWORK_OVERRIDE_USERS` | Repository variable | Comma-separated GitHub logins, without spaces | Allows only designated maintainers to issue manual Patchwork result commands | Production cutover | | `RISE_CI_READ_TOKEN` | Repository or organization secret | Read Actions artifacts and metadata from `riseproject-dev/gcc-postcommit-ci` | Download baseline sum files | First pre-commit comparison | | `GIST_TOKEN` | Repository or organization secret | Create gists from a RISE-managed account | Store oversized build or summary excerpts | Only needed for large report previews | @@ -54,8 +54,8 @@ Do not use personal GitHub tokens for any of these secrets. | --- | --- | --- | --- | --- | | `patchworks.yaml/fetch_patches` | `ubuntu-24.04` | Patchwork polling and patch artifact creation | Python dependencies and zip installed by the workflow | GitHub-hosted | | `staging.yaml/get-patch-info` | `ubuntu-24.04` | Staging patch lookup for pull requests | Python dependencies and zip installed by the workflow | GitHub-hosted | -| `test-regression.yaml/rerun-timeouts` | `self-hosted`, `linux`, `x64`, `rise-gcc-ci` | Long retry builds and tests | GCC build prerequisites, Python, enough disk for toolchain builds | Dedicated RISE runner group | -| `test-regression.yaml/run-on-self-hosted` | `self-hosted`, `linux`, `x64`, `rise-gcc-ci` | Long production build and tests | GCC build prerequisites, Python, enough disk for toolchain builds | Dedicated RISE runner group | +| `regression-worker.yaml/rerun-timeouts` | `self-hosted`, `linux`, `x64`, `rise-precommit-regression-07` | Long retry builds and tests | GCC build prerequisites, Python, enough disk for toolchain builds | Dedicated RISE runner group | +| `regression-worker.yaml/run-on-self-hosted` | `self-hosted`, `linux`, `x64`, `rise-precommit-regression-07` | Long production build and tests | GCC build prerequisites, Python, enough disk for toolchain builds | Dedicated RISE runner group | Polling and staging metadata lookup do not consume a self-hosted build slot. GitHub schedules can be delayed; retain the nightly recovery workflow and check @@ -117,7 +117,7 @@ reporting credentials in separate trusted jobs. and baseline artifacts. 3. Configure `RISE_CI_READ_TOKEN` in this repository. 4. Configure `PATCHWORK_CHECK_USERNAME` for the RISE Patchwork account and - leave `PATCHWORK_REPORTING_ENABLED` unset or set to a non-`true` value. + leave `PATCHWORK_REPORTING_ENABLED` unset or set it to `false`. 5. Run a workflow_dispatch or staging pre-commit job against a real Patchwork patch and inspect the generated RISE issue, artifact downloads, and skipped Patchwork log messages. @@ -155,7 +155,7 @@ owner in the RISE operations system. ## Rollback -Set `PATCHWORK_REPORTING_ENABLED` to any value other than `true` to stop +Set `PATCHWORK_REPORTING_ENABLED=false` to stop Patchwork writes while keeping patch fetch, build, and test artifacts running. If baseline reads fail, restore service by fixing `RISE_CI_READ_TOKEN` or by pausing pre-commit schedules until a valid RISE post-commit baseline is diff --git a/ops/precommit-runner/README.md b/ops/precommit-runner/README.md new file mode 100644 index 0000000..2e1f837 --- /dev/null +++ b/ops/precommit-runner/README.md @@ -0,0 +1,77 @@ +# Pre-commit runner on 07 + +The host runs one rootless Podman pre-commit worker alongside the post-commit +service. Each listener accepts one job. Its fresh container and workspace are +removed on exit. The production runner name and routing label are both +`rise-precommit-regression-07`. The pre-commit build workflow must request +that label. The worker uses the pilot image, systemd user service and resource +limits already installed on 07. Build jobs must use read-only repository +permissions and publish their results through a separate trusted job. + +## Install the worker launcher + +Run these commands on 07 from the reviewed pre-commit repository checkout. +The pilot account must already have its runner image, resource limits and +diagnostics directory. Install the Python host dependencies and enable its user +manager at boot. + +```sh +sudo apt-get install python3-requests python3-jwt python3-cryptography +sudo loginctl enable-linger rise-precommit-ci +sudo install -D -m 0755 ops/precommit-runner/replenish.py /usr/local/lib/rise-precommit-jit/replenish.py +worker_home=$(getent passwd rise-precommit-ci | cut -d: -f6) +worker_uid=$(id -u rise-precommit-ci) +sudo -u rise-precommit-ci mkdir -p "$worker_home/.config/systemd/user" +sudo install -o rise-precommit-ci -g rise-precommit-ci -m 0644 ops/precommit-runner/rise-precommit-pilot.service "$worker_home/.config/systemd/user/rise-precommit-pilot.service" +sudo -Hu rise-precommit-ci env XDG_RUNTIME_DIR="/run/user/$worker_uid" systemctl --user daemon-reload +``` + +## Start one worker from the operator machine + +This works before a GitHub App is installed. For a controlled rollout, use +the operator's existing GitHub login to issue a JIT for this repository and +stream it to the host. Each additional build job needs a new listener. Run +with a verified SSH host key for 07 and a drained pre-commit worker slot. +If switching back from automatic replenishment, first stop the timer and wait +for any active replenishment invocation and worker job to finish. This keeps +the operator and the timer from requesting the same registration. + +```bash +set -o pipefail +printf '%s\n' '{"name":"rise-precommit-regression-07","runner_group_id":1,"labels":["self-hosted","Linux","X64","rise-precommit-regression-07"],"work_folder":"/srv/work"}' | + gh api --method POST repos/riseproject-dev/gcc-precommit-ci/actions/runners/generate-jitconfig --input - --jq .encoded_jit_config | + ssh -o ForwardAgent=no -o StrictHostKeyChecking=yes jiawei@rise-gcc-ci-07.di.riseproject.dev \ + 'cd /tmp && sudo -nHu rise-precommit-ci /usr/bin/python3 /usr/local/lib/rise-precommit-jit/replenish.py --stdin' +``` + +## Keep the worker available automatically + +Use a dedicated RISE GitHub App installed only on `gcc-precommit-ci` with +repository Administration write access, the scope required by GitHub's +repository runner registration API. A system timer checks the local worker +once a minute. When the worker is stopped, the controller authenticates with +the App, requests a short-lived installation token scoped to this repository, +and creates a new JIT registration. Only the JIT enters the worker container. + +Store the App's private key in `/etc/rise-precommit-jit/app-key.pem`, owned by +root with mode 0600. Store `GITHUB_APP_ID=` in +`/etc/rise-precommit-jit/app.conf`. Systemd makes the key available to the +controller through `LoadCredential`. The next invocation reads any rotated key. +The installation ID is looked up using the repository URL. + +```sh +sudo install -m 0644 ops/precommit-runner/rise-precommit-jit.service ops/precommit-runner/rise-precommit-jit.timer /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable --now rise-precommit-jit.timer +sudo systemctl start rise-precommit-jit.service +journalctl -u rise-precommit-jit.service -n 30 +``` + +To drain the slot, disable the replenishment timer and allow a running build +to finish. If the listener is online and idle, stop the worker user unit during +the maintenance window. Each timer invocation checks the worker service and +container before renewing. It removes an offline, idle registration only when +both its name and routing label match this controller. Busy or online +registrations are left to finish. GitHub API and host errors appear in the +service journal and the timer retries. Check repository runner status with +`gh api repos/riseproject-dev/gcc-precommit-ci/actions/runners`. diff --git a/ops/precommit-runner/replenish.py b/ops/precommit-runner/replenish.py new file mode 100644 index 0000000..4f2cdd3 --- /dev/null +++ b/ops/precommit-runner/replenish.py @@ -0,0 +1,153 @@ +"""Keep one single-use listener ready for the RISE GCC pre-commit repository.""" + +import argparse +import base64 +import fcntl +import os +from pathlib import Path +import subprocess +import sys +import time + +import jwt +import requests + + +REPO = "/repos/riseproject-dev/gcc-precommit-ci" +RUNNERS = REPO + "/actions/runners" +NAME = "rise-precommit-regression-07" +SERVICE = "rise-precommit-pilot.service" +CONTAINER = "rise-precommit-07-pilot" +SECRET = "runner-jit-config" + + +def api(method, path, token, body=None, *, missing_ok=False): + response = requests.request( + method, + "https://api.github.com" + path, + headers={ + "Authorization": "Bearer " + token, + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + }, + json=body, + timeout=(10, 30), + allow_redirects=False, + ) + if missing_ok and response.status_code == 404: + return None + if response.status_code not in (200, 201, 204): + raise RuntimeError( + f"GitHub {method} {path} returned HTTP {response.status_code}" + ) + return response.json() if response.content else None + + +def installation_token(): + key = Path(os.environ["CREDENTIALS_DIRECTORY"]) / "app-key.pem" + now = int(time.time()) + assertion = jwt.encode( + {"iat": now - 60, "exp": now + 540, "iss": os.environ["GITHUB_APP_ID"]}, + key.read_bytes(), + algorithm="RS256", + ) + installation = api("GET", REPO + "/installation", assertion) + result = api( + "POST", + f"/app/installations/{installation['id']}/access_tokens", + assertion, + { + "repositories": ["gcc-precommit-ci"], + "permissions": {"administration": "write"}, + }, + ) + return result["token"] + + +def command(*args, stdin=None): + return subprocess.run( + args, input=stdin, text=True, stdout=subprocess.PIPE, check=True, timeout=60 + ).stdout.strip() + + +def worker_idle(): + info = command( + "systemctl", "--user", "show", SERVICE, "-p", "LoadState", "-p", "ActiveState" + ) + state = dict(line.split("=", 1) for line in info.splitlines()) + if state["LoadState"] != "loaded": + raise RuntimeError(f"{SERVICE} is not installed and loaded") + if state["ActiveState"] not in ("inactive", "failed"): + return False + containers = command("podman", "ps", "-a", "--format", "{{.Names}} {{.State}}") + for entry in containers.splitlines(): + name, status = entry.split() + if name == CONTAINER: + if status not in ("exited", "stopped", "created", "configured"): + return False + # Clean up an exited container left by a host reboot. Without + # --force Podman will refuse to remove a running container. + command("podman", "rm", CONTAINER) + return True + + +def next_config(): + token = installation_token() + registrations = api("GET", f"{RUNNERS}?name={NAME}", token)["runners"] + matches = [item for item in registrations if item["name"] == NAME] + if len(matches) > 1: + raise RuntimeError(f"Multiple registrations are named {NAME}") + if matches: + runner = matches[0] + if NAME not in {label["name"] for label in runner["labels"]}: + raise RuntimeError(f"The name {NAME} is in use by another registration") + if runner["status"] != "offline" or runner["busy"] is not False: + return None + # Our fixed name also recovers a previous failed start or lost JIT + # response. A missing registration means GitHub already retired it. + api("DELETE", f"{RUNNERS}/{int(runner['id'])}", token, missing_ok=True) + registration = api( + "POST", + RUNNERS + "/generate-jitconfig", + token, + { + "name": NAME, + "runner_group_id": 1, + "labels": ["self-hosted", "Linux", "X64", NAME], + "work_folder": "/srv/work", + }, + ) + return registration["encoded_jit_config"] + + +def replenish(from_stdin): + if not worker_idle(): + if from_stdin: + raise RuntimeError("The pre-commit worker is already running") + return + config = sys.stdin.read().strip() if from_stdin else next_config() + if config is None: + return + if not config or not base64.b64decode(config, validate=True): + raise ValueError("Invalid JIT configuration") + command("podman", "secret", "rm", "--ignore", SECRET) + command("podman", "secret", "create", SECRET, "-", stdin=config) + command("systemctl", "--user", "start", SERVICE) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--stdin", action="store_true", help="Start once with an externally issued JIT" + ) + args = parser.parse_args() + runtime = Path("/run/user") / str(os.getuid()) + os.environ["XDG_RUNTIME_DIR"] = str(runtime) + os.environ["DBUS_SESSION_BUS_ADDRESS"] = f"unix:path={runtime}/bus" + with (runtime / "rise-precommit-jit.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + replenish(args.stdin) + + +if __name__ == "__main__": + main() diff --git a/ops/precommit-runner/rise-precommit-jit.service b/ops/precommit-runner/rise-precommit-jit.service new file mode 100644 index 0000000..60bfe4e --- /dev/null +++ b/ops/precommit-runner/rise-precommit-jit.service @@ -0,0 +1,12 @@ +[Unit] +Description=Replenish the RISE GCC pre-commit single-job runner on 07 +Wants=network-online.target +After=network-online.target + +[Service] +Type=oneshot +User=rise-precommit-ci +EnvironmentFile=/etc/rise-precommit-jit/app.conf +LoadCredential=app-key.pem:/etc/rise-precommit-jit/app-key.pem +ExecStart=/usr/bin/python3 /usr/local/lib/rise-precommit-jit/replenish.py +UMask=0077 diff --git a/ops/precommit-runner/rise-precommit-jit.timer b/ops/precommit-runner/rise-precommit-jit.timer new file mode 100644 index 0000000..7b9d5c7 --- /dev/null +++ b/ops/precommit-runner/rise-precommit-jit.timer @@ -0,0 +1,10 @@ +[Unit] +Description=Keep one ephemeral RISE GCC pre-commit runner ready on 07 + +[Timer] +OnBootSec=1min +OnUnitInactiveSec=1min +AccuracySec=5s + +[Install] +WantedBy=timers.target diff --git a/ops/precommit-runner/rise-precommit-pilot.service b/ops/precommit-runner/rise-precommit-pilot.service index aae360a..859ad01 100644 --- a/ops/precommit-runner/rise-precommit-pilot.service +++ b/ops/precommit-runner/rise-precommit-pilot.service @@ -5,7 +5,7 @@ Description=RISE pre-commit isolated single-job pilot Type=simple WorkingDirectory=/srv/rise-precommit-ci ExecStart=/usr/bin/podman run --rm --pull=never --name rise-precommit-07-pilot --userns=keep-id:uid=1001,gid=1001 --network=slirp4netns:allow_host_loopback=false --cpus=20 --memory=76g --pids-limit=8192 --cap-drop=ALL --security-opt=no-new-privileges --secret=runner-jit-config,uid=1001,gid=1001,mode=0400 --volume=/srv/rise-precommit-ci/diag:/opt/actions-runner/_diag localhost/rise-precommit-runner:20261117 -ExecStop=/usr/bin/podman stop --time=900 rise-precommit-07-pilot +ExecStop=/usr/bin/podman stop --ignore --time=900 rise-precommit-07-pilot Restart=no TimeoutStartSec=120 TimeoutStopSec=960 diff --git a/scripts/build_log_preview.py b/scripts/build_log_preview.py new file mode 100644 index 0000000..1721524 --- /dev/null +++ b/scripts/build_log_preview.py @@ -0,0 +1,82 @@ +"""Read small text previews from a build job's log artifact without extracting it.""" + +import argparse +import os +import re +import tempfile +import zipfile +from pathlib import Path + +import requests + + +PREVIEW_BYTES = 1_048_000 +MAX_ARCHIVE_BYTES = 128 * 1024 * 1024 +MAX_LOG_BYTES = 256 * 1024 * 1024 + + +def write_previews(archive_file, log_name, output): + if not re.fullmatch(r"[0-9]+-[a-zA-Z0-9_.-]+-build-log", log_name): + raise ValueError("Invalid build log name") + output.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(archive_file) as archive: + for member, dest in [ + (log_name + ".log", "stdout.txt"), + (log_name + "-stderr.log", "stderr.txt"), + ]: + info = archive.getinfo(member) + if info.file_size > MAX_LOG_BYTES: + raise ValueError("Log exceeds preview size limit") + with archive.open(info) as stream: + stream.seek(max(0, info.file_size - PREVIEW_BYTES)) + tail = stream.read(PREVIEW_BYTES) + # The two fixed files are text inputs to the gist API. Archive paths, + # modes, links and other entries never materialize on the reporter. + (output / dest).write_text(tail.decode("utf-8", errors="replace")) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("log_name") + parser.add_argument("output", type=Path) + args = parser.parse_args() + api = ( + os.environ["GITHUB_API_URL"] + + "/repos/" + + os.environ["GITHUB_REPOSITORY"] + + "/actions" + ) + headers = {"Authorization": "Bearer " + os.environ["GH_TOKEN"]} + response = requests.get( + f"{api}/runs/{os.environ['GITHUB_RUN_ID']}/artifacts", + params={"name": args.log_name}, + headers=headers, + timeout=30, + ) + response.raise_for_status() + matching = [ + a + for a in response.json()["artifacts"] + if a["name"] == args.log_name and not a["expired"] + ] + if len(matching) != 1 or matching[0]["size_in_bytes"] > MAX_ARCHIVE_BYTES: + raise ValueError( + "No single current-run log artifact within the preview size limit" + ) + with requests.get( + f"{api}/artifacts/{int(matching[0]['id'])}/zip", + headers=headers, + stream=True, + timeout=60, + ) as download, tempfile.TemporaryFile() as tmp: + download.raise_for_status() + for block in download.iter_content(256 * 1024): + if tmp.tell() + len(block) > MAX_ARCHIVE_BYTES: + raise ValueError("Downloaded archive exceeds preview size limit") + tmp.write(block) + tmp.seek(0) + write_previews(tmp, args.log_name, args.output) + + +if __name__ == "__main__": + main() diff --git a/scripts/collect_testsuite_report.py b/scripts/collect_testsuite_report.py new file mode 100644 index 0000000..912057a --- /dev/null +++ b/scripts/collect_testsuite_report.py @@ -0,0 +1,48 @@ +"""Read the expected report as data without extracting the build worker's archive.""" + +import re +import sys +from pathlib import Path +from zipfile import ZipFile + + +MAX_REPORT_BYTES = 256 * 1024 * 1024 + + +def collect(archive_path, report_name, output_dir): + if not re.fullmatch( + r"gcc-(?:linux|newlib)-[a-z0-9_]+-[a-z0-9]+-[0-9a-f]{40}-multilib-report\.log", + report_name, + ): + raise ValueError("Invalid report name") + report_path = output_dir / report_name + temporary = report_path.with_suffix(".partial") + try: + with ZipFile(archive_path) as archive: + if archive.namelist().count(report_name) != 1: + raise ValueError("Expected exactly one matching report") + if archive.getinfo(report_name).file_size > MAX_REPORT_BYTES: + raise ValueError("Report exceeds the comparison size limit") + header = True + with archive.open(report_name) as source, temporary.open("wb") as dest: + for line in source: + if header: + # The multilib splitter uses these target names in filenames. + if ( + b"===" in line + and b"Unexpected fails for" in line + and b"/" in line + ): + raise ValueError("Invalid multilib target in report") + if line in (b"\n", b"\r\n"): + header = False + dest.write(line) + if header: + raise ValueError("Incomplete multilib report header") + temporary.replace(report_path) + finally: + temporary.unlink(missing_ok=True) + + +if __name__ == "__main__": + collect(Path(sys.argv[1]), sys.argv[2], Path(sys.argv[3])) diff --git a/scripts/patch_matrix.py b/scripts/patch_matrix.py new file mode 100644 index 0000000..7884877 --- /dev/null +++ b/scripts/patch_matrix.py @@ -0,0 +1,22 @@ +"""Bind patch reporting IDs to matrix entries during hosted Patchwork discovery.""" + +import json +import re +from pathlib import Path + + +def patch_targets(names, metadata): + targets = [] + for name in names: + if not re.fullmatch(r"[0-9]+-\w*-[1-9][0-9]*", name): + raise ValueError(f"Invalid patch artifact name: {name!r}") + patch_id = (metadata / name).read_text().splitlines()[-1] + if not re.fullmatch(r"[1-9][0-9]*", patch_id): + raise ValueError(f"Invalid Patchwork ID in {name}") + targets.append({"patch_name": name, "patch_id": patch_id}) + return targets + + +if __name__ == "__main__": + names = json.loads(Path("artifact_names.txt").read_text()) + print(json.dumps(patch_targets(names, Path("patchworks_metadata")))) diff --git a/scripts/staging_replay.py b/scripts/staging_replay.py new file mode 100644 index 0000000..a9584e9 --- /dev/null +++ b/scripts/staging_replay.py @@ -0,0 +1,80 @@ +"""Select the historical patch for a staging pull request.""" + +from datetime import datetime +import os +from pathlib import Path +import re +import sys + +import requests + + +def github_list(repo, token, path): + response = requests.get( + f"https://api.github.com/repos/{repo}/{path}", + headers={ + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + }, + timeout=60, + ) + response.raise_for_status() + items = response.json() + if not isinstance(items, list): + raise ValueError("Expected a list in the GitHub response") + return items + + +def replay_outputs(repo, token, staging, patch_detail): + # Match the shared staging selector's window and issue eligibility. + issues = github_list(repo, token, "issues?state=closed&per_page=100") + issue = next((issue for issue in issues if staging.filter_issue(issue)), None) + if issue is None: + print("Staging replay skipped: no eligible closed issue") + return {"found": "false"} + + number = issue["number"] + if type(number) is not int or number <= 0: + raise ValueError("Invalid historical issue number") + comments = github_list(repo, token, f"issues/{number}/comments") + if len(comments) < 3: + raise ValueError(f"Missing staging metadata in issue #{number}") + patch_id, baseline, trunk = staging.parse_info(issue, comments[1]) + if not re.fullmatch(r"[1-9][0-9]*", patch_id) or not all( + re.fullmatch(r"[0-9a-fA-F]{4,40}", sha) for sha in (baseline, trunk) + ): + raise ValueError(f"Invalid staging metadata in issue #{number}") + timestamp = datetime.fromisoformat(patch_detail(patch_id)["date"]).isoformat() + return { + "found": "true", + "timestamp": timestamp, + "baseline_hash": baseline, + "tot_hash": trunk, + "patch_id": patch_id, + "issue_num": str(number), + } + + +def main(): + sys.path.insert( + 0, str(Path(__file__).resolve().parents[1] / "riscv-gnu-toolchain/scripts") + ) + import get_staging_patch + from riscv_patch_scope import patch_detail + + fields = replay_outputs( + os.environ["PRECOMMIT_REPOSITORY"], + os.environ["GH_TOKEN"], + get_staging_patch, + patch_detail, + ) + with open(os.environ["GITHUB_OUTPUT"], "a") as output: + for key, value in fields.items(): + print(f"{key}={value}", file=output) + if fields["found"] == "false": + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as summary: + print("Staging replay skipped: no eligible closed issue", file=summary) + + +if __name__ == "__main__": + main() diff --git a/tests/test_precommit_jit.py b/tests/test_precommit_jit.py new file mode 100644 index 0000000..b483160 --- /dev/null +++ b/tests/test_precommit_jit.py @@ -0,0 +1,156 @@ +import base64 +import io +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "ops/precommit-runner")) +import replenish as jit + + +CONFIG = base64.b64encode(b"fixture single-use configuration").decode() + + +class AppTokenTests(unittest.TestCase): + def test_exchange_scopes_new_tokens_to_precommit_administration(self): + with tempfile.TemporaryDirectory() as directory: + (Path(directory) / "app-key.pem").write_text("fixture") + with ( + patch.dict( + jit.os.environ, CREDENTIALS_DIRECTORY=directory, GITHUB_APP_ID="1" + ), + patch.object(jit.jwt, "encode", return_value="fixture-assertion"), + patch.object( + jit, + "api", + side_effect=[{"id": 5}, {"token": "fixture-installation"}], + ) as api, + ): + self.assertEqual(jit.installation_token(), "fixture-installation") + self.assertEqual( + api.call_args_list[0].args, + ("GET", jit.REPO + "/installation", "fixture-assertion"), + ) + self.assertEqual( + api.call_args_list[-1].args, + ( + "POST", + "/app/installations/5/access_tokens", + "fixture-assertion", + { + "repositories": ["gcc-precommit-ci"], + "permissions": {"administration": "write"}, + }, + ), + ) + + +class ReplenishmentTests(unittest.TestCase): + def setUp(self): + self.token = self.enterContext(patch.object(jit, "installation_token")) + self.api = self.enterContext(patch.object(jit, "api")) + self.command = self.enterContext(patch.object(jit, "command")) + + def test_active_worker_never_renews_or_modifies_a_registration(self): + self.command.return_value = "LoadState=loaded\nActiveState=active" + jit.replenish(False) + self.assertEqual(self.command.call_count, 1) + self.token.assert_not_called() + self.api.assert_not_called() + + def test_live_container_is_not_replaced_on_service_state_mismatch(self): + self.command.side_effect = [ + "LoadState=loaded\nActiveState=failed", + f"{jit.CONTAINER} running", + ] + jit.replenish(False) + self.token.assert_not_called() + self.assertEqual(self.command.call_count, 2) + + def test_reboot_cleanup_only_removes_the_stopped_precommit_container(self): + self.command.side_effect = [ + "LoadState=loaded\nActiveState=inactive", + f"unrelated running\n{jit.CONTAINER} exited", + "", + ] + self.assertTrue(jit.worker_idle()) + self.command.assert_called_with("podman", "rm", jit.CONTAINER) + + def test_uncertain_registration_never_allows_deletion(self): + for status, busy in (("online", False), ("offline", True), ("unknown", False)): + with self.subTest(status=status, busy=busy): + self.api.reset_mock() + self.api.return_value = { + "runners": [ + { + "name": jit.NAME, + "status": status, + "busy": busy, + "labels": [{"name": jit.NAME}], + } + ] + } + self.assertIsNone(jit.next_config()) + self.assertEqual(self.api.call_count, 1) + + def test_foreign_registration_is_retained(self): + self.api.return_value = { + "runners": [{"name": jit.NAME, "labels": [{"name": "other"}]}] + } + with self.assertRaises(RuntimeError): + jit.next_config() + self.assertEqual(self.api.call_count, 1) + + def test_lost_jit_is_replaced_by_one_dedicated_listener(self): + stale = { + "name": jit.NAME, + "labels": [{"name": jit.NAME}], + "id": 21, + "status": "offline", + "busy": False, + } + self.api.side_effect = [ + {"runners": [stale]}, + None, + {"encoded_jit_config": CONFIG}, + ] + self.assertEqual(jit.next_config(), CONFIG) + delete, create = self.api.call_args_list[1:] + self.assertEqual(delete.args[:2], ("DELETE", f"{jit.RUNNERS}/21")) + self.assertEqual(create.args[:2], ("POST", jit.RUNNERS + "/generate-jitconfig")) + self.assertEqual( + create.args[3]["labels"], ["self-hosted", "Linux", "X64", jit.NAME] + ) + + def test_registration_api_failure_prevents_changes_to_local_runner(self): + self.command.side_effect = ["LoadState=loaded\nActiveState=inactive", ""] + self.api.side_effect = RuntimeError("HTTP 503") + with self.assertRaisesRegex(RuntimeError, "503"): + jit.replenish(False) + self.assertEqual(self.command.call_count, 2) + + def test_manual_rollout_uses_only_external_jit_on_stdin(self): + self.command.side_effect = [ + "LoadState=loaded\nActiveState=inactive", + "", + "", + "", + "", + ] + with patch.object(sys, "stdin", io.StringIO(CONFIG + "\n")): + jit.replenish(True) + self.token.assert_not_called() + self.api.assert_not_called() + secret, start = self.command.call_args_list[-2:] + self.assertEqual(secret.args, ("podman", "secret", "create", jit.SECRET, "-")) + self.assertEqual(secret.kwargs, {"stdin": CONFIG}) + self.assertEqual(start.args, ("systemctl", "--user", "start", jit.SERVICE)) + + def test_empty_manual_input_leaves_current_secret_intact(self): + self.command.side_effect = ["LoadState=loaded\nActiveState=inactive", ""] + with patch.object(sys, "stdin", io.StringIO("")), self.assertRaises(ValueError): + jit.replenish(True) + self.assertEqual(self.command.call_count, 2) diff --git a/tests/test_report_isolation.py b/tests/test_report_isolation.py new file mode 100644 index 0000000..c86db8f --- /dev/null +++ b/tests/test_report_isolation.py @@ -0,0 +1,82 @@ +"""Check credential boundaries and safe handling of logs from patch builds.""" + +import io +import re +import sys +import tempfile +import unittest +import zipfile +from pathlib import Path +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) + +import build_log_preview + + +class ReportingTests(unittest.TestCase): + def test_patch_execution_jobs_use_only_read_permissions(self): + folder = ROOT / ".github/workflows" + worker = (folder / "regression-worker.yaml").read_text() + defaults, worker_jobs = worker.split("\njobs:\n") + self.assertEqual( + defaults.split("\npermissions:\n")[1].rstrip(), + " actions: read\n contents: read", + ) + self.assertNotIn("secrets", defaults) + blocks = re.split(r"(?m)^ ([a-z-]+):\n", worker_jobs) + jobs = dict(zip(blocks[1::2], blocks[2::2], strict=True)) + workers = {"build", "test", "rerun-timeouts", "run-on-self-hosted"} + self.assertEqual(set(jobs), workers) + for name in workers: + with self.subTest(name=name): + job = jobs[name] + for forbidden in ( + "secrets.", + "issues: write", + "environment:", + "report-build-complete-status", + ): + self.assertNotIn(forbidden, job) + self.assertIn("persist-credentials: false", job) + if "self-hosted," in job: + self.assertIn("rise-precommit-regression-07", job) + self.assertNotIn("rise-gcc-ci", job) + self.assertIn("steps.build-gcc-status.outcome", jobs["run-on-self-hosted"]) + reporter_jobs = ( + (folder / "test-regression.yaml").read_text().split("\njobs:\n")[1] + ) + blocks = re.split(r"(?m)^ ([a-z-]+):\n", reporter_jobs) + reporters = dict(zip(blocks[1::2], blocks[2::2], strict=True)) + self.assertIn( + "uses: ./.github/workflows/regression-worker.yaml", reporters["execute"] + ) + self.assertNotIn("secrets:", reporters["execute"]) + self.assertIn("cache-mode: none", reporters["execute"]) + for name in ("report-queued", "report-complete"): + self.assertIn("runs-on: ubuntu-24.04", reporters[name]) + self.assertIn("environment: production", reporters[name]) + self.assertNotIn("extract-apply-patches", reporters[name]) + self.assertNotIn("download-artifact@", reporters[name]) + self.assertIn("&& 'success' || 'failure'", reporters["report-complete"]) + + def test_only_allowlisted_log_tails_become_text_inputs(self): + name = "123-linux-rv64gc-multilib-build-log" + archive = io.BytesIO() + with zipfile.ZipFile(archive, "w") as data: + data.writestr(name + ".log", b"olddata-new") + data.writestr(name + "-stderr.log", b"bad\xff") + data.writestr("extra.sh", b"irrelevant") + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "previews" + with patch.object(build_log_preview, "PREVIEW_BYTES", 4): + build_log_preview.write_previews(archive, name, output) + self.assertEqual( + sorted(p.name for p in output.iterdir()), ["stderr.txt", "stdout.txt"] + ) + self.assertEqual((output / "stdout.txt").read_text(), "-new") + self.assertEqual((output / "stderr.txt").read_text(), "bad\ufffd") + with patch.object(build_log_preview, "MAX_LOG_BYTES", 4): + with self.assertRaises(ValueError): + build_log_preview.write_previews(archive, name, output) diff --git a/tests/test_staging_replay.py b/tests/test_staging_replay.py new file mode 100644 index 0000000..a378dde --- /dev/null +++ b/tests/test_staging_replay.py @@ -0,0 +1,88 @@ +from pathlib import Path +import sys +import unittest +from unittest.mock import Mock, patch + +import requests + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) +import staging_replay as replay + + +class StagingReplayTests(unittest.TestCase): + def setUp(self): + get = self.enterContext(patch.object(replay.requests, "get")) + self.responses = [] + get.side_effect = self.responses + self.staging = Mock() + self.details = Mock(return_value={"date": "2026-11-17T07:17:22Z"}) + + def page(self, items): + self.responses.append(Mock(json=Mock(return_value=items))) + + def outputs(self): + return replay.replay_outputs( + "org/repository", "test-credential", self.staging, self.details + ) + + def test_no_eligible_closed_issue_skips_replay(self): + self.page([{"title": "ordinary PR", "pull_request": {}}]) + self.staging.filter_issue.return_value = False + self.assertEqual(self.outputs(), {"found": "false"}) + self.staging.parse_info.assert_not_called() + self.details.assert_not_called() + workflow = (ROOT / ".github/workflows/staging.yaml").read_text() + caller = workflow.split("\n run-workflow:\n", 1)[1] + self.assertIn("needs.get-patch-info.outputs.found == 'true'", caller) + + def test_eligible_history_preserves_identifiers_and_timestamps(self): + issue, comment = {"number": 2}, {"body": "apply report"} + self.page([issue]) + self.page([{}, comment, {}]) + self.staging.filter_issue.return_value = True + baseline, trunk = "a" * 40, "b" * 40 + self.staging.parse_info.return_value = ("149346", baseline, trunk) + self.assertEqual( + self.outputs(), + { + "found": "true", + "timestamp": "2026-11-17T07:17:22+00:00", + "baseline_hash": baseline, + "tot_hash": trunk, + "patch_id": "149346", + "issue_num": "2", + }, + ) + self.staging.parse_info.assert_called_once_with(issue, comment) + self.details.assert_called_once_with("149346") + + def test_api_error_fails_before_selection(self): + failed = Mock() + failed.raise_for_status.side_effect = requests.HTTPError("HTTP 403") + self.responses.append(failed) + with self.assertRaises(requests.HTTPError): + self.outputs() + self.staging.filter_issue.assert_not_called() + + def test_malformed_response_is_not_an_empty_sample(self): + self.page({}) + with self.assertRaisesRegex(ValueError, "Expected a list"): + self.outputs() + + def test_incomplete_issue_cannot_be_skipped_or_replayed(self): + self.page([{"number": 2}]) + self.page([]) + self.staging.filter_issue.return_value = True + with self.assertRaisesRegex(ValueError, "Missing staging metadata"): + self.outputs() + self.details.assert_not_called() + + def test_malformed_hash_cannot_be_forwarded_to_actions(self): + self.page([{"number": 2}]) + self.page([{}, {}, {}]) + self.staging.filter_issue.return_value = True + self.staging.parse_info.return_value = ("149346", "aaa\nfound=true", "b" * 40) + with self.assertRaisesRegex(ValueError, "Invalid staging metadata"): + self.outputs() + self.details.assert_not_called() diff --git a/tests/test_workflow_recovery.py b/tests/test_workflow_recovery.py index 07c83ae..d4269d6 100644 --- a/tests/test_workflow_recovery.py +++ b/tests/test_workflow_recovery.py @@ -3,13 +3,20 @@ import os import re import subprocess +import sys import tempfile import textwrap import unittest from pathlib import Path +from zipfile import ZipFile ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) +from collect_testsuite_report import collect +from patch_matrix import patch_targets + + WORKFLOWS = ROOT / ".github/workflows" DOWNLOAD_ACTION = ( ROOT / ".github/actions/common/download-comparison-artifacts/action.yaml" @@ -76,6 +83,41 @@ def hash_files(pattern): class WorkflowRecoveryTests(unittest.TestCase): + def test_reporting_can_be_bound_to_a_reviewed_dispatch(self): + sha = "1" * 40 + modes = ( + (sha, "Patchworks", "workflow_dispatch", sha, "true"), + (sha, "Patchworks", "workflow_dispatch", "2" * 40, "false"), + (sha, "Patchworks", "schedule", sha, "false"), + (sha, "Staging", "workflow_dispatch", sha, "false"), + ("true", "Patchworks", "schedule", sha, "true"), + ("false", "Patchworks", "workflow_dispatch", sha, "false"), + ) + for name in ( + "run-checks", + "lint", + "test-regression", + "generate-precommit-summary", + ): + workflow = (WORKFLOWS / (name + ".yaml")).read_text() + match = re.search( + r" PATCHWORK_REPORTING_ENABLED: >-\n((?: .+\n)+)", workflow + ) + self.assertIsNotNone(match) + expr = " ".join(match[1].split()) + for mode, source, event, commit, expected in modes: + with self.subTest(workflow=name, event=event, mode=mode): + result = evaluate( + expr, + { + "vars.PATCHWORK_REPORTING_ENABLED": mode, + "github.workflow": source, + "github.event_name": event, + "github.sha": commit, + }, + ) + self.assertEqual(result, expected) + def test_summary_requires_original_run_context(self): text = (WORKFLOWS / "generate-precommit-summary.yaml").read_text() trigger = text.split("\non:\n", 1)[1].split("\nenv:\n", 1)[0] @@ -103,17 +145,9 @@ def test_summary_requires_original_run_context(self): + re.escape("}}") + "$", ) - patches = [ - block - for name, block in step_blocks( - WORKFLOWS / "generate-precommit-summary.yaml" - ) - if name == "Download patches artifact" - ] - self.assertEqual(len(patches), 2) - for block in patches: - self.assertIn("uses: actions/download-artifact@v4", block) - self.assertNotIn("if:", block) + self.assertIn("patch_id: ${{ inputs.patch_id }}", caller) + self.assertIn(' -pid "$PATCH_ID"', text) + self.assertNotIn("debug-url.md", text) def test_manual_override_consumes_extracted_metadata(self): path = WORKFLOWS / "call-patchworks-api.yaml" @@ -181,62 +215,73 @@ def test_empty_patch_selection_skips_build_setup(self): text = (WORKFLOWS / workflow).read_text() setup = text.split("\n init-submodules:\n", 1)[1] expression = condition(setup) - output = "needs.fetch_patches.outputs.list_of_patch_names" + output = "needs.fetch_patches.outputs.patch_targets" self.assertFalse(evaluate(expression, {output: "[]"})) self.assertTrue(evaluate(expression, {output: '["one-patch"]'})) matrix = text.split("\n patch_matrix:\n", 1)[1] self.assertIn("init-submodules", re.search(r"needs: (.+)", matrix)[1]) - def test_available_report_skips_fallbacks_and_failure_marker(self): - report = "gcc-linux-rv64gcv-lp64d-fixture-multilib-report.log" - values = { - "inputs.report-artifact-name": report, - "steps.same-workflow-binary.outcome": "failure", - } + def test_only_selected_run_reports_enter_comparison(self): + name = "gcc-linux-rv64gcv-lp64d-" + "a" * 40 + "-multilib-report.log" + step = named_step(DOWNLOAD_ACTION, "Collect the expected report from this run") + self.assertIn("actions/runs/$GITHUB_RUN_ID/artifacts", step) + self.assertIn("failed_testsuite.txt", step) with tempfile.TemporaryDirectory() as directory: workspace = Path(directory) - path = workspace / "riscv-gnu-toolchain/current_logs" / report - path.parent.mkdir(parents=True) - path.write_text("Testsuite report\n") - for name in ( - "Download report from another workflow", - "Download rv32 non-multilib binary", - "Download binary from another workflow", - "Record missing testsuite report", - ): - with self.subTest(step=name): - self.assertFalse( - evaluate( - condition(named_step(DOWNLOAD_ACTION, name)), - values, - workspace, - ) - ) - path.unlink() - block = named_step(DOWNLOAD_ACTION, "Record missing testsuite report") - self.assertTrue(evaluate(condition(block), values, workspace)) - subprocess.run( - ["bash", "-e", "-c", shell_body(block)], - cwd=directory, - env=dict(os.environ, REPORT_ARTIFACT_NAME=report), - check=True, + archive = workspace / "report.zip" + output = workspace / "current_logs" + output.mkdir() + text = b"\t\t=== gcc: Unexpected fails for rv64gcv lp64d medlow ===\n\nSummary\n" + with ZipFile(archive, "w") as zipped: + zipped.writestr(name, text) + zipped.writestr("extra.log", "Unrelated file") + collect(archive, name, output) + self.assertEqual([p.name for p in output.iterdir()], [name]) + self.assertEqual((output / name).read_bytes(), text) + with ZipFile(archive, "w") as zipped: + zipped.writestr(name, b"incomplete without the summary separator") + with self.assertRaises(ValueError): + collect(archive, name, output) + self.assertFalse((output / name).with_suffix(".partial").exists()) + + def test_discovery_preserves_patch_ids_for_reporting(self): + with tempfile.TemporaryDirectory() as directory: + metadata = Path(directory) + name = "69792-v2_RISCV_changes-1" + path = metadata / name + path.write_text("Patch and series metadata\n149346") + self.assertEqual(patch_targets([], metadata), []) + self.assertEqual( + patch_targets([name], metadata), + [{"patch_name": name, "patch_id": "149346"}], ) - marker = path.parent / "failed_testsuite.txt" - self.assertIn(report + "|Testsuite report artifact", marker.read_text()) + path.write_text("Patch and series metadata\ninvalid") + with self.assertRaises(ValueError): + patch_targets([name], metadata) def test_publishing_errors_are_not_ignored(self): paths = list(WORKFLOWS.glob("*.yaml")) + list( (ROOT / ".github/actions").rglob("action.yaml") ) - publishing_steps = 0 + publishing_files = set() for path in paths: for name, block in step_blocks(path): if "scripts/post_check_to_patchworks.py" not in block: continue - publishing_steps += 1 + publishing_files.add(path.relative_to(ROOT).as_posix()) with self.subTest(path=path.name, step=name): self.assertNotIn("continue-on-error: true", block) - self.assertGreater(publishing_steps, 15) + self.assertEqual( + publishing_files, + { + ".github/actions/report-build-complete-status/action.yaml", + ".github/workflows/call-patchworks-api.yaml", + ".github/workflows/generate-precommit-summary.yaml", + ".github/workflows/lint.yaml", + ".github/workflows/run-checks.yaml", + ".github/workflows/test-regression.yaml", + }, + ) def test_recovery_checkpoint_advances_only_completed_windows(self): text = (WORKFLOWS / "downtime-runner.yaml").read_text() @@ -245,7 +290,7 @@ def test_recovery_checkpoint_advances_only_completed_windows(self): base = { "needs.check_last_runner.result": "success", "needs.fetch_patches.result": "success", - "needs.fetch_patches.outputs.list_of_patch_names": "['fixture']", + "needs.fetch_patches.outputs.patch_targets": "['fixture']", "needs.init-submodules.result": "success", "needs.patch_matrix.result": "success", } @@ -253,7 +298,7 @@ def test_recovery_checkpoint_advances_only_completed_windows(self): empty = dict(base) empty.update( { - "needs.fetch_patches.outputs.list_of_patch_names": "[]", + "needs.fetch_patches.outputs.patch_targets": "[]", "needs.init-submodules.result": "skipped", "needs.patch_matrix.result": "skipped", }