Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,19 @@ python -I scripts/red_green.py <pull request number>
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 <name>` adds a crate, `--no-cargo` or `--no-python` leaves one kind out, `--base <ref>` tests on another
base, and `--no-fetch` uses the refs as they are.

Expand Down
131 changes: 124 additions & 7 deletions scripts/red_green.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<git common dir>/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.
Expand All @@ -34,6 +35,7 @@
import subprocess
import sys
import tempfile
from collections import Counter
from pathlib import Path

IDENTITY = {
Expand Down Expand Up @@ -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))
Expand All @@ -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)",
Expand All @@ -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
Expand All @@ -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


Expand Down Expand Up @@ -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"
Expand All @@ -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",
Expand All @@ -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)

Expand All @@ -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"))
Expand Down Expand Up @@ -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")
Expand Down
Loading
Loading