From dc63e371ce211540f50f8cfb640f1daab97b285f Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:09:56 +0100 Subject: scripts: red_green.py --mutate checks that the tests catch the change itself (TEST-RED-GREEN-MUTATION) Verifiers remove a line of the fix by hand on nearly every test pull request to see the new test fail. --mutate does it for each hunk of the pull request's code outside its tests (Rust and Python files it changes; hunks taken without context, so a test changed next to the code stays out): after the green side, it undoes that hunk alone, runs the tests again and reports it as caught (a test that went red then green fails), not caught, does not build or does not apply, up to --mutate-max hunks (10); the hunk is put back after each run. Python tests now run with -B: an undone change of the same size within the same second would otherwise run the stale bytecode. --- docs/testing.md | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'docs/testing.md') diff --git a/docs/testing.md b/docs/testing.md index a5686330c..b213c71d2 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -157,6 +157,12 @@ python -I scripts/red_green.py 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. -- cgit v1.2.3 From de6db4b7337a09e57f49f2f4d727521e3e6df811 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:03:10 +0100 Subject: scripts: red_green.py removes the work tree's __pycache__ before each Python run, so no test runs stale bytecode (review) -B only stops writing bytecode. An ignored .pyc left in the work tree (git clean keeps it) ran instead of the reverted source: red passed and an undone hunk was not caught. -X pycache_prefix would cover the unittest process only, not the processes its tests start; removing the folders covers both. --- docs/testing.md | 9 +++++---- scripts/red_green.py | 13 ++++++++++++- tests/test_red_green.py | 31 +++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 5 deletions(-) (limited to 'docs/testing.md') diff --git a/docs/testing.md b/docs/testing.md index b213c71d2..d5d6cfbc7 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -144,10 +144,11 @@ python -I scripts/red_green.py cherry-picked with a 3-way merge. A conflict, or a pull request that changes no test, is "red not constructible". A hunk that mixes test and other code stays on the green side only. - It runs `cargo test --no-fail-fast` for the crates under `d3d12/crates` and `d3d12/apps` the pull request touches, - from `d3d12/` so the pinned toolchain applies. It also runs each changed `tests/**/test*.py` with unittest. Both - sides run in one worktree with one cargo target dir, red first, under `/red-green` (`--work-dir` - to move it). The worktree and the target dir stay for the next run, which then builds only what changed. The - target dir takes several GB; delete the folder (and run `git worktree prune`) when done. + from `d3d12/` so the pinned toolchain applies. It also runs each changed `tests/**/test*.py` with unittest, after + removing the worktree's `__pycache__` folders so that no test runs stale bytecode. Both sides run in one worktree + with one cargo target dir, red first, under `/red-green` (`--work-dir` to move it). The worktree + and the target dir stay for the next run, which then builds only what changed. The 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`, diff --git a/scripts/red_green.py b/scripts/red_green.py index 57dd8de6a..6c5102857 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -32,6 +32,7 @@ import argparse import json import os import re +import shutil import subprocess import sys import tempfile @@ -322,11 +323,21 @@ PY_TEST = re.compile(r"^(\w+) \(([\w.]+)\)(?:\n[^\n]*?)? \.\.\. (ok|FAIL|ERROR|s 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.""" + for folder in [p for p in tree.rglob("__pycache__") if p.is_dir()]: + shutil.rmtree(folder) + + def python_tests(tree: Path, files: list[str]) -> dict: tests, no_build = {}, [] + drop_bytecode(tree) for f in files: start = "tests/semantic" if f.startswith("tests/semantic/") else str(Path(f).parent) - # -B: no bytecode. An undone change of the same size within the same second would run the stale .pyc. + # -B only stops writing bytecode, not reading it: drop_bytecode() above keeps stale bytecode out. 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) diff --git a/tests/test_red_green.py b/tests/test_red_green.py index be4a60c2e..e28f87c68 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -2,6 +2,7 @@ import io import json import os +import py_compile import subprocess import sys import tempfile @@ -235,6 +236,36 @@ class Python(unittest.TestCase): self.assertIn("does not import", r["red"]["no_build"][0]) self.assertEqual(code, 1) + # The same test, and once more in a process it starts, as the tests of a command-line tool do. + CHILD_TEST = TEST + ( + "\n def test_two_in_a_child(self):\n" + " import subprocess\n" + " tools = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'tools')\n" + " code = 'import sys; sys.path.insert(0, sys.argv[1]); import bar; print(bar.two())'\n" + " out = subprocess.run([sys.executable, '-I', '-c', code, tools], capture_output=True, text=True)\n" + " self.assertEqual(out.stdout.strip(), '2')\n") + + def test_stale_bytecode_in_the_work_tree_is_never_run(self): + repo = Repo(self) + repo.commit("base", {".gitignore": "__pycache__/\n", "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": self.CHILD_TEST}) + self.assertEqual(repo.run("--no-cargo")[1]["verdict"], "red then green") + # An ignored .pyc of the fixed bar.py left in the work tree (`git clean` keeps ignored files). An unchecked-hash + # .pyc is taken without looking at the source, like a timestamp one whose time and size still match. + tools = os.path.join(repo.dir, ".git", "red-green", "tree", "tools") + src = os.path.join(repo.tmp.name, "bar_fixed.py") + with open(src, "w", encoding="utf-8", newline="\n") as f: + f.write("def two():\n return 2\n") + py_compile.compile(src, cfile=os.path.join(tools, "__pycache__", f"bar.{sys.implementation.cache_tag}.pyc"), + doraise=True, invalidation_mode=py_compile.PycInvalidationMode.UNCHECKED_HASH) + code, r, _ = repo.run("--no-cargo", "--mutate") + # Read, it would make red pass in both processes and the undone fix not caught. + self.assertEqual((code, r["verdict"]), (0, "red then green"), r) + self.assertEqual(r["rows"]["red_to_green"], ["tests/test_bar.py::test_bar.T.test_two", + "tests/test_bar.py::test_bar.T.test_two_in_a_child"]) + self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], [("tools/bar.py", "caught")]) + class Mutation(unittest.TestCase): # Two code changes far enough apart to be two hunks: the tested one and one no test looks at. -- cgit v1.2.3 From 745808fc3b3d4779e1165633775f7463fdb105be Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:07:04 +0100 Subject: scripts: red_green.py --mutate-timeout stops a mutated run that hangs and reports it as caught by timeout (review) Each command of a mutated run (cargo test, one Python test file) is stopped after --mutate-timeout seconds (600) together with the processes it started (taskkill /T on Windows, the process group elsewhere): a test binary or a process a test starts would otherwise keep the output pipe open. The hunk is then 'caught by timeout', apart from 'caught'. The red and green sides have no timeout, as before. --- docs/testing.md | 3 ++ scripts/red_green.py | 113 ++++++++++++++++++++++++++++++++++-------------- tests/test_red_green.py | 25 +++++++++++ 3 files changed, 109 insertions(+), 32 deletions(-) (limited to 'docs/testing.md') diff --git a/docs/testing.md b/docs/testing.md index d5d6cfbc7..0cd88f7df 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -164,6 +164,9 @@ python -I scripts/red_green.py 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. +- Each command of a mutated run (`cargo test`, one Python test file) is stopped with the processes it started after + `--mutate-timeout` seconds (600), and the hunk is `caught by timeout`: the undone code made a test hang, or the + build took longer than that (raise the option for a crate that builds slowly). - `--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 6c5102857..08c5ebc35 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -3,6 +3,7 @@ python -I scripts/red_green.py [--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 (`/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 @@ -33,6 +34,7 @@ import json import os import re import shutil +import signal import subprocess import sys import tempfile @@ -53,6 +55,42 @@ def run(args: list[str], cwd: Path, env: dict | None = None, data: bytes | None return subprocess.run(args, cwd=cwd, env=env, input=data, capture_output=True) +def kill_tree(p: subprocess.Popen) -> None: + """Stops `p` and the processes it started (a test binary under cargo, a process a test starts).""" + if os.name == "nt": + subprocess.run(["taskkill", "/F", "/T", "/PID", str(p.pid)], capture_output=True) + else: + try: + os.killpg(p.pid, signal.SIGKILL) + except ProcessLookupError: + pass + 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`. Past `timeout` seconds it is stopped with the + processes it started, whose copies of the output pipe would hold the read open, and the exit code is None.""" + 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") + p = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + start_new_session=os.name != "nt") + try: + out, _ = p.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + kill_tree(p) + try: + out, _ = p.communicate(timeout=60) + except subprocess.TimeoutExpired: # a process outside the tree still holds the pipe: leave its output + out = b"" + return None, out.decode("utf-8", "replace") + except BaseException: # Ctrl+C: on POSIX the new session keeps it from the processes started + kill_tree(p) + raise + return p.returncode, out.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: @@ -284,12 +322,11 @@ COMPILER_CRASH = re.compile( 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: +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)) - r = subprocess.run(cmd, cwd=tree / "d3d12", env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) - out = r.stdout.decode("utf-8", "replace") + code, out = run_output(cmd, tree / "d3d12", env, timeout) tests, unit, error = {}, "?", None for line in out.splitlines(): m = UNIT.match(line) @@ -301,19 +338,20 @@ def cargo_once(tree: Path, crates: list[str], cargo: str, target: Path) -> dict: 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 = r.returncode != 0 and not tests + no_build = code is not None and code != 0 and not tests 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} + 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": code is None} -def cargo_tests(tree: Path, crates: list[str], cargo: str, target: Path) -> dict: - first = cargo_once(tree, crates, cargo, target) +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"]} + 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) - result = {"tests": again["tests"], "no_build": again["no_build"], "rerun_after": first["crash"]} + 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 @@ -332,16 +370,15 @@ def drop_bytecode(tree: Path) -> None: shutil.rmtree(folder) -def python_tests(tree: Path, files: list[str]) -> dict: - tests, no_build = {}, [] +def python_tests(tree: Path, files: list[str], timeout: float | None) -> dict: + tests, no_build, timed_out = {}, [], False 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. - 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") + code, out = run_output([sys.executable, "-I", "-B", "-m", "unittest", "discover", "-s", start, + "-p", Path(f).name, "-v"], tree, timeout=timeout) + timed_out |= code is None found = 0 for name, where, status in PY_TEST.findall(out): if "_FailedTest" in where: @@ -350,19 +387,22 @@ def python_tests(tree: Path, files: list[str]) -> dict: 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 r.returncode != 0 and f"{f}: does not import" not in no_build: - no_build.append(f"{f}: exit {r.returncode}") - return {"tests": tests, "no_build": "; ".join(no_build) or None} - - -def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target: Path) -> dict: - 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 []): + 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. With a timeout (the mutated runs), a command that runs past it is stopped and the side + is marked `timed_out`.""" + result = {"tests": {}, "no_build": [], "compiler_crashed": None, "rerun_after": None, "timed_out": False} + 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"): + for key in ("compiler_crashed", "rerun_after", "timed_out"): result[key] = result[key] or part.get(key) return result @@ -462,6 +502,9 @@ def main(argv: list[str] | None = None) -> int: 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 and count " + "the hunk as caught by timeout (600)") a = p.parse_args(argv) try: repo = Path(git(Path.cwd(), "rev-parse", "--show-toplevel")) @@ -532,7 +575,8 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer 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) + mutations = mutate(repo, tree, merge_base, head, targets, crates, py_files, a.cargo, target, a.mutate_max, + a.mutate_timeout) if mutations is None: checkout(repo, tree, base_commit) git(tree, "merge", "--no-commit", "--no-ff", head, env=env, check=False) @@ -583,9 +627,10 @@ def code_hunks(repo: Path, merge_base: str, head: str) -> list[tuple[str, int, s 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: + py_files: list[str], cargo: str, target: Path, most: int, timeout: float) -> 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).""" + that went red then green fails, or caught by timeout when a command runs past `timeout` seconds. 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} @@ -594,13 +639,17 @@ def mutate(repo: Path, tree: Path, merge_base: str, head: str, targets: list[str 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) + s = side(tree, crates, [f for f in py_files if (tree / f).is_file()], 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"]: + entry["result"] = "caught by timeout" 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" + entry["result"] = "not caught" results.append(entry) if run(["git", "apply", "--unidiff-zero", "-"], tree, data=patch.encode()).returncode != 0: return None diff --git a/tests/test_red_green.py b/tests/test_red_green.py index e28f87c68..655ba13d6 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -6,6 +6,7 @@ import py_compile import subprocess import sys import tempfile +import time import unittest from contextlib import redirect_stderr, redirect_stdout @@ -300,6 +301,30 @@ class Mutation(unittest.TestCase): 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_a_mutated_run_that_hangs_is_caught_by_timeout(self): + # Undone alone, the second hunk makes the test start a process that sleeps. Red has neither hunk, so it does + # not hang there. + base = ("def two():\n return 1\n" + "".join(f"# padding line {i}\n" for i in range(10)) + + "\ndef settled():\n return False\n") + test = ("import os, subprocess, sys, unittest\n" + "sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'tools'))\n" + "import bar\n\n\nclass T(unittest.TestCase):\n def test_two(self):\n" + " if bar.two() == 2 and not bar.settled():\n" + " subprocess.run([sys.executable, '-c', 'import time; time.sleep(120)'])\n" + " self.assertEqual(bar.two(), 2)\n") + repo = Repo(self) + repo.commit("base", {"tools/bar.py": base}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"tools/bar.py": base.replace("return 1", "return 2").replace("False", "True"), + "tests/test_bar.py": test}) + start = time.monotonic() + _code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-timeout", "5") + self.assertEqual(r["verdict"], "red then green", r) + self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "caught by timeout")]) + self.assertIn("mutations (2 hunks undone one at a time): 1 caught, 1 caught by timeout", rg.report(r)) + # The sleeping process was stopped with the test's: left running, it would hold the output pipe for 120 s. + self.assertLess(time.monotonic() - start, 60) + def test_no_mutation_without_the_option(self): repo = Repo(self) repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"}) -- cgit v1.2.3 From 89274bac6e991f404608a371c2cab614bb1475aa Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:11:01 +0100 Subject: scripts: red_green.py --mutate says when it stopped, why nothing was undone, and which added files it does not mutate (review) A hunk that cannot be put back no longer drops the whole mutations section: the report and --json (mutations_stopped) name the hunk, the reason and how many hunks were not tried. With --mutate, mutations is always a list and mutations_not_run says why none was undone: nothing to undo (a test-only pull request), or no test went red then green. Files the pull request adds stay unmutated, and the report and --json (added_not_mutated) now list them. Verdicts and exit codes are unchanged. --- docs/testing.md | 7 +++++ scripts/red_green.py | 79 +++++++++++++++++++++++++++++++------------------ tests/test_red_green.py | 67 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 125 insertions(+), 28 deletions(-) (limited to 'docs/testing.md') diff --git a/docs/testing.md b/docs/testing.md index 0cd88f7df..a7b1b4ea9 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -164,6 +164,13 @@ python -I scripts/red_green.py 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. +- Files the pull request adds are not mutated: undoing one would delete it, which only shows that something uses it. + The report lists them (`not mutated, added by the pull request`), so a fix whose code sits in a new file is not + read as covered. When no hunk is undone, the report says why: `nothing to undo` when the pull request changes no + Rust or Python code outside its tests (a test-only one, whose `no red` then says nothing against its test), or + `not run` when no test went red then green. A hunk that cannot be put back (a test wrote into the code) stops the + mutations, and the report names that hunk and the reason. `--json` has these in `mutations_not_run`, + `mutations_stopped` and `added_not_mutated`. - Each command of a mutated run (`cargo test`, one Python test file) is stopped with the processes it started after `--mutate-timeout` seconds (600), and the hunk is `caught by timeout`: the undone code made a test hang, or the build took longer than that (raise the option for a crate that builds slowly). diff --git a/scripts/red_green.py b/scripts/red_green.py index 08c5ebc35..69d9d18b7 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -478,11 +478,19 @@ def report(r: dict) -> str: 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"]] + 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"]] + stop = r.get("mutations_stopped") + if stop: + out.append(f"mutations stopped at {stop['file']}:{stop['line']}: {stop['why']}; " + f"hunks not tried: {stop['untried']}") + 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) @@ -570,32 +578,44 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer 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: + # With --mutate, `mutations` is a list (empty when no hunk was undone, and `mutations_not_run` says why). + mutations, not_run, stopped, 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(repo, tree, merge_base, head, targets, crates, py_files, a.cargo, target, a.mutate_max, - a.mutate_timeout) - if mutations is None: - checkout(repo, tree, base_commit) - git(tree, "merge", "--no-commit", "--no-ff", head, env=env, check=False) + mutations, stopped = mutate(tree, hunks[:a.mutate_max], rows["red_to_green"], crates, py_files, a.cargo, + target, a.mutate_timeout) 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_stopped": stopped, "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: 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).""" + """(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 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 + for path in code_files(repo, merge_base, head, "M"): 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: @@ -626,13 +646,13 @@ def code_hunks(repo: Path, merge_base: str, head: str) -> list[tuple[str, int, s 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, timeout: float) -> list[dict] | None: +def mutate(tree: Path, hunks: list[tuple[str, int, str]], targets: list[str], crates: list[str], py_files: list[str], + cargo: str, target: Path, timeout: float) -> tuple[list[dict], 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, or caught by timeout when a command runs past `timeout` seconds. Returns None - when the tree could not be put back (the caller rebuilds it).""" + that went red then green fails, or caught by timeout when a command runs past `timeout` seconds. Stops at a hunk + that cannot be put back (a test wrote into the code): the second value says where and why.""" results = [] - for path, line, patch in code_hunks(repo, merge_base, head)[:most]: + for path, line, patch in hunks: entry = {"file": path, "line": line, "result": None} undo = run(["git", "apply", "-R", "--unidiff-zero", "-"], tree, data=patch.encode()) if undo.returncode != 0: @@ -651,9 +671,12 @@ def mutate(repo: Path, tree: Path, merge_base: str, head: str, targets: list[str else: entry["result"] = "not caught" results.append(entry) - if run(["git", "apply", "--unidiff-zero", "-"], tree, data=patch.encode()).returncode != 0: - return None - return results + back = run(["git", "apply", "--unidiff-zero", "-"], tree, data=patch.encode()) + if back.returncode != 0: + why = back.stderr.decode("utf-8", "replace").strip().splitlines() + return results, {"file": path, "line": line, "untried": len(hunks) - len(results), + "why": "git apply could not put the hunk back" + (f" ({why[-1]})" if why else "")} + return results, None if __name__ == "__main__": diff --git a/tests/test_red_green.py b/tests/test_red_green.py index 655ba13d6..29ec4e365 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -325,6 +325,72 @@ class Mutation(unittest.TestCase): # The sleeping process was stopped with the test's: left running, it would hold the output pipe for 120 s. self.assertLess(time.monotonic() - start, 60) + def test_a_hunk_that_cannot_be_put_back_stops_the_mutations_and_says_where(self): + # The test writes over the code it tests when it finds it wrong, so the undone hunk no longer applies back. + base = ("def two():\n return 1\n" + "".join(f"# padding line {i}\n" for i in range(10)) + + "\ndef spare():\n return 5\n") + test = Python.TEST.replace( + " def test_two(self):\n", + " def test_two(self):\n if bar.two() != 2:\n" + " with open(bar.__file__, 'w', encoding='utf-8', newline='\\n') as f:\n" + " f.write('def two():\\n return 3\\n')\n") + repo = Repo(self) + repo.commit("base", {"tools/bar.py": base}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"tools/bar.py": base.replace("return 1", "return 2").replace("return 5", "return 6"), + "tests/test_bar.py": test}) + code, r, _ = repo.run("--no-cargo", "--mutate") + self.assertEqual((code, r["verdict"]), (0, "red then green"), r) + self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught")]) + stop = r["mutations_stopped"] + self.assertEqual((stop["file"], stop["line"], stop["untried"]), ("tools/bar.py", 2, 1), stop) + self.assertIn("could not put the hunk back", stop["why"]) + self.assertIn("mutations stopped at tools/bar.py:2: git apply could not put the hunk back", rg.report(r)) + self.assertIn("hunks not tried: 1", rg.report(r)) + 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_test_only_pull_request_has_nothing_to_undo(self): + repo = Repo(self) + repo.commit("base", {"tools/bar.py": "def two():\n return 2\n"}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("test", {"tests/test_bar.py": Python.TEST}) + code, r, _ = repo.run("--no-cargo", "--mutate") + # The verdict and exit code are those of any test that passes on both. + self.assertEqual((code, r["verdict"]), (1, "no red"), r) + self.assertEqual(r["mutations"], []) + self.assertEqual(r["mutations_not_run"], "nothing to undo: the diff changes no Rust or Python code outside its " + "tests") + self.assertIn("mutations: nothing to undo: the diff changes no Rust or Python code outside its tests", + rg.report(r)) + + def test_code_with_no_test_gone_red_is_not_mutated_and_said_so(self): + repo = Repo(self) + repo.commit("base", {"tools/bar.py": "def two():\n return 2\n\n\ndef three():\n return 3\n"}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("change", {"tools/bar.py": "def two():\n return 2\n\n\ndef three():\n return 4\n", + "tests/test_bar.py": Python.TEST}) + code, r, _ = repo.run("--no-cargo", "--mutate") + self.assertEqual((code, r["verdict"]), (1, "no red"), r) + self.assertEqual(r["mutations"], []) + self.assertIn("mutations: not run: no test went red then green", rg.report(r)) + + def test_files_the_pull_request_adds_are_listed_as_not_mutated(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/helper.py": "def value():\n return 2\n", + "tools/bar.py": "from helper import value\n\n\ndef two():\n return value()\n", + "tests/test_bar.py": Python.TEST}) + code, r, _ = repo.run("--no-cargo", "--mutate") + self.assertEqual((code, r["verdict"]), (0, "red then green"), r) + self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], + [("tools/bar.py", "caught"), ("tools/bar.py", "caught")]) + # helper.py holds the change and is never undone: the report says so rather than read as full coverage. + self.assertEqual(r["added_not_mutated"], ["tools/helper.py"]) + self.assertIn("not mutated, added by the pull request: tools/helper.py", rg.report(r)) + def test_no_mutation_without_the_option(self): repo = Repo(self) repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"}) @@ -332,6 +398,7 @@ class Mutation(unittest.TestCase): 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"]) + self.assertNotIn("mutations", rg.report(r)) class CompilerCrash(unittest.TestCase): -- cgit v1.2.3 From 3b3e5ee5dadd0e028d4d6a63186ea57830d0f4bf Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:12:01 +0100 Subject: docs/testing.md: red_green.py --work-dir leaves its worktree registered; git worktree remove /tree removes it (review) --- docs/testing.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'docs/testing.md') diff --git a/docs/testing.md b/docs/testing.md index a7b1b4ea9..4ec81fec6 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -148,7 +148,8 @@ python -I scripts/red_green.py removing the worktree's `__pycache__` folders so that no test runs stale bytecode. Both sides run in one worktree with one cargo target dir, red first, under `/red-green` (`--work-dir` to move it). The worktree and the target dir stay for the next run, which then builds only what changed. The target dir takes several GB; - delete the folder (and run `git worktree prune`) when done. + delete the folder (and run `git worktree prune`) when done. With `--work-dir `, the worktree stays registered + in git: `git worktree remove /tree` removes it, then delete ``. - 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`, -- cgit v1.2.3 From 312bf7c892aab1838980385edb039d47ff1c00de Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:49:46 +0100 Subject: scripts: red_green.py stops what a mutated run leaves behind, so an orphan holding its output does not hold the run (review) taskkill /T on a command that has already ended finds no tree: a child it left behind kept the output pipe open, the run waited for the timeout and a real caught read caught by timeout. A mutated run now writes its output to a temporary file and, on Windows, runs in a job object (kill on close) that its children join; once the command ends or times out, the job (the process group elsewhere) is stopped. --- docs/testing.md | 3 +- scripts/red_green.py | 92 +++++++++++++++++++++++++++++++++++++------------ tests/test_red_green.py | 42 +++++++++++++++------- 3 files changed, 102 insertions(+), 35 deletions(-) (limited to 'docs/testing.md') diff --git a/docs/testing.md b/docs/testing.md index 4ec81fec6..c0d1d7c49 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -174,7 +174,8 @@ python -I scripts/red_green.py `mutations_stopped` and `added_not_mutated`. - Each command of a mutated run (`cargo test`, one Python test file) is stopped with the processes it started after `--mutate-timeout` seconds (600), and the hunk is `caught by timeout`: the undone code made a test hang, or the - build took longer than that (raise the option for a crate that builds slowly). + build took longer than that (raise the option for a crate that builds slowly). When the command ends, the + processes it left behind are stopped too (a Windows job object, the process group elsewhere). - `--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 db2320f8d..f4eec79c6 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -56,40 +56,88 @@ def run(args: list[str], cwd: Path, env: dict | None = None, data: bytes | None return subprocess.run(args, cwd=cwd, env=env, input=data, capture_output=True) -def kill_tree(p: subprocess.Popen) -> None: - """Stops `p` and the processes it started (a test binary under cargo, a process a test starts).""" - if os.name == "nt": - subprocess.run(["taskkill", "/F", "/T", "/PID", str(p.pid)], capture_output=True) - else: +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 - p.kill() + 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`. Past `timeout` seconds it is stopped with the - processes it started, whose copies of the output pipe would hold the read open, and the exit code is None.""" + """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") - p = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, - start_new_session=os.name != "nt") - try: - out, _ = p.communicate(timeout=timeout) - except subprocess.TimeoutExpired: - kill_tree(p) + 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: - out, _ = p.communicate(timeout=60) - except subprocess.TimeoutExpired: # a process outside the tree still holds the pipe: leave its output - out = b"" - return None, out.decode("utf-8", "replace") - except BaseException: # Ctrl+C: on POSIX the new session keeps it from the processes started - kill_tree(p) - raise - return p.returncode, out.decode("utf-8", "replace") + 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: diff --git a/tests/test_red_green.py b/tests/test_red_green.py index cfdf1b20d..a3e724a37 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -337,22 +337,28 @@ class Mutation(unittest.TestCase): 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_a_mutated_run_that_hangs_is_caught_by_timeout(self): - # Undone alone, the second hunk makes the test start a process that sleeps. Red has neither hunk, so it does - # not hang there. - base = ("def two():\n return 1\n" + "".join(f"# padding line {i}\n" for i in range(10)) - + "\ndef settled():\n return False\n") + # tools/bar.py with two hunks far apart, two() at line 2 (the fix) and settled() at line 15; a test of two(). + BAR = ("def two():\n return 1\n" + "".join(f"# padding line {i}\n" for i in range(10)) + + "\ndef settled():\n return False\n") + + def bar_repo(self, body, base_files=None): test = ("import os, subprocess, sys, unittest\n" - "sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'tools'))\n" - "import bar\n\n\nclass T(unittest.TestCase):\n def test_two(self):\n" - " if bar.two() == 2 and not bar.settled():\n" - " subprocess.run([sys.executable, '-c', 'import time; time.sleep(120)'])\n" - " self.assertEqual(bar.two(), 2)\n") + "tools = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'tools')\n" + "sys.path.insert(0, tools)\n" + "import bar\n\n\nclass T(unittest.TestCase):\n def test_two(self):\n" + body + + " self.assertEqual(bar.two(), 2)\n") repo = Repo(self) - repo.commit("base", {"tools/bar.py": base}) + repo.commit("base", {"tools/bar.py": self.BAR, **(base_files or {})}) repo.git("switch", "-q", "-c", "pr") - repo.commit("fix", {"tools/bar.py": base.replace("return 1", "return 2").replace("False", "True"), + repo.commit("fix", {"tools/bar.py": self.BAR.replace("return 1", "return 2").replace("False", "True"), "tests/test_bar.py": test}) + return repo + + def test_a_mutated_run_that_hangs_is_caught_by_timeout(self): + # Undone alone, the second hunk makes the test start a process that sleeps. Red has neither hunk, so it does + # not hang there. + repo = self.bar_repo(" if bar.two() == 2 and not bar.settled():\n" + " subprocess.run([sys.executable, '-c', 'import time; time.sleep(120)'])\n") start = time.monotonic() _code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-timeout", "5") self.assertEqual(r["verdict"], "red then green", r) @@ -361,6 +367,18 @@ class Mutation(unittest.TestCase): # The sleeping process was stopped with the test's: left running, it would hold the output pipe for 120 s. self.assertLess(time.monotonic() - start, 60) + def test_a_process_left_behind_does_not_hold_a_mutated_run(self): + # Undone alone, the fix makes the test leave a process behind that outlives it with its output; the test still + # fails, so the hunk is caught, as soon as the test ends and not when the timeout runs out. (Kept in T, so + # that no ResourceWarning cuts the test's line in the verbose output.) + repo = self.bar_repo(" if bar.two() != 2 and bar.settled():\n" + " T.left = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)'])\n") + start = time.monotonic() + _code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-timeout", "20") + self.assertEqual(r["verdict"], "red then green", r) + self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "not caught")]) + self.assertLess(time.monotonic() - start, 20) + def test_a_hunk_that_cannot_be_put_back_stops_the_mutations_and_says_where(self): # The test writes over the code it tests when it finds it wrong, so the undone hunk no longer applies back. base = ("def two():\n return 1\n" + "".join(f"# padding line {i}\n" for i in range(10)) -- cgit v1.2.3 From 29712017c4c22eb61368504932e5844328b01868 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:52:03 +0100 Subject: scripts: red_green.py starts each mutation from a commit of the green merge, reset and cleaned (review) A put-back that applies did not prove the tree green again: a test that wrote into a tracked file changed the result of the next hunk. The green merge is now committed with the tool's identity before its tests run, and each mutation resets the tree to it and cleans it before undoing its hunk. A hunk can no longer fail to go back, so mutations_stopped and its test are gone; a test that dirties the tree now has its own. --- docs/testing.md | 7 +++---- scripts/red_green.py | 34 +++++++++++++++------------------- tests/test_red_green.py | 30 ++++++++++-------------------- 3 files changed, 28 insertions(+), 43 deletions(-) (limited to 'docs/testing.md') diff --git a/docs/testing.md b/docs/testing.md index c0d1d7c49..301f12888 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -163,15 +163,14 @@ python -I scripts/red_green.py 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 + lines since). Each mutation starts from the green tree, reset and cleaned, so what a test writes into the tree + changes no other. 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. - Files the pull request adds are not mutated: undoing one would delete it, which only shows that something uses it. The report lists them (`not mutated, added by the pull request`), so a fix whose code sits in a new file is not read as covered. When no hunk is undone, the report says why: `nothing to undo` when the pull request changes no Rust or Python code outside its tests (a test-only one, whose `no red` then says nothing against its test), or - `not run` when no test went red then green. A hunk that cannot be put back (a test wrote into the code) stops the - mutations, and the report names that hunk and the reason. `--json` has these in `mutations_not_run`, - `mutations_stopped` and `added_not_mutated`. + `not run` when no test went red then green. `--json` has these in `mutations_not_run` and `added_not_mutated`. - Each command of a mutated run (`cargo test`, one Python test file) is stopped with the processes it started after `--mutate-timeout` seconds (600), and the hunk is `caught by timeout`: the undone code made a test hang, or the build took longer than that (raise the option for a crate that builds slowly). When the command ends, the diff --git a/scripts/red_green.py b/scripts/red_green.py index f4eec79c6..a08344ed6 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -544,10 +544,6 @@ def report(r: dict) -> str: 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"]] - stop = r.get("mutations_stopped") - if stop: - out.append(f"mutations stopped at {stop['file']}:{stop['line']}: {stop['why']}; " - f"hunks not tried: {stop['untried']}") 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']}") @@ -627,18 +623,21 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer print("red_green: red side...", file=sys.stderr) red = side(tree, crates, py_files, a.cargo, target) - green, green_why = None, None + 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, stopped, added = None, None, None, None + mutations, not_run, added = 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: @@ -650,14 +649,14 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer 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, stopped = mutate(tree, hunks[:a.mutate_max], rows["red_to_green"], crates, py_files, a.cargo, - target, a.mutate_timeout) + mutations = mutate(tree, green_commit, hunks[:a.mutate_max], rows["red_to_green"], crates, py_files, + a.cargo, target, a.mutate_timeout) 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_stopped": stopped, "added_not_mutated": added, + "mutations_not_run": not_run, "added_not_mutated": added, "verdict": verdict(red_why, green_why, red, green, rows)} @@ -705,14 +704,16 @@ def code_hunks(repo: Path, merge_base: str, head: str) -> list[tuple[str, int, s return out -def mutate(tree: Path, hunks: list[tuple[str, int, str]], targets: list[str], crates: list[str], py_files: list[str], - cargo: str, target: Path, timeout: float) -> tuple[list[dict], dict | None]: +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. Stops at a hunk - that cannot be put back (a test wrote into the code): the second value says where and why.""" + 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" @@ -730,12 +731,7 @@ def mutate(tree: Path, hunks: list[tuple[str, int, str]], targets: list[str], cr else: entry["result"] = "not caught" results.append(entry) - back = run(["git", "apply", "--unidiff-zero", "-"], tree, data=patch.encode()) - if back.returncode != 0: - why = back.stderr.decode("utf-8", "replace").strip().splitlines() - return results, {"file": path, "line": line, "untried": len(hunks) - len(results), - "why": "git apply could not put the hunk back" + (f" ({why[-1]})" if why else "")} - return results, None + return results if __name__ == "__main__": diff --git a/tests/test_red_green.py b/tests/test_red_green.py index a3e724a37..41b18101c 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -379,28 +379,18 @@ class Mutation(unittest.TestCase): self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "not caught")]) self.assertLess(time.monotonic() - start, 20) - def test_a_hunk_that_cannot_be_put_back_stops_the_mutations_and_says_where(self): - # The test writes over the code it tests when it finds it wrong, so the undone hunk no longer applies back. - base = ("def two():\n return 1\n" + "".join(f"# padding line {i}\n" for i in range(10)) - + "\ndef spare():\n return 5\n") - test = Python.TEST.replace( - " def test_two(self):\n", - " def test_two(self):\n if bar.two() != 2:\n" - " with open(bar.__file__, 'w', encoding='utf-8', newline='\\n') as f:\n" - " f.write('def two():\\n return 3\\n')\n") - repo = Repo(self) - repo.commit("base", {"tools/bar.py": base}) - repo.git("switch", "-q", "-c", "pr") - repo.commit("fix", {"tools/bar.py": base.replace("return 1", "return 2").replace("return 5", "return 6"), - "tests/test_bar.py": test}) + def test_a_test_that_dirties_the_tree_does_not_change_the_next_hunk(self): + # When it finds two() wrong, the test writes into a tracked file that it also checks. Each mutation starts from + # the green tree, so the second hunk (settled(), which no test looks at) is not caught for that. + repo = self.bar_repo(" flag = os.path.join(tools, 'flag.txt')\n" + " if bar.two() != 2:\n" + " with open(flag, 'w', encoding='utf-8', newline='\\n') as f:\n" + " f.write('dirty\\n')\n" + " with open(flag, encoding='utf-8') as f:\n" + " self.assertEqual(f.read(), 'clean\\n')\n", {"tools/flag.txt": "clean\n"}) code, r, _ = repo.run("--no-cargo", "--mutate") self.assertEqual((code, r["verdict"]), (0, "red then green"), r) - self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught")]) - stop = r["mutations_stopped"] - self.assertEqual((stop["file"], stop["line"], stop["untried"]), ("tools/bar.py", 2, 1), stop) - self.assertIn("could not put the hunk back", stop["why"]) - self.assertIn("mutations stopped at tools/bar.py:2: git apply could not put the hunk back", rg.report(r)) - self.assertIn("hunks not tried: 1", rg.report(r)) + self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "not caught")]) 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, "") -- cgit v1.2.3 From 4a0aa701d04616e4b2024f90390f67b2ba576bac Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:54:50 +0100 Subject: scripts: red_green.py lists the hunks --mutate-max leaves out (review) With more code hunks than --mutate-max, the report read as if every hunk was tried. The hunks left out are now in --json (mutations_skipped, file and line) and in the text (not tried, past --mutate-max). --- docs/testing.md | 5 +++-- scripts/red_green.py | 8 ++++++-- tests/test_red_green.py | 14 ++++++++++++++ 3 files changed, 23 insertions(+), 4 deletions(-) (limited to 'docs/testing.md') diff --git a/docs/testing.md b/docs/testing.md index 301f12888..339283e1b 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -164,8 +164,9 @@ python -I scripts/red_green.py 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). Each mutation starts from the green tree, reset and cleaned, so what a test writes into the tree - changes no other. 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. + changes no other. It tries at most `--mutate-max` hunks (10) and lists the others as `not tried, past + --mutate-max` (`mutations_skipped` in `--json`). A `not caught` hunk is code no new test looks at; it does not + change the verdict. - Files the pull request adds are not mutated: undoing one would delete it, which only shows that something uses it. The report lists them (`not mutated, added by the pull request`), so a fix whose code sits in a new file is not read as covered. When no hunk is undone, the report says why: `nothing to undo` when the pull request changes no diff --git a/scripts/red_green.py b/scripts/red_green.py index 3e2e2726d..8d748d534 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -551,6 +551,9 @@ def report(r: dict) -> str: 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']}") @@ -644,7 +647,7 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer 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, added = None, None, None + 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: @@ -658,12 +661,13 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer 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, "added_not_mutated": added, + "mutations_not_run": not_run, "mutations_skipped": skipped, "added_not_mutated": added, "verdict": verdict(red_why, green_why, red, green, rows)} diff --git a/tests/test_red_green.py b/tests/test_red_green.py index ff8928b6e..49bc7b188 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -413,6 +413,20 @@ class Mutation(unittest.TestCase): status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout self.assertEqual(status, "") + def test_hunks_past_mutate_max_are_listed_as_not_tried(self): + base = "".join(f"def f{n}():\n return 1\n" + "# padding\n" * 4 for n in range(1, 5)) + test = Python.TEST.replace("bar.two(), 2", "bar.f1(), 2") + repo = Repo(self) + repo.commit("base", {"tools/bar.py": base}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"tools/bar.py": base.replace("return 1", "return 2"), "tests/test_bar.py": test}) + code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-max", "2") + self.assertEqual((code, r["verdict"]), (0, "red then green"), r) + self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (8, "not caught")]) + self.assertEqual(r["mutations_skipped"], [{"file": "tools/bar.py", "line": 14}, + {"file": "tools/bar.py", "line": 20}]) + self.assertIn("not tried, past --mutate-max: tools/bar.py:14, tools/bar.py:20", rg.report(r)) + def test_a_test_only_pull_request_has_nothing_to_undo(self): repo = Repo(self) repo.commit("base", {"tools/bar.py": "def two():\n return 2\n"}) -- cgit v1.2.3 From fc0ce37ac47d4e0c57308bf24ced4a090ecbe1ea Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:57:39 +0100 Subject: 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. --- docs/testing.md | 7 ++++--- scripts/red_green.py | 24 +++++++++++++++--------- tests/test_red_green.py | 25 +++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 12 deletions(-) (limited to 'docs/testing.md') diff --git a/docs/testing.md b/docs/testing.md index 339283e1b..becb61310 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -173,9 +173,10 @@ python -I scripts/red_green.py Rust or Python code outside its tests (a test-only one, whose `no red` then says nothing against its test), or `not run` when no test went red then green. `--json` has these in `mutations_not_run` and `added_not_mutated`. - Each command of a mutated run (`cargo test`, one Python test file) is stopped with the processes it started after - `--mutate-timeout` seconds (600), and the hunk is `caught by timeout`: the undone code made a test hang, or the - build took longer than that (raise the option for a crate that builds slowly). When the command ends, the - processes it left behind are stopped too (a Windows job object, the process group elsewhere). + `--mutate-timeout` seconds (600). The hunk is then `caught by timeout` when a test was running (the undone code + made it hang), or `timed out building` when cargo had not started a test yet, which says nothing about the tests + (raise the option for a crate that builds slowly). When the command ends, the processes it left behind are + stopped too (a Windows job object, the process group elsewhere). - `--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 8d748d534..d487d9315 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -383,11 +383,11 @@ def cargo_once(tree: Path, crates: list[str], cargo: str, target: Path, timeout: 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 = {}, "?", None + tests, unit, error, ran = {}, "?", None, False for line in out.splitlines(): m = UNIT.match(line) if m: - unit = m.group(1) or "doc:" + m.group(2) + unit, ran = m.group(1) or "doc:" + m.group(2), True continue m = CARGO_TEST.match(line) if m: @@ -396,8 +396,10 @@ def cargo_once(tree: Path, crates: list[str], cargo: str, target: Path, timeout: 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": code is 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: @@ -436,14 +438,15 @@ def drop_bytecode(tree: Path) -> None: def python_tests(tree: Path, files: list[str], timeout: float | None) -> dict: - tests, no_build, timed_out = {}, [], False + 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) - timed_out |= code is None + if code is None: + timed_out = "running" found = 0 for name, where, status in PY_TEST.findall(out): if "_FailedTest" in where: @@ -460,9 +463,10 @@ def python_tests(tree: Path, files: list[str], timeout: float | None) -> dict: 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 the side is marked `timed_out`.""" + 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": False} + 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"]) @@ -576,8 +580,8 @@ def main(argv: list[str] | None = None) -> int: 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 and count " - "the hunk as caught by timeout (600)") + 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")) @@ -727,6 +731,8 @@ def mutate(tree: Path, green: str, hunks: list[tuple[str, int, str]], targets: l 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): diff --git a/tests/test_red_green.py b/tests/test_red_green.py index 49bc7b188..04d996cc8 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -69,6 +69,18 @@ runpy.run_path(os.path.join(here, "cargo_stub.py"), run_name="__main__") ''' +def hang_stub(repo, where): + """STUB_CARGO that sleeps when value() is 2 and spare() is 5 (Mutation.BASE's second hunk undone alone): before + its `Running` line, as a build that hangs, or after it, as a test that hangs.""" + hang = "sys.stdout.flush()\nif fns.get('value') == '2' and fns.get('spare') == '5':\n __import__('time').sleep(120)\n" + text = STUB_CARGO.replace('print(" Running', (hang if where == "build" else "") + 'print(" Running') + text = text.replace("failed = False\n", "failed = False\n" + (hang if where == "test" else "")) + path = os.path.join(repo.tmp.name, f"cargo_hang_{where}.py") + with open(path, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + return path + + class Repo: def crash_stub(self, mode): path = os.path.join(self.tmp.name, f"cargo_crash_{mode}.py") @@ -328,6 +340,19 @@ class Mutation(unittest.TestCase): status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout self.assertEqual(status, "") + def test_a_cargo_run_that_hangs_is_stopped_and_said_where(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);")}) + # A test binary that hangs is caught; a build that hangs (no `Running` line yet) is no answer. + for where, result in (("test", "caught by timeout"), ("build", "timed out building")): + _code, r, _ = repo.run("--mutate", "--mutate-timeout", "5", "--cargo", hang_stub(repo, where)) + self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (17, result)], where) + def test_a_hunk_that_only_deletes_a_test_is_not_mutated(self): # The pull request also deletes an obsolete test: a hunk of test code only, like the one that renames the # other test. Neither is mutated; only the fix is. -- cgit v1.2.3 From 2051ccd0aadb43ef42aa3fe3cf7bd5a1d43fde1d Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:59:33 +0100 Subject: docs/testing.md: red_green.py --mutate results include compiler crashed; one way to remove the worktree, default folder or --work-dir (review) --- docs/testing.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'docs/testing.md') diff --git a/docs/testing.md b/docs/testing.md index becb61310..11b184ff4 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -147,9 +147,9 @@ python -I scripts/red_green.py from `d3d12/` so the pinned toolchain applies. It also runs each changed `tests/**/test*.py` with unittest, after removing the worktree's `__pycache__` folders so that no test runs stale bytecode. Both sides run in one worktree with one cargo target dir, red first, under `/red-green` (`--work-dir` to move it). The worktree - and the target dir stay for the next run, which then builds only what changed. The target dir takes several GB; - delete the folder (and run `git worktree prune`) when done. With `--work-dir `, the worktree stays registered - in git: `git worktree remove /tree` removes it, then delete ``. + and the target dir stay for the next run, which then builds only what changed. The target dir takes several GB. + The worktree stays registered in git, in the default folder as with `--work-dir`: when done, run + `git worktree remove --force /tree` and delete the folder, or delete the folder and run `git worktree prune`. - 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`, @@ -162,9 +162,9 @@ python -I scripts/red_green.py - `--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). Each mutation starts from the green tree, reset and cleaned, so what a test writes into the tree - changes no other. It tries at most `--mutate-max` hunks (10) and lists the others as `not tried, past + then green fails, `not caught` when they all still pass, `does not build` when those tests no longer run, + `compiler crashed` when the compiler crashed twice, or `does not apply` when `main` moved those lines since. Each + mutation starts from the green tree, reset and cleaned, so what a test writes into the tree changes no other. It tries at most `--mutate-max` hunks (10) and lists the others as `not tried, past --mutate-max` (`mutations_skipped` in `--json`). A `not caught` hunk is code no new test looks at; it does not change the verdict. - Files the pull request adds are not mutated: undoing one would delete it, which only shows that something uses it. -- cgit v1.2.3 From bf65aa4505aeccd8feb9bfca2c93a33d103747c8 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:19:38 +0100 Subject: scripts: red_green.py skips a folder it cannot list, stops with the tree put back on a __pycache__ it cannot remove, and four smaller fixes (review) drop_bytecode skips a folder it may not list (Python cannot import from it either). A __pycache__ it cannot remove is now a usage error naming it (exit 2), and any such error during a run puts the tree back on the base, where before the undone hunk stayed. --mutate-timeout must also be finite. In a mutated run, a Python test stopped while running outweighs a cargo build that was stopped. job_of says once on stderr when it has no job object. docs/testing.md: one line rewrapped. --- docs/testing.md | 7 ++-- scripts/red_green.py | 65 +++++++++++++++++++++++++----------- tests/test_red_green.py | 87 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 137 insertions(+), 22 deletions(-) (limited to 'docs/testing.md') diff --git a/docs/testing.md b/docs/testing.md index 11b184ff4..31ab93653 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -164,9 +164,10 @@ python -I scripts/red_green.py 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` when those tests no longer run, `compiler crashed` when the compiler crashed twice, or `does not apply` when `main` moved those lines since. Each - mutation starts from the green tree, reset and cleaned, so what a test writes into the tree changes no other. It tries at most `--mutate-max` hunks (10) and lists the others as `not tried, past - --mutate-max` (`mutations_skipped` in `--json`). A `not caught` hunk is code no new test looks at; it does not - change the verdict. + mutation starts from the green tree, reset and cleaned, so what a test writes into the tree changes no other. It + tries at most `--mutate-max` hunks (10) and lists the others as `not tried, past --mutate-max` + (`mutations_skipped` in `--json`). A `not caught` hunk is code no new test looks at; it does not change the + verdict. - Files the pull request adds are not mutated: undoing one would delete it, which only shows that something uses it. The report lists them (`not mutated, added by the pull request`), so a fix whose code sits in a new file is not read as covered. When no hunk is undone, the report says why: `nothing to undo` when the pull request changes no diff --git a/scripts/red_green.py b/scripts/red_green.py index ec6c31d49..e15b1c23f 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -31,6 +31,7 @@ from __future__ import annotations import argparse import json +import math import os import re import shutil @@ -81,25 +82,33 @@ if os.name == "nt": _KERNEL32.CloseHandle.argtypes = (wintypes.HANDLE,) +_JOB_WARNED = False # job_of() says once that it has no job object + + 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.""" + stays out. Without one, it says so on stderr once.""" + global _JOB_WARNED 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 + handle = job and _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)) + error = ctypes.get_last_error() if handle: _KERNEL32.CloseHandle(handle) - if not joined: + if joined: + return job + if job: _KERNEL32.CloseHandle(job) - return None - return job + if not _JOB_WARNED: + _JOB_WARNED = True + print(f"red_green: no Windows job object for the mutated runs (error {error}): a process one leaves behind " + "is not stopped", file=sys.stderr) + return None def stop_all(p: subprocess.Popen, job) -> None: @@ -424,18 +433,26 @@ def drop_bytecode(tree: Path) -> None: 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.""" + `is_symlink()` does not see) are neither followed nor removed: what they point at is not the tree's. A folder it + cannot list is skipped: Python cannot import from it either. A `__pycache__` it cannot remove stops the run.""" folders, todo = [], [tree] while todo: - with os.scandir(todo.pop()) as entries: - for e in entries: - if not e.is_dir(follow_symlinks=False) or e.is_symlink(): - continue - if getattr(e.stat(follow_symlinks=False), "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT: - continue # a junction (Windows) - (folders if e.name == "__pycache__" else todo).append(e.path) + try: + with os.scandir(todo.pop()) as entries: + for e in entries: + if not e.is_dir(follow_symlinks=False) or e.is_symlink(): + continue + if getattr(e.stat(follow_symlinks=False), "st_file_attributes", 0) \ + & stat.FILE_ATTRIBUTE_REPARSE_POINT: + continue # a junction (Windows) + (folders if e.name == "__pycache__" else todo).append(e.path) + except OSError: + continue for folder in folders: - shutil.rmtree(folder) + try: + shutil.rmtree(folder) + except OSError as e: + raise Failure(f"cannot remove {folder}, whose bytecode could run instead of the code: {e}") from None def python_tests(tree: Path, files: list[str], timeout: float | None) -> dict: @@ -473,8 +490,10 @@ def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target: 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"): + for key in ("compiler_crashed", "rerun_after"): result[key] = result[key] or part.get(key) + if part.get("timed_out") and result["timed_out"] != "running": # a test stopped running outweighs a build + result["timed_out"] = part["timed_out"] return result @@ -588,8 +607,8 @@ def main(argv: list[str] | None = None) -> int: p.error("--mutate-max and --mutate-timeout go with --mutate") if a.mutate_max is not None and a.mutate_max < 1: p.error("--mutate-max must be 1 or more") - if a.mutate_timeout is not None and not a.mutate_timeout > 0: # NaN too - p.error("--mutate-timeout must be more than 0 seconds") + if a.mutate_timeout is not None and not (math.isfinite(a.mutate_timeout) and a.mutate_timeout > 0): + p.error("--mutate-timeout must be a number of seconds above 0") a.mutate_max = 10 if a.mutate_max is None else a.mutate_max a.mutate_timeout = 600.0 if a.mutate_timeout is None else a.mutate_timeout try: @@ -615,6 +634,14 @@ def main(argv: list[str] | None = None) -> int: os.close(fd) try: result = check(repo, work, a, base, base_commit, head, merge_base) + except Failure: + # Stopped midway (a side, a mutation): the tree goes back on the base, as at the end of a run. + if (work / "tree" / ".git").exists(): + try: + checkout(repo, work / "tree", base_commit) + except Failure: + pass + raise finally: lock.unlink(missing_ok=True) except Failure as e: diff --git a/tests/test_red_green.py b/tests/test_red_green.py index 84d09d49b..85ccae0ee 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -10,6 +10,7 @@ import time import unittest from contextlib import redirect_stderr, redirect_stdout from pathlib import Path +from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "scripts")) @@ -280,6 +281,24 @@ class Python(unittest.TestCase): "tests/test_bar.py::test_bar.T.test_two_in_a_child"]) self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], [("tools/bar.py", "caught")]) + def test_bytecode_it_cannot_remove_stops_the_run_with_the_tree_put_back(self): + repo = Repo(self) + repo.commit("base", {".gitignore": "__pycache__/\n", "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": self.TEST}) + self.assertEqual(repo.run("--no-cargo")[1]["verdict"], "red then green") + tree = os.path.join(repo.dir, ".git", "red-green", "tree") + cache = os.path.join(tree, "tools", "__pycache__") + os.makedirs(cache, exist_ok=True) + block_removal(self, cache) + code, r, err = repo.run("--no-cargo") + self.assertEqual((code, r), (2, None), err) + self.assertIn("cannot remove", err) + self.assertIn(os.path.join("tools", "__pycache__"), err) + # The red side had begun: the tree is back on the base all the same. + status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout + self.assertEqual(status, "") + def link_dir(test, link, target): """A directory junction on Windows (no privilege needed), a symbolic link elsewhere; removed at the end of `test` @@ -292,6 +311,34 @@ def link_dir(test, link, target): test.addCleanup(os.unlink, link) +def deny_listing(test, folder): + """Takes away the right to list `folder` (a deny entry for Everyone on Windows, mode 0 elsewhere) until the end of + `test`.""" + if os.name == "nt": + subprocess.run(["icacls", folder, "/deny", "*S-1-1-0:(RD)"], check=True, capture_output=True) + test.addCleanup(subprocess.run, ["icacls", folder, "/remove:d", "*S-1-1-0"], check=True, capture_output=True) + else: + if os.geteuid() == 0: + test.skipTest("root lists any folder") + os.chmod(folder, 0) + test.addCleanup(os.chmod, folder, 0o700) + + +def block_removal(test, folder): + """Keeps `folder` from being removed until the end of `test`: a file in it held open on Windows, the folder + read-only elsewhere.""" + path = os.path.join(folder, "held.pyc") + if os.name == "nt": + held = open(path, "wb") + test.addCleanup(held.close) + else: + if os.geteuid() == 0: + test.skipTest("root removes any file") + open(path, "wb").close() + os.chmod(folder, 0o500) + test.addCleanup(os.chmod, folder, 0o700) + + class DropBytecode(unittest.TestCase): def setUp(self): tmp = tempfile.TemporaryDirectory(prefix="red-green-test-", ignore_cleanup_errors=True) @@ -315,6 +362,23 @@ class DropBytecode(unittest.TestCase): link_dir(self, os.path.join(self.tree, "__pycache__"), os.path.join(self.outside, "__pycache__")) self.check() + def test_a_folder_it_cannot_list_is_skipped(self): + locked = os.path.join(self.tree, "locked") + os.makedirs(os.path.join(locked, "__pycache__")) + deny_listing(self, locked) + self.check() + + +@unittest.skipUnless(os.name == "nt", "job objects are Windows'") +class Job(unittest.TestCase): + def test_a_job_object_that_cannot_be_joined_is_said_once(self): + err = io.StringIO() + with mock.patch.object(rg._KERNEL32, "AssignProcessToJobObject", return_value=0), \ + mock.patch.object(rg, "_JOB_WARNED", False, create=True), redirect_stderr(err): + runs = [rg.run_output([sys.executable, "-c", "print(1)"], Path(ROOT), timeout=60) for _ in range(2)] + self.assertEqual([(code, out.strip()) for code, out in runs], [(0, "1"), (0, "1")]) + self.assertEqual(err.getvalue().count("no Windows job object"), 1, err.getvalue()) + class Mutation(unittest.TestCase): # Two code changes far enough apart to be two hunks: the tested one and one no test looks at. @@ -353,6 +417,28 @@ class Mutation(unittest.TestCase): _code, r, _ = repo.run("--mutate", "--mutate-timeout", "5", "--cargo", hang_stub(repo, where)) self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (17, result)], where) + def test_a_test_stopped_running_outweighs_a_build_stopped(self): + # Undone alone, the second hunk makes cargo hang in its build and a Python test hang while running: the hunk + # is caught by timeout, since a test did hang. + watch = ("import os, time, unittest\n\n\nclass T(unittest.TestCase):\n def test_lib(self):\n" + " root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n" + " with open(os.path.join(root, 'd3d12', 'crates', 'foo', 'src', 'lib.rs'), encoding='utf-8') as f:\n" + " text = f.read()\n" + " if ' 2\\n' in text and ' 5\\n' in text:\n" + " time.sleep(120)\n") + 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", {"tests/test_watch.py": watch, + "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", "--mutate-timeout", "5", "--cargo", hang_stub(repo, "build")) + self.assertEqual(r["verdict"], "red then green", r) + self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (17, "caught by timeout")]) + def test_a_hunk_that_only_deletes_a_test_is_not_mutated(self): # The pull request also deletes an obsolete test: a hunk of test code only, like the one that renames the # other test. Neither is mutated; only the fix is. @@ -514,6 +600,7 @@ class Mutation(unittest.TestCase): for args, why in ((["--mutate", "--mutate-max", "0"], "--mutate-max"), (["--mutate", "--mutate-timeout", "0"], "--mutate-timeout"), (["--mutate", "--mutate-timeout", "nan"], "--mutate-timeout"), + (["--mutate", "--mutate-timeout", "inf"], "--mutate-timeout"), (["--mutate-max", "3"], "--mutate"), (["--mutate-timeout", "60"], "--mutate")): err = io.StringIO() with redirect_stderr(err), self.assertRaises(SystemExit) as stop: -- cgit v1.2.3