diff --git a/.github/workflows/generate-summary.yaml b/.github/workflows/generate-summary.yaml index 7f74e239f..cfe8f6e8f 100644 --- a/.github/workflows/generate-summary.yaml +++ b/.github/workflows/generate-summary.yaml @@ -64,6 +64,7 @@ permissions: env: POSTCOMMIT_REPOSITORY: ${{ github.repository }} + TRUNK_STATUS: ${{ inputs.prefix == '' && inputs.issue_hash_prefix == 'Testsuite Status' && inputs.gcc_branch == 'master' }} jobs: check-early-exit: @@ -390,18 +391,37 @@ jobs: https://api.github.com/rate_limit - name: Aggregate information + env: + REPORT_SHA: ${{ inputs.gcchash }} + ISSUE_TITLE: ${{ inputs.issue_hash_prefix }} run: | unzip summaries.zip unzip current_logs.zip unzip previous_logs.zip python ./scripts/aggregate.py \ - -chash ${{ inputs.gcchash }} \ + -chash "$REPORT_SHA" \ -o temp_issue.md \ - -title "${{ inputs.issue_hash_prefix }}" + -title "$ISSUE_TITLE" cat temp_issue.md - tail -n+5 temp_issue.md > issue.md + sed '1,/^---$/d' temp_issue.md > issue.md cat issue.md + - name: Verify trunk regression candidates + if: env.TRUNK_STATUS == 'true' + env: + GH_TOKEN: ${{ github.token }} + REPORT_SHA: ${{ inputs.gcchash }} + run: python3 ../scripts/trunk_regressions.py --repo "$POSTCOMMIT_REPOSITORY" --sha "$REPORT_SHA" + + - name: Archive the complete trunk test report + if: env.TRUNK_STATUS == 'true' + continue-on-error: true + id: report-artifact + uses: actions/upload-artifact@v4 + with: + name: ${{ inputs.gcchash }}-trunk-test-report-${{ github.run_attempt }} + path: riscv-gnu-toolchain/issue.md + - name: Get labels id: issue-labels run: | @@ -435,10 +455,13 @@ jobs: https://api.github.com/rate_limit - name: Trim issue length # reduce the number of lines in final issue so github always creates issue + env: + REPORT_URL: ${{ steps.report-artifact.outputs.artifact-url }} run: | head -c 65000 issue.md > trimmed_issue.md if [ $(stat -c%s issue.md) -gt 65000 ]; then printf "\n\`\`\`\nIssue text has been trimmed. Please check the following Gist Link for the untrimmed issue.\n" >> trimmed_issue.md + if [[ -n "$REPORT_URL" ]]; then printf '\n[Complete test report](%s)\n' "$REPORT_URL" >> trimmed_issue.md; fi FILE_SIZE=$(stat -c%s "issue.md") ONE_MB_IN_BYTES=1048000 if [ "$FILE_SIZE" -gt "$ONE_MB_IN_BYTES" ]; then @@ -473,8 +496,8 @@ jobs: - name: Trim comment length # reduce the number of lines in final comment so github always create comment run: | - printf "## Important unresolved errors\n" > trimmed_comment.md - printf 'A list of all unresolved "internal compiler error", "Segmentation fault", "test for excess errors" failures present at this hash\n\n' >> trimmed_comment.md + printf "## Selected current test failures\n\n" > trimmed_comment.md + printf 'These include internal compiler errors, excess diagnostics and execution failures. On targets without a distinct baseline, these are first observations. See the issue body for the comparison.\n\n' >> trimmed_comment.md printf -- '---\n\n' >> trimmed_comment.md head -c 65000 unresolved_important_failures.md >> trimmed_comment.md if [ $(stat -c%s unresolved_important_failures.md) -gt 65000 ]; then @@ -783,12 +806,16 @@ jobs: - name: Initialize Bisection Hash id: bisection-hash + env: + GH_TOKEN: ${{ github.token }} + ISSUE_NUMBER: ${{ inputs.issue_num }} run: | sudo apt remove python3-pip wget https://bootstrap.pypa.io/get-pip.py sudo python3 get-pip.py pip install pygithub requests - export ORIG_GCCHASH=$(python ./scripts/scrape_issue_info.py -num ${{ inputs.issue_num }} -token ${{ secrets.GITHUB_TOKEN }}) + ORIG_GCCHASH=$(python ./scripts/scrape_issue_info.py -num "$ISSUE_NUMBER" -token "$GH_TOKEN") + [[ "$ORIG_GCCHASH" =~ ^[0-9a-f]{40}$ ]] echo $ORIG_GCCHASH echo "orig_gcchash=$ORIG_GCCHASH" >> "$GITHUB_OUTPUT" @@ -881,13 +908,35 @@ jobs: retention-days: 90 - name: Aggregate information + env: + REPORT_SHA: ${{ env.TRUNK_STATUS == 'true' && steps.bisection-hash.outputs.orig_gcchash || inputs.gcchash }} + ISSUE_TITLE: ${{ inputs.issue_hash_prefix }} run: | python ./scripts/aggregate.py \ - -chash ${{ inputs.gcchash }} \ + -chash "$REPORT_SHA" \ -o issue.md \ - -title "${{ inputs.issue_hash_prefix }}" + -title "$ISSUE_TITLE" cat issue.md + - name: Verify regenerated trunk regression candidates + if: env.TRUNK_STATUS == 'true' + env: + GH_TOKEN: ${{ github.token }} + REPORT_SHA: ${{ steps.bisection-hash.outputs.orig_gcchash }} + run: | + mv issue.md temp_issue.md + sed '1,/^---$/d' temp_issue.md > issue.md + python3 ../scripts/trunk_regressions.py --repo "$POSTCOMMIT_REPOSITORY" --sha "$REPORT_SHA" + + - name: Archive the regenerated trunk test report + if: env.TRUNK_STATUS == 'true' + continue-on-error: true + id: report-artifact + uses: actions/upload-artifact@v4 + with: + name: ${{ steps.bisection-hash.outputs.orig_gcchash }}-regenerated-trunk-test-report-${{ github.run_attempt }} + path: riscv-gnu-toolchain/issue.md + - name: Print API usage info run: | curl \ @@ -896,12 +945,46 @@ jobs: https://api.github.com/rate_limit - name: Trim issue length # reduce the number of lines in final issue so github always creates issue + env: + REPORT_URL: ${{ steps.report-artifact.outputs.artifact-url }} run: | head -c 65000 issue.md > trimmed_issue.md - if [ $(cat trimmed_issue.md | wc -l) -ne $(cat issue.md | wc -l) ]; then printf "\n\`\`\`\nIssue text has been trimmed. Please check logs for the untrimmed issue.\n" >> trimmed_issue.md; fi + if [ "$(stat -c%s issue.md)" -gt 65000 ]; then + printf "\n\`\`\`\nIssue text has been trimmed. See the run for the complete comparison.\n" >> trimmed_issue.md + if [[ -n "$REPORT_URL" ]]; then printf '\n[Complete test report](%s)\n' "$REPORT_URL" >> trimmed_issue.md; fi + fi run_id=${{ github.run_id }} && echo "Associated run is: ${{ github.server_url }}/${{ github.repository }}/actions/runs/$run_id" >> trimmed_issue.md cat trimmed_issue.md + # Trunk status titles may be shared by a production, staging or bisect + # issue. Update only the intended issue and preserve unrelated labels. + - name: Update regenerated trunk issue + if: env.TRUNK_STATUS == 'true' && (github.workflow != 'Staging' || inputs.gcchash == steps.bisection-hash.outputs.orig_gcchash) + uses: actions/github-script@v7 + env: + REPORT_SHA: ${{ steps.bisection-hash.outputs.orig_gcchash }} + ORIGINAL_ISSUE_NUMBER: ${{ inputs.issue_num }} + STAGING_ISSUE_NUMBER: ${{ needs.generate-issues.outputs.new_issue_num }} + with: + script: | + const fs = require('fs'); + const issueNumber = context.workflow === 'Staging' ? process.env.STAGING_ISSUE_NUMBER : process.env.ORIGINAL_ISSUE_NUMBER; + const params = { ...context.repo, issue_number: Number(issueNumber) }; + const {data: issue} = await github.rest.issues.get(params); + if (issue.pull_request || issue.title !== `Testsuite Status ${process.env.REPORT_SHA}`) { + throw new Error('Regenerated report does not match the selected trunk issue'); + } + const dir = 'riscv-gnu-toolchain'; + const body = fs.readFileSync(`${dir}/trimmed_issue.md`, 'utf8'); + const wanted = fs.readFileSync(`${dir}/labels.txt`, 'utf8').trim().split(',').filter(Boolean); + const managed = ['new-regressions', 'resolved-regressions', 'build-failure', 'testsuite-failure', 'invalid']; + if (wanted.some(label => ['build-failure', 'testsuite-failure', 'invalid'].includes(label))) { + managed.push('valid-baseline'); + } + const preserved = issue.labels.map(label => label.name).filter(name => !managed.includes(name)); + const labels = [...new Set([...preserved, ...wanted])]; + await github.rest.issues.update({...params, body, labels}); + # Leave this for now since peter-evans doesn't have a good way # of updating the original issue comment since all the create # an issue outputs is the issue number and not the issue comment @@ -909,6 +992,7 @@ jobs: # Therefore will need toquery for issue comment id and then use that # with peter-evans/create-or-update-comment. - name: Create or update summary issue + if: env.TRUNK_STATUS != 'true' uses: JasonEtco/create-an-issue@v2 id: create-issue env: diff --git a/.github/workflows/pre-pull-request.yaml b/.github/workflows/pre-pull-request.yaml index 58154e960..45b854df9 100644 --- a/.github/workflows/pre-pull-request.yaml +++ b/.github/workflows/pre-pull-request.yaml @@ -32,5 +32,8 @@ jobs: run: | python -m unittest discover -s dashboard/tests -v + - name: Test trunk regression reporting + run: python -m unittest discover -s scripts -p 'test_trunk*.py' -v + - name: Run pre-commit uses: pre-commit/action@v3.0.1 diff --git a/docs/postcommit-maintenance-runbook.md b/docs/postcommit-maintenance-runbook.md index f20b5f605..55bb0821f 100644 --- a/docs/postcommit-maintenance-runbook.md +++ b/docs/postcommit-maintenance-runbook.md @@ -9,14 +9,29 @@ they do not replace maintainer investigation or upstream bug reporting. Start with the open [`new-regressions` queue](https://github.com/riseproject-dev/gcc-postcommit-ci/issues?q=is%3Aissue+is%3Aopen+label%3Anew-regressions), then review open issues labelled `build-failure`, `testsuite-failure`, or -`resolved-regressions`. If there are no new failures, no triage action is -required. +`resolved-regressions`. Check the latest trunk report's **Results needing +review** section for new tests and gaps in baseline evidence. Each `Testsuite Status ` issue must link to its Actions run. Use the run's `*-current-logs`, `*-previous-logs`, report, summary, and build-log artifacts when reproducing a result. Artifacts are retained for a limited time, so preserve the relevant excerpt in the upstream bug before it expires. +For trunk, `new-regressions` means that at least one newly observed testsuite +failure has a matching prior PASS in the original DejaGnu summaries. The issue +links the two artifacts and lists the language, board configuration, compiler +options and subtest. The comparison uses each target's own prior GCC revision. +A timeout counts as an observed PASS → FAIL transition when the evidence +matches. Reproducing it helps distinguish a compiler defect from runner or +simulator variability. + +Use the unresolved table to track failures already present in the baseline. +First observations, unexpected passes, and candidates with missing or ambiguous +artifacts remain visible for review. Missing builds and testsuite results have +their own labels and can coexist with verified regressions on another target. +The per-revision status issues continue to serve as the dashboard history and +as baseline records for pre-commit. + ## New Regression Triage 1. Re-run or reproduce the failure on current GCC trunk. Do not report a bug diff --git a/scripts/test_trunk_regressions.py b/scripts/test_trunk_regressions.py new file mode 100644 index 000000000..a25f12db4 --- /dev/null +++ b/scripts/test_trunk_regressions.py @@ -0,0 +1,224 @@ +"""Test which observations justify the new-regressions label on trunk issues.""" + +from contextlib import contextmanager +from io import StringIO +from pathlib import Path +import tempfile +import unittest + +from trunk_regressions import separate_snapshot_rows, update_report +from trunk_sum_artifacts import EvidenceUnavailable + + +BASE = "a" * 40 +CURRENT = "b" * 40 +TARGET = "gcc-linux-rv64gc-lp64d" +GROUP = "rv64gc lp64d medlow" +BOARD = "riscv-sim/-march=rv64gc/-mabi=lp64d/-mcmodel=medlow" +CASE = "gcc.dg/atomic/c11-atomic-exec-4.c -O0 execution test" + + +def raw_sum(*results, board=BOARD, driver="gcc.dg/dg.exp", triple="riscv64-linux-gnu"): + return ( + f"Target is {triple}\nRunning target {board}\nRunning /work/gcc/testsuite/{driver} ...\n" + + "\n".join(results) + + "\n" + ) + + +class FixtureArtifact: + def __init__(self, path, tools): + self.url = f"https://example.org/{path.name}" + self.tools = tools + + def open_tool(self, tool): + if tool not in self.tools: + raise EvidenceUnavailable(f"missing {tool}.sum") + return StringIO(self.tools[tool]) + + +class TrunkRegressionTests(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + for name in ("current_logs", "previous_logs", "summaries"): + (self.root / name).mkdir() + self.sums = {} + + def pair(self, *candidates, before=None, after=None, target=TARGET): + def report(directory, revision): + path = ( + self.root / directory / f"{target}-{revision}-non-multilib-report.log" + ) + path.touch() + return path + + baseline = report("previous_logs", BASE) + current = report("current_logs", CURRENT) + self.sums[baseline] = {"gcc": before} if before is not None else {} + self.sums[current] = {"gcc": after} if after is not None else {} + summary = self.root / "summaries" / (current.stem + "-summary.md") + summary.write_text( + f"---\ntitle: {BASE}->{CURRENT}\n---\n" + + "# New Failures\n" + + (f"## {GROUP}\n### gcc failures\n" if candidates else "") + + "\n".join(candidates) + + "\n" + ) + return baseline, current, summary + + @contextmanager + def load(self, repo, path): + yield FixtureArtifact(path, self.sums[path]) + + def render(self, labels="new-regressions"): + label_file = self.root / "labels.txt" + issue = self.root / "issue.md" + label_file.write_text(labels) + issue.write_text("|New Failures|gcc|g++|gfortran|Previous Hash|\n") + update_report( + self.root, CURRENT, "riseproject-dev/gcc-postcommit-ci", self.load + ) + return set(filter(None, label_file.read_text().split(","))), issue.read_text() + + def test_known_failures_retain_usable_baseline(self): + previous, current, _ = self.pair() + self.sums.pop(previous) + self.sums.pop(current) + labels, _ = self.render("valid-baseline,new-regressions") + self.assertEqual(labels, {"valid-baseline"}) + + def test_self_comparison_is_a_snapshot(self): + header = "|Unresolved Failures|gcc|g++|gfortran|Previous Hash|\n" + old = f"|linux|3/1|0/0|0/0|[{BASE}](compare)|" + snapshot = f"|newlib|2/1|0/0|0/0|[{CURRENT}-no-baseline](compare)|" + body = header + "|---|---|---|---|---|\n" + old + "\n" + snapshot + "\n\nMore\n" + known, fresh = separate_snapshot_rows(body, CURRENT).split( + "|Current failures without a distinct baseline" + ) + self.assertIn(old, known) + self.assertNotIn("newlib", known) + self.assertIn("|newlib|2/1|0/0|0/0|\n\nMore", fresh) + + def test_timeout_has_paired_evidence_even_with_other_build_failures(self): + self.pair( + "FAIL: " + CASE, + before=raw_sum("PASS: " + CASE), + after=raw_sum(f"WARNING: {CASE} program timed out.", "FAIL: " + CASE), + ) + labels, issue = self.render("build-failure") + self.assertEqual(labels, {"new-regressions", "build-failure"}) + self.assertIn(CASE, issue) + self.assertIn(BASE[:12], issue) + self.assertIn(CURRENT[:12], issue) + self.assertIn("1 timed out", issue) + self.assertIn("Coverage is incomplete", issue) + self.assertIn("[baseline sums]", issue) + self.assertIn("[current sums]", issue) + + def test_unmatched_cases_and_non_pass_do_not_confirm_a_new_failure(self): + # Reordering the board options preserves the filtered group name but + # changes the raw board identity used to pair the two outcomes. + other_board = "riscv-sim/-mabi=lp64d/-march=rv64gc/-mcmodel=medlow" + baselines = { + "different option": raw_sum("PASS: " + CASE.replace("-O0", "-O2")), + "different subtest": raw_sum( + "PASS: " + CASE.replace("execution test", "compilation") + ), + "different board": raw_sum("PASS: " + CASE, board=other_board), + "different triple": raw_sum("PASS: " + CASE, triple="riscv64-unknown-elf"), + "different driver": raw_sum("PASS: " + CASE, driver="gcc.dg/other.exp"), + "already failing": raw_sum("FAIL: " + CASE), + "never ran": raw_sum("UNSUPPORTED: " + CASE), + } + for description, previous in baselines.items(): + with self.subTest(description): + self.pair( + "FAIL: " + CASE, before=previous, after=raw_sum("FAIL: " + CASE) + ) + labels, issue = self.render() + self.assertNotIn("new-regressions", labels) + self.assertIn(CASE, issue.partition("## Results needing review")[2]) + + def test_ambiguous_repeated_results_only_confirm_necessary_transitions(self): + fail = "FAIL: " + CASE + passed = "PASS: " + CASE + self.pair( + fail, + fail, + before=raw_sum(fail, passed, passed), + after=raw_sum(fail, fail, passed), + ) + labels, issue = self.render() + self.assertIn("new-regressions", labels) + self.assertIn("PASS → FAIL × 1", issue) + self.assertIn("FAIL × 1", issue.partition("## Results needing review")[2]) + + self.pair(fail, before=raw_sum(passed), after=raw_sum(passed, fail)) + labels, issue = self.render() + self.assertNotIn("new-regressions", labels) + self.assertIn(CASE, issue.partition("## Results needing review")[2]) + + def test_xpass_is_retained_for_review(self): + self.pair( + "XPASS: " + CASE, + before=raw_sum("XFAIL: " + CASE), + after=raw_sum("XPASS: " + CASE), + ) + labels, issue = self.render() + self.assertNotIn("new-regressions", labels) + self.assertIn("XPASS", issue.partition("## Results needing review")[2]) + + def test_comparison_requires_the_right_revisions_and_both_reports(self): + for problem in ( + "synthetic", + "same hash", + "wrong current", + "missing previous", + "missing summary", + ): + with self.subTest(problem): + previous, _, summary = self.pair( + "FAIL: " + CASE, + before=raw_sum("PASS: " + CASE), + after=raw_sum("FAIL: " + CASE), + ) + if problem == "missing previous": + previous.unlink() + elif problem == "missing summary": + summary.unlink() + else: + title = { + "synthetic": f"{CURRENT}-no-baseline->{CURRENT}", + "same hash": f"{CURRENT}->{CURRENT}", + "wrong current": f"{BASE}->{'c' * 40}", + }[problem] + summary.write_text( + summary.read_text().replace(f"{BASE}->{CURRENT}", title) + ) + labels, issue = self.render() + self.assertNotIn("new-regressions", labels) + self.assertIn("## Results needing review", issue) + + def test_missing_sum_leaves_other_verified_observations_visible(self): + self.pair( + "FAIL: " + CASE, + before=raw_sum("PASS: " + CASE), + after=raw_sum("FAIL: " + CASE), + ) + self.pair( + "FAIL: " + CASE, + after=raw_sum("FAIL: " + CASE), + target="gcc-newlib-rv64gc-lp64d", + ) + labels, issue = self.render() + self.assertIn("new-regressions", labels) + self.assertIn("PASS → FAIL × 1", issue) + self.assertIn( + "missing gcc.sum", issue.partition("## Results needing review")[2] + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/test_trunk_sum_artifacts.py b/scripts/test_trunk_sum_artifacts.py new file mode 100644 index 000000000..fc882a40e --- /dev/null +++ b/scripts/test_trunk_sum_artifacts.py @@ -0,0 +1,109 @@ +import io +import json +from pathlib import Path +from tempfile import TemporaryDirectory +import unittest +from unittest.mock import patch +from urllib.parse import parse_qs, urlsplit +from zipfile import ZipFile + +import trunk_sum_artifacts as artifacts + + +def bundle(members): + buffer = io.BytesIO() + with ZipFile(buffer, "w") as archive: + for name, contents in members.items(): + archive.writestr(name, contents) + return buffer.getvalue() + + +class TestSumArtifacts(unittest.TestCase): + def setUp(self): + directory = TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.report = Path(directory.name) / "gcc-target-revision-multilib-report.log" + self.report.write_bytes(b"chosen report\n") + self.sum_name = self.report.name.removesuffix("-report.log") + "-sum-files" + self.records = [] + self.archives = {} + self.add(1, 10, self.report.name, bundle({self.report.name: b"other run\n"})) + self.add( + 2, + 20, + self.report.name, + bundle({self.report.name: self.report.read_bytes()}), + ) + inner = bundle( + {"sum_files/gcc.sum": b"PASS: case\n", "sum_files/g++.sum": b"\xff"} + ) + self.add(3, 20, self.sum_name, bundle({self.sum_name + ".zip": inner})) + self.add(4, 10, self.sum_name, b"wrong run") + self.enterContext(patch.object(artifacts, "_api", side_effect=self.api)) + + def add(self, artifact_id, run_id, name, archive, expired=False): + self.records.append( + { + "name": name, + "id": artifact_id, + "workflow_run": {"id": run_id}, + "expired": expired, + } + ) + self.archives[artifact_id] = archive + + def api(self, args, output=None): + url = urlsplit(args[0]) + if output is not None: + output.write(self.archives[int(url.path.split("/")[-2])]) + return + name = parse_qs(url.query)["name"][0] + records = [r for r in self.records if r["name"] == name] + if "/runs/" in url.path: + run = int(url.path.split("/")[-2]) + records = [r for r in records if r["workflow_run"]["id"] == run] + return "\n".join(json.dumps(r) for r in records).encode() + + def test_matches_local_report_and_its_sibling_archive(self): + with artifacts.open_sum_artifact("owner/repo", self.report) as artifact: + self.assertEqual( + artifact.url, + "https://github.com/owner/repo/actions/runs/20/artifacts/3", + ) + for tool in ("g++", "gfortran"): + with self.assertRaises(artifacts.EvidenceUnavailable): + with artifact.open_tool(tool) as lines: + list(lines) + with artifact.open_tool("gcc") as lines: + self.assertEqual(list(lines), ["PASS: case\n"]) + + def test_ambiguous_identical_report_or_sums(self): + for name, source in ((self.report.name, 2), (self.sum_name, 3)): + with self.subTest(name=name): + self.add(5, 20, name, self.archives[source]) + with self.assertRaises(artifacts.EvidenceUnavailable): + with artifacts.open_sum_artifact("owner/repo", self.report): + pass + self.records.pop() + + def test_expired_sums_do_not_fall_back_to_other_run(self): + self.records[2]["expired"] = True + with self.assertRaisesRegex(artifacts.EvidenceUnavailable, "unexpired sum"): + with artifacts.open_sum_artifact("owner/repo", self.report): + pass + + def test_no_matching_content_or_malformed_metadata(self): + self.report.write_bytes(b"different") + with self.assertRaisesRegex( + artifacts.EvidenceUnavailable, "no unique workflow" + ): + with artifacts.open_sum_artifact("owner/repo", self.report): + pass + with patch.object(artifacts, "_api", return_value=b"broken"): + with self.assertRaisesRegex(artifacts.EvidenceUnavailable, "metadata"): + with artifacts.open_sum_artifact("owner/repo", self.report): + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/trunk_regressions.py b/scripts/trunk_regressions.py new file mode 100644 index 000000000..5dab6350a --- /dev/null +++ b/scripts/trunk_regressions.py @@ -0,0 +1,310 @@ +"""Verify newly observed trunk test failures against the paired DejaGnu sums.""" + +import argparse +import re +from collections import Counter, defaultdict +from html import escape +from pathlib import Path + +from trunk_sum_artifacts import EvidenceUnavailable, open_sum_artifact + + +HASH = r"[0-9a-f]{40}" +RESULTS = { + "PASS", + "FAIL", + "XPASS", + "XFAIL", + "ERROR", + "UNRESOLVED", + "UNTESTED", + "UNSUPPORTED", + "KFAIL", + "KPASS", +} + + +def board_description(board, multilib): + """Reproduce the description printed by testsuite-filter and compare_testsuite_log.""" + flags = {"-march": "", "-mabi": "", "-mcmodel": ""} + extra = [] + for part in board.split("/"): + option, _, value = part.partition("=") + if option in flags: + flags[option] = value.lower() + elif part != "riscv-sim": + extra.append(part) + parts = [*flags.values()] + if multilib: + parts.append("multilib") + return " ".join([*parts, " ".join(extra)]).strip() + + +def new_results(summary): + """Read the per-tool detail; the aggregate table loses individual options.""" + _, heading, details = summary.partition("\n# New Failures\n") + if not heading: + raise ValueError("missing New Failures section") + candidates = defaultdict(Counter) + group = tool = None + for line in details.splitlines(): + if line.startswith("## "): + group = line[3:].strip() + tool = None + elif line.startswith("### ") and line.endswith(" failures"): + tool = line[4 : -len(" failures")] + elif line.strip(): + status, sep, case = line.partition(": ") + if tool not in {"gcc", "g++", "gfortran"} or group is None or not sep: + raise ValueError("unrecognized test result in comparison") + candidates[tool][group, case, status] += 1 + return candidates + + +def read_outcomes(lines, candidates, multilib): + """Keep only requested tests, preserving their raw board and .exp driver.""" + wanted = {(group, case) for group, case, _ in candidates} + outcomes = defaultdict(lambda: defaultdict(Counter)) + timeouts = Counter() + triple = board = group = driver = warning = None + for line in lines: + line = line.rstrip("\r\n") + if line.startswith("Test run by "): + triple = board = group = driver = None + elif line.startswith("Target is "): + triple = line.removeprefix("Target is ").strip() + elif line.startswith("Running target "): + board = line.removeprefix("Running target ").strip() + group = board_description(board, multilib) + driver = None + elif line.startswith("Running "): + # Worker paths differ between GitHub and the Hetzner runners. + match = re.search(r"/testsuite/(.+\.exp) \.\.\.$", line) + driver = match[1] if match else None + elif driver and board: + status, sep, case = line.partition(": ") + key = (group, case) + if sep and status in RESULTS and key in wanted: + scope = (triple, board, driver) + outcomes[key][scope][status] += 1 + if ( + status == "FAIL" + and warning == f"WARNING: {case} program timed out." + ): + timeouts[key, scope] += 1 + warning = line if line.startswith("WARNING: ") else None + return outcomes, timeouts + + +def transitions(before, after, timeouts, key): + confirmed = timed_out = 0 + for scope, counts in after.get(key, {}).items(): + previous = before.get(key, {}).get(scope, {}) + total = sum(previous.values()) + if not total or total != sum(counts.values()): + continue + # Repeated identical subtests have no execution ID. Count just the + # FAILs that cannot be accounted for by any previous non-PASS. + changed = max(0, counts["FAIL"] - (total - previous.get("PASS", 0))) + confirmed += changed + timed_out += max(0, changed - (counts["FAIL"] - timeouts[key, scope])) + return confirmed, timed_out + + +def comparison_note(before, after, key, status): + if status == "XPASS": + return "unexpected pass" + scopes = [scope for scope, counts in after.get(key, {}).items() if counts[status]] + if not scopes: + return "outcome missing from the current raw results" + matched = [before[key][scope] for scope in scopes if scope in before.get(key, {})] + if not matched: + return "no baseline result for the same board, test driver and subtest" + prior = sum(matched, Counter()) + return "matching baseline outcomes: " + ", ".join( + f"{result} × {count}" for result, count in sorted(prior.items()) + ) + + +def code(text): + return f"{escape(text)}" + + +def separate_snapshot_rows(body, sha): + """The shared comparator compares a first report with itself to seed history.""" + heading = "|Unresolved Failures|gcc|g++|gfortran|Previous Hash|\n" + head, marker, tail = body.partition(heading) + if not marker: + return body + table, blank, rest = tail.partition("\n\n") + if not table.startswith("|---|"): + return body + header, *rows = table.splitlines() + kept, snapshots = [], [] + for row in rows: + if f"|[{sha}-no-baseline](" in row or f"|[{sha}](" in row: + snapshots.append(row.rsplit("|", 2)[0] + "|") + else: + kept.append(row) + if not snapshots: + return body + return ( + head + + marker + + "\n".join( + [ + header, + *kept, + "", + "|Current failures without a distinct baseline|gcc|g++|gfortran|", + "|---|---|---|---|", + *snapshots, + ] + ) + + blank + + rest + ) + + +def verify_tool(tool, candidates, artifacts, multilib, confirmed, review): + try: + previous, current = artifacts + with previous.open_tool(tool) as lines: + before, _ = read_outcomes(lines, candidates, multilib) + with current.open_tool(tool) as lines: + after, timeouts = read_outcomes(lines, candidates, multilib) + except EvidenceUnavailable as err: + review.append(f"- {tool}: {escape(str(err))}. See the observed results below.") + return + for (group, case, status), observed in candidates.items(): + key = (group, case) + count, timed_out = ( + transitions(before, after, timeouts, key) if status == "FAIL" else (0, 0) + ) + verified = min(count, observed) + name = f"{code(tool)} {code(group)} {code(case)}" + if verified: + timeout = f" ({min(verified, timed_out)} timed out)" if timed_out else "" + confirmed.append(f"- PASS → FAIL × {verified}{timeout}: {name}") + if verified < observed: + note = comparison_note(before, after, key, status) + review.append( + f"- {escape(status)} × {observed - verified}: {name} ({note})" + ) + + +def verify_report(root, current, sha, repo, load): + summary = root / "summaries" / (current.stem + "-summary.md") + if not summary.is_file(): + raise ValueError("comparison summary unavailable") + text = summary.read_text() + pair = re.search(rf"^title: ({HASH})->({HASH})$", text, re.MULTILINE) + if not pair or pair[2] != sha or pair[1] == sha: + raise ValueError("no distinct baseline in the comparison summary") + previous = root / "previous_logs" / current.name.replace(f"-{sha}-", f"-{pair[1]}-") + if not previous.is_file(): + raise ValueError("matching previous filtered report unavailable") + candidates = new_results(text) + if not candidates: + return [], [] + target = current.name.removesuffix("-report.log").replace(f"-{sha}-", "-") + heading = f"**{code(target)}** · {code(pair[1][:12])} → {code(sha[:12])}" + verified, review = [], [] + try: + with load(repo, previous) as old, load(repo, current) as new: + heading += f" · [baseline sums]({old.url}) · [current sums]({new.url})" + for tool, cases in candidates.items(): + verify_tool( + tool, + cases, + (old, new), + "-non-multilib-" not in current.name, + verified, + review, + ) + except EvidenceUnavailable as err: + review.append(f"- {escape(str(err))}. See the observed results below.") + return ( + [heading, "", *verified, ""] if verified else [], + [heading, "", *review, ""] if review else [], + ) + + +def update_report(root, sha, repo, load=open_sum_artifact): + if not re.fullmatch(HASH, sha): + raise ValueError("invalid GCC revision") + verified, review = [], [] + paired = 0 + for current in sorted((root / "current_logs").glob("*-report.log")): + try: + if f"-{sha}-" not in current.name: + raise ValueError("current report has a different revision") + confirmed, pending = verify_report(root, current, sha, repo, load) + except ValueError as err: + review.append(f"- {code(current.name)}: {escape(str(err))}.") + continue + paired += 1 + verified.extend(confirmed) + review.extend(pending) + + labels_file = root / "labels.txt" + labels = set(filter(None, labels_file.read_text().strip().split(","))) + labels.discard("new-regressions") + if verified: + labels.add("new-regressions") + + lines = [ + "## Verified test regressions", + "", + f"Target reports compared with a distinct baseline: {paired}.", + ] + if {"invalid", "build-failure", "testsuite-failure"} & labels: + lines.append( + "Coverage is incomplete. See the build, testsuite and comparison details below." + ) + lines.extend( + [ + "", + *( + verified + or [ + "No PASS → FAIL transition was confirmed in the available comparisons." + ] + ), + ] + ) + if review: + lines.extend( + [ + "", + "## Results needing review", + "", + "A comparable prior PASS could not be established for these observations.", + "", + *review, + ] + ) + + body_file = root / "issue.md" + body = separate_snapshot_rows(body_file.read_text(), sha) + # The shared comparator lists differences between filtered reports, + # including results for newly introduced tests and configurations. + body = body.replace("|New Failures|gcc|", "|Newly observed results|gcc|") + body = body.replace( + "\n## New Failures Across All Affected Targets", + "\n## Newly observed results across affected targets", + ) + body = body.replace( + "\n## Architecture Specific New Failures", + "\n## Newly observed results by architecture", + ) + body_file.write_text("\n".join(lines).rstrip() + "\n\n" + body.lstrip()) + labels_file.write_text(",".join(sorted(labels))) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--repo", required=True) + parser.add_argument("--sha", required=True) + args = parser.parse_args() + update_report(Path.cwd(), args.sha, args.repo) diff --git a/scripts/trunk_sum_artifacts.py b/scripts/trunk_sum_artifacts.py new file mode 100644 index 000000000..bc6cc21d8 --- /dev/null +++ b/scripts/trunk_sum_artifacts.py @@ -0,0 +1,153 @@ +"""Find the original DejaGnu results for a locally selected trunk report.""" + +from contextlib import contextmanager +from dataclasses import dataclass +from io import TextIOWrapper +import json +from pathlib import Path +import re +import shutil +import subprocess +from tempfile import TemporaryFile +from time import sleep +from urllib.parse import urlencode +from zipfile import BadZipFile, ZipFile +import zlib + + +class EvidenceUnavailable(Exception): + """The selected report cannot be tied to readable raw test outcomes.""" + + +def _api(args, output=None): + for attempt in range(2): + try: + return subprocess.run( + ["gh", "api", *args], + stdout=output or subprocess.PIPE, + stderr=subprocess.PIPE, + check=True, + timeout=180, + ).stdout + except (OSError, subprocess.SubprocessError) as exc: + # gh stderr may contain a signed storage URL. Keep it out of issues. + message = getattr(exc, "stderr", None) or b"" + transient = isinstance(exc, subprocess.TimeoutExpired) or re.search( + rb"timeout|timed out|deadline exceeded|EOF|connection reset|HTTP 5\d\d", + message, + re.IGNORECASE, + ) + if attempt or not transient: + raise EvidenceUnavailable( + "GitHub Actions artifact lookup or download failed" + ) from exc + if output is not None: + output.seek(0) + output.truncate() + sleep(1) + + +def _find_artifacts(endpoint, name): + query = urlencode({"name": name, "per_page": 100}) + lines = _api([f"{endpoint}?{query}", "--paginate", "--jq", ".artifacts[] | @json"]) + try: + found = [json.loads(line) for line in lines.splitlines()] + return [ + item for item in found if item["name"] == name and item["expired"] is False + ] + except (ValueError, KeyError, TypeError) as exc: + raise EvidenceUnavailable("malformed Actions artifact metadata") from exc + + +@contextmanager +def _download(repository, artifact_id): + with TemporaryFile() as archive: + _api( + [f"repos/{repository}/actions/artifacts/{artifact_id}/zip"], output=archive + ) + archive.seek(0) + with ZipFile(archive) as bundle: + yield bundle + + +def _member(archive, name): + matches = [member for member in archive.infolist() if member.filename == name] + if len(matches) != 1: + raise EvidenceUnavailable(f"archive has no unique {name}") + return matches[0] + + +@dataclass +class SumArtifact: + url: str + archive: ZipFile + + @contextmanager + def open_tool(self, tool): + """Yield decoded .sum lines for the given DejaGnu tool (e.g. 'g++').""" + member = _member(self.archive, f"sum_files/{tool}.sum") + try: + with self.archive.open(member) as raw, TextIOWrapper( + raw, encoding="utf-8" + ) as lines: + yield lines + except ( + UnicodeError, + BadZipFile, + RuntimeError, + EOFError, + OSError, + zlib.error, + ) as exc: + raise EvidenceUnavailable(f"unreadable {tool}.sum") from exc + + +@contextmanager +def open_sum_artifact(repository, report_path): + """Open the raw results uploaded by the run that produced this exact report. + + The workflow can reuse reports from other runs. The GCC hash alone cannot + distinguish reruns. Require a byte match with the downloaded report and + retrieve its sibling sum archive from that run. + """ + report_path = Path(report_path) + name = report_path.name + if not name.endswith("-report.log"): + raise EvidenceUnavailable("expected a testsuite report filename") + actions = f"repos/{repository}/actions" + sum_name = name.removesuffix("-report.log") + "-sum-files" + try: + contents = report_path.read_bytes() + matches = [] + for report in _find_artifacts(f"{actions}/artifacts", name): + with _download(repository, report["id"]) as bundle: + if bundle.read(_member(bundle, name)) == contents: + matches.append(report["workflow_run"]["id"]) + if len(matches) != 1: + raise EvidenceUnavailable( + "no unique workflow run matches the filtered report" + ) + run_id = matches[0] + sums = _find_artifacts(f"{actions}/runs/{run_id}/artifacts", sum_name) + if len(sums) != 1: + raise EvidenceUnavailable( + f"run {run_id} has no unique unexpired sum archive" + ) + artifact_id = sums[0]["id"] + url = f"https://github.com/{repository}/actions/runs/{run_id}/artifacts/{artifact_id}" + with _download(repository, artifact_id) as outer, TemporaryFile() as inner: + with outer.open(_member(outer, sum_name + ".zip")) as packed: + shutil.copyfileobj(packed, inner) + inner.seek(0) + with ZipFile(inner) as archive: + yield SumArtifact(url, archive) + except ( + KeyError, + TypeError, + BadZipFile, + RuntimeError, + EOFError, + OSError, + zlib.error, + ) as exc: + raise EvidenceUnavailable(f"cannot read the artifacts for {name}") from exc