diff options
Diffstat (limited to 'scripts/red_green.py')
| -rw-r--r-- | scripts/red_green.py | 347 |
1 files changed, 307 insertions, 40 deletions
diff --git a/scripts/red_green.py b/scripts/red_green.py index 7d8305f45..e15b1c23f 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py | |||
| @@ -3,6 +3,7 @@ | |||
| 3 | 3 | ||
| 4 | python -I scripts/red_green.py <pull request number | git ref> [--base REF] [--remote NAME] [--no-fetch] | 4 | python -I scripts/red_green.py <pull request number | git ref> [--base REF] [--remote NAME] [--no-fetch] |
| 5 | [--work-dir DIR] [--crate NAME ...] [--no-cargo] [--no-python] [--cargo PATH] [--json] | 5 | [--work-dir DIR] [--crate NAME ...] [--no-cargo] [--no-python] [--cargo PATH] [--json] |
| 6 | [--mutate [--mutate-max N] [--mutate-timeout SECONDS]] | ||
| 6 | 7 | ||
| 7 | Green is the base (`<remote>/main` after a fetch, by default) with the pull request merged. Red is the base with | 8 | Green is the base (`<remote>/main` after a fetch, by default) with the pull request merged. Red is the base with |
| 8 | only the pull request's tests. A test that fails on red and passes on green shows that the change is what makes it | 9 | only the pull request's tests. A test that fails on red and passes on green shows that the change is what makes it |
| @@ -30,11 +31,16 @@ from __future__ import annotations | |||
| 30 | 31 | ||
| 31 | import argparse | 32 | import argparse |
| 32 | import json | 33 | import json |
| 34 | import math | ||
| 33 | import os | 35 | import os |
| 34 | import re | 36 | import re |
| 37 | import shutil | ||
| 38 | import signal | ||
| 39 | import stat | ||
| 35 | import subprocess | 40 | import subprocess |
| 36 | import sys | 41 | import sys |
| 37 | import tempfile | 42 | import tempfile |
| 43 | from collections import Counter | ||
| 38 | from pathlib import Path | 44 | from pathlib import Path |
| 39 | 45 | ||
| 40 | IDENTITY = { | 46 | IDENTITY = { |
| @@ -51,6 +57,98 @@ def run(args: list[str], cwd: Path, env: dict | None = None, data: bytes | None | |||
| 51 | return subprocess.run(args, cwd=cwd, env=env, input=data, capture_output=True) | 57 | return subprocess.run(args, cwd=cwd, env=env, input=data, capture_output=True) |
| 52 | 58 | ||
| 53 | 59 | ||
| 60 | if os.name == "nt": | ||
| 61 | import ctypes | ||
| 62 | from ctypes import wintypes | ||
| 63 | |||
| 64 | class _JobLimits(ctypes.Structure): | ||
| 65 | """JOBOBJECT_EXTENDED_LIMIT_INFORMATION; only LimitFlags is set.""" | ||
| 66 | _fields_ = [("per_process_user_time", ctypes.c_int64), ("per_job_user_time", ctypes.c_int64), | ||
| 67 | ("limit_flags", wintypes.DWORD), ("min_working_set", ctypes.c_size_t), | ||
| 68 | ("max_working_set", ctypes.c_size_t), ("active_process_limit", wintypes.DWORD), | ||
| 69 | ("affinity", ctypes.c_size_t), ("priority_class", wintypes.DWORD), | ||
| 70 | ("scheduling_class", wintypes.DWORD), ("io_counters", ctypes.c_uint64 * 6), | ||
| 71 | ("process_memory_limit", ctypes.c_size_t), ("job_memory_limit", ctypes.c_size_t), | ||
| 72 | ("peak_process_memory_used", ctypes.c_size_t), ("peak_job_memory_used", ctypes.c_size_t)] | ||
| 73 | |||
| 74 | _KERNEL32 = ctypes.WinDLL("kernel32", use_last_error=True) | ||
| 75 | _KERNEL32.CreateJobObjectW.restype = wintypes.HANDLE | ||
| 76 | _KERNEL32.CreateJobObjectW.argtypes = (ctypes.c_void_p, wintypes.LPCWSTR) | ||
| 77 | _KERNEL32.SetInformationJobObject.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD) | ||
| 78 | _KERNEL32.OpenProcess.restype = wintypes.HANDLE | ||
| 79 | _KERNEL32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD) | ||
| 80 | _KERNEL32.AssignProcessToJobObject.argtypes = (wintypes.HANDLE, wintypes.HANDLE) | ||
| 81 | _KERNEL32.TerminateJobObject.argtypes = (wintypes.HANDLE, wintypes.UINT) | ||
| 82 | _KERNEL32.CloseHandle.argtypes = (wintypes.HANDLE,) | ||
| 83 | |||
| 84 | |||
| 85 | _JOB_WARNED = False # job_of() says once that it has no job object | ||
| 86 | |||
| 87 | |||
| 88 | def job_of(p: subprocess.Popen): | ||
| 89 | """On Windows, a job object holding `p`, or None. The processes `p` starts join it, and closing it stops every | ||
| 90 | process in it (JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE): a process that outlives `p` is stopped with the job, where | ||
| 91 | `taskkill /T` no longer finds it once `p` has ended. A process `p` starts before it joins (its first instants) | ||
| 92 | stays out. Without one, it says so on stderr once.""" | ||
| 93 | global _JOB_WARNED | ||
| 94 | job = _KERNEL32.CreateJobObjectW(None, None) | ||
| 95 | limits = _JobLimits(limit_flags=0x2000) # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | ||
| 96 | handle = job and _KERNEL32.OpenProcess(0x0101, False, p.pid) # PROCESS_TERMINATE | PROCESS_SET_QUOTA | ||
| 97 | # 9: JobObjectExtendedLimitInformation | ||
| 98 | joined = (handle and _KERNEL32.SetInformationJobObject(job, 9, ctypes.byref(limits), ctypes.sizeof(limits)) | ||
| 99 | and _KERNEL32.AssignProcessToJobObject(job, handle)) | ||
| 100 | error = ctypes.get_last_error() | ||
| 101 | if handle: | ||
| 102 | _KERNEL32.CloseHandle(handle) | ||
| 103 | if joined: | ||
| 104 | return job | ||
| 105 | if job: | ||
| 106 | _KERNEL32.CloseHandle(job) | ||
| 107 | if not _JOB_WARNED: | ||
| 108 | _JOB_WARNED = True | ||
| 109 | print(f"red_green: no Windows job object for the mutated runs (error {error}): a process one leaves behind " | ||
| 110 | "is not stopped", file=sys.stderr) | ||
| 111 | return None | ||
| 112 | |||
| 113 | |||
| 114 | def stop_all(p: subprocess.Popen, job) -> None: | ||
| 115 | """Stops `p` and every process it started, still running or left behind: the job on Windows, the process group | ||
| 116 | elsewhere.""" | ||
| 117 | if job is not None: | ||
| 118 | _KERNEL32.TerminateJobObject(job, 1) | ||
| 119 | _KERNEL32.CloseHandle(job) | ||
| 120 | elif os.name != "nt": | ||
| 121 | try: | ||
| 122 | os.killpg(p.pid, signal.SIGKILL) | ||
| 123 | except ProcessLookupError: | ||
| 124 | pass | ||
| 125 | if p.poll() is None: | ||
| 126 | p.kill() | ||
| 127 | |||
| 128 | |||
| 129 | def run_output(cmd: list[str], cwd: Path, env: dict | None = None, | ||
| 130 | timeout: float | None = None) -> tuple[int | None, str]: | ||
| 131 | """The exit code and the output (error output included) of `cmd`. With a timeout, the output goes to a file, so | ||
| 132 | that a process left behind holding it does not hold the run; once `cmd` ends, or after `timeout` seconds (then | ||
| 133 | the exit code is None), it is stopped with every process it started.""" | ||
| 134 | if timeout is None: | ||
| 135 | r = subprocess.run(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | ||
| 136 | return r.returncode, r.stdout.decode("utf-8", "replace") | ||
| 137 | with tempfile.TemporaryFile() as log: | ||
| 138 | p = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=log, stderr=subprocess.STDOUT, | ||
| 139 | start_new_session=os.name != "nt") | ||
| 140 | job = job_of(p) if os.name == "nt" else None | ||
| 141 | try: | ||
| 142 | code = p.wait(timeout=timeout) | ||
| 143 | except subprocess.TimeoutExpired: | ||
| 144 | code = None | ||
| 145 | finally: # Ctrl+C too: on POSIX the new session keeps it from the processes started | ||
| 146 | stop_all(p, job) | ||
| 147 | p.wait() | ||
| 148 | log.seek(0) | ||
| 149 | return code, log.read().decode("utf-8", "replace") | ||
| 150 | |||
| 151 | |||
| 54 | def git(cwd: Path, *args: str, env: dict | None = None, data: bytes | None = None, check: bool = True) -> str: | 152 | def git(cwd: Path, *args: str, env: dict | None = None, data: bytes | None = None, check: bool = True) -> str: |
| 55 | r = run(["git", *args], cwd, env, data) | 153 | r = run(["git", *args], cwd, env, data) |
| 56 | if check and r.returncode != 0: | 154 | if check and r.returncode != 0: |
| @@ -180,17 +278,24 @@ def hunks(diff: str) -> list[tuple[int, int, int, int]]: | |||
| 180 | return out | 278 | return out |
| 181 | 279 | ||
| 182 | 280 | ||
| 183 | def test_hunks(old: bytes, new: bytes, diff: str) -> bytes | None: | 281 | def test_hunk_flags(old: bytes, new: bytes, diff: str) -> list[bool]: |
| 184 | """`old` with only the hunks of `diff` (made with -U0) that change test code; None when there is none.""" | 282 | """For each hunk of `diff` (a Rust file's, made with -U0), in order, whether it changes only test code: each line |
| 283 | it removes or adds is in a `#[cfg(test)]` item, blank or a comment, and one at least is in such an item. The red | ||
| 284 | side takes these hunks, and a mutation leaves them alone.""" | ||
| 185 | old_lines, new_lines = lines_of(old), lines_of(new) | 285 | old_lines, new_lines = lines_of(old), lines_of(new) |
| 186 | old_tests, new_tests = test_lines(old), test_lines(new) | 286 | old_tests, new_tests = test_lines(old), test_lines(new) |
| 187 | keep = [] | 287 | flags = [] |
| 188 | for a, b, c, d in hunks(diff): | 288 | for a, b, c, d in hunks(diff): |
| 189 | removed = range(a - 1, a - 1 + b) | 289 | lines = [(i in old_tests, old_lines[i]) for i in range(a - 1, a - 1 + b)] + \ |
| 190 | added = range(c - 1, c - 1 + d) | 290 | [(i in new_tests, new_lines[i]) for i in range(c - 1, c - 1 + d)] |
| 191 | lines = [(i in old_tests, old_lines[i]) for i in removed] + [(i in new_tests, new_lines[i]) for i in added] | 291 | flags.append(bool(lines) and all(t or neutral(line) for t, line in lines) and any(t for t, _ in lines)) |
| 192 | if lines and all(t or neutral(line) for t, line in lines) and any(t for t, _ in lines): | 292 | return flags |
| 193 | keep.append((a, b, c, d)) | 293 | |
| 294 | |||
| 295 | def test_hunks(old: bytes, new: bytes, diff: str) -> bytes | None: | ||
| 296 | """`old` with only the hunks of `diff` (made with -U0) that change test code; None when there is none.""" | ||
| 297 | old_lines, new_lines = lines_of(old), lines_of(new) | ||
| 298 | keep = [h for h, test in zip(hunks(diff), test_hunk_flags(old, new, diff)) if test] | ||
| 194 | if not keep: | 299 | if not keep: |
| 195 | return None | 300 | return None |
| 196 | out = list(old_lines) | 301 | out = list(old_lines) |
| @@ -282,36 +387,38 @@ COMPILER_CRASH = re.compile( | |||
| 282 | r"|(internal compiler error)|(the compiler unexpectedly panicked)|(memory allocation of \d+ bytes failed)") | 387 | r"|(internal compiler error)|(the compiler unexpectedly panicked)|(memory allocation of \d+ bytes failed)") |
| 283 | 388 | ||
| 284 | 389 | ||
| 285 | def cargo_once(tree: Path, crates: list[str], cargo: str, target: Path) -> dict: | 390 | def cargo_once(tree: Path, crates: list[str], cargo: str, target: Path, timeout: float | None) -> dict: |
| 286 | cmd = [sys.executable, cargo] if cargo.endswith(".py") else [cargo] | 391 | cmd = [sys.executable, cargo] if cargo.endswith(".py") else [cargo] |
| 287 | cmd += ["test", "--locked", "--no-fail-fast"] + [a for c in crates for a in ("-p", c)] | 392 | cmd += ["test", "--locked", "--no-fail-fast"] + [a for c in crates for a in ("-p", c)] |
| 288 | env = dict(os.environ, CARGO_TARGET_DIR=str(target)) | 393 | env = dict(os.environ, CARGO_TARGET_DIR=str(target)) |
| 289 | r = subprocess.run(cmd, cwd=tree / "d3d12", env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | 394 | code, out = run_output(cmd, tree / "d3d12", env, timeout) |
| 290 | out = r.stdout.decode("utf-8", "replace") | 395 | tests, unit, error, ran = {}, "?", None, False |
| 291 | tests, unit, error = {}, "?", None | ||
| 292 | for line in out.splitlines(): | 396 | for line in out.splitlines(): |
| 293 | m = UNIT.match(line) | 397 | m = UNIT.match(line) |
| 294 | if m: | 398 | if m: |
| 295 | unit = m.group(1) or "doc:" + m.group(2) | 399 | unit, ran = m.group(1) or "doc:" + m.group(2), True |
| 296 | continue | 400 | continue |
| 297 | m = CARGO_TEST.match(line) | 401 | m = CARGO_TEST.match(line) |
| 298 | if m: | 402 | if m: |
| 299 | tests[f"{unit}::{m.group(1)}"] = {"ok": "ok", "FAILED": "failed", "ignored": "ignored"}[m.group(2)] | 403 | tests[f"{unit}::{m.group(1)}"] = {"ok": "ok", "FAILED": "failed", "ignored": "ignored"}[m.group(2)] |
| 300 | elif error is None and CARGO_ERROR.match(line): | 404 | elif error is None and CARGO_ERROR.match(line): |
| 301 | error = line.strip() | 405 | error = line.strip() |
| 302 | no_build = r.returncode != 0 and not tests | 406 | no_build = code is not None and code != 0 and not tests |
| 303 | crash = COMPILER_CRASH.search(out) if no_build else None | 407 | crash = COMPILER_CRASH.search(out) if no_build else None |
| 304 | return {"tests": tests, "no_build": (error or f"cargo exit {r.returncode}") if no_build and not crash else None, | 408 | # Stopped by the timeout: while building (no test binary had started) or while running the tests. |
| 305 | "crash": next(g for g in crash.groups() if g) if crash else None} | 409 | timed_out = None if code is not None else "running" if ran else "building" |
| 410 | return {"tests": tests, "no_build": (error or f"cargo exit {code}") if no_build and not crash else None, | ||
| 411 | "crash": next(g for g in crash.groups() if g) if crash else None, "timed_out": timed_out} | ||
| 306 | 412 | ||
| 307 | 413 | ||
| 308 | def cargo_tests(tree: Path, crates: list[str], cargo: str, target: Path) -> dict: | 414 | def cargo_tests(tree: Path, crates: list[str], cargo: str, target: Path, timeout: float | None) -> dict: |
| 309 | first = cargo_once(tree, crates, cargo, target) | 415 | first = cargo_once(tree, crates, cargo, target, timeout) |
| 310 | if not first["crash"]: | 416 | if not first["crash"]: |
| 311 | return {"tests": first["tests"], "no_build": first["no_build"]} | 417 | return {"tests": first["tests"], "no_build": first["no_build"], "timed_out": first["timed_out"]} |
| 312 | print(f"red_green: the compiler crashed ({first['crash']}), running again", file=sys.stderr) | 418 | print(f"red_green: the compiler crashed ({first['crash']}), running again", file=sys.stderr) |
| 313 | again = cargo_once(tree, crates, cargo, target) | 419 | again = cargo_once(tree, crates, cargo, target, timeout) |
| 314 | result = {"tests": again["tests"], "no_build": again["no_build"], "rerun_after": first["crash"]} | 420 | result = {"tests": again["tests"], "no_build": again["no_build"], "rerun_after": first["crash"], |
| 421 | "timed_out": again["timed_out"]} | ||
| 315 | if again["crash"]: | 422 | if again["crash"]: |
| 316 | result["compiler_crashed"] = again["crash"] | 423 | result["compiler_crashed"] = again["crash"] |
| 317 | return result | 424 | return result |
| @@ -321,13 +428,43 @@ PY_TEST = re.compile(r"^(\w+) \(([\w.]+)\)(?:\n[^\n]*?)? \.\.\. (ok|FAIL|ERROR|s | |||
| 321 | re.M) | 428 | re.M) |
| 322 | 429 | ||
| 323 | 430 | ||
| 324 | def python_tests(tree: Path, files: list[str]) -> dict: | 431 | def drop_bytecode(tree: Path) -> None: |
| 325 | tests, no_build = {}, [] | 432 | """Removes every `__pycache__` folder of the work tree. Python runs a .pyc instead of its source when the source |
| 433 | time and size it records still match (an undone change of the same size within the same second) or when it is an | ||
| 434 | unchecked-hash one, and `git clean` keeps them (they are ignored). An option of the run's own Python, such as | ||
| 435 | `-X pycache_prefix`, would not reach the processes its tests start. Links (symbolic links, and junctions, which | ||
| 436 | `is_symlink()` does not see) are neither followed nor removed: what they point at is not the tree's. A folder it | ||
| 437 | cannot list is skipped: Python cannot import from it either. A `__pycache__` it cannot remove stops the run.""" | ||
| 438 | folders, todo = [], [tree] | ||
| 439 | while todo: | ||
| 440 | try: | ||
| 441 | with os.scandir(todo.pop()) as entries: | ||
| 442 | for e in entries: | ||
| 443 | if not e.is_dir(follow_symlinks=False) or e.is_symlink(): | ||
| 444 | continue | ||
| 445 | if getattr(e.stat(follow_symlinks=False), "st_file_attributes", 0) \ | ||
| 446 | & stat.FILE_ATTRIBUTE_REPARSE_POINT: | ||
| 447 | continue # a junction (Windows) | ||
| 448 | (folders if e.name == "__pycache__" else todo).append(e.path) | ||
| 449 | except OSError: | ||
| 450 | continue | ||
| 451 | for folder in folders: | ||
| 452 | try: | ||
| 453 | shutil.rmtree(folder) | ||
| 454 | except OSError as e: | ||
| 455 | raise Failure(f"cannot remove {folder}, whose bytecode could run instead of the code: {e}") from None | ||
| 456 | |||
| 457 | |||
| 458 | def python_tests(tree: Path, files: list[str], timeout: float | None) -> dict: | ||
| 459 | tests, no_build, timed_out = {}, [], None | ||
| 460 | drop_bytecode(tree) | ||
| 326 | for f in files: | 461 | for f in files: |
| 327 | start = "tests/semantic" if f.startswith("tests/semantic/") else str(Path(f).parent) | 462 | start = "tests/semantic" if f.startswith("tests/semantic/") else str(Path(f).parent) |
| 328 | r = subprocess.run([sys.executable, "-I", "-m", "unittest", "discover", "-s", start, "-p", Path(f).name, "-v"], | 463 | # -B only stops writing bytecode, not reading it: drop_bytecode() above keeps stale bytecode out. |
| 329 | cwd=tree, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | 464 | code, out = run_output([sys.executable, "-I", "-B", "-m", "unittest", "discover", "-s", start, |
| 330 | out = r.stdout.decode("utf-8", "replace") | 465 | "-p", Path(f).name, "-v"], tree, timeout=timeout) |
| 466 | if code is None: | ||
| 467 | timed_out = "running" | ||
| 331 | found = 0 | 468 | found = 0 |
| 332 | for name, where, status in PY_TEST.findall(out): | 469 | for name, where, status in PY_TEST.findall(out): |
| 333 | if "_FailedTest" in where: | 470 | if "_FailedTest" in where: |
| @@ -336,20 +473,27 @@ def python_tests(tree: Path, files: list[str]) -> dict: | |||
| 336 | key = where if where.endswith("." + name) else f"{where}.{name}" | 473 | key = where if where.endswith("." + name) else f"{where}.{name}" |
| 337 | tests[f"{f}::{key}"] = {"ok": "ok", "skipped": "ignored", "expected failure": "ok"}.get(status, "failed") | 474 | tests[f"{f}::{key}"] = {"ok": "ok", "skipped": "ignored", "expected failure": "ok"}.get(status, "failed") |
| 338 | found += 1 | 475 | found += 1 |
| 339 | if not found and r.returncode != 0 and f"{f}: does not import" not in no_build: | 476 | if not found and code not in (0, None) and f"{f}: does not import" not in no_build: |
| 340 | no_build.append(f"{f}: exit {r.returncode}") | 477 | no_build.append(f"{f}: exit {code}") |
| 341 | return {"tests": tests, "no_build": "; ".join(no_build) or None} | 478 | return {"tests": tests, "no_build": "; ".join(no_build) or None, "timed_out": timed_out} |
| 342 | 479 | ||
| 343 | 480 | ||
| 344 | def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target: Path) -> dict: | 481 | def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target: Path, |
| 345 | result = {"tests": {}, "no_build": [], "compiler_crashed": None, "rerun_after": None} | 482 | timeout: float | None = None) -> dict: |
| 346 | for part in ([cargo_tests(tree, crates, cargo, target)] if crates else []) + \ | 483 | """The tests of one side: the crates, and those of the Python test files that this tree has. With a timeout (the |
| 347 | ([python_tests(tree, py_files)] if py_files else []): | 484 | mutated runs), a command that runs past it is stopped and `timed_out` says when: "building" (cargo, before any |
| 485 | test binary ran) or "running".""" | ||
| 486 | py_files = [f for f in py_files if (tree / f).is_file()] | ||
| 487 | result = {"tests": {}, "no_build": [], "compiler_crashed": None, "rerun_after": None, "timed_out": None} | ||
| 488 | for part in ([cargo_tests(tree, crates, cargo, target, timeout)] if crates else []) + \ | ||
| 489 | ([python_tests(tree, py_files, timeout)] if py_files else []): | ||
| 348 | result["tests"].update(part["tests"]) | 490 | result["tests"].update(part["tests"]) |
| 349 | if part["no_build"]: | 491 | if part["no_build"]: |
| 350 | result["no_build"].append(part["no_build"]) | 492 | result["no_build"].append(part["no_build"]) |
| 351 | for key in ("compiler_crashed", "rerun_after"): | 493 | for key in ("compiler_crashed", "rerun_after"): |
| 352 | result[key] = result[key] or part.get(key) | 494 | result[key] = result[key] or part.get(key) |
| 495 | if part.get("timed_out") and result["timed_out"] != "running": # a test stopped running outweighs a build | ||
| 496 | result["timed_out"] = part["timed_out"] | ||
| 353 | return result | 497 | return result |
| 354 | 498 | ||
| 355 | 499 | ||
| @@ -423,6 +567,19 @@ def report(r: dict) -> str: | |||
| 423 | if len(rows[key]) > 40: | 567 | if len(rows[key]) > 40: |
| 424 | out.append(f" ... {len(rows[key]) - 40} more") | 568 | out.append(f" ... {len(rows[key]) - 40} more") |
| 425 | out.append(f"pass on both: {rows['pass_on_both']}") | 569 | out.append(f"pass on both: {rows['pass_on_both']}") |
| 570 | if r.get("mutations") is not None: | ||
| 571 | if r.get("mutations_not_run"): | ||
| 572 | out.append(f"mutations: {r['mutations_not_run']}") | ||
| 573 | else: | ||
| 574 | counts = Counter(m["result"] for m in r["mutations"]) | ||
| 575 | out.append(f"mutations ({len(r['mutations'])} hunks undone one at a time): " | ||
| 576 | + ", ".join(f"{n} {k}" for k, n in sorted(counts.items()))) | ||
| 577 | out += [f" {m['file']}:{m['line']}: {m['result']}" for m in r["mutations"]] | ||
| 578 | if r.get("mutations_skipped"): | ||
| 579 | out.append("not tried, past --mutate-max: " | ||
| 580 | + ", ".join(f"{m['file']}:{m['line']}" for m in r["mutations_skipped"])) | ||
| 581 | if r.get("added_not_mutated"): | ||
| 582 | out.append("not mutated, added by the pull request: " + ", ".join(r["added_not_mutated"])) | ||
| 426 | out.append(f"verdict: {r['verdict']}") | 583 | out.append(f"verdict: {r['verdict']}") |
| 427 | return "\n".join(out) | 584 | return "\n".join(out) |
| 428 | 585 | ||
| @@ -439,7 +596,21 @@ def main(argv: list[str] | None = None) -> int: | |||
| 439 | p.add_argument("--no-python", action="store_true", help="skip the Python tests") | 596 | p.add_argument("--no-python", action="store_true", help="skip the Python tests") |
| 440 | p.add_argument("--cargo", default="cargo", help="the cargo to run (a .py file runs with this Python)") | 597 | p.add_argument("--cargo", default="cargo", help="the cargo to run (a .py file runs with this Python)") |
| 441 | p.add_argument("--json", action="store_true", help="print the result as JSON") | 598 | p.add_argument("--json", action="store_true", help="print the result as JSON") |
| 599 | p.add_argument("--mutate", action="store_true", | ||
| 600 | help="undo each code hunk alone on green and run the tests again (caught or not)") | ||
| 601 | p.add_argument("--mutate-max", type=int, help="the most hunks --mutate tries, 1 or more (10)") | ||
| 602 | p.add_argument("--mutate-timeout", type=float, metavar="SECONDS", | ||
| 603 | help="stop a command of a mutated run (cargo test, one Python test file) after this long: the hunk " | ||
| 604 | "is caught by timeout, or timed out building if cargo had not started a test (600)") | ||
| 442 | a = p.parse_args(argv) | 605 | a = p.parse_args(argv) |
| 606 | if not a.mutate and (a.mutate_max is not None or a.mutate_timeout is not None): | ||
| 607 | p.error("--mutate-max and --mutate-timeout go with --mutate") | ||
| 608 | if a.mutate_max is not None and a.mutate_max < 1: | ||
| 609 | p.error("--mutate-max must be 1 or more") | ||
| 610 | if a.mutate_timeout is not None and not (math.isfinite(a.mutate_timeout) and a.mutate_timeout > 0): | ||
| 611 | p.error("--mutate-timeout must be a number of seconds above 0") | ||
| 612 | a.mutate_max = 10 if a.mutate_max is None else a.mutate_max | ||
| 613 | a.mutate_timeout = 600.0 if a.mutate_timeout is None else a.mutate_timeout | ||
| 443 | try: | 614 | try: |
| 444 | repo = Path(git(Path.cwd(), "rev-parse", "--show-toplevel")) | 615 | repo = Path(git(Path.cwd(), "rev-parse", "--show-toplevel")) |
| 445 | common = Path(git(repo, "rev-parse", "--path-format=absolute", "--git-common-dir")) | 616 | common = Path(git(repo, "rev-parse", "--path-format=absolute", "--git-common-dir")) |
| @@ -463,6 +634,14 @@ def main(argv: list[str] | None = None) -> int: | |||
| 463 | os.close(fd) | 634 | os.close(fd) |
| 464 | try: | 635 | try: |
| 465 | result = check(repo, work, a, base, base_commit, head, merge_base) | 636 | result = check(repo, work, a, base, base_commit, head, merge_base) |
| 637 | except Failure: | ||
| 638 | # Stopped midway (a side, a mutation): the tree goes back on the base, as at the end of a run. | ||
| 639 | if (work / "tree" / ".git").exists(): | ||
| 640 | try: | ||
| 641 | checkout(repo, work / "tree", base_commit) | ||
| 642 | except Failure: | ||
| 643 | pass | ||
| 644 | raise | ||
| 466 | finally: | 645 | finally: |
| 467 | lock.unlink(missing_ok=True) | 646 | lock.unlink(missing_ok=True) |
| 468 | except Failure as e: | 647 | except Failure as e: |
| @@ -492,26 +671,114 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer | |||
| 492 | red_why = "not constructible: the tests conflict with the base in " + ", ".join(stuck) | 671 | red_why = "not constructible: the tests conflict with the base in " + ", ".join(stuck) |
| 493 | else: | 672 | else: |
| 494 | print("red_green: red side...", file=sys.stderr) | 673 | print("red_green: red side...", file=sys.stderr) |
| 495 | red = side(tree, crates, [f for f in py_files if (tree / f).is_file()], a.cargo, target) | 674 | red = side(tree, crates, py_files, a.cargo, target) |
| 496 | 675 | ||
| 497 | green, green_why = None, None | 676 | green, green_why, green_commit = None, None, None |
| 498 | checkout(repo, tree, base_commit) | 677 | checkout(repo, tree, base_commit) |
| 499 | git(tree, "merge", "--no-commit", "--no-ff", head, env=env, check=False) | 678 | git(tree, "merge", "--no-commit", "--no-ff", head, env=env, check=False) |
| 500 | stuck = conflicts(tree) | 679 | stuck = conflicts(tree) |
| 501 | if stuck: | 680 | if stuck: |
| 502 | green_why = "not constructible: the pull request conflicts with the base in " + ", ".join(stuck) | 681 | green_why = "not constructible: the pull request conflicts with the base in " + ", ".join(stuck) |
| 503 | else: | 682 | else: |
| 683 | if a.mutate: # the merge as it is now, before a test can write into the tree: each mutation starts from it | ||
| 684 | green_commit = git(tree, "commit-tree", git(tree, "write-tree"), "-p", base_commit, "-p", head, | ||
| 685 | "-m", f"red_green: {head[:12]} merged", env=env) | ||
| 504 | print("red_green: green side...", file=sys.stderr) | 686 | print("red_green: green side...", file=sys.stderr) |
| 505 | green = side(tree, crates, [f for f in py_files if (tree / f).is_file()], a.cargo, target) | 687 | green = side(tree, crates, py_files, a.cargo, target) |
| 688 | rows = compare(red, green) | ||
| 689 | # With --mutate, `mutations` is a list (empty when no hunk was undone, and `mutations_not_run` says why). | ||
| 690 | mutations, not_run, skipped, added = None, None, None, None | ||
| 691 | if a.mutate: | ||
| 692 | hunks, added, mutations = code_hunks(repo, merge_base, head), code_files(repo, merge_base, head, "A"), [] | ||
| 693 | if green is None: | ||
| 694 | not_run = "not run: there is no green side" | ||
| 695 | elif not hunks: | ||
| 696 | not_run = ("nothing to undo in the files it modifies: its code changes are in files it adds" if added else | ||
| 697 | "nothing to undo: the diff changes no Rust or Python code outside its tests") | ||
| 698 | elif not rows["red_to_green"]: | ||
| 699 | not_run = "not run: no test went red then green, so none can catch a hunk" | ||
| 700 | else: | ||
| 701 | print("red_green: mutations...", file=sys.stderr) | ||
| 702 | mutations = mutate(tree, green_commit, hunks[:a.mutate_max], rows["red_to_green"], crates, py_files, | ||
| 703 | a.cargo, target, a.mutate_timeout) | ||
| 704 | skipped = [{"file": path, "line": line} for path, line, _ in hunks[a.mutate_max:]] | ||
| 506 | checkout(repo, tree, base_commit) | 705 | checkout(repo, tree, base_commit) |
| 507 | 706 | ||
| 508 | rows = compare(red, green) | ||
| 509 | return {"base": base, "base_commit": base_commit, "head": a.pr, "head_commit": head, "merge_base": merge_base, | 707 | return {"base": base, "base_commit": base_commit, "head": a.pr, "head_commit": head, "merge_base": merge_base, |
| 510 | "red_files": red_files, "red_why": red_why, "green_why": green_why, "crates": crates, | 708 | "red_files": red_files, "red_why": red_why, "green_why": green_why, "crates": crates, |
| 511 | "python_files": py_files, "red": red, "green": green, "rows": rows, | 709 | "python_files": py_files, "red": red, "green": green, "rows": rows, "mutations": mutations, |
| 710 | "mutations_not_run": not_run, "mutations_skipped": skipped, "added_not_mutated": added, | ||
| 512 | "verdict": verdict(red_why, green_why, red, green, rows)} | 711 | "verdict": verdict(red_why, green_why, red, green, rows)} |
| 513 | 712 | ||
| 514 | 713 | ||
| 714 | def code_files(repo: Path, merge_base: str, head: str, status: str) -> list[str]: | ||
| 715 | """The Rust and Python files outside the tests that the pull request changes with git status `status` (M | ||
| 716 | modified, A added). Added files are not mutated: undoing one deletes it, which only shows that something uses it.""" | ||
| 717 | paths = git(repo, "diff", "--name-only", "--no-renames", f"--diff-filter={status}", merge_base, head).splitlines() | ||
| 718 | return [p for p in paths if not is_test_file(p) | ||
| 719 | and (p.endswith(".rs") or (p.endswith(".py") and not p.startswith("tests/")))] | ||
| 720 | |||
| 721 | |||
| 722 | def code_hunks(repo: Path, merge_base: str, head: str) -> list[tuple[str, int, str]]: | ||
| 723 | """(file, first changed line in the pull request, patch) for each hunk of its code outside its tests in the files | ||
| 724 | it modifies: the hunks a mutation undoes one at a time. Without context, so that a test changed next to the code is | ||
| 725 | a hunk of its own (a hunk does not apply where `main` moved the lines since).""" | ||
| 726 | out = [] | ||
| 727 | for path in code_files(repo, merge_base, head, "M"): | ||
| 728 | diff = git(repo, "diff", "-U0", "--no-color", "--no-ext-diff", merge_base, head, "--", path) | ||
| 729 | lines = diff.split("\n") | ||
| 730 | first = next((i for i, line in enumerate(lines) if line.startswith("@@")), None) | ||
| 731 | if first is None: | ||
| 732 | continue | ||
| 733 | header = "\n".join(lines[:first]) | ||
| 734 | blocks: list[list[str]] = [] | ||
| 735 | for line in lines[first:]: | ||
| 736 | if line.startswith("@@"): | ||
| 737 | blocks.append([line]) | ||
| 738 | else: | ||
| 739 | blocks[-1].append(line) | ||
| 740 | # A hunk of test code only is the tests' own, not the fix: the same rule as the red side's. | ||
| 741 | tests_only = (test_hunk_flags(blob(repo, merge_base, path) or b"", blob(repo, head, path) or b"", diff) | ||
| 742 | if path.endswith(".rs") else [False] * len(blocks)) | ||
| 743 | for block, test in zip(blocks, tests_only): | ||
| 744 | m = HUNK.match(block[0]) | ||
| 745 | if m and not test: | ||
| 746 | out.append((path, int(m.group(3)), header + "\n" + "\n".join(block).rstrip("\n") + "\n")) | ||
| 747 | return out | ||
| 748 | |||
| 749 | |||
| 750 | def mutate(tree: Path, green: str, hunks: list[tuple[str, int, str]], targets: list[str], crates: list[str], | ||
| 751 | py_files: list[str], cargo: str, target: Path, timeout: float) -> list[dict]: | ||
| 752 | """Undoes each code hunk alone on the green tree and runs the tests again: a hunk is caught when one of the tests | ||
| 753 | that went red then green fails, or caught by timeout when a command runs past `timeout` seconds. Each one starts | ||
| 754 | from the commit `green`, reset and cleaned, so what a test wrote into the tree changes no other.""" | ||
| 755 | results = [] | ||
| 756 | for path, line, patch in hunks: | ||
| 757 | entry = {"file": path, "line": line, "result": None} | ||
| 758 | git(tree, "reset", "--hard", "-q", green) | ||
| 759 | git(tree, "clean", "-fdq") | ||
| 760 | undo = run(["git", "apply", "-R", "--unidiff-zero", "-"], tree, data=patch.encode()) | ||
| 761 | if undo.returncode != 0: | ||
| 762 | entry["result"] = "does not apply" | ||
| 763 | results.append(entry) | ||
| 764 | continue | ||
| 765 | s = side(tree, crates, py_files, cargo, target, timeout) | ||
| 766 | if s.get("compiler_crashed"): | ||
| 767 | entry["result"] = "compiler crashed" | ||
| 768 | elif any(s["tests"].get(t) == "failed" for t in targets): | ||
| 769 | entry["result"] = "caught" | ||
| 770 | elif s["timed_out"] == "building": # no answer: the build was too slow, or the undone code made it hang | ||
| 771 | entry["result"] = "timed out building" | ||
| 772 | elif s["timed_out"]: | ||
| 773 | entry["result"] = "caught by timeout" | ||
| 774 | elif not any(t in s["tests"] for t in targets): | ||
| 775 | entry["result"] = "does not build" | ||
| 776 | else: | ||
| 777 | entry["result"] = "not caught" | ||
| 778 | results.append(entry) | ||
| 779 | return results | ||
| 780 | |||
| 781 | |||
| 515 | if __name__ == "__main__": | 782 | if __name__ == "__main__": |
| 516 | try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode | 783 | try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode |
| 517 | sys.stdout.reconfigure(errors="replace") | 784 | sys.stdout.reconfigure(errors="replace") |