diff --git a/docs/testing.md b/docs/testing.md index 635c700a65..f09fbc550e 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -150,10 +150,19 @@ python -I scripts/red_green.py target dir takes several GB; delete the folder (and run `git worktree prune`) when done. - It prints the tests that go from red to green, those that pass on red and fail on green, those that fail on both (failing on `main` too), and those found on one side only. The verdict is one of: `red then green` (exit 0), - `no red`, `red does not build`, `green fails`, `red not constructible`, `green not constructible`, `no tests ran` - (exit 1). `--json` prints all of it. + `no red`, `red does not build`, `green fails`, `red not constructible`, `green not constructible`, `no tests ran`, + `compiler crashed` (exit 1). `--json` prints all of it. +- A crashed compiler is not a build error: rustc or a build script ending with a Windows crash status (such as + 0xC0000005, an access violation), an internal compiler error, or a failed allocation. That side builds again once, + and the report says so; a second crash gives `compiler crashed`. Run it again later, or on another machine. - `red does not build` is the case the fork-CI steps above call "does not build without the pull request's new file": the test needs the new code, which does not show that it catches the bug. +- `--mutate` also checks that the tests catch the change itself, what verifiers do by hand by removing a line of the + fix. After the green side, it undoes each hunk of the pull request's code alone (Rust and Python files it changes, + outside the tests and `#[cfg(test)]` code) and runs the tests again. A hunk is `caught` when a test that went red + then green fails, `not caught` when they all still pass, `does not build`, or `does not apply` (`main` moved those + lines since). It tries at most `--mutate-max` hunks (10). A `not caught` hunk is code no new test looks at; it + does not change the verdict. - `--crate ` adds a crate, `--no-cargo` or `--no-python` leaves one kind out, `--base ` tests on another base, and `--no-fetch` uses the refs as they are. diff --git a/scripts/red_green.py b/scripts/red_green.py index 1af2fd1677..57dd8de6a7 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -20,7 +20,8 @@ toolchain applies) and the changed `tests/**/test*.py` files with unittest, on both sides, in one worktree and one cargo target dir under --work-dir (default `/red-green`), red first. It keeps both between runs: the second run on the same crates builds only what changed. C++ `runtime/` tests are not run here (docs/testing.md has -the fork-CI way). +the fork-CI way). A side whose compiler crashed (a Windows crash status of rustc or a build script, an internal +compiler error, a failed allocation) builds again once; a second crash is the verdict `compiler crashed`. Exit 0: at least one test went from red to green and no test that passes on red fails on green. 1: any other verdict. 2: a usage or git error. @@ -34,6 +35,7 @@ import subprocess import sys import tempfile +from collections import Counter from pathlib import Path IDENTITY = { @@ -272,7 +274,16 @@ def crates_of(tree: Path, paths: list[str]) -> list[str]: return names -def cargo_tests(tree: Path, crates: list[str], cargo: str, target: Path) -> dict: +# A crashed compiler, not an error in the code: rustc or a build script ending with a Windows crash status +# (0xC0000005 access violation, 0xC00000FD stack overflow, 0xC0000409 abort, ...), an internal compiler error, or a +# failed allocation. Such a side runs again once (a crash of a test binary stays a test result). +COMPILER_CRASH = re.compile( + r"process didn't exit successfully: `[^`]*(?:rustc|build-script-\w+)[^`]*` \(exit (?:code|status): " + r"(0x[cC][0-9a-fA-F]{7}(?:, \w+)?)\)" + r"|(internal compiler error)|(the compiler unexpectedly panicked)|(memory allocation of \d+ bytes failed)") + + +def cargo_once(tree: Path, crates: list[str], cargo: str, target: Path) -> dict: cmd = [sys.executable, cargo] if cargo.endswith(".py") else [cargo] cmd += ["test", "--locked", "--no-fail-fast"] + [a for c in crates for a in ("-p", c)] env = dict(os.environ, CARGO_TARGET_DIR=str(target)) @@ -290,7 +301,21 @@ def cargo_tests(tree: Path, crates: list[str], cargo: str, target: Path) -> dict elif error is None and CARGO_ERROR.match(line): error = line.strip() no_build = r.returncode != 0 and not tests - return {"tests": tests, "no_build": (error or f"cargo exit {r.returncode}") if no_build else None} + crash = COMPILER_CRASH.search(out) if no_build else None + return {"tests": tests, "no_build": (error or f"cargo exit {r.returncode}") if no_build and not crash else None, + "crash": next(g for g in crash.groups() if g) if crash else None} + + +def cargo_tests(tree: Path, crates: list[str], cargo: str, target: Path) -> dict: + first = cargo_once(tree, crates, cargo, target) + if not first["crash"]: + return {"tests": first["tests"], "no_build": first["no_build"]} + print(f"red_green: the compiler crashed ({first['crash']}), running again", file=sys.stderr) + again = cargo_once(tree, crates, cargo, target) + result = {"tests": again["tests"], "no_build": again["no_build"], "rerun_after": first["crash"]} + if again["crash"]: + result["compiler_crashed"] = again["crash"] + return result PY_TEST = re.compile(r"^(\w+) \(([\w.]+)\)(?:\n[^\n]*?)? \.\.\. (ok|FAIL|ERROR|skipped|expected failure|unexpected success)", @@ -301,7 +326,9 @@ def python_tests(tree: Path, files: list[str]) -> dict: tests, no_build = {}, [] for f in files: start = "tests/semantic" if f.startswith("tests/semantic/") else str(Path(f).parent) - r = subprocess.run([sys.executable, "-I", "-m", "unittest", "discover", "-s", start, "-p", Path(f).name, "-v"], + # -B: no bytecode. An undone change of the same size within the same second would run the stale .pyc. + r = subprocess.run([sys.executable, "-I", "-B", "-m", "unittest", "discover", "-s", start, "-p", Path(f).name, + "-v"], cwd=tree, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = r.stdout.decode("utf-8", "replace") found = 0 @@ -318,12 +345,14 @@ def python_tests(tree: Path, files: list[str]) -> dict: def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target: Path) -> dict: - result = {"tests": {}, "no_build": []} + result = {"tests": {}, "no_build": [], "compiler_crashed": None, "rerun_after": None} for part in ([cargo_tests(tree, crates, cargo, target)] if crates else []) + \ ([python_tests(tree, py_files)] if py_files else []): result["tests"].update(part["tests"]) if part["no_build"]: result["no_build"].append(part["no_build"]) + for key in ("compiler_crashed", "rerun_after"): + result[key] = result[key] or part.get(key) return result @@ -355,6 +384,9 @@ def compare(red: dict | None, green: dict | None) -> dict: def verdict(red_why: str | None, green_why: str | None, red: dict | None, green: dict | None, rows: dict) -> str: if green_why: return "green not constructible" + # Twice in a row on a side: the build cannot tell anything; not a code error, run it again later. + if any(s and s.get("compiler_crashed") for s in (red, green)): + return "compiler crashed" green_failed = rows["regressions"] or any(r.endswith("(failed)") for r in rows["only_on_green"]) if green and green["no_build"] or green_failed: return "green fails" @@ -379,6 +411,10 @@ def report(r: dict) -> str: s = r[name] if s and s["no_build"]: out.append(f"{name} does not build: " + "; ".join(s["no_build"])) + if s and s.get("compiler_crashed"): + out.append(f"{name}: the compiler crashed twice ({s['compiler_crashed']})") + elif s and s.get("rerun_after"): + out.append(f"{name}: the compiler crashed once ({s['rerun_after']}), the second build is the one shown") rows = r["rows"] labels = {"red_to_green": "red then green", "regressions": "pass on red, FAIL on green", "fail_on_both": "fail on both (failing on the base too?)", "only_on_green": "only on green", @@ -390,6 +426,12 @@ def report(r: dict) -> str: if len(rows[key]) > 40: out.append(f" ... {len(rows[key]) - 40} more") out.append(f"pass on both: {rows['pass_on_both']}") + if r.get("mutations") is not None: + counts = Counter(m["result"] for m in r["mutations"]) + out.append(f"mutations ({len(r['mutations'])} hunks undone one at a time): " + + ", ".join(f"{n} {k}" for k, n in sorted(counts.items())) if r["mutations"] else + "mutations: no code hunk outside the tests") + out += [f" {m['file']}:{m['line']}: {m['result']}" for m in r["mutations"]] out.append(f"verdict: {r['verdict']}") return "\n".join(out) @@ -406,6 +448,9 @@ def main(argv: list[str] | None = None) -> int: p.add_argument("--no-python", action="store_true", help="skip the Python tests") p.add_argument("--cargo", default="cargo", help="the cargo to run (a .py file runs with this Python)") p.add_argument("--json", action="store_true", help="print the result as JSON") + p.add_argument("--mutate", action="store_true", + help="undo each code hunk alone on green and run the tests again (caught or not)") + p.add_argument("--mutate-max", type=int, default=10, help="the most hunks --mutate tries (10)") a = p.parse_args(argv) try: repo = Path(git(Path.cwd(), "rev-parse", "--show-toplevel")) @@ -470,15 +515,87 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer else: print("red_green: green side...", file=sys.stderr) green = side(tree, crates, [f for f in py_files if (tree / f).is_file()], a.cargo, target) + rows = compare(red, green) + mutations = None + if a.mutate and green is not None: + targets = list(rows["red_to_green"]) + if targets: + print("red_green: mutations...", file=sys.stderr) + mutations = mutate(repo, tree, merge_base, head, targets, crates, py_files, a.cargo, target, a.mutate_max) + if mutations is None: + checkout(repo, tree, base_commit) + git(tree, "merge", "--no-commit", "--no-ff", head, env=env, check=False) checkout(repo, tree, base_commit) - rows = compare(red, green) return {"base": base, "base_commit": base_commit, "head": a.pr, "head_commit": head, "merge_base": merge_base, "red_files": red_files, "red_why": red_why, "green_why": green_why, "crates": crates, - "python_files": py_files, "red": red, "green": green, "rows": rows, + "python_files": py_files, "red": red, "green": green, "rows": rows, "mutations": mutations, "verdict": verdict(red_why, green_why, red, green, rows)} +def code_hunks(repo: Path, merge_base: str, head: str) -> list[tuple[str, int, str]]: + """(file, first changed line in the pull request, patch) for each hunk of its code outside its tests: the hunks + a mutation undoes one at a time. Without context, so that a test changed next to the code is a hunk of its own (a + hunk does not apply where `main` moved the lines since).""" + out = [] + for path in git(repo, "diff", "--name-only", "--no-renames", "--diff-filter=M", merge_base, head).splitlines(): + if is_test_file(path) or not (path.endswith(".rs") or (path.endswith(".py") and not path.startswith("tests/"))): + continue + lines = git(repo, "diff", "-U0", "--no-color", "--no-ext-diff", merge_base, head, "--", path).split("\n") + first = next((i for i, line in enumerate(lines) if line.startswith("@@")), None) + if first is None: + continue + header = "\n".join(lines[:first]) + hunks: list[list[str]] = [] + for line in lines[first:]: + if line.startswith("@@"): + hunks.append([line]) + else: + hunks[-1].append(line) + tests_new = test_lines(blob(repo, head, path) or b"") if path.endswith(".rs") else set() + for hunk in hunks: + m = HUNK.match(hunk[0]) + if not m: + continue + at, added = int(m.group(3)) - 1, [] # 0-based line of the pull request's side + for line in hunk[1:]: + if line.startswith("+"): + added.append(at) + at += 1 + elif line.startswith(" "): + at += 1 + # A hunk that only adds test code is the tests' own, not the fix. + if added and all(i in tests_new for i in added): + continue + out.append((path, int(m.group(3)), header + "\n" + "\n".join(hunk).rstrip("\n") + "\n")) + return out + + +def mutate(repo: Path, tree: Path, merge_base: str, head: str, targets: list[str], crates: list[str], + py_files: list[str], cargo: str, target: Path, most: int) -> list[dict] | None: + """Undoes each code hunk alone on the green tree and runs the tests again: a hunk is caught when one of the tests + that went red then green fails. Returns None when the tree could not be put back (the caller rebuilds it).""" + results = [] + for path, line, patch in code_hunks(repo, merge_base, head)[:most]: + entry = {"file": path, "line": line, "result": None} + undo = run(["git", "apply", "-R", "--unidiff-zero", "-"], tree, data=patch.encode()) + if undo.returncode != 0: + entry["result"] = "does not apply" + results.append(entry) + continue + s = side(tree, crates, [f for f in py_files if (tree / f).is_file()], cargo, target) + if s.get("compiler_crashed"): + entry["result"] = "compiler crashed" + elif not any(t in s["tests"] for t in targets): + entry["result"] = "does not build" + else: + entry["result"] = "caught" if any(s["tests"].get(t) == "failed" for t in targets) else "not caught" + results.append(entry) + if run(["git", "apply", "--unidiff-zero", "-"], tree, data=patch.encode()).returncode != 0: + return None + return results + + if __name__ == "__main__": try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode sys.stdout.reconfigure(errors="replace") diff --git a/tests/test_red_green.py b/tests/test_red_green.py index 4d20e5c902..be4a60c2ed 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -47,7 +47,32 @@ ''' +# A cargo whose rustc crashes like an access violation on Windows: always, or on its first call only (a marker file +# beside it), then the stub above. +CRASH_STUB = r''' +import os, runpy, sys +here = os.path.dirname(os.path.abspath(__file__)) +mark = os.path.join(here, "crashed") +if __MODE__ == "always" or not os.path.exists(mark): + open(mark, "w").close() + print(" Compiling foo v0.1.0") + print("error: could not compile `foo` (lib test)") + print("") + print("Caused by:") + print(" process didn't exit successfully: `rustc --crate-name foo --edition=2021 src/lib.rs --test` " + "(exit code: 0xc0000005, STATUS_ACCESS_VIOLATION)") + sys.exit(101) +runpy.run_path(os.path.join(here, "cargo_stub.py"), run_name="__main__") +''' + + class Repo: + def crash_stub(self, mode): + path = os.path.join(self.tmp.name, f"cargo_crash_{mode}.py") + with open(path, "w", encoding="utf-8") as f: + f.write(CRASH_STUB.replace("__MODE__", repr(mode))) + return path + def __init__(self, test): self.tmp = tempfile.TemporaryDirectory(prefix="red-green-test-", ignore_cleanup_errors=True) test.addCleanup(self.tmp.cleanup) @@ -211,6 +236,92 @@ def test_a_test_of_a_new_tool_does_not_import_on_red(self): self.assertEqual(code, 1) +class Mutation(unittest.TestCase): + # Two code changes far enough apart to be two hunks: the tested one and one no test looks at. + BASE = ("pub fn value() -> u32 {\n 1\n}\n\n" + "".join(f"// padding line {i}\n" for i in range(10)) + + "\npub fn spare() -> u32 {\n 5\n}\n" + LIB[LIB.index("\n#[cfg(test)]"):]) + + def test_each_code_hunk_undone_alone_is_caught_or_not(self): + repo = Repo(self) + repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n', + "d3d12/crates/foo/src/lib.rs": self.BASE}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"d3d12/crates/foo/src/lib.rs": self.BASE.replace(" 1\n", " 2\n").replace( + " 5\n", " 6\n").replace("fn value_is_one() {\n assert_eq!(super::value(), 1);", + "fn value_is_two() {\n assert_eq!(super::value(), 2);")}) + code, r, _ = repo.run("--mutate") + self.assertEqual((code, r["verdict"]), (0, "red then green"), r) + self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (17, "not caught")]) + text = rg.report(r) + self.assertIn("mutations (2 hunks undone one at a time): 1 caught, 1 not caught", text) + self.assertIn("d3d12/crates/foo/src/lib.rs:17: not caught", text) + # The worktree is back on the base afterwards: the mutations left nothing behind. + tree = os.path.join(repo.dir, ".git", "red-green", "tree") + status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout + self.assertEqual(status, "") + + def test_a_python_fix_undone_is_caught(self): + repo = Repo(self) + repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": Python.TEST}) + code, r, _ = repo.run("--no-cargo", "--mutate") + self.assertEqual(r["verdict"], "red then green", r) + self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], [("tools/bar.py", "caught")]) + + def test_no_mutation_without_the_option(self): + repo = Repo(self) + repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": Python.TEST}) + _code, r, _ = repo.run("--no-cargo") + self.assertIsNone(r["mutations"]) + + +class CompilerCrash(unittest.TestCase): + def fixed_repo(self): + repo = crate_repo(self) + repo.commit("fix", {"d3d12/crates/foo/src/lib.rs": LIB.replace(" 1\n", " 2\n").replace( + "fn value_is_one() {\n assert_eq!(super::value(), 1);", + "fn value_is_two() {\n assert_eq!(super::value(), 2);")}) + return repo + + def test_a_compiler_that_crashes_once_is_run_again(self): + repo = self.fixed_repo() + code, r, err = repo.run("--cargo", repo.crash_stub("once")) + self.assertEqual((code, r["verdict"]), (0, "red then green"), r) + self.assertEqual(r["red"]["rerun_after"], "0xc0000005, STATUS_ACCESS_VIOLATION") + self.assertIsNone(r["red"]["compiler_crashed"]) + self.assertIn("the compiler crashed (0xc0000005, STATUS_ACCESS_VIOLATION), running again", err) + + def test_a_compiler_that_crashes_twice_is_not_a_build_error(self): + repo = self.fixed_repo() + code, r, _ = repo.run("--cargo", repo.crash_stub("always")) + self.assertEqual((code, r["verdict"]), (1, "compiler crashed"), r) + self.assertEqual(r["red"]["compiler_crashed"], "0xc0000005, STATUS_ACCESS_VIOLATION") + self.assertEqual(r["red"]["no_build"], []) + self.assertIn("red: the compiler crashed twice", rg.report(r)) + + def test_what_counts_as_a_crashed_compiler(self): + crashed = [ + " process didn't exit successfully: `C:\\x\\rustc.exe --crate-name a` (exit code: 0xc00000fd, STATUS_STACK_OVERFLOW)", + " process didn't exit successfully: `C:\\t\\build\\a-1\\build-script-build` (exit code: 0xc0000409)", + "error: internal compiler error: compiler/rustc_middle/src/ty/mod.rs:1: oops", + "note: the compiler unexpectedly panicked. this is a bug.", + "memory allocation of 1048576 bytes failed", + ] + for line in crashed: + self.assertIsNotNone(rg.COMPILER_CRASH.search(line), line) + not_crashed = [ + # A test binary that crashes is a test result, and an ordinary failure is a build error. + " process didn't exit successfully: `C:\\t\\debug\\deps\\foo-0123456789abcdef.exe` (exit code: 0xc0000005, STATUS_ACCESS_VIOLATION)", + " process didn't exit successfully: `C:\\x\\rustc.exe --crate-name a` (exit code: 1)", + "error[E0425]: cannot find value `x` in this scope", + ] + for line in not_crashed: + self.assertIsNone(rg.COMPILER_CRASH.search(line), line) + + class Hunks(unittest.TestCase): def diff(self, old, new): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: