Files
mandy/scripts/red_green.py
TheGeogeo fc0ce37ac4 scripts: red_green.py reports a cargo run stopped before any test ran as timed out building, not caught (review)
A mutated cargo run that times out before its first Running line was still a build: it says nothing about the tests, so it is no longer counted as caught by timeout. A stub cargo that hangs in its build or in a test binary now covers the cargo timeout path, which no test reached before.
2026-12-02 05:19:44 +01:00

752 lines
37 KiB
Python

#!/usr/bin/env python3
"""Checks a pull request red and green on this machine (docs/testing.md, "Red and green on your machine").
python -I scripts/red_green.py <pull request number | git ref> [--base REF] [--remote NAME] [--no-fetch]
[--work-dir DIR] [--crate NAME ...] [--no-cargo] [--no-python] [--cargo PATH] [--json]
[--mutate [--mutate-max N] [--mutate-timeout SECONDS]]
Green is the base (`<remote>/main` after a fetch, by default) with the pull request merged. Red is the base with
only the pull request's tests. A test that fails on red and passes on green shows that the change is what makes it
pass; a test that passes on both proves nothing about the change.
The red side comes from the pull request's diff against its merge base with the base:
- test files, whole: a file under a `tests` folder (`tests/**`, a crate's `tests/`, `src/tests/`), `*_tests.rs`,
`tests.rs`;
- in other Rust files, the hunks that change only `#[cfg(test)]` items (a `#[cfg(test)] mod x { ... }` block, a
`#[cfg(test)] mod x_tests;` line, a `#[cfg(test)]` function), blank lines and comments around them allowed.
That change is committed on the merge base, then cherry-picked onto the base. A conflict, or a pull request with no
test, is "red not constructible".
It runs `cargo test --no-fail-fast` for the D3D12 crates the pull request touches (from `d3d12/`, so the pinned
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). 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.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import shutil
import signal
import stat
import subprocess
import sys
import tempfile
from collections import Counter
from pathlib import Path
IDENTITY = {
"GIT_AUTHOR_NAME": "red_green", "GIT_AUTHOR_EMAIL": "red_green@localhost",
"GIT_COMMITTER_NAME": "red_green", "GIT_COMMITTER_EMAIL": "red_green@localhost",
}
class Failure(Exception):
"""A usage or git error: the command exits 2 with its message."""
def run(args: list[str], cwd: Path, env: dict | None = None, data: bytes | None = None) -> subprocess.CompletedProcess:
return subprocess.run(args, cwd=cwd, env=env, input=data, capture_output=True)
if os.name == "nt":
import ctypes
from ctypes import wintypes
class _JobLimits(ctypes.Structure):
"""JOBOBJECT_EXTENDED_LIMIT_INFORMATION; only LimitFlags is set."""
_fields_ = [("per_process_user_time", ctypes.c_int64), ("per_job_user_time", ctypes.c_int64),
("limit_flags", wintypes.DWORD), ("min_working_set", ctypes.c_size_t),
("max_working_set", ctypes.c_size_t), ("active_process_limit", wintypes.DWORD),
("affinity", ctypes.c_size_t), ("priority_class", wintypes.DWORD),
("scheduling_class", wintypes.DWORD), ("io_counters", ctypes.c_uint64 * 6),
("process_memory_limit", ctypes.c_size_t), ("job_memory_limit", ctypes.c_size_t),
("peak_process_memory_used", ctypes.c_size_t), ("peak_job_memory_used", ctypes.c_size_t)]
_KERNEL32 = ctypes.WinDLL("kernel32", use_last_error=True)
_KERNEL32.CreateJobObjectW.restype = wintypes.HANDLE
_KERNEL32.CreateJobObjectW.argtypes = (ctypes.c_void_p, wintypes.LPCWSTR)
_KERNEL32.SetInformationJobObject.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD)
_KERNEL32.OpenProcess.restype = wintypes.HANDLE
_KERNEL32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)
_KERNEL32.AssignProcessToJobObject.argtypes = (wintypes.HANDLE, wintypes.HANDLE)
_KERNEL32.TerminateJobObject.argtypes = (wintypes.HANDLE, wintypes.UINT)
_KERNEL32.CloseHandle.argtypes = (wintypes.HANDLE,)
def job_of(p: subprocess.Popen):
"""On Windows, a job object holding `p`, or None. The processes `p` starts join it, and closing it stops every
process in it (JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE): a process that outlives `p` is stopped with the job, where
`taskkill /T` no longer finds it once `p` has ended. A process `p` starts before it joins (its first instants)
stays out."""
job = _KERNEL32.CreateJobObjectW(None, None)
if not job:
return None
limits = _JobLimits(limit_flags=0x2000) # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
handle = _KERNEL32.OpenProcess(0x0101, False, p.pid) # PROCESS_TERMINATE | PROCESS_SET_QUOTA
# 9: JobObjectExtendedLimitInformation
joined = (handle and _KERNEL32.SetInformationJobObject(job, 9, ctypes.byref(limits), ctypes.sizeof(limits))
and _KERNEL32.AssignProcessToJobObject(job, handle))
if handle:
_KERNEL32.CloseHandle(handle)
if not joined:
_KERNEL32.CloseHandle(job)
return None
return job
def stop_all(p: subprocess.Popen, job) -> None:
"""Stops `p` and every process it started, still running or left behind: the job on Windows, the process group
elsewhere."""
if job is not None:
_KERNEL32.TerminateJobObject(job, 1)
_KERNEL32.CloseHandle(job)
elif os.name != "nt":
try:
os.killpg(p.pid, signal.SIGKILL)
except ProcessLookupError:
pass
if p.poll() is None:
p.kill()
def run_output(cmd: list[str], cwd: Path, env: dict | None = None,
timeout: float | None = None) -> tuple[int | None, str]:
"""The exit code and the output (error output included) of `cmd`. With a timeout, the output goes to a file, so
that a process left behind holding it does not hold the run; once `cmd` ends, or after `timeout` seconds (then
the exit code is None), it is stopped with every process it started."""
if timeout is None:
r = subprocess.run(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
return r.returncode, r.stdout.decode("utf-8", "replace")
with tempfile.TemporaryFile() as log:
p = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=log, stderr=subprocess.STDOUT,
start_new_session=os.name != "nt")
job = job_of(p) if os.name == "nt" else None
try:
code = p.wait(timeout=timeout)
except subprocess.TimeoutExpired:
code = None
finally: # Ctrl+C too: on POSIX the new session keeps it from the processes started
stop_all(p, job)
p.wait()
log.seek(0)
return code, log.read().decode("utf-8", "replace")
def git(cwd: Path, *args: str, env: dict | None = None, data: bytes | None = None, check: bool = True) -> str:
r = run(["git", *args], cwd, env, data)
if check and r.returncode != 0:
why = (r.stderr or r.stdout).decode("utf-8", "replace").strip().splitlines()
raise Failure(f"git {' '.join(args)}: {why[-1] if why else 'exit ' + str(r.returncode)}")
return r.stdout.decode("utf-8", "replace").strip()
def blob(cwd: Path, rev: str, path: str) -> bytes | None:
r = run(["git", "cat-file", "blob", f"{rev}:{path}"], cwd)
return r.stdout if r.returncode == 0 else None
def lines_of(data: bytes) -> list[bytes]:
"""Lines as git counts them (on \\n only), each with its end."""
parts = data.split(b"\n")
out = [p + b"\n" for p in parts[:-1]]
if parts[-1]:
out.append(parts[-1])
return out
# --- which files and hunks are tests ---------------------------------------------------------------------------
def is_test_file(path: str) -> bool:
parts = path.split("/")
return "tests" in parts[:-1] or parts[-1].endswith("_tests.rs") or parts[-1] == "tests.rs"
CFG = re.compile(r"^\s*#\[cfg\((.*)\)\]\s*$")
RAW_OPEN = re.compile(r'b?r(#*)"')
CHAR = re.compile(r"b?'(?:\\(?:x[0-9a-fA-F]{2}|u\{[0-9a-fA-F]+\}|.)|[^\\'])'")
def is_test_cfg(expr: str) -> bool:
expr = expr.replace(" ", "")
if "not(test" in expr:
return False
return expr == "test" or (expr.startswith("all(") and re.search(r"[(,]test[,)]", expr) is not None)
def item_end(lines: list[str], start: int) -> int | None:
"""The last line of the Rust item that starts at `start`: its `;` before any brace, or its closing brace."""
depth, opened, state = 0, False, None
for i in range(start, len(lines)):
s, k = lines[i], 0
while k < len(s):
c = s[k]
if state == "str":
if c == "\\":
k += 2
continue
if c == '"':
state = None
elif isinstance(state, int): # a raw string with `state` hashes
close = '"' + "#" * state
if s.startswith(close, k):
state, k = None, k + len(close)
continue
elif state == "comment":
if s.startswith("*/", k):
state, k = None, k + 2
continue
else:
if s.startswith("//", k):
break
if s.startswith("/*", k):
state, k = "comment", k + 2
continue
m = RAW_OPEN.match(s, k)
if m and (k == 0 or not (s[k - 1].isalnum() or s[k - 1] == "_")):
state, k = len(m.group(1)), m.end()
continue
m = CHAR.match(s, k)
if m and (k == 0 or not (s[k - 1].isalnum() or s[k - 1] == "_")):
k = m.end()
continue
if c == '"':
state = "str"
elif c == "{":
depth, opened = depth + 1, True
elif c == "}":
depth -= 1
if opened and depth == 0:
return i
elif c == ";" and not opened and depth == 0:
return i
k += 1
return None
def test_lines(data: bytes) -> set[int]:
"""0-based indexes of the lines that belong to `#[cfg(test)]` items."""
lines = [line.decode("utf-8", "replace") for line in lines_of(data)]
out: set[int] = set()
i = 0
while i < len(lines):
m = CFG.match(lines[i])
if m and is_test_cfg(m.group(1)):
j = i + 1
while j < len(lines) and (not lines[j].strip() or lines[j].lstrip().startswith(("#[", "//"))):
j += 1
end = item_end(lines, j) if j < len(lines) else None
if end is not None:
out.update(range(i, end + 1))
i = end + 1
continue
i += 1
return out
def neutral(line: bytes) -> bool:
text = line.decode("utf-8", "replace").strip()
return not text or text.startswith("//")
HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
def hunks(diff: str) -> list[tuple[int, int, int, int]]:
out = []
for line in diff.splitlines():
m = HUNK.match(line)
if m:
a, b, c, d = m.group(1), m.group(2), m.group(3), m.group(4)
out.append((int(a), 1 if b is None else int(b), int(c), 1 if d is None else int(d)))
return out
def test_hunk_flags(old: bytes, new: bytes, diff: str) -> list[bool]:
"""For each hunk of `diff` (a Rust file's, made with -U0), in order, whether it changes only test code: each line
it removes or adds is in a `#[cfg(test)]` item, blank or a comment, and one at least is in such an item. The red
side takes these hunks, and a mutation leaves them alone."""
old_lines, new_lines = lines_of(old), lines_of(new)
old_tests, new_tests = test_lines(old), test_lines(new)
flags = []
for a, b, c, d in hunks(diff):
lines = [(i in old_tests, old_lines[i]) for i in range(a - 1, a - 1 + b)] + \
[(i in new_tests, new_lines[i]) for i in range(c - 1, c - 1 + d)]
flags.append(bool(lines) and all(t or neutral(line) for t, line in lines) and any(t for t, _ in lines))
return flags
def test_hunks(old: bytes, new: bytes, diff: str) -> bytes | None:
"""`old` with only the hunks of `diff` (made with -U0) that change test code; None when there is none."""
old_lines, new_lines = lines_of(old), lines_of(new)
keep = [h for h, test in zip(hunks(diff), test_hunk_flags(old, new, diff)) if test]
if not keep:
return None
out = list(old_lines)
for a, b, c, d in sorted(keep, reverse=True):
at = a if b == 0 else a - 1
out[at:at + b] = new_lines[c - 1:c - 1 + d]
return b"".join(out)
# --- the two sides ------------------------------------------------------------------------------------------------
def red_commit(repo: Path, merge_base: str, head: str) -> tuple[str | None, list[str]]:
"""A commit on the merge base with only the pull request's tests, and the files it takes them from."""
changed = git(repo, "diff", "--name-status", "--no-renames", "-z", merge_base, head).split("\0")
pairs = [(changed[i], changed[i + 1]) for i in range(0, len(changed) - 1, 2)]
plan: list[tuple[str, tuple[str, bytes] | None]] = []
for status, path in pairs:
if is_test_file(path):
if status == "D":
plan.append((path, None))
continue
mode = git(repo, "ls-tree", head, "--", path).split(" ", 1)[0]
plan.append((path, (mode, blob(repo, head, path) or b"")))
elif path.endswith(".rs") and status == "M":
diff = git(repo, "diff", "-U0", "--no-color", "--no-ext-diff", merge_base, head, "--", path)
merged = test_hunks(blob(repo, merge_base, path) or b"", blob(repo, head, path) or b"", diff)
if merged is not None:
mode = git(repo, "ls-tree", merge_base, "--", path).split(" ", 1)[0]
plan.append((path, (mode, merged)))
if not plan:
return None, []
with tempfile.TemporaryDirectory(prefix="red-green-index-") as tmp:
env = dict(os.environ, GIT_INDEX_FILE=str(Path(tmp) / "index"), **IDENTITY)
git(repo, "read-tree", merge_base, env=env)
for path, change in plan:
if change is None:
git(repo, "update-index", "--force-remove", "--", path, env=env)
else:
mode, data = change
sha = git(repo, "hash-object", "-w", "--stdin", data=data)
git(repo, "update-index", "--add", "--cacheinfo", f"{mode},{sha},{path}", env=env)
tree = git(repo, "write-tree", env=env)
commit = git(repo, "commit-tree", tree, "-p", merge_base, "-m", f"red_green: the tests of {head[:12]} only",
env=env)
return commit, [path for path, _ in plan]
def checkout(repo: Path, tree: Path, base: str) -> None:
if not (tree / ".git").exists():
git(repo, "worktree", "add", "--detach", "--force", str(tree), base)
return
git(tree, "cherry-pick", "--quit", check=False)
git(tree, "merge", "--quit", check=False)
git(tree, "reset", "--hard", "-q")
git(tree, "clean", "-fdq")
git(tree, "checkout", "--detach", "--force", "-q", base)
def conflicts(tree: Path) -> list[str]:
return [p for p in git(tree, "diff", "--name-only", "--diff-filter=U").splitlines() if p]
# --- running the tests --------------------------------------------------------------------------------------------
UNIT = re.compile(r"^\s*(?:Running\s.*?([\w-]+?)-[0-9a-f]{16}(?:\.exe)?\)|Doc-tests\s+(\S+))\s*$")
CARGO_TEST = re.compile(r"^test (.+?) \.\.\. (ok|FAILED|ignored)\b")
CARGO_ERROR = re.compile(r"^error(?:\[E\d+\])?: ")
def crates_of(tree: Path, paths: list[str]) -> list[str]:
names = []
for path in paths:
parts = path.split("/")
if len(parts) > 3 and parts[0] == "d3d12" and parts[1] in ("crates", "apps"):
manifest = tree / "d3d12" / parts[1] / parts[2] / "Cargo.toml"
if manifest.is_file():
m = re.search(r'^\s*name\s*=\s*"([^"]+)"', manifest.read_text(encoding="utf-8"), re.M)
if m and m.group(1) not in names:
names.append(m.group(1))
return names
# 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, timeout: float | None) -> 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))
code, out = run_output(cmd, tree / "d3d12", env, timeout)
tests, unit, error, ran = {}, "?", None, False
for line in out.splitlines():
m = UNIT.match(line)
if m:
unit, ran = m.group(1) or "doc:" + m.group(2), True
continue
m = CARGO_TEST.match(line)
if m:
tests[f"{unit}::{m.group(1)}"] = {"ok": "ok", "FAILED": "failed", "ignored": "ignored"}[m.group(2)]
elif error is None and CARGO_ERROR.match(line):
error = line.strip()
no_build = code is not None and code != 0 and not tests
crash = COMPILER_CRASH.search(out) if no_build else None
# Stopped by the timeout: while building (no test binary had started) or while running the tests.
timed_out = None if code is not None else "running" if ran else "building"
return {"tests": tests, "no_build": (error or f"cargo exit {code}") if no_build and not crash else None,
"crash": next(g for g in crash.groups() if g) if crash else None, "timed_out": timed_out}
def cargo_tests(tree: Path, crates: list[str], cargo: str, target: Path, timeout: float | None) -> dict:
first = cargo_once(tree, crates, cargo, target, timeout)
if not first["crash"]:
return {"tests": first["tests"], "no_build": first["no_build"], "timed_out": first["timed_out"]}
print(f"red_green: the compiler crashed ({first['crash']}), running again", file=sys.stderr)
again = cargo_once(tree, crates, cargo, target, timeout)
result = {"tests": again["tests"], "no_build": again["no_build"], "rerun_after": first["crash"],
"timed_out": again["timed_out"]}
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)",
re.M)
def drop_bytecode(tree: Path) -> None:
"""Removes every `__pycache__` folder of the work tree. Python runs a .pyc instead of its source when the source
time and size it records still match (an undone change of the same size within the same second) or when it is an
unchecked-hash one, and `git clean` keeps them (they are ignored). An option of the run's own Python, such as
`-X pycache_prefix`, would not reach the processes its tests start. Links (symbolic links, and junctions, which
`is_symlink()` does not see) are neither followed nor removed: what they point at is not the tree's."""
folders, todo = [], [tree]
while todo:
with os.scandir(todo.pop()) as entries:
for e in entries:
link = e.is_symlink() or bool(getattr(e.stat(follow_symlinks=False), "st_file_attributes", 0)
& stat.FILE_ATTRIBUTE_REPARSE_POINT)
if not link and e.is_dir(follow_symlinks=False):
(folders if e.name == "__pycache__" else todo).append(e.path)
for folder in folders:
shutil.rmtree(folder)
def python_tests(tree: Path, files: list[str], timeout: float | None) -> dict:
tests, no_build, timed_out = {}, [], None
drop_bytecode(tree)
for f in files:
start = "tests/semantic" if f.startswith("tests/semantic/") else str(Path(f).parent)
# -B only stops writing bytecode, not reading it: drop_bytecode() above keeps stale bytecode out.
code, out = run_output([sys.executable, "-I", "-B", "-m", "unittest", "discover", "-s", start,
"-p", Path(f).name, "-v"], tree, timeout=timeout)
if code is None:
timed_out = "running"
found = 0
for name, where, status in PY_TEST.findall(out):
if "_FailedTest" in where:
no_build.append(f"{f}: does not import")
continue
key = where if where.endswith("." + name) else f"{where}.{name}"
tests[f"{f}::{key}"] = {"ok": "ok", "skipped": "ignored", "expected failure": "ok"}.get(status, "failed")
found += 1
if not found and code not in (0, None) and f"{f}: does not import" not in no_build:
no_build.append(f"{f}: exit {code}")
return {"tests": tests, "no_build": "; ".join(no_build) or None, "timed_out": timed_out}
def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target: Path,
timeout: float | None = None) -> dict:
"""The tests of one side: the crates, and those of the Python test files that this tree has. With a timeout (the
mutated runs), a command that runs past it is stopped and `timed_out` says when: "building" (cargo, before any
test binary ran) or "running"."""
py_files = [f for f in py_files if (tree / f).is_file()]
result = {"tests": {}, "no_build": [], "compiler_crashed": None, "rerun_after": None, "timed_out": None}
for part in ([cargo_tests(tree, crates, cargo, target, timeout)] if crates else []) + \
([python_tests(tree, py_files, timeout)] 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", "timed_out"):
result[key] = result[key] or part.get(key)
return result
# --- reading the two sides ----------------------------------------------------------------------------------------
def compare(red: dict | None, green: dict | None) -> dict:
r = red["tests"] if red else {}
g = green["tests"] if green else {}
rows = {"red_to_green": [], "regressions": [], "fail_on_both": [], "only_on_green": [], "only_on_red": []}
both_ok = 0
for key in sorted(set(r) | set(g)):
a, b = r.get(key), g.get(key)
if a == "failed" and b == "ok":
rows["red_to_green"].append(key)
elif a == "ok" and b == "failed":
rows["regressions"].append(key)
elif a == "failed" and b == "failed":
rows["fail_on_both"].append(key)
elif a is None and b is not None:
rows["only_on_green"].append(f"{key} ({b})")
elif b is None and a is not None:
rows["only_on_red"].append(f"{key} ({a})")
elif a == "ok" and b == "ok":
both_ok += 1
rows["pass_on_both"] = both_ok
return rows
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"
if red_why:
return "red not constructible"
if not (red and red["tests"]) and not (green and green["tests"]):
return "no tests ran"
if rows["red_to_green"]:
return "red then green"
if red and red["no_build"] and rows["only_on_green"]:
return "red does not build"
return "no red"
def report(r: dict) -> str:
out = [f"base {r['base']} {r['base_commit'][:9]}, head {r['head']} {r['head_commit'][:9]}, "
f"merge base {r['merge_base'][:9]}"]
out.append("red: " + (r["red_why"] or "the base plus the tests of " + ", ".join(r["red_files"])))
out.append("green: " + (r["green_why"] or "the base with the pull request merged"))
out.append("ran: " + ", ".join([f"cargo -p {c}" for c in r["crates"]] + r["python_files"] or ["nothing"]))
for name in ("red", "green"):
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",
"only_on_red": "only on red"}
for key, label in labels.items():
if rows[key]:
out.append(f"{label} ({len(rows[key])}):")
out += [f" {t}" for t in rows[key][:40]]
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:
if r.get("mutations_not_run"):
out.append(f"mutations: {r['mutations_not_run']}")
else:
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())))
out += [f" {m['file']}:{m['line']}: {m['result']}" for m in r["mutations"]]
if r.get("mutations_skipped"):
out.append("not tried, past --mutate-max: "
+ ", ".join(f"{m['file']}:{m['line']}" for m in r["mutations_skipped"]))
if r.get("added_not_mutated"):
out.append("not mutated, added by the pull request: " + ", ".join(r["added_not_mutated"]))
out.append(f"verdict: {r['verdict']}")
return "\n".join(out)
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
p.add_argument("pr", help="a pull request number (fetched from --remote) or a git ref")
p.add_argument("--base", help="the base to test on (default <remote>/main, fetched)")
p.add_argument("--remote", default="origin", help="where main and pull requests are fetched from (origin)")
p.add_argument("--no-fetch", action="store_true", help="use the refs as they are")
p.add_argument("--work-dir", type=Path, help="the worktree and cargo target dir (<git common dir>/red-green)")
p.add_argument("--crate", action="append", default=[], help="a cargo package to test as well (repeatable)")
p.add_argument("--no-cargo", action="store_true", help="skip the cargo tests")
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)")
p.add_argument("--mutate-timeout", type=float, default=600, metavar="SECONDS",
help="stop a command of a mutated run (cargo test, one Python test file) after this long: the hunk "
"is caught by timeout, or timed out building if cargo had not started a test (600)")
a = p.parse_args(argv)
try:
repo = Path(git(Path.cwd(), "rev-parse", "--show-toplevel"))
common = Path(git(repo, "rev-parse", "--path-format=absolute", "--git-common-dir"))
base = a.base or f"{a.remote}/main"
if not a.no_fetch:
if not a.base:
git(repo, "fetch", "-q", a.remote, "main")
if a.pr.isdigit():
git(repo, "fetch", "-q", a.remote, f"pull/{a.pr}/head")
head = git(repo, "rev-parse", "FETCH_HEAD" if a.pr.isdigit() and not a.no_fetch else a.pr + "^{commit}")
base_commit = git(repo, "rev-parse", base + "^{commit}")
merge_base = git(repo, "merge-base", base_commit, head)
work = (a.work_dir or common / "red-green").resolve()
work.mkdir(parents=True, exist_ok=True)
lock = work / "lock"
try:
fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except FileExistsError:
raise Failure(f"{lock} exists: another run is going, or delete it if none is") from None
os.write(fd, str(os.getpid()).encode())
os.close(fd)
try:
result = check(repo, work, a, base, base_commit, head, merge_base)
finally:
lock.unlink(missing_ok=True)
except Failure as e:
print(f"red_green: {e}", file=sys.stderr)
return 2
print(json.dumps(result, indent=1) if a.json else report(result))
return 0 if result["verdict"] == "red then green" else 1
def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, merge_base: str) -> dict:
tree, target = work / "tree", work / "target"
changed = [p for p in git(repo, "diff", "--name-only", "--no-renames", merge_base, head).splitlines() if p]
checkout(repo, tree, base_commit)
crates = [] if a.no_cargo else crates_of(tree, changed) + [c for c in a.crate if c not in crates_of(tree, changed)]
py_files = [] if a.no_python else [
f for f in changed if f.startswith("tests/") and re.fullmatch(r"test\w*\.py", f.rsplit("/", 1)[-1])]
env = dict(os.environ, **IDENTITY)
red, red_why = None, None
commit, red_files = red_commit(repo, merge_base, head)
if commit is None:
red_why = "not constructible: the pull request changes no test"
else:
git(tree, "cherry-pick", "--no-commit", commit, env=env, check=False)
stuck = conflicts(tree)
if stuck:
red_why = "not constructible: the tests conflict with the base in " + ", ".join(stuck)
else:
print("red_green: red side...", file=sys.stderr)
red = side(tree, crates, py_files, a.cargo, target)
green, green_why, green_commit = None, None, None
checkout(repo, tree, base_commit)
git(tree, "merge", "--no-commit", "--no-ff", head, env=env, check=False)
stuck = conflicts(tree)
if stuck:
green_why = "not constructible: the pull request conflicts with the base in " + ", ".join(stuck)
else:
if a.mutate: # the merge as it is now, before a test can write into the tree: each mutation starts from it
green_commit = git(tree, "commit-tree", git(tree, "write-tree"), "-p", base_commit, "-p", head,
"-m", f"red_green: {head[:12]} merged", env=env)
print("red_green: green side...", file=sys.stderr)
green = side(tree, crates, py_files, a.cargo, target)
rows = compare(red, green)
# With --mutate, `mutations` is a list (empty when no hunk was undone, and `mutations_not_run` says why).
mutations, not_run, skipped, added = None, None, None, None
if a.mutate:
hunks, added, mutations = code_hunks(repo, merge_base, head), code_files(repo, merge_base, head, "A"), []
if green is None:
not_run = "not run: there is no green side"
elif not hunks:
not_run = ("nothing to undo in the files it modifies: its code changes are in files it adds" if added else
"nothing to undo: the diff changes no Rust or Python code outside its tests")
elif not rows["red_to_green"]:
not_run = "not run: no test went red then green, so none can catch a hunk"
else:
print("red_green: mutations...", file=sys.stderr)
mutations = mutate(tree, green_commit, hunks[:a.mutate_max], rows["red_to_green"], crates, py_files,
a.cargo, target, a.mutate_timeout)
skipped = [{"file": path, "line": line} for path, line, _ in hunks[a.mutate_max:]]
checkout(repo, tree, base_commit)
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, "mutations": mutations,
"mutations_not_run": not_run, "mutations_skipped": skipped, "added_not_mutated": added,
"verdict": verdict(red_why, green_why, red, green, rows)}
def code_files(repo: Path, merge_base: str, head: str, status: str) -> list[str]:
"""The Rust and Python files outside the tests that the pull request changes with git status `status` (M
modified, A added). Added files are not mutated: undoing one deletes it, which only shows that something uses it."""
paths = git(repo, "diff", "--name-only", "--no-renames", f"--diff-filter={status}", merge_base, head).splitlines()
return [p for p in paths if not is_test_file(p)
and (p.endswith(".rs") or (p.endswith(".py") and not p.startswith("tests/")))]
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 in the files
it modifies: 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 code_files(repo, merge_base, head, "M"):
diff = git(repo, "diff", "-U0", "--no-color", "--no-ext-diff", merge_base, head, "--", path)
lines = diff.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])
blocks: list[list[str]] = []
for line in lines[first:]:
if line.startswith("@@"):
blocks.append([line])
else:
blocks[-1].append(line)
# A hunk of test code only is the tests' own, not the fix: the same rule as the red side's.
tests_only = (test_hunk_flags(blob(repo, merge_base, path) or b"", blob(repo, head, path) or b"", diff)
if path.endswith(".rs") else [False] * len(blocks))
for block, test in zip(blocks, tests_only):
m = HUNK.match(block[0])
if m and not test:
out.append((path, int(m.group(3)), header + "\n" + "\n".join(block).rstrip("\n") + "\n"))
return out
def mutate(tree: Path, green: str, hunks: list[tuple[str, int, str]], targets: list[str], crates: list[str],
py_files: list[str], cargo: str, target: Path, timeout: float) -> list[dict]:
"""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, or caught by timeout when a command runs past `timeout` seconds. Each one starts
from the commit `green`, reset and cleaned, so what a test wrote into the tree changes no other."""
results = []
for path, line, patch in hunks:
entry = {"file": path, "line": line, "result": None}
git(tree, "reset", "--hard", "-q", green)
git(tree, "clean", "-fdq")
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, py_files, cargo, target, timeout)
if s.get("compiler_crashed"):
entry["result"] = "compiler crashed"
elif any(s["tests"].get(t) == "failed" for t in targets):
entry["result"] = "caught"
elif s["timed_out"] == "building": # no answer: the build was too slow, or the undone code made it hang
entry["result"] = "timed out building"
elif s["timed_out"]:
entry["result"] = "caught by timeout"
elif not any(t in s["tests"] for t in targets):
entry["result"] = "does not build"
else:
entry["result"] = "not caught"
results.append(entry)
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")
except (AttributeError, ValueError, OSError):
pass
sys.exit(main())