From 4fea24766035df65c3dd1cbb371ba3c1ea8e4271 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 04:22:01 +0000 Subject: [PATCH] Do not count an unmutated worker build as a kill. A worker that fails before any mutation was recording every mutant as killed. Run the tests once on the unmutated overlay and stop the way a failed baseline does. The tests also kill the mutants in the functions this change touches. Proved by a stand-in xcodebuild that fails only inside a worker, and by mutator on engine.py and workers.py: 140 killed, 0 survived, 0 uncovered. pytest: 139 passed, 1 skipped. Co-authored-by: Robert C. Martin --- README.md | 6 +- src/mutator/engine.py | 38 +++++++--- src/mutator/workers.py | 63 +++++++++++----- tests/test_boundaries.py | 4 +- tests/test_engine.py | 151 +++++++++++++++++++++++++++++++++++++-- tests/test_swift.py | 68 ++++++++++++++++++ tests/test_workers.py | 38 ++++++++++ 7 files changed, 332 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 5b75607..a95e91c 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Mutation testing for Clojure, Java, Go, TypeScript, Rust, Python, and Swift. One Clojure follows [clj-mutate](https://github.com/unclebob/clj-mutate). Go follows [mutate4go](https://github.com/unclebob/mutate4go). Java follows [mutate4java](https://github.com/unclebob/mutate4java). TypeScript, Rust, and Python use the same decisions as Java, spelled in that language. Function names and namespaces come from [crapper](https://github.com/unclebob/crapper), which is what uml-viewer joins to `.metrics/crap.edn`. -A mutant is killed when the tests fail or time out. It survives when the tests still pass. A site on a line the coverage report does not hit is uncovered and is not run. The score uml-viewer paints is killed / (killed + survived). +A mutant is killed when the tests fail or time out. It survives when the tests still pass. A worker that cannot run the tests on the unmutated source is not a kill. That run stops the way a failed baseline does, and the snapshot is left as it was. A site on a line the coverage report does not hit is uncovered and is not run. The score uml-viewer paints is killed / (killed + survived). ## Run @@ -31,7 +31,7 @@ The first run of a tree executes every covered mutant. Start with the file you a Once a snapshot exists, the next run is differential. It reruns survivors and every site in a function whose text changed. Killed mutants in an unchanged function stay killed. `--since-last-run` is that same selection. `--mutate-all` ignores it. -Exit `0` when every executed mutant was killed. Exit `2` when the baseline tests fail. Exit `3` when a mutant survives. A failed baseline does not rewrite the snapshot. +Exit `0` when every executed mutant was killed. Exit `2` when the baseline tests fail, or the unmutated worker cannot run them. Exit `3` when a mutant survives. A failed baseline does not rewrite the snapshot. ## Workers @@ -39,7 +39,7 @@ Mutants of one file run at the same time. The default is one worker per core. `- Each worker is a directory under `target/mutation-workers`. The file being mutated is a private copy. A module that reaches that file through a relative import is copied too, so Node resolves the import to the private copy. The rest of the tree is linked. An Xcode project, workspace, or asset catalog is copied: xcodebuild realpaths a project symlink, and actool will not follow a symlinked catalog. The original files stay as they are. The overlay is removed when that file's mutants finish. -The baseline still runs once, in the real tree, before any worker starts. The mutant command then runs inside the worker, in the same directory it would have used in the real tree, so a relative path such as `src` or `./pkg` refers to the overlay. A copy left under `target/mutator-backup/` by an interrupted older run is restored before a non-scan run. +The baseline still runs once, in the real tree, before any worker starts. One worker then runs that same command on the unmutated copy. If that fails, the failure is not a kill. The mutant command runs inside the worker, in the same directory it would have used in the real tree, so a relative path such as `src` or `./pkg` refers to the overlay. A copy left under `target/mutator-backup/` by an interrupted older run is restored before a non-scan run. ## Snapshot diff --git a/src/mutator/engine.py b/src/mutator/engine.py index 1930830..c30902b 100644 --- a/src/mutator/engine.py +++ b/src/mutator/engine.py @@ -11,7 +11,7 @@ from mutator.metrics import load_history, source_key, write_results from mutator.model import FormResult, RunResult, Site from mutator.report import format_scan from mutator.runner import Command, CommandRunner, display_command, test_plan -from mutator.workers import run_mutants +from mutator.workers import WorkerBuildFailure, run_mutants def restore_backups(root: Path) -> list[Path]: @@ -188,22 +188,42 @@ def _command_key(command: Command) -> tuple[str, ...]: return ("argv", *command) +def _output_tail(output: str) -> str: + return "\n".join(output.splitlines()[-20:]) + + +def _with_tail(message: str, tail: str) -> str: + if tail: + return f"{message}\n{tail}" + return message + + +def _stopped(file_key: str, command: Command, lead: str, tail: str) -> RunResult: + message = _with_tail(f"{lead}: {display_command(command)}", tail) + return RunResult(path=file_key, forms=[], written=[], baseline_failed=True, baseline_message=message) + + def _remember_baseline(baselines, cache_key, runner, command: Command, cwd: Path) -> None: if cache_key in baselines: return baseline = runner.run(command, cwd, None) if baseline.code != 0: - tail = "\n".join(baseline.output.splitlines()[-20:]) - baselines[cache_key] = (False, baseline.seconds, tail) + baselines[cache_key] = (False, baseline.seconds, _output_tail(baseline.output)) return baselines[cache_key] = (True, baseline.seconds, "") def _baseline_failure(file_key: str, command: Command, tail: str) -> RunResult: - message = f"Baseline failed for {file_key}: {display_command(command)}" - if tail: - message = f"{message}\n{tail}" - return RunResult(path=file_key, forms=[], written=[], baseline_failed=True, baseline_message=message) + return _stopped(file_key, command, f"Baseline failed for {file_key}", tail) + + +def _worker_failure(file_key: str, command: Command, failure: WorkerBuildFailure) -> RunResult: + return _stopped( + file_key, + command, + f"Worker build failed for {file_key} before any mutation", + _output_tail(failure.output), + ) def _apply_selected( @@ -238,7 +258,7 @@ def _apply_selected( if not ok: return _baseline_failure(file_key, command, tail) timeout = max(2.0, seconds * timeout_factor) - run_mutants( + failure = run_mutants( root, path, original, @@ -251,6 +271,8 @@ def _apply_selected( file_key, outcomes, ) + if failure is not None: + return _worker_failure(file_key, command, failure) return None diff --git a/src/mutator/workers.py b/src/mutator/workers.py index 4795125..d07d231 100644 --- a/src/mutator/workers.py +++ b/src/mutator/workers.py @@ -17,6 +17,7 @@ import sys import time import uuid from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass from pathlib import Path from queue import Empty, Queue from threading import Lock @@ -84,7 +85,7 @@ def worker_count(site_count: int, requested: int | None) -> int: processors = os.cpu_count() or 1 limit = processors if requested is None else requested - return max(1, min(site_count, processors, limit)) + return min(site_count, processors, limit) def new_run_dir(root: Path) -> Path: @@ -302,7 +303,7 @@ def _copy_importer(worker: Path, root: Path, relative: str) -> None: if current.is_symlink(): _expand_directory(current, real) elif not current.exists(): - current.mkdir(parents=True) + current.mkdir() destination = worker / relative if destination.is_symlink(): destination.unlink() @@ -341,6 +342,13 @@ def create_workers( return created +@dataclass(frozen=True) +class WorkerBuildFailure: + """The unmutated worker could not run the tests. This is not a kill.""" + + output: str + + def mapped_cwd(worker: Path, root: Path, cwd: Path) -> Path: try: relative = cwd.resolve().relative_to(root.resolve()) @@ -462,6 +470,17 @@ def _run_all( future.result() +def _probe_worker( + directory: Path, root: Path, runner, command: Command, cwd: Path +) -> WorkerBuildFailure | None: + """Run the tests on the unmutated overlay. ``None`` means they passed.""" + + result = runner.run(command, mapped_cwd(directory, root, cwd), None) + if result.code == 0: + return None + return WorkerBuildFailure(result.output) + + def run_mutants( root: Path, source: Path, @@ -474,29 +493,37 @@ def run_mutants( timeout: float, file_key: str, outcomes: dict[str, str], -) -> None: - """Mutate ``sites`` in parallel overlays of ``root``. The source stays put.""" +) -> WorkerBuildFailure | None: + """Mutate ``sites`` in parallel overlays of ``root``. The source stays put. + + The unmutated overlay runs once before any mutant. A failure there is + returned, and nothing is recorded as killed. + """ if not sites: - return + return None base = new_run_dir(root) + failure: WorkerBuildFailure | None = None try: relative = source.resolve().relative_to(root.resolve()).as_posix() directories = create_workers( base, root, relative, original, worker_count(len(sites), max_workers) ) - _run_all( - directories, - sites, - outcomes, - root, - relative, - original, - runner, - command, - cwd, - timeout, - file_key, - ) + failure = _probe_worker(directories[0], root, runner, command, cwd) + if failure is None: + _run_all( + directories, + sites, + outcomes, + root, + relative, + original, + runner, + command, + cwd, + timeout, + file_key, + ) finally: delete_tree(base) + return failure diff --git a/tests/test_boundaries.py b/tests/test_boundaries.py index 61edc55..09e66e9 100644 --- a/tests/test_boundaries.py +++ b/tests/test_boundaries.py @@ -721,8 +721,10 @@ def test_selection_coverage_and_timeouts_keep_their_boundaries(tmp_path, capsys, mutation_warning=50, baselines={}, ) + # Project baseline, then the unmutated worker, then a mutant at 10x. assert clock.timeouts[0] is None - assert clock.timeouts[1] == 300 + assert clock.timeouts[1] is None + assert clock.timeouts[2] == 300 class Red: verbose = False diff --git a/tests/test_engine.py b/tests/test_engine.py index 1bdb2da..5b200d1 100644 --- a/tests/test_engine.py +++ b/tests/test_engine.py @@ -2,12 +2,14 @@ import os import shutil import subprocess import threading +from pathlib import Path -from mutator.engine import mutate_file, restore_backups -from mutator.edn import loads -from mutator.metrics import snapshot_path +from mutator.engine import _backup, _drop_bytecode, mutate_file, restore_backups, scan_file from mutator.runner import CommandResult -from mutator.workers import create_workers, delete_tree, new_run_dir, worker_count +from mutator.edn import dumps, loads +from mutator.functions import form_digests +from mutator.metrics import snapshot_path +from mutator.workers import create_workers, delete_tree, importers_of, new_run_dir, worker_count class FakeRunner: @@ -85,8 +87,10 @@ def test_mutants_are_killed_or_kept_and_the_snapshot_is_differential(tmp_path): ) assert second.forms[0].killed == 1 assert second.forms[0].survived == 3 - # Baseline plus the three survivors. The killed mutant stays in the snapshot. - assert runner.calls - first_calls == 4 + # Baseline, the unmutated worker, and the three survivors. + # The killed mutant stays in the snapshot and is not run again. + assert first_calls == 6 + assert runner.calls - first_calls == 5 def test_uncovered_sites_are_not_executed(tmp_path): @@ -300,3 +304,138 @@ def test_restore_backups_puts_an_interrupted_mutant_back(tmp_path): assert restored == [source] assert source.read_text(encoding="utf-8") == "original\n" assert not backup.exists() + + +def test_worker_count_is_one_when_the_processor_count_is_unknown(monkeypatch): + monkeypatch.setattr(os, "cpu_count", lambda: None) + assert worker_count(4, None) == 1 + assert worker_count(4, 3) == 1 + + +def test_workers_can_be_created_twice_and_under_a_missing_directory(tmp_path): + source = tmp_path / "src" / "demo.py" + source.parent.mkdir() + source.write_text("def place(x):\n return x > 0\n", encoding="utf-8") + original = source.read_bytes() + base = tmp_path / "fresh" / "run" + first = create_workers(base, tmp_path, "src/demo.py", original, 1) + second = create_workers(base, tmp_path, "src/demo.py", original, 1) + assert first[0] == second[0] + assert (second[0] / "src" / "demo.py").read_bytes() == original + assert source.read_bytes() == original + + +def test_a_module_is_not_listed_as_its_own_importer(tmp_path): + source = tmp_path / "src" / "find.mjs" + source.parent.mkdir() + source.write_text( + 'import { value } from "./find.mjs";\nexport const value = 1\n', + encoding="utf-8", + ) + assert importers_of(tmp_path, "src/find.mjs") == set() + + +def test_importers_keep_queries_hashes_bare_specifiers_and_nesting(tmp_path): + source = tmp_path / "src" / "find.mjs" + source.parent.mkdir() + source.write_text('export const value = "real"\n', encoding="utf-8") + plain = tmp_path / "src" / "plain.mjs" + plain.write_text('import { value } from "./find";\n', encoding="utf-8") + typed = tmp_path / "src" / "typed.mjs" + typed.write_text('import { value } from "./find.js";\n', encoding="utf-8") + query = tmp_path / "src" / "query.mjs" + query.write_text('import { value } from "./find.mjs?raw";\n', encoding="utf-8") + hashed = tmp_path / "src" / "hashed.mjs" + hashed.write_text('import { value } from "./find.mjs#part";\n', encoding="utf-8") + nested = tmp_path / "src" / "nested" / "use.mjs" + nested.parent.mkdir() + nested.write_text('import { value } from "../find.mjs";\n', encoding="utf-8") + escape = tmp_path / "src" / "escape.mjs" + escape.write_text('import x from "../../outside.js";\n', encoding="utf-8") + git_hook = tmp_path / ".git" / "hook.mjs" + git_hook.parent.mkdir() + git_hook.write_text('import { value } from "../src/find.mjs";\n', encoding="utf-8") + original = source.read_bytes() + base = new_run_dir(tmp_path) + try: + worker = create_workers(base, tmp_path, "src/find.mjs", original, 1)[0] + nested_dir = worker / "src" / "nested" + assert nested_dir.is_dir() and not nested_dir.is_symlink() + for relative in ( + "src/plain.mjs", + "src/typed.mjs", + "src/query.mjs", + "src/hashed.mjs", + "src/nested/use.mjs", + ): + copied = worker / relative + assert copied.is_file() + assert not copied.is_symlink() + assert not (worker / ".git").exists() + assert escape.read_text(encoding="utf-8").startswith("import") + finally: + delete_tree(base) + assert source.read_bytes() == original + assert nested.read_text(encoding="utf-8").startswith("import") + + +def test_the_first_backup_creates_a_nested_directory(tmp_path): + path = tmp_path / "src" / "demo.py" + path.parent.mkdir() + path.write_bytes(b"original") + saved = _backup(tmp_path, path, b"original") + assert saved == tmp_path / "target" / "mutator-backup" / "src" / "demo.py" + assert saved.read_bytes() == b"original" + assert path.read_bytes() == b"original" + + +def test_dropping_bytecode_ignores_a_pyc_that_vanishes(tmp_path, monkeypatch): + path = tmp_path / "src" / "demo.py" + path.parent.mkdir() + path.write_text("x", encoding="utf-8") + missing = path.parent / "__pycache__" / "demo.cpython-314.pyc" + missing.parent.mkdir() + + def glob(self, pattern): + if self == missing.parent and pattern.startswith("demo."): + return [missing] + return [] + + monkeypatch.setattr(Path, "glob", glob) + _drop_bytecode(path) + assert not missing.exists() + + +def test_a_scan_without_coverage_does_not_call_a_site_uncovered(tmp_path): + path = tmp_path / "src" / "demo.py" + path.parent.mkdir() + path.write_text("def place(x):\n return x > 0\n", encoding="utf-8") + text = scan_file(path, tmp_path, covered_lines=None, ignore_coverage=False, lines=None) + assert "uncovered" not in text + assert "> -> >=" in text + + +def test_a_scan_marks_a_function_whose_recorded_text_changed(tmp_path): + path = tmp_path / "src" / "demo.py" + path.parent.mkdir() + source = "def place(x):\n return x > 0\n" + path.write_text(source, encoding="utf-8") + digests = form_digests(source, path, tmp_path) + (namespace, form_id), _digest = next(iter(digests.items())) + snapshot = snapshot_path(tmp_path, namespace) + snapshot.parent.mkdir(parents=True) + snapshot.write_text( + dumps( + { + "namespace": namespace, + "source": "src/demo.py", + "forms": [{"id": form_id, "hash": "stale", "file": "src/demo.py"}], + "outcomes": {}, + } + ) + + "\n", + encoding="utf-8", + ) + text = scan_file(path, tmp_path, covered_lines=None, ignore_coverage=True, lines=None) + assert "whose text changed" in text + assert any(line.startswith("* ") for line in text.splitlines()) diff --git a/tests/test_swift.py b/tests/test_swift.py index b096a25..7f0f553 100644 --- a/tests/test_swift.py +++ b/tests/test_swift.py @@ -294,6 +294,7 @@ def test_a_worker_copies_an_asset_catalog_and_keeps_safe_links(tmp_path): catalog = root / "DungeonDoor" / "Assets.xcassets" _write(catalog / "AccentColor.colorset" / "Contents.json", '{"color":"accent"}\n') (catalog / "AppIcon.appiconset").symlink_to(shared) + _write(root / "DungeonDoor" / "Core" / "Other.swift", "func other() -> Int { 2 }\n") _write(root / "DungeonDoor" / "Notes.xcassets", "not a catalog\n") _write(root / "DungeonDoor" / "Preview" / "readme.txt", "preview\n") _write(root / "Docs" / "readme.txt", "notes\n") @@ -314,6 +315,11 @@ def test_a_worker_copies_an_asset_catalog_and_keeps_safe_links(tmp_path): assert icon.read_text(encoding="utf-8") == "png-bytes" assert accent.is_file() and not accent.is_symlink() assert accent.read_text(encoding="utf-8") == '{"color":"accent"}\n' + core = worker / "DungeonDoor" / "Core" + other = core / "Other.swift" + assert core.is_dir() and not core.is_symlink() + assert other.is_symlink() + assert other.read_text(encoding="utf-8").startswith("func other") assert (worker / "DungeonDoor" / "Notes.xcassets").is_symlink() assert (worker / "DungeonDoor" / "Preview").is_symlink() assert (worker / "Docs").is_symlink() @@ -647,6 +653,68 @@ def test_a_compiling_mutant_survives_when_the_worker_catalog_is_real(tmp_path, m assert catalog.is_dir() and not catalog.is_symlink() +def _worker_only_failure(bin_dir: Path, body: str) -> None: + bin_dir.mkdir(parents=True, exist_ok=True) + tool = bin_dir / "xcodebuild" + tool.write_text(body, encoding="utf-8") + tool.chmod(0o755) + + +def test_an_unmutated_worker_build_failure_is_not_a_kill(tmp_path, monkeypatch, capsys): + bin_dir = tmp_path / "bin" + _worker_only_failure( + bin_dir, + "#!/bin/sh\n" + 'case "$PWD" in\n' + "*mutation-workers*)\n" + " echo WORKER-BOOM\n" + " exit 65\n" + " ;;\n" + "esac\n" + "exit 0\n", + ) + monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}") + root = tmp_path / "ios" + source = _ios_source(root, "App.xcodeproj") + code = run(["--no-coverage", "--root", str(root), "--max-workers", "1"]) + captured = capsys.readouterr() + assert code == 2 + assert "Worker build failed for App/ContentView.swift before any mutation:" in captured.err + assert "WORKER-BOOM" in captured.err + assert "KILLED" not in captured.out + assert "SURVIVED" not in captured.out + assert source.read_text(encoding="utf-8") == _IOS_BODY + assert not (root / ".metrics" / "mutate").exists() + + +def test_an_unmutated_worker_build_failure_without_output_is_not_a_kill( + tmp_path, monkeypatch, capsys +): + bin_dir = tmp_path / "bin" + _worker_only_failure( + bin_dir, + "#!/bin/sh\n" + 'case "$PWD" in\n' + "*mutation-workers*) exit 65 ;;\n" + "esac\n" + "exit 0\n", + ) + monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}") + root = tmp_path / "ios" + source = _ios_source(root, "App.xcodeproj") + code = run(["--no-coverage", "--root", str(root), "--max-workers", "1"]) + captured = capsys.readouterr() + lines = [line for line in captured.err.splitlines() if line.strip()] + assert code == 2 + assert len(lines) == 1 + assert lines[0].startswith( + "Worker build failed for App/ContentView.swift before any mutation: xcodebuild test " + ) + assert "KILLED" not in captured.out + assert source.read_text(encoding="utf-8") == _IOS_BODY + assert not (root / ".metrics" / "mutate").exists() + + def test_scan_marks_a_swift_line_uncovered_when_llvm_cov_did_not_hit_it(tmp_path, capsys): import json diff --git a/tests/test_workers.py b/tests/test_workers.py index 2fd14ec..ac528d0 100644 --- a/tests/test_workers.py +++ b/tests/test_workers.py @@ -73,6 +73,44 @@ def test_delete_tree_unlinks_a_symlink_without_following_it(tmp_path): assert kept.read_text(encoding="utf-8") == "keep" +def test_delete_tree_unlinks_a_symlink_that_vanishes(tmp_path, monkeypatch): + real = tmp_path / "project" + real.mkdir() + kept = real / "important.txt" + kept.write_text("keep", encoding="utf-8") + link = tmp_path / "worker-link" + link.symlink_to(real) + original_unlink = Path.unlink + + def unlink(self, *args, **kwargs): + if self == link and link.is_symlink(): + original_unlink(self) + return original_unlink(self, *args, **kwargs) + + monkeypatch.setattr(Path, "unlink", unlink) + delete_tree(link, attempts=1, sleep=lambda _: None) + assert not link.exists() + assert kept.read_text(encoding="utf-8") == "keep" + + +def test_symlink_replaces_a_file_and_creates_a_missing_parent(tmp_path): + from mutator.workers import symlink + + target = tmp_path / "real.txt" + target.write_text("keep", encoding="utf-8") + link = tmp_path / "nested" / "link.txt" + link.parent.mkdir() + link.write_text("old", encoding="utf-8") + symlink(link, target) + other = tmp_path / "deep" / "child" / "link.txt" + symlink(other, target) + assert link.is_symlink() + assert link.read_text(encoding="utf-8") == "keep" + assert other.is_symlink() + assert other.read_text(encoding="utf-8") == "keep" + assert target.read_text(encoding="utf-8") == "keep" + + def test_delete_tree_reraises_after_the_attempts_are_exhausted(tmp_path, monkeypatch): tree = tmp_path / "worker" tree.mkdir()