diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml index f80078c..5a3bee1 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -14,22 +14,90 @@ concurrency: permissions: contents: read +env: + PYTHONHASHSEED: "0" + TRAILMARK_REQUIRE_BINARY_TOOLS: "1" + TRAILMARK_LLVM_OBJDUMP: /usr/bin/llvm-objdump + TRAILMARK_LLVM_SYMBOLIZER: /usr/bin/llvm-symbolizer + TRAILMARK_LLVM_READOBJ: /usr/bin/llvm-readobj + TRAILMARK_GNU_OBJDUMP: /usr/bin/objdump + TRAILMARK_GNU_SYMBOLIZER: /usr/bin/addr2line + jobs: + scope: + name: Select mutation scope + runs-on: ubuntu-latest + outputs: + reviewed: ${{ steps.scope.outputs.reviewed }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + fetch-depth: 0 + - name: Include the full campaign for runner changes + id: scope + env: + PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + reviewed=false + if [[ "$GITHUB_EVENT_NAME" == pull_request ]]; then + reviewed=true + changed=$(git diff --name-only "$PR_BASE_SHA" HEAD) + if grep -Eq '^(\.github/workflows/mutation\.yml$|tests/(run_mutations|mutation_[^/]+|test_mutation_[^/]+|conftest|parse_work|test_test_policy)\.py$|pyproject\.toml$|uv\.lock$)' <<< "$changed"; then + reviewed=false + fi + fi + echo "reviewed=$reviewed" >> "$GITHUB_OUTPUT" + + baselines: + name: Mutation baseline and coverage + needs: scope + runs-on: ubuntu-latest + env: + BASELINE_SHARD: 1/1 + MUTATION_REVIEWED: ${{ needs.scope.outputs.reviewed }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + version: "0.13.9" + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.13" + - run: sudo apt-get update && sudo apt-get install -y llvm binutils-multiarch + - run: npm ci + - run: uv sync --locked --all-groups --extra binary + - name: Validate baseline and collect test coverage + run: | + scope=() + if [[ "$MUTATION_REVIEWED" == true ]]; then scope+=(--reviewed); fi + uv run --locked --extra binary python -m tests.run_mutations "${scope[@]}" --baseline-shard="$BASELINE_SHARD" + - name: Upload validated baselines + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: mutation-baseline + overwrite: true + path: | + coverage/gremlins/baseline-*.json + coverage/gremlins/coverage-plan.json + if-no-files-found: error + gremlins: - name: Mutation shard ${{ matrix.shard }}/8 + name: Mutation shard ${{ matrix.shard }}/32 + needs: [scope, baselines] runs-on: ubuntu-latest strategy: fail-fast: false matrix: - shard: [1, 2, 3, 4, 5, 6, 7, 8] + shard: [ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, + ] env: - MUTATION_SHARD: ${{ matrix.shard }}/8 - TRAILMARK_REQUIRE_BINARY_TOOLS: "1" - TRAILMARK_LLVM_OBJDUMP: /usr/bin/llvm-objdump - TRAILMARK_LLVM_SYMBOLIZER: /usr/bin/llvm-symbolizer - TRAILMARK_LLVM_READOBJ: /usr/bin/llvm-readobj - TRAILMARK_GNU_OBJDUMP: /usr/bin/objdump - TRAILMARK_GNU_SYMBOLIZER: /usr/bin/addr2line + MUTATION_SHARD: ${{ matrix.shard }}/32 + MUTATION_REVIEWED: ${{ needs.scope.outputs.reviewed }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -38,22 +106,21 @@ jobs: - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: version: "0.13.9" - - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.13" - - run: sudo apt-get update && sudo apt-get install -y llvm binutils-multiarch - run: npm ci - run: uv sync --locked --all-groups --extra binary - - - name: Run reviewed mutation scope - if: github.event_name == 'pull_request' - run: uv run --locked --extra binary python -m tests.run_mutations --reviewed --workers=4 --shard="$MUTATION_SHARD" - - - name: Run full mutation campaign - if: github.event_name != 'pull_request' - run: uv run --locked --extra binary python -m tests.run_mutations --workers=4 --shard="$MUTATION_SHARD" + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: mutation-baseline + path: coverage/gremlins/baselines + - name: Run mutation campaign with shared baselines + run: | + scope=() + if [[ "$MUTATION_REVIEWED" == true ]]; then scope+=(--reviewed); fi + uv run --locked --extra binary python -m tests.run_mutations "${scope[@]}" --workers=4 --shard="$MUTATION_SHARD" --baselines=coverage/gremlins/baselines - name: Enforce reviewed mutation baseline run: uv run --locked --extra binary python -m tests.mutation_gate --shard="$MUTATION_SHARD" @@ -69,16 +136,22 @@ jobs: uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: mutation-report-${{ github.sha }}-shard-${{ matrix.shard }} + overwrite: true path: coverage/gremlins/ if-no-files-found: error mutation-gate: name: Mutation Testing if: always() - needs: gremlins + needs: [scope, baselines, gremlins] runs-on: ubuntu-latest steps: - name: Require all mutation shards to pass env: MUTATION_RESULT: ${{ needs.gremlins.result }} - run: test "$MUTATION_RESULT" = success + BASELINE_RESULT: ${{ needs.baselines.result }} + SCOPE_RESULT: ${{ needs.scope.result }} + run: | + test "$SCOPE_RESULT" = success + test "$BASELINE_RESULT" = success + test "$MUTATION_RESULT" = success diff --git a/AGENTS.md b/AGENTS.md index cdd702d..d02724b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -105,13 +105,24 @@ uv run python -m tests.run_mutations --reviewed --workers=4 uv run python -m tests.mutation_gate ``` -The runner uses real pytest subprocesses and validates clean and instrumented -baselines. It orders component unit tests first and retains all selected tests -as fallback. Use it rather than invoking the pinned plugin directly. Omit +The runner uses real pytest subprocesses and coverage-driven test selection. +It validates clean and instrumented baselines, expands shared-fixture coverage +to every consumer, and retains tests whose subprocesses or tracing obscure +coverage. Import-time and unmapped mutations run the full suite. Ordinary kills +require a passing neutral failure-prefix check or a matching validated full-suite +order. The control retains the full selected collection and fixture teardown. Use it +rather than invoking the pinned plugin directly. Omit `--reviewed` for a full repository campaign; CI runs that after merges and on manual dispatch. `--workers` already enables parallel execution. -CI additionally splits mutants across eight concurrent jobs. To reproduce a -partition, pass the same `--shard=1/8` (one-based index/total) to both commands. +CI produces one baseline receipt and coverage plan from a single instrumented +coverage pass. Its 32 mutation jobs reuse that evidence and execute mutants +without replaying full baselines or prevalidating selected subsets. +Local runs validate their own baselines by default. To reproduce a partition, +pass the same `--shard=1/32` (one-based index/total) to both commands. +Use `--test-selection=full` for a full-suite reference campaign. Shared coverage +preparation uses `--baseline-shard=1/1`; copy both `baseline-1-of-1.json` and +`coverage-plan.json` together when using `--baselines=PATH`. +See `CONTRIBUTING.md` for baseline sharing and failure-prefix confirmation. Do not enable `TRAILMARK_UPDATE_SNAPSHOTS` during CI or mutation testing. ## Adding Features diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 72ec78f..3ff2dde 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -87,66 +87,110 @@ Confirmed execution outcomes are streamed to `coverage/gremlins/progress.jsonl` for investigation during long campaigns. This journal can be incomplete; only the completed reports and `run.json` establish results for the gate. -CI runs eight mutation shards concurrently, each with four workers. Mutation +CI runs 32 mutation shards concurrently, each with four workers. Mutation jobs install the `binary` extra and GNU and LLVM tools, and set `TRAILMARK_REQUIRE_BINARY_TOOLS=1` so missing native-image dependencies fail -instead of silently skipping their tests. Each file's -mutants are dealt round-robin across the shards, retaining the full selected test -suite for every mutant. Every shard checks the clean and instrumented baselines -and gates its exact share of the source inventory. The final `Mutation Testing` -check requires all eight shards to pass; reports are uploaded separately per shard. +instead of silently skipping their tests. Each file's mutants are dealt +round-robin across the shards. One preparation job runs the selected suite once +with neutral instrumentation and per-test coverage. The normal CI test jobs run +the clean suite. +Mutation jobs reuse its baseline receipt and coverage plan only when repository +inputs, Python packages, native tool binaries, relevant environment settings, +test collection, and runner configuration match. Missing, stale, or incomplete receipts fail the run. +The outer pytest session collects tests and dispatches mutations without replaying +the clean suite in each shard. +The mutation shards then execute their assigned mutants. The final +`Mutation Testing` check requires the baseline job and all 32 mutation shards to pass. +Each mutation shard enforces +the reviewed gate for its assigned inventory and uploads its own reports. To reproduce one CI shard locally, pass the same one-based `--shard=INDEX/TOTAL` to both commands (omit `--reviewed` for a full repository shard): ```bash -uv run python -m tests.run_mutations --reviewed --workers=4 --shard=1/8 -uv run python -m tests.mutation_gate --shard=1/8 +uv run python -m tests.run_mutations --reviewed --workers=4 --shard=1/32 +uv run python -m tests.mutation_gate --shard=1/32 ``` Omitting `--shard` runs and gates the complete campaign as before. +Local campaigns prepare their own coverage and baselines by default. For shared +preparation, run `--baseline-shard=1/1` with the same targets, tests, and test-order +setting. Copy `coverage/gremlins/baseline-1-of-1.json` and +`coverage/gremlins/coverage-plan.json` together into a directory and pass +`--baselines=PATH` to mutation runs. Preparation executes no mutants and creates +no gate report; evidence is written only after successful validation. Keep these +files within the same trusted campaign. **Scope and gate.** Pull requests mutate the reviewed files named in `tests/mutation_baseline.json`. Full repository campaigns run on pushes to main and through the mutation workflow's manual trigger. The reviewed scope gates all functions in those files, including -unchanged legacy functions. The gate rejects unreviewed -survivors, missing tests or results, errors, and timeouts. An exception +unchanged legacy functions. The gate rejects unreviewed survivors and incomplete +mutation inventories in that scope. Across the entire campaign, errors, timeouts, +pardons, and missing tests +fail the gate, including outside the reviewed scope. An exception requires a reason and a fingerprint of the function and mutation; changing that function requires reviewing its exceptions again. Source hashes and mutation fingerprints use a canonical AST representation so reviews remain valid across supported Python versions. +PRs that change the mutation runner, its controls, the mutation workflow, or +Python dependency configuration run the full campaign before merging. **How the runner works.** The runner pins pytest-gremlins 1.14.3 and uses its pytest subprocesses and import handling, including fixtures, parametrized tests, -package metadata, and instrumentation in spawned child processes. Trailmark -checks the clean baseline and each distinct instrumented test ordering before -mutating, skips the redundant coverage pre-scan, preserves exact parameter IDs, -and rejects skipped instrumentation. Tests use deterministic work bounds rather +package metadata, and instrumentation in spawned child processes. Coverage-driven +test selection runs only tests observed to execute the mutated line, with shared +fixture setup and teardown attributed to every consumer. Tests that run unknown +child processes or replace Python tracing are retained for every mutant. Known +native GNU/LLVM tools, C compilers, and the fixed `git -C ROOT rev-parse HEAD` +provenance query are recognized through fingerprints of their executable contents. +Other Git commands and Python or script wrappers remain opaque. Import-time and +unmapped locations use the full suite. + +After mutant execution, ordinary test failures receive a neutral failure-prefix +check. The control collects the same selected tests, executes only through the +test that failed, and includes fixture teardown. Matching full-suite orders reuse +the passing baseline. For each remaining selected collection, one successful +longest prefix also validates its shorter failure prefixes. These controls use +the same worker budget after the mutant pool closes. A failing neutral prefix +invalidates the campaign before scores are accepted. Survivors require no extra +test executions. The gate verifies each reported test selection against the saved plan. +The runner preserves exact parameter IDs and rejects skipped instrumentation. +Tests use deterministic work bounds rather than wall-clock thresholds. The test suite has no elapsed-time assertions, pytest timeout markers, or test subprocess deadlines. Hypothesis deadlines and -its generation-speed health check are disabled. Test product timeout behavior +its generation-speed health check are disabled. Mutation campaigns also use +deterministic Hypothesis examples with its example database disabled, so coverage +collection and mutant execution use the same generated inputs. Test product timeout behavior with a simulated clock and process; keep optional wall-clock measurements in `tests/benchmark_analysis.py` or `tests/smoke_binary_projects.py`. The adapter uses private plugin APIs; its control tests must pass before upgrading the plugin. +Collection-time `SystemExit` counts as a kill only when its traceback includes +an instrumented application source and the unmutated test selection loads +successfully. Harness failures and unrelated internal errors remain errors. + Each mutant subprocess may run for 240 seconds so the full fallback suite can finish with four workers competing for CI resources. A timeout is not counted as a kill unless the unmutated confirmation run establishes sufficient headroom; inconclusive outcomes still fail the gate. -**Test ordering.** Each mutant keeps the full selected test suite: component -unit tests run first, followed by the remaining tests, stopping at the first -failure. Shared-helper mutants retain tests from every language. Tests stay in +**Test ordering.** Within a coverage-selected subset, component unit tests run first, +stopping at the first failure. Shared-helper mutants retain tests from every +language that covers the mutation. Full-suite fallbacks keep collection order so +they can reuse the shared neutral baseline. Tests stay in their existing files; `tests/mutation_order.py` defines the ordering, and unknown components keep collection order. Use `--test-order=collection` to -compare against pytest's original order. +keep pytest's original order within each subset. Use `--test-selection=full` to +run every selected test against every mutant as a reference. Full mode validates +its distinct complete orders; `--baseline-shard=INDEX/TOTAL` can split those checks. Private helpers use their component test names without the leading underscore; Python decorator helpers start with `test_python_decorator_bindings.py`. Snapshot and binary model mutants start with `test_snapshots.py` and -`test_binary_models.py`, respectively, before falling back to general model tests. +`test_binary_models.py`, respectively, when those files are selected, followed by +any selected general model tests. Snapshot mutants also prioritize binary and proxy round trips. Callable-reference mutants prioritize binding-boundary and PHP callable tests; shared parser mutants prioritize directory-linking regressions after their utility tests. diff --git a/pyproject.toml b/pyproject.toml index 386e6d1..8489930 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -87,6 +87,9 @@ select = [ "ANN", "S", "B", "C4", "SIM", ] +[tool.ruff.lint.isort] +known-third-party = ["coverage"] + [tool.ruff.lint.per-file-ignores] "tests/**" = ["S101", "ANN401"] diff --git a/tests/conftest.py b/tests/conftest.py index b1751b3..05609c6 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -8,7 +8,15 @@ from hypothesis import HealthCheck, settings settings.register_profile("trailmark", deadline=None, suppress_health_check=[HealthCheck.too_slow]) -settings.load_profile("trailmark") +settings.register_profile( + "trailmark-mutation", + parent=settings.get_profile("trailmark"), + derandomize=True, + database=None, +) +settings.load_profile( + "trailmark-mutation" if os.environ.get("TRAILMARK_MUTATION_TESTING") else "trailmark" +) def pytest_sessionstart(session: pytest.Session) -> None: diff --git a/tests/fixtures/dafny_type_scanner.c b/tests/fixtures/dafny_type_scanner.c new file mode 100644 index 0000000..5d5f9eb --- /dev/null +++ b/tests/fixtures/dafny_type_scanner.c @@ -0,0 +1,55 @@ +/* Check speculative type lookahead at its depth and work boundaries. */ +#include +#include +#include "dafny/src/scanner.c" + +typedef struct { + TSLexer lexer; + const char *cursor; + size_t advances; +} Input; + +static void advance(TSLexer *lexer, bool skip) { + (void)skip; + Input *input = (Input *)lexer; + assert(*input->cursor != '\0'); + input->advances++; + lexer->lookahead = *++input->cursor; +} + +static Input input_for(const char *source) { + Input input = { + .lexer = {.lookahead = *source, .advance = advance}, + .cursor = source, + }; + return input; +} + +int main(void) { + Input below = input_for("int"); + assert(scan_type(&below.lexer, 255)); + assert(below.advances == 3); + + for (unsigned depth = 256; depth <= 257; depth++) { + Input limited = input_for("int"); + assert(!scan_type(&limited.lexer, depth)); + assert(limited.advances == 0); + } + + char nested[512 * 3 + 4]; + char *next = nested; + for (unsigned index = 0; index < 512; index++) { + *next++ = 'A'; + *next++ = '<'; + } + memcpy(next, "int", 3); + next += 3; + for (unsigned index = 0; index < 512; index++) *next++ = '>'; + *next = '\0'; + + Input deep = input_for(nested); + assert(!scan_type(&deep.lexer, 0)); + /* Each A< advances twice and increases the recursive depth twice. */ + assert(deep.advances == 256); + return 0; +} diff --git a/tests/mutation_bootstrap.py b/tests/mutation_bootstrap.py new file mode 100644 index 0000000..3c91187 --- /dev/null +++ b/tests/mutation_bootstrap.py @@ -0,0 +1,119 @@ +"""Recognize application exits during collection without hiding harness errors.""" + +import os +from pathlib import Path + +import pytest +from pytest_gremlins import plugin +from pytest_gremlins.instrumentation.spawn_hook import export_spawn_hook + + +def record_source_collection_exits(directory: Path) -> None: + """Extend the pinned bootstrap's load recorder, retaining upstream confirmation.""" + path = directory / "gremlin_bootstrap.py" + source = path.read_text() + replacements = { + " self.suite_failed_to_load = False\n": ( + " self.suite_failed_to_load = False\n" + " self.source_collection_exit = False\n" + ), + " def pytest_collection(self, session):\n outcome = yield\n": ( + " def pytest_collection(self, session):\n" + " outcome = yield\n" + " if outcome.excinfo is not None and issubclass(\n" + " outcome.excinfo[0], SystemExit\n" + " ):\n" + " self.source_collection_exit = any(\n" + " normalize_origin(frame.f_code.co_filename) " + "in instrumented_sources\n" + " for frame, _ in traceback.walk_tb(outcome.excinfo[2])\n" + " )\n" + " if self.source_collection_exit:\n" + " self.suite_failed_to_load = True\n" + ), + " load_failure_exit = exit_code in (pytest.ExitCode.USAGE_ERROR, " + "pytest.ExitCode.INTERRUPTED)\n": ( + " load_failure_exit = (\n" + " exit_code in (pytest.ExitCode.USAGE_ERROR, pytest.ExitCode.INTERRUPTED)\n" + " or (exit_code == pytest.ExitCode.INTERNAL_ERROR " + "and recorder.source_collection_exit)\n" + " )\n" + ), + } + for original, replacement in replacements.items(): + if source.count(original) != 1: + raise pytest.UsageError("Revalidate the pinned mutation bootstrap adapter") + source = source.replace(original, replacement) + path.write_text(source) + + +def test_command(directory: Path, session: plugin.GremlinSession) -> list[str]: + return plugin._build_test_command( + directory, + session.preserved_addopts, + xdist_loaded=session.xdist_loaded, + xdist_loader_options=session.xdist_loader_options, + doctest_ini_overrides=session.doctest_ini_overrides, + config_file_options=session.config_file_options, + rerun_options=session.rerun_options, + pytest_cov_options=session.pytest_cov_options, + ) + + +def baseline_environment(directory: Path) -> dict[str, str]: + env = os.environ.copy() + env.pop("ACTIVE_GREMLIN", None) + env["PYTEST_GREMLINS_SOURCES_FILE"] = str(directory / "sources.json") + env["GREMLIN_ROOTDIR"] = str(Path.cwd()) + export_spawn_hook(env) + return env + + +def record_test_execution(directory: Path) -> None: + """Record executed test prefixes and stop neutral checks after their target.""" + path = directory / "gremlin_bootstrap.py" + source = path.read_text() + original = ( + " recorder = SuiteLoadRecorder()\n" + " exit_code = pytest.main(pytest_args, plugins=[FinderFronter(), recorder])\n" + ) + replacement = """ class ExecutionRecorder: + def __init__(self): + self.started = [] + self.failed = False + self.stopped = False + self.limit = int(os.environ.get('TRAILMARK_PREFIX_LIMIT', '0')) + + def pytest_runtest_logstart(self, nodeid): + self.started.append(nodeid) + + def pytest_runtest_logreport(self, report): + if report.failed: + self.failed = True + + @pytest.hookimpl(wrapper=True, tryfirst=True) + def pytest_runtest_protocol(self, item): + outcome = yield + if self.limit and len(self.started) == self.limit: + self.stopped = True + pytest.exit('Unmutated failure prefix completed', returncode=0) + return outcome + + recorder = SuiteLoadRecorder() + execution = ExecutionRecorder() + exit_code = pytest.main(pytest_args, plugins=[FinderFronter(), recorder, execution]) + active = os.environ.get('ACTIVE_GREMLIN') + destination = os.environ.get('TRAILMARK_PREFIX_REPORT') + if active: + import hashlib + destination = os.path.join(os.path.dirname(sources_file), + 'execution-' + hashlib.sha256(active.encode()).hexdigest() + '.json') + if destination: + with open(destination + '.tmp', 'w') as output: + json.dump({'tests': execution.started, 'failed': execution.failed, + 'stopped': execution.stopped, 'exit_code': int(exit_code)}, output) + os.replace(destination + '.tmp', destination) +""" + if source.count(original) != 1: + raise pytest.UsageError("Revalidate the pinned failure-prefix bootstrap adapter") + path.write_text(source.replace(original, replacement)) diff --git a/tests/mutation_confirmation.py b/tests/mutation_confirmation.py new file mode 100644 index 0000000..aa6cb06 --- /dev/null +++ b/tests/mutation_confirmation.py @@ -0,0 +1,194 @@ +"""Confirm actual failure prefixes without replaying every selected test subset.""" + +from __future__ import annotations + +import hashlib +import json +import subprocess +import time +from collections import defaultdict +from collections.abc import Callable, Sequence +from concurrent.futures import ThreadPoolExecutor, as_completed +from pathlib import Path +from typing import Any + +import pytest +from pytest_gremlins import plugin +from pytest_gremlins.instrumentation.gremlin import Gremlin +from pytest_gremlins.node_id_file import command_with_node_ids_file +from pytest_gremlins.parallel.exit_codes import COLLECTION_KILLING_TEST + +from tests.mutation_bootstrap import baseline_environment, test_command + +type _PendingKill = tuple[Gremlin, list[str], plugin.GremlinResult, plugin.GremlinSession] +type _ControlKey = tuple[tuple[str, ...], tuple[str, ...]] +type _Recorder = Callable[ + [Gremlin, Sequence[str], plugin.GremlinResult, plugin.GremlinSession], None +] + + +def _execution_path(directory: Path, gremlin_id: str) -> Path: + identifier = hashlib.sha256(gremlin_id.encode()).hexdigest() + return directory / f"execution-{identifier}.json" + + +def _read_execution(path: Path) -> dict[str, Any]: + evidence = json.loads(path.read_text()) + if ( + not isinstance(evidence, dict) + or not isinstance(evidence.get("tests"), list) + or not all(isinstance(test, str) for test in evidence["tests"]) + or type(evidence.get("failed")) is not bool + or type(evidence.get("stopped")) is not bool + or type(evidence.get("exit_code")) is not int + ): + raise ValueError("Invalid test execution evidence") + return evidence + + +class FailurePrefixControls: + def __init__(self, workers: int, output: Path, *, checked_orders: bool = False) -> None: + self.workers = workers + self.output = output + self.checked_orders = checked_orders + self.pending: list[_PendingKill] = [] + + def defer( + self, + gremlin: Gremlin, + selected: Sequence[str], + result: plugin.GremlinResult, + session: plugin.GremlinSession, + ) -> bool: + if result.status.value != "zapped" or result.killing_test == COLLECTION_KILLING_TEST: + return False + self.pending.append((gremlin, list(selected), result, session)) + return True + + def flush(self, session: plugin.GremlinSession, record: _Recorder) -> None: + """Validate deferred kills after the mutant pool closes, within its worker budget.""" + started_at = time.perf_counter() + directory = session.instrumented_dir + if directory is None: + raise pytest.UsageError("Missing instrumented sources for failure confirmation") + groups: dict[_ControlKey, list[_PendingKill]] = defaultdict(list) + baseline_reused = 0 + executions: dict[str, dict[str, Any]] = {} + with (self.output / "executions.jsonl").open("w") as output: + for gremlin in session.gremlins: + try: + evidence = _read_execution(_execution_path(directory, gremlin.gremlin_id)) + executions[gremlin.gremlin_id] = evidence + except (OSError, ValueError): + evidence = None + output.write( + json.dumps( + { + "gremlin_id": gremlin.gremlin_id, + "executed_tests": len(evidence["tests"]) if evidence else None, + "last_test": ( + evidence["tests"][-1] if evidence and evidence["tests"] else None + ), + "failed": evidence["failed"] if evidence else None, + "exit_code": evidence["exit_code"] if evidence else None, + } + ) + + "\n" + ) + for row in self.pending: + gremlin, selected, _, _ = row + if gremlin.gremlin_id not in executions: + raise pytest.UsageError("Missing actual failing-test execution evidence") + evidence = executions[gremlin.gremlin_id] + prefix = evidence["tests"] + if ( + not prefix + or evidence["exit_code"] != 1 + or not evidence["failed"] + or prefix != selected[: len(prefix)] + ): + raise pytest.UsageError("Invalid actual failing-test execution evidence") + if self.checked_orders or selected == list(session.test_node_ids): + record(*row) + baseline_reused += 1 + else: + groups[(tuple(selected), tuple(prefix))].append(row) + + # Each prefix is an initial segment of the same collected selection. A + # successful longer prefix also proves its shorter failure prefixes. + original_prefixes = len(groups) + longest: dict[tuple[str, ...], tuple[_ControlKey, list[_PendingKill]]] = {} + for key, rows in groups.items(): + selected, prefix = key + if selected not in longest: + longest[selected] = (key, list(rows)) + else: + previous, previous_rows = longest[selected] + longest[selected] = ( + key if len(prefix) > len(previous[1]) else previous, + previous_rows + rows, + ) + groups = dict(longest.values()) + command = test_command(directory, session) + + def confirm(key: _ControlKey) -> _ControlKey: + selected, prefix = key + identifier = hashlib.sha256(json.dumps(key).encode()).hexdigest() + report = directory / f"prefix-{identifier}.json" + env = baseline_environment(directory) + env["TRAILMARK_PREFIX_LIMIT"] = str(len(prefix)) + env["TRAILMARK_PREFIX_REPORT"] = str(report) + control = subprocess.run( # noqa: S603 + command_with_node_ids_file(command, selected, directory), + env=env, + capture_output=True, + text=True, + timeout=240, + check=False, + ) + try: + evidence = _read_execution(report) + except (OSError, ValueError) as exc: + raise pytest.UsageError("Missing neutral failure-prefix evidence") from exc + if ( + control.returncode + or evidence["failed"] + or evidence["tests"] != list(prefix) + or not evidence["stopped"] + or evidence["exit_code"] != 0 + ): + raise pytest.UsageError( + "Unmutated failure prefix failed: " + + control.stdout[-2000:] + + control.stderr[-2000:] + ) + return key + + print( + f"Confirming {len(groups)} actual failure prefixes for {len(self.pending)} kills", + flush=True, + ) + pool = ThreadPoolExecutor(max_workers=self.workers) + try: + futures = {pool.submit(confirm, key): key for key in groups} + for completed, future in enumerate(as_completed(futures), 1): + key = future.result() + for row in groups[key]: + record(*row) + if completed % 25 == 0 or completed == len(futures): + print(f"Confirmed failure prefixes: {completed}/{len(futures)}", flush=True) + finally: + pool.shutdown(wait=True, cancel_futures=True) + summary = { + "recorded_mutants": len(executions), + "actual_mutant_test_executions": sum(len(e["tests"]) for e in executions.values()), + "kills": len(self.pending), + "baseline_reused_kills": baseline_reused, + "distinct_prefix_controls": len(groups), + "prefixes_before_reuse": original_prefixes, + "executed_neutral_tests": sum(len(key[1]) for key in groups), + "full_subset_neutral_tests": sum(len(key[0]) for key in groups), + "wall_seconds": time.perf_counter() - started_at, + } + (self.output / "prefix-summary.json").write_text(json.dumps(summary, indent=2) + "\n") + self.pending.clear() diff --git a/tests/mutation_controls.py b/tests/mutation_controls.py new file mode 100644 index 0000000..392d9fb --- /dev/null +++ b/tests/mutation_controls.py @@ -0,0 +1,122 @@ +"""Bind shared mutation baseline checks to their exact execution inputs.""" + +from __future__ import annotations + +import hashlib +import json +import os +import platform +import subprocess +import sys +from importlib.metadata import distributions +from pathlib import Path +from typing import Any + + +def _input_files(root: Path) -> list[Path]: + inventory = subprocess.run( # noqa: S603 + ["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"], # noqa: S607 + cwd=root, + capture_output=True, + check=False, + ) + if inventory.returncode == 0: + return sorted({root / os.fsdecode(name) for name in inventory.stdout.split(b"\0") if name}) + # Small standalone projects in the runner's subprocess controls need no Git repository. + paths = [] + for directory, children, files in os.walk(root): + children[:] = [ + name + for name in children + if not name.startswith(".") and name not in {"__pycache__", "coverage", "node_modules"} + ] + paths.extend(Path(directory) / name for name in files if not name.endswith(".pyc")) + return sorted(paths) + + +def digest(value: Any) -> str: + return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest() + + +def _file_digest(path: Path) -> str: + with path.open("rb") as source: + return hashlib.file_digest(source, "sha256").hexdigest() + + +def input_fingerprint(root: Path) -> str: + files = { + path.relative_to(root).as_posix(): _file_digest(path) + for path in _input_files(root) + if path.is_file() + } + environment = { + key: value + for key, value in os.environ.items() + if key.startswith("TRAILMARK_") + or key + in { + "PYTEST_ADDOPTS", + "PYTEST_PLUGINS", + "PYTEST_DISABLE_PLUGIN_AUTOLOAD", + "PYTHONHASHSEED", + "PYTHONPATH", + } + } + packages = sorted((dist.metadata["Name"], dist.version) for dist in distributions()) + return digest( + { + "files": files, + "python": sys.version, + "platform": [sys.platform, platform.machine()], + "packages": packages, + "environment": environment, + "native_tools": { + key: _file_digest(Path(value)) if Path(value).is_file() else None + for key, value in environment.items() + if key.startswith(("TRAILMARK_LLVM_", "TRAILMARK_GNU_")) + }, + } + ) + + +def baseline_receipt( + context: dict[str, Any], orders: list[tuple[str, ...]], shard: tuple[int, int] +) -> dict[str, Any]: + return _partition_receipt(context, [digest(order) for order in orders], shard) + + +def _partition_receipt( + context: dict[str, Any], identifiers: list[str], shard: tuple[int, int] +) -> dict[str, Any]: + index, count = shard + return { + "context": context, + "orders": identifiers, + "shard": list(shard), + "checked": identifiers[index - 1 :: count], + } + + +def validate_baselines( + directory: Path, + context: dict[str, Any], + orders: list[tuple[str, ...]], +) -> None: + paths = sorted(directory.glob("baseline-*.json")) + if not paths: + raise ValueError("Missing shared mutation baselines") + receipts = [json.loads(path.read_text()) for path in paths] + first_shard = receipts[0]["shard"] + if not isinstance(first_shard, list) or len(first_shard) != 2: + raise ValueError("Invalid shared mutation baseline partition") + count = first_shard[1] + if type(count) is not int or count != len(receipts): + raise ValueError("Incomplete shared mutation baselines") + by_partition = {tuple(receipt["shard"]): receipt for receipt in receipts} + identifiers = [digest(order) for order in orders] + expected = { + (index, count): _partition_receipt(context, identifiers, (index, count)) + for index in range(1, count + 1) + } + if len(by_partition) != len(receipts) or by_partition != expected: + raise ValueError("Stale, incomplete, or mismatched shared mutation baselines") diff --git a/tests/mutation_coverage.py b/tests/mutation_coverage.py new file mode 100644 index 0000000..6fac26f --- /dev/null +++ b/tests/mutation_coverage.py @@ -0,0 +1,405 @@ +"""Collect conservative per-test coverage for mutation test selection.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import shutil +import subprocess +import sys +from collections import defaultdict +from collections.abc import Generator, Sequence +from pathlib import Path +from typing import Any +from unittest.mock import patch + +import coverage +import pytest +from _pytest.fixtures import FixtureDef +from pytest_gremlins.instrumentation.spawn_hook import export_spawn_hook + +if __package__ in {None, ""}: + sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +from tests.mutation_controls import digest + + +def _fixture_key(fixture: Any) -> str: + return json.dumps([fixture.baseid, fixture.argname, fixture.scope]) + + +def native_tool_fingerprints() -> dict[str, str]: + """Known native tools cannot execute the Python mutation in their own process.""" + candidates = { + value + for key, value in os.environ.items() + if key.startswith(("TRAILMARK_LLVM_", "TRAILMARK_GNU_")) + } + candidates.update( + path + for command in ("cc", "clang", "clang++", "gcc", "g++", "git") + if (path := shutil.which(command)) + ) + for candidate in tuple(candidates): + if Path(candidate).name == "llvm-objdump": + candidates.add(str(Path(candidate).with_name("llvm-strip"))) + native = {} + for candidate in candidates: + path = Path(candidate).resolve() + if ( + path.name.lower().startswith(("python", "pypy")) + or path == Path(sys.executable).resolve() + ): + continue + if str(path) in native: + continue + try: + with path.open("rb") as executable: + magic = executable.read(4) + # Script wrappers remain opaque even under a configured tool name. + if magic in { + b"\x7fELF", + b"\xcf\xfa\xed\xfe", + b"\xfe\xed\xfa\xcf", + b"\xca\xfe\xba\xbe", + }: + executable.seek(0) + native[str(path)] = hashlib.file_digest(executable, "sha256").hexdigest() + except OSError: + continue + return native + + +class SelectionCoverage: + """Attribute fixture setup to every consumer and preserve opaque executions.""" + + def __init__(self, measured: coverage.Coverage, tests: list[str]) -> None: + self.measured = measured + self.tests = tests + self.context: tuple[str, str] | None = None + self.consumers: dict[str, set[str]] = defaultdict(set) + self.uncertain: set[tuple[str, str]] = set() + self.collection_uncertain = False + self.completed: set[str] = set() + self._finish_fixture = FixtureDef.finish + self.native_tools = native_tool_fingerprints() + git = shutil.which("git") + self.git_tool = str(Path(git).resolve()) if git else None + self.tracer: object = None + self.recording = True + self.switching_context = False + + def audit(self, event: str, arguments: tuple[object, ...]) -> None: + if not self.recording: + return + if event in {"sys.settrace", "sys._settraceallthreads"} and self.switching_context: + return + if event in {"subprocess.Popen", "os.posix_spawn", "os.exec"} and arguments: + executable = arguments[0] + if isinstance(executable, (str, bytes)): + name = os.fsdecode(executable) + resolved = shutil.which(name) if not Path(name).is_absolute() else name + if resolved is not None and str(Path(resolved).resolve()) in self.native_tools: + if str(Path(resolved).resolve()) != self.git_tool: + return + argv = arguments[1] if len(arguments) > 1 else None + if ( + isinstance(argv, (list, tuple)) + and len(argv) == 5 + and all(isinstance(arg, (str, bytes)) for arg in argv) + ): + argv = [os.fsdecode(arg) for arg in argv] + if argv[:2] == [name, "-C"] and argv[3:] == ["rev-parse", "HEAD"]: + return + if event in { + "subprocess.Popen", + "os.fork", + "os.forkpty", + "os.posix_spawn", + "os.exec", + "sys.settrace", + "sys._settraceallthreads", + }: + if self.context is not None: + self.uncertain.add(self.context) + else: + self.collection_uncertain = True + + def _switch(self, context: tuple[str, str] | None) -> None: + self.context = context + self.switching_context = True + try: + self.measured.switch_context(json.dumps(context) if context is not None else "") + finally: + self.switching_context = False + + def _phase(self, item: pytest.Item) -> Generator[None, None, None]: + if sys.gettrace() is not self.tracer: + raise pytest.UsageError("Coverage tracer was replaced between tests") + previous = self.context + self._switch(("test", item.nodeid)) + try: + yield + finally: + self._switch(previous) + if sys.gettrace() is not self.tracer: + raise pytest.UsageError("Test did not restore the coverage tracer") + + @pytest.hookimpl(hookwrapper=True, tryfirst=True) + def pytest_runtest_setup(self, item: pytest.Item) -> Generator[None, None, None]: + yield from self._phase(item) + + @pytest.hookimpl(hookwrapper=True, tryfirst=True) + def pytest_runtest_call(self, item: pytest.Item) -> Generator[None, None, None]: + yield from self._phase(item) + + @pytest.hookimpl(hookwrapper=True, tryfirst=True) + def pytest_runtest_teardown(self, item: pytest.Item) -> Generator[None, None, None]: + # This includes cached fixtures and fixtures obtained with getfixturevalue. + request = getattr(item, "_request", None) + if request is not None: + for fixture in request._fixture_defs.values(): + if hasattr(fixture, "baseid"): + self.consumers[_fixture_key(fixture)].add(item.nodeid) + yield from self._phase(item) + + @pytest.hookimpl(hookwrapper=True, tryfirst=True) + def pytest_fixture_setup(self, fixturedef: Any) -> Generator[None, None, None]: + previous = self.context + self._switch(("fixture", _fixture_key(fixturedef))) + try: + yield + finally: + self._switch(previous) + + def finish_fixture(self, fixturedef: Any, request: Any) -> None: + previous = self.context + self._switch(("fixture", _fixture_key(fixturedef))) + try: + self._finish_fixture(fixturedef, request) + finally: + self._switch(previous) + + @pytest.hookimpl(tryfirst=True) + def pytest_load_initial_conftests(self) -> None: + for finder in list(sys.meta_path): + if getattr(finder, "is_gremlin_finder", False): + sys.meta_path.remove(finder) + sys.meta_path.insert(0, finder) + + def pytest_collection_finish(self, session: pytest.Session) -> None: + if [item.nodeid for item in session.items] != self.tests: + raise pytest.UsageError("Coverage collection changed the requested test selection") + + def pytest_runtest_logreport(self, report: pytest.TestReport) -> None: + if report.when == "call" or (report.when == "setup" and report.skipped): + self.completed.add(report.nodeid) + + def _tests_for(self, context: tuple[str, str]) -> set[str]: + kind, name = context + if kind == "test": + return {name} + if kind == "fixture": + # A fixture skipped during setup may never enter request._fixture_defs. + return self.consumers.get(name, set(self.tests)) + raise ValueError(f"Unresolved coverage context: {context}") + + def selection(self, root: Path) -> dict[str, Any]: + if self.completed != set(self.tests): + raise ValueError("Coverage run did not finish every selected test") + opaque = set() + indices = {test: index for index, test in enumerate(self.tests)} + for context in self.uncertain: + opaque.update(self._tests_for(context)) + locations: dict[str, dict[str, list[int]]] = {} + imported: dict[str, list[int]] = {} + data = self.measured.get_data() + for filename in sorted(data.measured_files()): + path = Path(filename).resolve().relative_to(root).as_posix() + lines = {} + imports = [] + for line, contexts in data.contexts_by_lineno(filename).items(): + # Python 3.15 can report a synthetic line zero for an empty module. + if line < 1: + continue + tests = set() + for raw in contexts: + if raw: + tests.update(self._tests_for(tuple(json.loads(raw)))) + else: + imports.append(line) + if tests: + lines[str(line)] = sorted(indices[test] for test in tests) + locations[path] = lines + imported[path] = sorted(imports) + return { + "tests": self.tests, + "locations": locations, + "imported": imported, + "uncertain": sorted(indices[test] for test in opaque), + "collection_uncertain": self.collection_uncertain, + "native_tools": self.native_tools, + } + + +def select_tests( + plan: dict[str, Any], source: str, line: int, tests: list[str], *, root: Path | None = None +) -> list[str]: + """Use observed coverage, retaining opaque executions and unknown locations.""" + root = (root or Path.cwd()).resolve() + path = Path(source) + path = (path if path.is_absolute() else root / path).resolve().relative_to(root).as_posix() + covered = plan["locations"].get(path, {}).get(str(line)) + if not covered or plan["collection_uncertain"] or line in plan["imported"].get(path, []): + return tests + selected = set(covered) | set(plan["uncertain"]) + return [test for index, test in enumerate(tests) if index in selected] + + +def collect_plan( + directory: Path, + command: Sequence[str], + tests: list[str], + sources: list[str], + *, + instrumented: bool = False, +) -> dict[str, Any]: + """Require a successful complete pre-scan; never reuse a partial coverage map.""" + specification = directory / "coverage-input.json" + destination = directory / "coverage-plan.json" + destination.unlink(missing_ok=True) + specification.write_text(json.dumps({"tests": tests, "sources": sources})) + env = os.environ.copy() + env.pop("ACTIVE_GREMLIN", None) + if instrumented: + sources_file = directory / "sources.json" + if not sources_file.is_file(): + raise pytest.UsageError("Missing sources for the instrumented coverage baseline") + env["PYTEST_GREMLINS_SOURCES_FILE"] = str(sources_file) + env["GREMLIN_ROOTDIR"] = str(Path.cwd()) + export_spawn_hook(env) + else: + env.pop("PYTEST_GREMLINS_SOURCES_FILE", None) + env.pop("COVERAGE_PROCESS_CONFIG", None) + env.pop("COVERAGE_PROCESS_START", None) + env["COVERAGE_CORE"] = "ctrace" + env["TRAILMARK_MUTATION_COVERAGE"] = "1" + result = subprocess.run( # noqa: S603 + [ + sys.executable, + str(Path(__file__).resolve()), + str(specification), + str(destination), + *command, + ], + env=env, + check=False, + ) + if result.returncode: + if instrumented: + raise pytest.UsageError( + "Instrumented baseline failed during coverage collection; refusing a partial map" + ) + raise pytest.UsageError("Coverage baseline failed; refusing a partial selection map") + try: + return json.loads(destination.read_text()) + except (OSError, ValueError) as exc: + raise pytest.UsageError( + "Coverage baseline did not produce complete selection evidence" + ) from exc + + +def validate_plan( + envelope: dict[str, Any], + context: dict[str, Any], + tests: list[str], + sources: set[str], +) -> dict[str, Any]: + """Reject stale, incomplete, or unresolvable shared selection evidence.""" + if not isinstance(envelope, dict) or not {"plan", "context", "digest"} <= envelope.keys(): + raise ValueError("Incomplete coverage selection evidence") + plan = envelope["plan"] + if ( + not isinstance(plan, dict) + or not { + "tests", + "locations", + "imported", + "uncertain", + "collection_uncertain", + "native_tools", + } + <= plan.keys() + ): + raise ValueError("Incomplete coverage selection plan") + if envelope["context"] != context or envelope["digest"] != digest(plan): + raise ValueError("Stale or corrupt coverage selection plan") + if plan["native_tools"] != native_tool_fingerprints(): + raise ValueError("Native tools changed after coverage selection") + if plan["tests"] != tests or type(plan["collection_uncertain"]) is not bool: + raise ValueError("Coverage plan does not match the selected tests") + + def test_list(value: Any) -> None: + if ( + not isinstance(value, list) + or not all(type(item) is int and 0 <= item < len(tests) for item in value) + or len(value) != len(set(value)) + ): + raise ValueError("Coverage plan contains unknown or duplicate test IDs") + + test_list(plan["uncertain"]) + if not isinstance(plan["locations"], dict) or not isinstance(plan["imported"], dict): + raise ValueError("Invalid coverage location inventory") + for source, lines in plan["locations"].items(): + if source not in sources or not isinstance(lines, dict): + raise ValueError("Coverage plan contains an unknown source") + for line, selected in lines.items(): + if not isinstance(line, str) or not line.isdecimal() or int(line) < 1: + raise ValueError("Coverage plan contains an invalid line number") + test_list(selected) + for source, lines in plan["imported"].items(): + if source not in sources or not isinstance(lines, list): + raise ValueError("Coverage plan contains an unknown imported source") + if any(type(line) is not int or line < 1 for line in lines): + raise ValueError("Coverage plan contains an invalid import line") + return plan + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("specification", type=Path) + parser.add_argument("destination", type=Path) + parser.add_argument("pytest_arguments", nargs=argparse.REMAINDER) + args = parser.parse_args() + specification = json.loads(args.specification.read_text()) + measured = coverage.Coverage( + config_file=False, + include=specification["sources"], + data_file=str(args.specification.with_suffix(".coverage")), + ) + collector = SelectionCoverage(measured, specification["tests"]) + measured.start() + collector.tracer = sys.gettrace() + sys.addaudithook(collector.audit) + + def finish_fixture(fixturedef: Any, request: Any) -> None: + collector.finish_fixture(fixturedef, request) + + try: + with patch.object(FixtureDef, "finish", finish_fixture): + result = pytest.main( + [*args.pytest_arguments, *specification["tests"]], plugins=[collector] + ) + finally: + collector.recording = False + measured.stop() + if result == 0: + plan = collector.selection(Path.cwd()) + args.destination.write_text(json.dumps({"plan": plan, "digest": digest(plan)}) + "\n") + return int(result) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/mutation_gate.py b/tests/mutation_gate.py index 29a5761..1b8970c 100644 --- a/tests/mutation_gate.py +++ b/tests/mutation_gate.py @@ -16,6 +16,9 @@ from pytest_gremlins.instrumentation.gremlin import Gremlin from pytest_gremlins.instrumentation.transformer import transform_source +from tests.mutation_coverage import select_tests as coverage_tests +from tests.mutation_coverage import validate_plan +from tests.mutation_order import prioritize_tests from tests.run_mutations import RUNNER, VERSION, parse_shard, select_shard @@ -120,6 +123,39 @@ def _validate_versions(run: dict[str, Any], baseline: dict[str, Any]) -> None: raise ValueError("Mutation version does not match the reviewed baseline") if run["runner"] != RUNNER: raise ValueError("Report lacks validated pytest execution") + if run.get("test_selection") not in {"coverage", "full"}: + raise ValueError("Unknown mutation test selection mode") + confirmation = "baseline-orders" if run["test_selection"] == "full" else "failure-prefix" + if run.get("kill_confirmation") != confirmation: + raise ValueError("Report lacks validated pytest failure confirmation") + + +def _validate_test_selection(root: Path, report: dict[str, Any], run: dict[str, Any]) -> None: + if run["test_selection"] == "full": + return + envelope = json.loads((root / "coverage/gremlins/coverage-plan.json").read_text()) + expected = { + key: run[key] + for key in ( + "inputs", + "pytest_gremlins", + "runner", + "targets", + "tests", + "test_order", + "test_selection", + ) + } + expected["addopts"] = envelope["context"]["addopts"] + expected["coverage_plan"] = run["selection_plan"] + tests = envelope["plan"]["tests"] + plan = validate_plan(envelope, expected, tests, set(run["sources"])) + for row in report["results"]: + selected = coverage_tests(plan, row["file_path"], row["line_number"], tests, root=root) + if selected != tests and run["test_order"] == "component": + selected = prioritize_tests(row["file_path"], selected) + if row["selected_tests"] != selected: + raise ValueError("Mutation test selection differs from the validated coverage plan") def _validate_report( @@ -207,6 +243,18 @@ def check( if run.get("shard") != list(shard): raise ValueError("Mutation report shard does not match the requested partition") _validate_report(report, baseline, allow_empty=shard[1] > 1) + _validate_test_selection(root, report, run) + inconclusive = [ + { + "path": row["file_path"], + "gremlin_id": row["gremlin_id"], + "status": row["status"] if row.get("selected_tests") else "no tests", + } + for row in report["results"] + if row["status"] in {"timeout", "error", "pardoned"} or not row.get("selected_tests") + ] + if inconclusive: + return [json.dumps(row, sort_keys=True) for row in inconclusive] reviewed = _reviewed_exceptions(baseline) legacy = { (entry["path"], entry["function"]): entry["source_hash"] diff --git a/tests/mutation_order.py b/tests/mutation_order.py index 2f47145..7b45706 100644 --- a/tests/mutation_order.py +++ b/tests/mutation_order.py @@ -16,15 +16,20 @@ def prioritize_tests(source: str, node_ids: list[str]) -> list[str]: f"test_{language}_grammar.py", f"test_{language}_parser.py", ] - elif "parsers" in parts and path.name in {"parser.py", "_scopes.py"}: + elif "parsers" in parts and path.parent.name != "parsers": language = path.parent.name preferred = [ f"test_{language}_local_items.py", f"test_{language}_parser.py", + f"test_{language}_rule_references.py", f"test_{language}_verus_regressions.py", ] + if path.name not in {"parser.py", "_scopes.py"}: + preferred.insert(0, f"test_{language}_{path.stem.removeprefix('_')}.py") elif path.name == "_common.py": preferred = ["test_common_parser.py", "test_directory_linking.py"] + elif path.name == "_declarations.py": + preferred = ["test_declaration_identity.py"] elif "models" in parts: preferred = { "snapshot.py": ["test_snapshots.py", "test_binary_snapshots.py", "test_models.py"], diff --git a/tests/parse_work.py b/tests/parse_work.py index 740b472..d5b6bbf 100644 --- a/tests/parse_work.py +++ b/tests/parse_work.py @@ -1,4 +1,4 @@ -"""Deterministic Python work counts for parser scaling regressions.""" +"""Deterministic Python work counts for parser and analysis regressions.""" import sys from collections.abc import Callable @@ -11,10 +11,11 @@ type _Trace = Callable[[FrameType, str, object], _Trace | None] -def parse_work(path: Path) -> tuple[CodeGraph, int]: - """Count parser line events, including code instrumented in temporary files. +def count_work[T](operation: Callable[[], T], *, max_work: int | None = None) -> tuple[T, int]: + """Count application line events, including code instrumented in temporary files. This measures Python traversal work; native grammar execution is excluded. + An optional work budget also bounds nonterminating Python traversals. """ work = 0 @@ -22,6 +23,8 @@ def count(frame: FrameType, event: str, argument: object) -> _Trace: nonlocal work if event == "line": work += 1 + if max_work is not None and work > max_work: + raise AssertionError(f"Application exceeded its {max_work} line-event work budget") return count def select(frame: FrameType, event: str, argument: object) -> _Trace | None: @@ -30,7 +33,14 @@ def select(frame: FrameType, event: str, argument: object) -> _Trace | None: previous = sys.gettrace() try: sys.settrace(select) - graph = parse_file(str(path)) + result = operation() finally: sys.settrace(previous) - return graph, work + return result, work + + +def parse_work( + path: Path, *, language: str | None = None, max_work: int | None = None +) -> tuple[CodeGraph, int]: + """Count parser work and optionally bound nonterminating Python traversals.""" + return count_work(lambda: parse_file(str(path), language), max_work=max_work) diff --git a/tests/run_mutations.py b/tests/run_mutations.py index 3634bae..cf66c98 100644 --- a/tests/run_mutations.py +++ b/tests/run_mutations.py @@ -1,8 +1,8 @@ """Run pytest-gremlins with complete pytest semantics and baseline controls. Run as ``uv run python -m tests.run_mutations --targets=src/trailmark/...``. -Use upstream's full-pytest bootstrap and import handling, adding complete test -selection, component ordering, and executed instrumented baseline controls. +Use upstream's full-pytest bootstrap and import handling, adding coverage-driven +selection, component ordering, shared baselines, and failure-prefix controls. """ from __future__ import annotations @@ -18,21 +18,28 @@ from collections.abc import Callable, Sequence from importlib.metadata import version from pathlib import Path +from typing import Any from unittest.mock import patch import pytest from pytest_gremlins import plugin from pytest_gremlins.instrumentation.gremlin import Gremlin -from pytest_gremlins.instrumentation.spawn_hook import export_spawn_hook from pytest_gremlins.node_id_file import command_with_node_ids_file if __package__ in {None, ""}: sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from tests.mutation_bootstrap import baseline_environment as _baseline_environment +from tests.mutation_bootstrap import record_source_collection_exits, record_test_execution +from tests.mutation_bootstrap import test_command as _test_command +from tests.mutation_confirmation import FailurePrefixControls +from tests.mutation_controls import baseline_receipt, input_fingerprint, validate_baselines +from tests.mutation_coverage import collect_plan, validate_plan +from tests.mutation_coverage import select_tests as coverage_tests from tests.mutation_order import prioritize_tests, relative_node_ids VERSION = "1.14.3" -RUNNER = "trailmark-full-pytest-v4" +RUNNER = "trailmark-pytest-coverage-v9" def parse_shard(value: str) -> tuple[int, int]: @@ -66,14 +73,32 @@ def _arguments() -> argparse.Namespace: "--shard", type=parse_shard, default=(1, 1), help="Run partition INDEX/TOTAL (one-based)" ) parser.add_argument("--test-order", choices=["component", "collection"], default="component") + parser.add_argument("--test-selection", choices=["coverage", "full"], default="coverage") + controls = parser.add_mutually_exclusive_group() + controls.add_argument( + "--baseline-shard", + type=parse_shard, + help="Validate only partition INDEX/TOTAL of the instrumented test orders", + ) + controls.add_argument( + "--baselines", + type=Path, + help="Reuse a complete set of matching shared baseline receipts", + ) parser.add_argument("tests", nargs="*", default=["tests"]) args = parser.parse_args() + if args.workers < 1: + parser.error("--workers must be positive") if version("pytest-gremlins") != VERSION: parser.error( f"Revalidate the mutation runner adapter before changing pytest-gremlins {VERSION}" ) if os.environ.get("TRAILMARK_UPDATE_SNAPSHOTS") == "1": parser.error("Snapshot updates are disabled in mutation testing") + if args.baseline_shard and args.shard != (1, 1): + parser.error("--baseline-shard cannot be combined with --shard") + if args.test_selection == "coverage" and args.baseline_shard not in {None, (1, 1)}: + parser.error("Coverage selection uses a single --baseline-shard=1/1") if args.reviewed: baseline_path = Path(__file__).with_name("mutation_baseline.json") args.targets = ",".join(json.loads(baseline_path.read_text())["scope"]) @@ -91,30 +116,76 @@ def _source_hashes(targets: str) -> dict[str, str]: def _check_instrumented_orders( - directory: Path, instrumented_asts: dict[str, ast.Module], test_order: str -) -> None: - env = os.environ.copy() - env.pop("ACTIVE_GREMLIN", None) - env["PYTEST_GREMLINS_SOURCES_FILE"] = str(directory / "sources.json") - env["GREMLIN_ROOTDIR"] = str(Path.cwd()) - export_spawn_hook(env) + directory: Path, + instrumented_asts: dict[str, ast.Module], + args: argparse.Namespace, + fingerprint: str, + plans: list[dict[str, Any]], +) -> dict[str, object]: + env = _baseline_environment(directory) session = plugin._get_session() if session is None: raise pytest.UsageError("Missing mutation session for baseline validation") if session.skipped_files: raise pytest.UsageError(f"Mutation instrumentation skipped files: {session.skipped_files}") - command = plugin._build_test_command( - directory, session.preserved_addopts, xdist_loaded=session.xdist_loaded - ) + command = _test_command(directory, session) tests = list(session.test_node_ids) - orders = { - tuple(prioritize_tests(path, tests) if test_order == "component" else tests) - for path in instrumented_asts + orders = sorted( + { + tuple(prioritize_tests(path, tests) if args.test_order == "component" else tests) + for path in instrumented_asts + } + ) + if args.test_selection == "coverage": + orders = [tuple(tests)] + context = { + "inputs": fingerprint, + "pytest_gremlins": VERSION, + "runner": RUNNER, + "targets": args.targets, + "tests": args.tests, + "test_order": args.test_order, + "test_selection": args.test_selection, + "addopts": session.preserved_addopts, } - for index, order in enumerate(sorted(orders), 1): - print(f"Checking instrumented baseline order {index}/{len(orders)}", flush=True) + if args.test_selection == "coverage": + sources = { + Path(path).resolve().relative_to(Path.cwd()).as_posix() for path in instrumented_asts + } + try: + if args.baselines is None: + envelope = collect_plan( + directory, + [*command[2:], "-p", "no:gremlins"], + tests, + [str(Path(path).resolve()) for path in instrumented_asts], + instrumented=True, + ) + else: + envelope = json.loads((args.baselines / "coverage-plan.json").read_text()) + if not isinstance(envelope, dict): + raise ValueError("Coverage selection evidence is not an object") + context["coverage_plan"] = envelope["digest"] + if args.baselines is None: + envelope["context"] = context + validate_plan(envelope, context, tests, sources) + except (OSError, ValueError, KeyError, TypeError) as exc: + raise pytest.UsageError(f"Invalid shared coverage selection: {exc}") from exc + plans.append(envelope) + if args.baselines is not None: + try: + validate_baselines(args.baselines, context, orders) + except (OSError, ValueError, KeyError, TypeError) as exc: + raise pytest.UsageError(f"Invalid shared mutation baselines: {exc}") from exc + print(f"Reusing validated instrumented baseline orders: {len(orders)}", flush=True) + return {} + shard = args.baseline_shard or (1, 1) + if args.test_selection == "coverage": + return baseline_receipt(context, orders, shard) + for index in range(shard[0] - 1, len(orders), shard[1]): + print(f"Checking instrumented baseline order {index + 1}/{len(orders)}", flush=True) control = subprocess.run( # noqa: S603 - command_with_node_ids_file(command, order, directory), + command_with_node_ids_file(command, orders[index], directory), env=env, check=False, timeout=180, @@ -123,10 +194,14 @@ def _check_instrumented_orders( raise pytest.UsageError( "Instrumented baseline failed; mutation results would be invalid" ) + return baseline_receipt(context, orders, shard) def _instrumented_writer( - test_order: str, + args: argparse.Namespace, + fingerprint: str, + receipts: list[dict[str, object]], + plans: list[dict[str, Any]], ) -> Callable[ [dict[str, ast.Module], Path, dict[str, list[str]] | None, dict[str, str] | None], Path ]: @@ -141,15 +216,19 @@ def write_and_check( directory = write_sources(instrumented_asts, rootdir, duplicates, unwritable) if unwritable: raise pytest.UsageError(f"Mutation instrumentation skipped files: {unwritable}") - _check_instrumented_orders(directory, instrumented_asts, test_order) + record_source_collection_exits(directory) + record_test_execution(directory) + receipts.append( + _check_instrumented_orders(directory, instrumented_asts, args, fingerprint, plans) + ) return directory return write_and_check class _RequireCompleteInstrumentation: - def __init__(self, shard: tuple[int, int]) -> None: - self.shard = shard + def __init__(self, args: argparse.Namespace) -> None: + self.args = args self.empty_shard = False @pytest.hookimpl(trylast=True) @@ -161,22 +240,41 @@ def pytest_collection_finish(self) -> None: f"Mutation instrumentation skipped files: {session.skipped_files}" ) if session is not None: - selected = select_shard(session.gremlins, self.shard) + if self.args.baseline_shard: + session.enabled = False + selected = select_shard(session.gremlins, self.args.shard) self.empty_shard = bool(session.gremlins) and not selected session.gremlins = selected - -def _run_campaign(args: argparse.Namespace, report_dir: Path) -> int: - instrumentation = _RequireCompleteInstrumentation(args.shard) + def pytest_runtestloop(self) -> bool: + # A real pytest subprocess validated neutral instrumentation, or + # collection checked matching shared evidence. The outer + # session only collects tests and dispatches mutations at session finish. + return True + + +def _run_campaign( + args: argparse.Namespace, + report_dir: Path, + fingerprint: str, + receipts: list[dict[str, object]], + plans: list[dict[str, Any]], +) -> int: + controls = FailurePrefixControls( + args.workers, report_dir, checked_orders=args.test_selection == "full" + ) cache_result = plugin._cache_gremlin_result + dispatch = plugin._dispatch_mutation_run + selections: dict[str, list[str]] = {} - def record_result( + def record_confirmed_result( gremlin: Gremlin, selected_tests: Sequence[str], result: plugin.GremlinResult, session: plugin.GremlinSession, ) -> None: - # Upstream calls this only after confirming subprocess outcomes. + # Native collection/timeout checks and our failure-prefix checks have + # finished before a result reaches this publication point. cache_result(gremlin, selected_tests, result, session) with (report_dir / "progress.jsonl").open("a") as progress: progress.write( @@ -194,22 +292,59 @@ def record_result( + "\n" ) - def select_tests(gremlin: Gremlin, session: plugin.GremlinSession) -> list[str]: + def record_result( + gremlin: Gremlin, + selected_tests: Sequence[str], + result: plugin.GremlinResult, + session: plugin.GremlinSession, + ) -> None: + if not controls.defer(gremlin, selected_tests, result, session): + record_confirmed_result(gremlin, selected_tests, result, session) + + def dispatch_and_confirm( + session: pytest.Session, gremlin_session: plugin.GremlinSession + ) -> list[plugin.GremlinResult]: + results = dispatch(session, gremlin_session) + controls.flush(gremlin_session, record_confirmed_result) + return results + + def uncached_tests(gremlin: Gremlin, session: plugin.GremlinSession) -> list[str]: tests = list(session.test_node_ids) + if args.test_selection == "coverage": + selected = coverage_tests( + plans[0]["plan"], str(gremlin.file_path), gremlin.line_number, tests + ) + if selected == tests or args.test_order == "collection": + return selected + return prioritize_tests(str(gremlin.file_path), selected) return ( tests if args.test_order == "collection" else prioritize_tests(str(gremlin.file_path), tests) ) + def select_tests(gremlin: Gremlin, session: plugin.GremlinSession) -> list[str]: + if gremlin.gremlin_id not in selections: + selections[gremlin.gremlin_id] = uncached_tests(gremlin, session) + return selections[gremlin.gremlin_id].copy() + + def reuse_coverage(session: plugin.GremlinSession, rootdir: Path) -> None: + # The writer already collected coverage while validating neutral instrumentation. + if args.test_selection == "coverage": + print("Reusing coverage from the validated baseline", flush=True) + + instrumentation = _RequireCompleteInstrumentation(args) with ( patch.object( - plugin, "_write_instrumented_sources", side_effect=_instrumented_writer(args.test_order) + plugin, + "_write_instrumented_sources", + side_effect=_instrumented_writer(args, fingerprint, receipts, plans), ), patch.object(plugin, "_make_node_ids_relative", side_effect=relative_node_ids), patch.object(plugin, "_select_tests_for_gremlin_prioritized", side_effect=select_tests), - patch.object(plugin, "_collect_coverage"), + patch.object(plugin, "_collect_coverage", side_effect=reuse_coverage), patch.object(plugin, "_cache_gremlin_result", side_effect=record_result), + patch.object(plugin, "_dispatch_mutation_run", side_effect=dispatch_and_confirm), ): result = pytest.main( [ @@ -219,15 +354,15 @@ def select_tests(gremlin: Gremlin, session: plugin.GremlinSession) -> list[str]: "not mutation_infrastructure", "--gremlins", "--gremlin-executor=subprocess", - "--gremlin-no-coverage-filter", + *(["--gremlin-no-coverage-filter"] if args.test_selection == "full" else []), f"--gremlin-workers={args.workers}", f"--gremlin-targets={args.targets}", - "--gremlin-report=json,html", + "--gremlin-report=json", f"--gremlins-html-dir={report_dir}", ], plugins=[instrumentation], ) - if result == 0 and instrumentation.empty_shard: + if result == 0 and instrumentation.empty_shard and not args.baseline_shard: (report_dir / "gremlins.json").write_text( json.dumps({"summary": {"total": 0}, "results": []}) + "\n" ) @@ -236,28 +371,56 @@ def select_tests(gremlin: Gremlin, session: plugin.GremlinSession) -> list[str]: def main() -> int: args = _arguments() + os.environ["TRAILMARK_MUTATION_TESTING"] = "1" report_dir = Path("coverage/gremlins") report_dir.mkdir(parents=True, exist_ok=True) - for name in ("run.json", "gremlins.json", "progress.jsonl"): + for name in ( + "run.json", + "gremlins.json", + "progress.jsonl", + "coverage-plan.json", + "prefix-summary.json", + "executions.jsonl", + ): (report_dir / name).unlink(missing_ok=True) - baseline = subprocess.run( # noqa: S603 - [sys.executable, "-m", "pytest", "-q", *args.tests], check=False - ) - if baseline.returncode: - return baseline.returncode + receipt_path = None + if args.baseline_shard: + index, count = args.baseline_shard + receipt_path = report_dir / f"baseline-{index}-of-{count}.json" + receipt_path.unlink(missing_ok=True) + fingerprint = input_fingerprint(Path.cwd()) hashes = _source_hashes(args.targets) - result = _run_campaign(args, report_dir) - if result == 0: + receipts: list[dict[str, object]] = [] + plans: list[dict[str, Any]] = [] + result = _run_campaign(args, report_dir, fingerprint, receipts, plans) + if result == 0 and (not receipts or input_fingerprint(Path.cwd()) != fingerprint): + print( + "Mutation inputs changed or instrumented baseline validation is missing", + file=sys.stderr, + ) + return 1 + if result == 0 and plans: + (report_dir / "coverage-plan.json").write_text(json.dumps(plans[0]) + "\n") + if result == 0 and receipt_path is not None: + receipt_path.write_text(json.dumps(receipts[0], indent=2) + "\n") + elif result == 0: (report_dir / "run.json").write_text( json.dumps( { "pytest_gremlins": VERSION, "runner": RUNNER, + "inputs": fingerprint, "test_order": args.test_order, + "test_selection": args.test_selection, + "selection_plan": plans[0]["digest"] if plans else None, "shard": args.shard, "targets": args.targets, "sources": hashes, "tests": args.tests, + "baseline_validation": "shared" if args.baselines is not None else "local", + "kill_confirmation": ( + "baseline-orders" if args.test_selection == "full" else "failure-prefix" + ), }, indent=2, ) diff --git a/tests/test_aiken_parser.py b/tests/test_aiken_parser.py index 05a3445..50a8d00 100644 --- a/tests/test_aiken_parser.py +++ b/tests/test_aiken_parser.py @@ -7,8 +7,10 @@ from tree_sitter_language_pack import get_language from trailmark.models.edges import EdgeConfidence, EdgeKind +from trailmark.models.graph import CodeGraph from trailmark.models.nodes import NodeKind from trailmark.parse import detect_languages, parse_directory, parse_file +from trailmark.parsers.aiken.parser import _Extractor from trailmark.query.api import QueryEngine @@ -19,6 +21,14 @@ def _source(tmp_path: Path, text: str) -> Path: return path +@pytest.mark.parametrize( + ("owner", "expected"), [("sample", "sample:run"), ("sample:validator", "sample:validator.run")] +) +def test_callable_ids_keep_the_module_and_lexical_owner(owner: str, expected: str) -> None: + extractor = _Extractor(CodeGraph(language="aiken"), "sample", "sample.ak") + assert extractor.child_id(owner, "run") == expected + + def test_types_signatures_imports_and_branches(tmp_path: Path) -> None: path = _source( tmp_path, diff --git a/tests/test_c_macros.py b/tests/test_c_macros.py new file mode 100644 index 0000000..a132d94 --- /dev/null +++ b/tests/test_c_macros.py @@ -0,0 +1,26 @@ +"""Declaration macro collection skips unresolved and previously visited headers.""" + +from pathlib import Path +from unittest.mock import Mock + +import pytest +from tree_sitter import Parser +from tree_sitter_language_pack import get_language + +from trailmark.parsers.c._headers import HeaderSources +from trailmark.parsers.c._macros import DeclarationMacros + + +@pytest.mark.parametrize("resolved", [False, True], ids=["unresolved", "repeated"]) +def test_header_collection_does_not_repeat_directive_work(tmp_path: Path, resolved: bool) -> None: + path = tmp_path / "header.h" + root = Parser(get_language("c")).parse(b"#define FLAG 1\n").root_node + headers = Mock(spec=HeaderSources) + headers.resolve.return_value = path if resolved else None + headers.conditions.return_value = {} + headers.directives.return_value = [] + macros = DeclarationMacros(root, str(path), headers) + macros._collect(root, path, 0, 0) + macros._collect(root, path, 0, 0) + assert headers.conditions.call_count == int(resolved) + assert headers.directives.call_count == int(resolved) diff --git a/tests/test_cairo_parser.py b/tests/test_cairo_parser.py index dcbf952..b12dd3d 100644 --- a/tests/test_cairo_parser.py +++ b/tests/test_cairo_parser.py @@ -4,15 +4,27 @@ import os import tempfile +from pathlib import Path import pytest from tree_sitter import Node +from tests.parse_work import parse_work from trailmark.models.edges import EdgeConfidence, EdgeKind from trailmark.models.graph import CodeGraph from trailmark.models.nodes import NodeKind from trailmark.parsers.cairo.parser import CairoParser, _first_path_segment + +def test_qualified_calls_stop_at_the_enclosing_module(tmp_path: Path) -> None: + path = tmp_path / "sample.cairo" + path.write_text("mod nested { fn helper() {} }\nfn run() { nested::helper(); }\n") + graph, _ = parse_work(path, max_work=100_000) + assert [ + (edge.source_id, edge.target_id) for edge in graph.edges if edge.kind == EdgeKind.CALLS + ] == [("sample:run", "sample:nested.helper")] + + SAMPLE_CODE = """\ use starknet::ContractAddress; diff --git a/tests/test_cpp_declaration_markers.py b/tests/test_cpp_declaration_markers.py index 0c5166f..7741457 100644 --- a/tests/test_cpp_declaration_markers.py +++ b/tests/test_cpp_declaration_markers.py @@ -7,12 +7,22 @@ import pytest +from tests.parse_work import parse_work from trailmark.models.edges import EdgeKind from trailmark.models.nodes import NodeKind from trailmark.parse import parse_file from trailmark.query.api import QueryEngine +def test_adjacent_comments_before_a_template_do_not_repeat_the_scan(tmp_path: Path) -> None: + path = tmp_path / "sample.cpp" + path.write_text("#define API\nAPI\n/**//**/\ntemplate class View {};\n") + graph, _ = parse_work(path, language="cpp", max_work=100_000) + assert graph.nodes["sample:View"].kind == NodeKind.CLASS + markers = json.loads(str(dict(graph.nodes["sample"].attributes)["cpp_declaration_markers"])) + assert [marker["role"] for marker in markers] == ["template_prefix"] + + @pytest.mark.parametrize("newline", ["\n", "\r\n"]) def test_namespace_and_constexpr_constructor_owners_keep_physical_sites( tmp_path: Path, newline: str diff --git a/tests/test_dafny_parser.py b/tests/test_dafny_parser.py index 3ca303a..19f72e1 100644 --- a/tests/test_dafny_parser.py +++ b/tests/test_dafny_parser.py @@ -1,5 +1,6 @@ from __future__ import annotations +import shutil import subprocess import sys from pathlib import Path @@ -9,6 +10,7 @@ from trailmark.models.edges import EdgeKind from trailmark.models.graph import CodeGraph from trailmark.parse import parse_directory, parse_file +from trailmark.tree_sitter_custom import _native FIXTURE = Path(__file__).parent / "fixtures/kat/dafny/taxonomy.dfy" @@ -239,8 +241,29 @@ def test_local_binding_forms(tmp_path: Path, body: str) -> None: def test_deep_generic_lookahead_is_bounded_in_native_scanner(tmp_path: Path) -> None: + grammar_root = Path(_native.__file__).parent + compiler = shutil.which("cc") + assert compiler is not None + executable = tmp_path / "scanner" + subprocess.run( # noqa: S603 -- compile the checked-in scanner boundary harness. + [ + compiler, + "-std=c11", + f"-I{grammar_root}", + f"-I{grammar_root / 'dafny/src'}", + str(Path(__file__).parent / "fixtures/dafny_type_scanner.c"), + "-o", + str(executable), + ], + check=True, + capture_output=True, + ) + subprocess.run([str(executable)], check=True, capture_output=True) # noqa: S603 + path = tmp_path / "Deep.dfy" - path.write_text("method Run(){var y:=F<" + "A<" * 200_000 + "int" + ">" * 200_000 + ">(0);}") + # Still cross the scanner's depth limit through the public parser. The C + # harness checks the exact boundary and lookahead work without a huge file. + path.write_text("method Run(){var y:=F<" + "A<" * 512 + "int" + ">" * 512 + ">(0);}") subprocess.run( # noqa: S603 -- fixed interpreter and source; only a test path varies. [ sys.executable, diff --git a/tests/test_declaration_identity.py b/tests/test_declaration_identity.py index b5af026..0c76647 100644 --- a/tests/test_declaration_identity.py +++ b/tests/test_declaration_identity.py @@ -7,6 +7,7 @@ import pytest +from tests.parse_work import parse_work from trailmark.analysis.proxies import ensure_proxy_nodes from trailmark.models import ( CodeGraph, @@ -25,6 +26,21 @@ from trailmark.parsers.solidity import SolidityParser from trailmark.parsers.swift import SwiftParser + +def test_recursive_calls_do_not_become_containment_cycles(tmp_path: Path) -> None: + path = tmp_path / "recursive.ts" + path.write_text( + "namespace Scope { export function outer() { function inner() { inner(); } inner(); } }\n" + ) + graph, _ = parse_work(path, max_work=100_000) + assert { + (edge.source_id, edge.target_id) for edge in graph.edges if edge.kind == EdgeKind.CALLS + } == { + ("recursive:Scope.outer", "recursive:Scope.outer.inner"), + ("recursive:Scope.outer.inner", "recursive:Scope.outer.inner"), + } + + _OVERLOADS = [ pytest.param( CppParser, diff --git a/tests/test_docs.py b/tests/test_docs.py index f297160..c129dff 100644 --- a/tests/test_docs.py +++ b/tests/test_docs.py @@ -350,6 +350,7 @@ def pyproject_data() -> dict[str, object]: ("CONTRIBUTING.md", "tests.mutation_gate"), ("CONTRIBUTING.md", "Confirmed execution outcomes are streamed to"), ("CONTRIBUTING.md", "The reviewed scope gates all functions in those files"), + ("CONTRIBUTING.md", "including outside the reviewed scope"), ( "docs/entrypoints.md", "PHP `namespace\\` prefixes resolve first-class function and method references", @@ -363,16 +364,32 @@ def pyproject_data() -> dict[str, object]: ("docs/python-api.md", "Binary, proxy, and synthetic nodes may retain the line range `(0, 0)`"), ("CONTRIBUTING.md", "Shared-helper mutants retain tests from"), ("CONTRIBUTING.md", "`--workers=4` already enables parallel"), - ("CONTRIBUTING.md", "CI runs eight mutation shards concurrently"), + ("CONTRIBUTING.md", "CI runs 32 mutation shards concurrently"), ( "CONTRIBUTING.md", "`TRAILMARK_REQUIRE_BINARY_TOOLS=1` so missing native-image dependencies fail", ), ("CONTRIBUTING.md", "--shard=INDEX/TOTAL"), - ("CONTRIBUTING.md", "tests.mutation_gate --shard=1/8"), - ("CONTRIBUTING.md", "requires all eight shards to pass"), + ("CONTRIBUTING.md", "tests.mutation_gate --shard=1/32"), + ("CONTRIBUTING.md", "all 32 mutation shards to pass"), + ("CONTRIBUTING.md", "without replaying"), + ("CONTRIBUTING.md", "Coverage-driven"), + ("CONTRIBUTING.md", "--test-selection=full"), + ("CONTRIBUTING.md", "--baseline-shard=1/1"), + ("CONTRIBUTING.md", "shared fixture setup and teardown attributed to every consumer"), + ("CONTRIBUTING.md", "gate verifies each reported test selection against the saved plan"), + ("CONTRIBUTING.md", "--baseline-shard=INDEX/TOTAL"), + ("CONTRIBUTING.md", "--baselines=PATH"), + ("CONTRIBUTING.md", "with neutral instrumentation and per-test coverage"), + ("CONTRIBUTING.md", "neutral failure-prefix"), + ("CONTRIBUTING.md", "same selected tests"), + ("CONTRIBUTING.md", "longest prefix also validates its shorter failure prefixes"), + ("CONTRIBUTING.md", "git -C ROOT rev-parse HEAD"), + ("CONTRIBUTING.md", "Missing, stale, or incomplete receipts fail the run"), + ("CONTRIBUTING.md", "run the full campaign before merging"), ("CONTRIBUTING.md", "inconclusive outcomes still fail the gate"), ("CONTRIBUTING.md", "pins pytest-gremlins 1.14.3"), + ("CONTRIBUTING.md", "Harness failures and unrelated internal errors remain errors"), ("CONTRIBUTING.md", "pytest timeout markers, or test subprocess deadlines"), # CLI output streams ("docs/cli.md", "`trailmark augment --json`"), diff --git a/tests/test_entrypoints.py b/tests/test_entrypoints.py index 41d5e2a..2297bbd 100644 --- a/tests/test_entrypoints.py +++ b/tests/test_entrypoints.py @@ -73,6 +73,12 @@ def test_pyramid_view_detector_requires_pyramid_binding(tmp_path: Path) -> None: } +@pytest.fixture(scope="class") +def self_analysis_engine() -> QueryEngine: + """Parse the repository once for the read-only self-analysis checks.""" + return QueryEngine.from_directory(str(SRC), language="python") + + class TestSelfAnalysis: """Running Trailmark on its own source must produce entrypoints. @@ -81,22 +87,19 @@ class TestSelfAnalysis: silently returned an empty list. """ - def test_self_analysis_has_entrypoints(self) -> None: - engine = QueryEngine.from_directory(str(SRC), language="python") - summary = engine.summary() + def test_self_analysis_has_entrypoints(self, self_analysis_engine: QueryEngine) -> None: + summary = self_analysis_engine.summary() assert summary["entrypoints"] > 0, ( "Running Trailmark on its own src/ must detect at least one " "entrypoint (the pyproject [project.scripts] target)." ) - def test_self_analysis_attack_surface_nonempty(self) -> None: - engine = QueryEngine.from_directory(str(SRC), language="python") - surface = engine.attack_surface() + def test_self_analysis_attack_surface_nonempty(self, self_analysis_engine: QueryEngine) -> None: + surface = self_analysis_engine.attack_surface() assert surface, "attack_surface() returned empty on trailmark's own source" - def test_self_analysis_finds_pyproject_script(self) -> None: - engine = QueryEngine.from_directory(str(SRC), language="python") - surface = engine.attack_surface() + def test_self_analysis_finds_pyproject_script(self, self_analysis_engine: QueryEngine) -> None: + surface = self_analysis_engine.attack_surface() node_ids = {ep["node_id"] for ep in surface} assert "trailmark.cli:main" in node_ids, ( f"Expected trailmark.cli:main (the pyproject.toml script target) in {node_ids}" diff --git a/tests/test_fstar_parser.py b/tests/test_fstar_parser.py index 444d432..3035268 100644 --- a/tests/test_fstar_parser.py +++ b/tests/test_fstar_parser.py @@ -4,6 +4,7 @@ import pytest +from tests.parse_work import parse_work from trailmark.models.edges import EdgeKind from trailmark.models.nodes import NodeOrigin from trailmark.parse import parse_directory, parse_file @@ -12,6 +13,19 @@ FIXTURE = Path(__file__).parent / "fixtures/kat/fstar/taxonomy.fst" +def test_ghost_effect_aliases_reach_a_fixed_point(tmp_path: Path) -> None: + path = tmp_path / "Effects.fst" + path.write_text( + "module Effects\neffect Erased (a:Type) = GTot a\n" + "effect Hidden (a:Type) = Erased a\n" + "let proof (x:int) : Hidden int = x\nlet run (x:int) : Tot int = x\n" + ) + graph, _ = parse_work(path, language="fstar", max_work=100_000) + functions = {node.name: dict(node.attributes) for node in graph.nodes.values()} + assert functions["proof"]["executable"] is False + assert functions["run"]["executable"] is True + + @pytest.mark.parametrize("effect", ["Tot", "ML", "Stack", "Lemma"]) @pytest.mark.parametrize("interface", [False, True]) def test_implementation_inherits_signature_effect( diff --git a/tests/test_java_parser.py b/tests/test_java_parser.py index 91abecf..29c7b90 100644 --- a/tests/test_java_parser.py +++ b/tests/test_java_parser.py @@ -4,12 +4,33 @@ import os import tempfile +from pathlib import Path +from tests.parse_work import parse_work from trailmark.models.edges import EdgeConfidence, EdgeKind from trailmark.models.graph import CodeGraph from trailmark.models.nodes import NodeKind from trailmark.parsers.java.parser import JavaParser + +def test_anonymous_fallback_stops_at_its_lexical_owner(tmp_path: Path) -> None: + source = tmp_path / "sample.java" + source.write_text( + "class Outer { class Base {} void helper() {}\n" + "Base make() { return new Base() { void run() { helper(); } }; } }\n" + ) + graph, _ = parse_work(source, max_work=100_000) + call = next( + edge + for edge in graph.edges + if edge.kind == EdgeKind.CALLS + and "$anonymous@" in edge.source_id + and edge.source_id.endswith(".run") + ) + assert call.target_id == "sample:Outer.helper" + assert call.confidence == EdgeConfidence.INFERRED + + SAMPLE_CODE = """\ import java.util.List; import java.io.IOException; diff --git a/tests/test_lean_parser.py b/tests/test_lean_parser.py index cc1d220..4c8c09e 100644 --- a/tests/test_lean_parser.py +++ b/tests/test_lean_parser.py @@ -6,6 +6,8 @@ from pathlib import Path import pytest +from tree_sitter import Parser +from tree_sitter_language_pack import get_language from trailmark.analysis.entrypoints import detect_entrypoints from trailmark.models.edges import CodeEdge, EdgeConfidence, EdgeKind @@ -13,6 +15,7 @@ from trailmark.models.nodes import NodeKind, TypeRef from trailmark.parse import detect_languages, parse_directory, parse_file, supported_languages from trailmark.parsers.lean import LeanParser +from trailmark.parsers.lean._syntax import application, field from trailmark.query.api import QueryEngine from trailmark.source_policy import SourcePolicy, SourceRoot @@ -31,6 +34,16 @@ def _references(graph: CodeGraph, source: str) -> list[CodeEdge]: return [e for e in graph.edges if e.kind == EdgeKind.REFERENCES and e.source_id == source] +def test_application_returns_the_head_and_arguments_in_source_order() -> None: + root = Parser(get_language("lean")).parse(b"def use := combine first second\n").root_node + declaration = root.named_children[0].named_children[0] + body = field(declaration, "body") + assert body is not None and body.type == "app" + head, arguments = application(body) + assert head.type == "identifier" and head.text == b"combine" + assert [argument.text for argument in arguments] == [b"first", b"second"] + + def test_reference_fixture_and_opt_in_queries(tmp_path: Path) -> None: source = (Path(__file__).parent / "fixtures/lean/references.lean").read_text() graph = _parse(tmp_path, source) diff --git a/tests/test_mutation_confirmation.py b/tests/test_mutation_confirmation.py new file mode 100644 index 0000000..be2f9ac --- /dev/null +++ b/tests/test_mutation_confirmation.py @@ -0,0 +1,149 @@ +"""A mutation kill must survive a matching neutral failure-prefix check.""" + +from __future__ import annotations + +import json +import subprocess +import sys +from pathlib import Path + +import pytest + +from tests.mutation_bootstrap import record_test_execution + +pytestmark = pytest.mark.mutation_infrastructure + + +def _campaign( + project: Path, + files: dict[str, str], + source: str = "def checked():\n return True\n", + *, + selection: str = "coverage", +) -> subprocess.CompletedProcess[str]: + (project / "target.py").write_text(source) + for name, content in files.items(): + (project / name).write_text(content) + return subprocess.run( # noqa: S603 + [ + sys.executable, + str(Path(__file__).with_name("run_mutations.py")), + "--targets=target.py", + "--workers=2", + f"--test-selection={selection}", + ".", + ], + cwd=project, + capture_output=True, + text=True, + check=False, + ) + + +def test_longest_failure_prefix_covers_shorter_failures(tmp_path: Path) -> None: + result = _campaign( + tmp_path, + { + "test_target.py": ( + "from target import checked\n" + "def test_negative():\n assert checked(-1) is False\n" + "def test_zero():\n assert checked(0) is True\n" + "def test_positive():\n assert checked(1) is True\n" + "def test_unrelated():\n assert True\n" + ) + }, + "def checked(value):\n return value >= 0\n", + ) + assert result.returncode == 0, result.stdout + result.stderr + reports = tmp_path / "coverage/gremlins" + report = json.loads((reports / "gremlins.json").read_text()) + assert len(report["results"]) == 5 + assert {row["status"] for row in report["results"]} == {"zapped"} + controls = json.loads((reports / "prefix-summary.json").read_text()) + assert controls["recorded_mutants"] == 5 + assert controls["actual_mutant_test_executions"] == 7 + assert controls["prefixes_before_reuse"] == 2 + assert controls["distinct_prefix_controls"] == 1 + assert controls["executed_neutral_tests"] == 2 + assert controls["full_subset_neutral_tests"] == 3 + + +def test_failure_prefix_keeps_the_entire_selected_collection(tmp_path: Path) -> None: + result = _campaign( + tmp_path, + { + "state.py": "ready = False\n", + "test_a_target.py": ( + "import state\nfrom target import checked\n" + "def test_first():\n assert not state.ready\n assert checked() is True\n" + ), + "test_b_target.py": ( + "import state\nfrom target import checked\nstate.ready = True\n" + "def test_weak():\n checked()\n" + ), + "test_c_reset.py": ( + "import state\nstate.ready = False\ndef test_unrelated():\n assert True\n" + ), + }, + ) + # The full baseline passes, but the selected collection changes state. A + # control that imported only the failing test would falsely credit the kill. + assert result.returncode != 0 + assert "Unmutated failure prefix failed" in result.stdout + result.stderr + assert not (tmp_path / "coverage/gremlins/run.json").exists() + + +def test_failure_prefix_executes_fixture_teardown(tmp_path: Path) -> None: + result = _campaign( + tmp_path, + { + "test_target.py": ( + "from pathlib import Path\nimport pytest\nfrom target import checked\n" + "@pytest.fixture(autouse=True)\ndef check_after():\n yield\n" + " with Path('coverage/events').open('a') as output:\n" + " output.write('teardown\\n')\n" + " assert checked() is True\n" + "def test_first():\n assert True\n" + "def test_second():\n assert True\n" + ), + "test_z_unrelated.py": "def test_unrelated():\n assert True\n", + }, + ) + assert result.returncode == 0, result.stdout + result.stderr + reports = tmp_path / "coverage/gremlins" + report = json.loads((reports / "gremlins.json").read_text()) + assert len(report["results"]) == 2 + assert {row["status"] for row in report["results"]} == {"zapped"} + controls = json.loads((reports / "prefix-summary.json").read_text()) + assert controls["distinct_prefix_controls"] == controls["executed_neutral_tests"] == 1 + assert (tmp_path / "coverage/events").read_text().splitlines() == ["teardown"] * 5 + + +@pytest.mark.parametrize("selection", ["coverage", "full"]) +def test_harness_exit_without_a_failed_report_cannot_count_as_a_kill( + tmp_path: Path, selection: str +) -> None: + result = _campaign( + tmp_path, + { + "test_target.py": ( + "from target import checked\ndef test_first():\n assert checked() is True\n" + ), + "conftest.py": ( + "import os\ndef pytest_sessionfinish():\n" + " if os.environ.get('ACTIVE_GREMLIN'):\n raise SystemExit(1)\n" + ), + }, + selection=selection, + ) + assert result.returncode != 0 + assert "Missing actual failing-test execution evidence" in result.stdout + result.stderr + assert not (tmp_path / "coverage/gremlins/run.json").exists() + + +def test_execution_recorder_rejects_unknown_bootstrap_layout(tmp_path: Path) -> None: + path = tmp_path / "gremlin_bootstrap.py" + path.write_text("print('unrecognized bootstrap')\n") + with pytest.raises(pytest.UsageError, match="Revalidate"): + record_test_execution(tmp_path) + assert path.read_text() == "print('unrecognized bootstrap')\n" diff --git a/tests/test_mutation_controls.py b/tests/test_mutation_controls.py new file mode 100644 index 0000000..9f2b138 --- /dev/null +++ b/tests/test_mutation_controls.py @@ -0,0 +1,105 @@ +"""Shared baselines must cover every order and match the campaign's inputs.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from tests.mutation_controls import baseline_receipt, input_fingerprint, validate_baselines + +pytestmark = pytest.mark.mutation_infrastructure + + +@pytest.fixture +def receipts(tmp_path: Path) -> tuple[Path, dict, list[tuple[str, ...]]]: + context = {"inputs": "checked input fingerprint", "test_order": "component"} + orders = [("first", "second"), ("second", "first"), ("third", "first")] + directory = tmp_path / "receipts" + directory.mkdir() + for index in range(1, 3): + (directory / f"baseline-{index}-of-2.json").write_text( + json.dumps(baseline_receipt(context, orders, (index, 2))) + ) + return directory, context, orders + + +def test_shared_baselines_accept_complete_disjoint_orders(receipts: tuple) -> None: + validate_baselines(*receipts) + + +@pytest.mark.parametrize( + "corruption", + ["missing", "duplicate", "unchecked order", "stale inputs", "wrong order", "invalid partition"], +) +def test_shared_baselines_reject_incomplete_or_stale_checks( + receipts: tuple, corruption: str +) -> None: + directory, context, orders = receipts + path = directory / "baseline-2-of-2.json" + receipt = json.loads(path.read_text()) + if corruption == "missing": + path.unlink() + else: + if corruption == "duplicate": + receipt = json.loads((directory / "baseline-1-of-2.json").read_text()) + elif corruption == "unchecked order": + receipt["checked"] = [] + elif corruption == "stale inputs": + receipt["context"]["inputs"] = "different inputs" + elif corruption == "wrong order": + receipt["orders"].reverse() + else: + receipt["shard"] = [2, 3] + path.write_text(json.dumps(receipt)) + with pytest.raises(ValueError, match="baselines"): + validate_baselines(directory, context, orders) + + +def test_shared_baselines_reject_changed_test_collection(receipts: tuple) -> None: + directory, context, orders = receipts + with pytest.raises(ValueError, match="baselines"): + validate_baselines(directory, context, [*orders, ("new_test",)]) + + +def test_input_identity_includes_helpers_fixtures_and_environment( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + helper = tmp_path / "helper.py" + helper.write_text("VALUE = 1\n") + fixture = tmp_path / "resource.txt" + fixture.write_text("original fixture") + before = input_fingerprint(tmp_path) + helper.write_text("VALUE = 2\n") + assert input_fingerprint(tmp_path) != before + helper.write_text("VALUE = 1\n") + fixture.write_text("changed fixture") + assert input_fingerprint(tmp_path) != before + fixture.write_text("original fixture") + monkeypatch.setenv("TRAILMARK_REQUIRE_BINARY_TOOLS", "changed") + assert input_fingerprint(tmp_path) != before + + +def test_input_identity_ignores_report_and_bytecode_outputs(tmp_path: Path) -> None: + (tmp_path / "helper.py").write_text("VALUE = 1\n") + before = input_fingerprint(tmp_path) + for name in ("coverage", "__pycache__", ".pytest_cache"): + directory = tmp_path / name + directory.mkdir() + (directory / "output").write_text("generated output") + assert input_fingerprint(tmp_path) == before + + +def test_input_identity_includes_native_tool_contents( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + tool = tmp_path / "objdump" + tool.write_text("first tool build") + monkeypatch.setenv("TRAILMARK_GNU_OBJDUMP", str(tool)) + # Keep the executable outside the scanned project so only the tool identity changes. + project = tmp_path / "project" + project.mkdir() + before = input_fingerprint(project) + tool.write_text("second tool build") + assert input_fingerprint(project) != before diff --git a/tests/test_mutation_coverage.py b/tests/test_mutation_coverage.py new file mode 100644 index 0000000..8c7aed6 --- /dev/null +++ b/tests/test_mutation_coverage.py @@ -0,0 +1,403 @@ +"""Exercise the coverage selector's reductions and conservative boundaries.""" + +from __future__ import annotations + +import json +import subprocess +import sys +from copy import deepcopy +from pathlib import Path +from typing import Any + +import coverage +import pytest + +from tests.mutation_controls import digest +from tests.mutation_coverage import ( + SelectionCoverage, + collect_plan, + native_tool_fingerprints, + select_tests, + validate_plan, +) +from tests.mutation_gate import check +from tests.run_mutations import VERSION + +pytestmark = pytest.mark.mutation_infrastructure + + +@pytest.mark.parametrize( + ("source", "names", "selected"), + [ + ( + "from target import checked\ndef test_strong():\n assert checked() is True\n", + ["test_strong"], + ["test_strong"], + ), + ( + "import pytest\nfrom target import checked\n" + "@pytest.fixture(scope='module')\n" + "def flag():\n return checked()\n" + "def test_weak(flag):\n assert isinstance(flag, bool)\n" + "def test_strong(flag):\n assert flag is True\n", + ["test_weak", "test_strong"], + ["test_weak", "test_strong"], + ), + ( + "import pytest\nfrom target import checked\n" + "@pytest.fixture(scope='module')\n" + "def flag():\n return checked()\n" + "def test_weak(flag):\n assert isinstance(flag, bool)\n" + "def test_strong(request):\n assert request.getfixturevalue('flag') is True\n", + ["test_weak", "test_strong"], + ["test_weak", "test_strong"], + ), + ( + "import pytest\nfrom target import checked\n" + "@pytest.fixture(scope='module')\n" + "def flag():\n yield []\n assert checked() is True\n" + "def test_weak(flag):\n assert isinstance(flag, list)\n" + "def test_strong(flag):\n assert flag == []\n", + ["test_weak", "test_strong"], + ["test_weak", "test_strong"], + ), + ( + "import subprocess, sys\nfrom target import checked\n" + "def test_weak():\n assert isinstance(checked(), bool)\n" + "def test_strong():\n" + " subprocess.run([sys.executable, '-c', " + "'from target import checked; assert checked() is True'], check=True)\n", + ["test_weak", "test_strong"], + ["test_weak", "test_strong"], + ), + ( + "import sys\nfrom target import checked\n" + "def test_weak():\n assert isinstance(checked(), bool)\n" + "def test_strong():\n previous = sys.gettrace()\n" + " try:\n sys.settrace(None)\n assert checked() is True\n" + " finally:\n sys.settrace(previous)\n", + ["test_weak", "test_strong"], + ["test_weak", "test_strong"], + ), + ( + "import pytest\nfrom target import checked\n" + "@pytest.mark.parametrize('value', [0, 1], ids=['ZERO', 'one [B]'])\n" + "def test_strong(value):\n assert checked() is True\n", + ["test_strong[ZERO]", "test_strong[one [B]]"], + ["test_strong[ZERO]", "test_strong[one [B]]"], + ), + ], + ids=[ + "direct", + "shared-fixture", + "dynamic-fixture", + "fixture-teardown", + "child", + "tracer", + "params", + ], +) +def test_selection_preserves_consumers_and_opaque_tests_without_unrelated_tests( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + source: str, + names: list[str], + selected: list[str], +) -> None: + monkeypatch.chdir(tmp_path) + (tmp_path / "target.py").write_text("def checked():\n return True\n") + (tmp_path / "test_target.py").write_text(source + "def test_unrelated():\n assert 1 == 1\n") + names = [f"test_target.py::{name}" for name in names] + tests = [*names, "test_target.py::test_unrelated"] + envelope = collect_plan( + tmp_path, ["-q", "-p", "no:gremlins"], tests, [str(tmp_path / "target.py")] + ) + plan = envelope["plan"] + assert not plan["collection_uncertain"] + assert select_tests(plan, "target.py", 2, tests) == [ + f"test_target.py::{name}" for name in selected + ] + # Import-time and unobserved lines retain the complete suite. + assert select_tests(plan, "target.py", 1, tests) == tests + assert select_tests(plan, "target.py", 100, tests) == tests + + +@pytest.mark.parametrize( + "body", ["assert False", "import os; os._exit(0)", "import sys; sys.settrace(None)"] +) +def test_failed_or_incomplete_prescan_cannot_reuse_a_stale_plan( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, body: str +) -> None: + monkeypatch.chdir(tmp_path) + (tmp_path / "target.py").write_text("def checked():\n return True\n") + (tmp_path / "test_target.py").write_text(f"def test_case():\n {body}\n") + (tmp_path / "coverage-plan.json").write_text("{}") + with pytest.raises(pytest.UsageError, match="Coverage baseline"): + collect_plan( + tmp_path, + ["-q", "-p", "no:gremlins"], + ["test_target.py::test_case"], + [str(tmp_path / "target.py")], + ) + assert not (tmp_path / "coverage-plan.json").exists() + + +@pytest.mark.parametrize( + "change", + ["context", "digest", "tests", "unknown-test", "duplicate-test", "source", "line", "import"], +) +def test_shared_plan_rejects_stale_or_invalid_evidence(change: str) -> None: + tests = ["test_target.py::test_case"] + context = {"inputs": "known"} + plan = { + "tests": tests, + "locations": {"target.py": {"2": [0]}}, + "imported": {"target.py": [1]}, + "uncertain": [], + "collection_uncertain": False, + "native_tools": native_tool_fingerprints(), + } + envelope: dict[str, Any] = {"context": context, "plan": plan, "digest": digest(plan)} + assert validate_plan(envelope, context, tests, {"target.py"}) == plan + broken = deepcopy(envelope) + if change == "context": + broken["context"] = {"inputs": "stale"} + elif change == "digest": + broken["digest"] = "stale" + elif change == "tests": + broken["plan"]["tests"] = [] + elif change in {"unknown-test", "duplicate-test"}: + broken["plan"]["uncertain"] = [1] if change == "unknown-test" else [0, 0] + elif change == "source": + broken["plan"]["locations"] = {"other.py": {"2": [0]}} + elif change == "line": + broken["plan"]["locations"]["target.py"]["0"] = [0] + else: + broken["plan"]["imported"]["target.py"] = [True] + if change != "digest": + broken["digest"] = digest(broken["plan"]) + with pytest.raises(ValueError): + validate_plan(broken, context, tests, {"target.py"}) + + +def test_python_and_script_wrappers_never_become_trusted_native_tools( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + wrapper = tmp_path / "llvm-objdump" + wrapper.write_text("#!/bin/sh\nexit 0\n") + monkeypatch.setenv("TRAILMARK_LLVM_OBJDUMP", str(wrapper)) + monkeypatch.setenv("TRAILMARK_GNU_OBJDUMP", sys.executable) + trusted = native_tool_fingerprints() + assert str(wrapper) not in trusted + assert str(Path(sys.executable).resolve()) not in trusted + + +@pytest.mark.parametrize("kind", ["native", "script", "python"]) +@pytest.mark.parametrize( + ("arguments", "spoof_argv", "native_query"), + [ + (["-C", "root with spaces", "rev-parse", "HEAD"], False, True), + (["status"], False, False), + (["-C", "root", "rev-parse", "main"], False, False), + (["-c", "alias.query=external", "-C", "root", "rev-parse", "HEAD"], False, False), + (["-C", "root", "rev-parse", "HEAD"], True, False), + ], +) +def test_only_fixed_native_git_revision_queries_avoid_opaque_coverage( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + kind: str, + arguments: list[str], + spoof_argv: bool, + native_query: bool, +) -> None: + tool = tmp_path / "git" + if kind == "python": + tool.symlink_to(sys.executable) + else: + tool.write_bytes(b"\x7fELFnative tool" if kind == "native" else b"#!/usr/bin/env python3\n") + monkeypatch.setattr( + "tests.mutation_coverage.shutil.which", lambda name: str(tool) if name == "git" else None + ) + collector = SelectionCoverage(coverage.Coverage(config_file=False), ["test_query"]) + collector.context = ("test", "test_query") + command = ["different-git" if spoof_argv else str(tool), *arguments] + collector.audit("subprocess.Popen", (str(tool), command, None, None)) + assert bool(collector.uncertain) == (kind != "native" or not native_query) + assert not collector.collection_uncertain + + +def test_collection_tracing_gaps_require_the_full_suite( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.chdir(tmp_path) + (tmp_path / "target.py").write_text("def checked():\n return True\n") + (tmp_path / "test_a_collection.py").write_text( + "import sys\nfrom target import checked\nprevious = sys.gettrace()\n" + "try:\n sys.settrace(None)\n assert checked() is True\n" + "finally:\n sys.settrace(previous)\n" + "def test_unrelated():\n assert 1 == 1\n" + ) + (tmp_path / "test_target.py").write_text( + "from target import checked\ndef test_weak():\n assert isinstance(checked(), bool)\n" + ) + tests = ["test_a_collection.py::test_unrelated", "test_target.py::test_weak"] + plan = collect_plan( + tmp_path, ["-q", "-p", "no:gremlins"], tests, [str(tmp_path / "target.py")] + )["plan"] + assert plan["collection_uncertain"] + assert select_tests(plan, "target.py", 2, tests) == tests + + +def test_empty_module_coverage_does_not_create_a_line_zero( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.chdir(tmp_path) + (tmp_path / "empty.py").touch() + (tmp_path / "target.py").write_text("def checked():\n return True\n") + (tmp_path / "test_target.py").write_text( + "import empty\nfrom target import checked\ndef test_case():\n assert checked() is True\n" + ) + tests = ["test_target.py::test_case"] + envelope = collect_plan( + tmp_path, + ["-q", "-p", "no:gremlins"], + tests, + [str(tmp_path / "target.py"), str(tmp_path / "empty.py")], + ) + envelope["context"] = {"inputs": "known"} + plan = validate_plan(envelope, envelope["context"], tests, {"target.py", "empty.py"}) + assert all(line > 0 for lines in plan["imported"].values() for line in lines) + assert all(int(line) > 0 for lines in plan["locations"].values() for line in lines) + + +def test_plan_rejects_changes_to_trusted_native_tool_contents( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + tool = tmp_path / "native-tool" + tool.write_bytes(b"\x7fELFbefore") + monkeypatch.setenv("TRAILMARK_LLVM_OBJDUMP", str(tool)) + tests = ["test_target.py::test_case"] + context = {"inputs": "known"} + plan = { + "tests": tests, + "locations": {}, + "imported": {}, + "uncertain": [], + "collection_uncertain": False, + "native_tools": native_tool_fingerprints(), + } + assert str(tool) in plan["native_tools"] + envelope = {"plan": plan, "context": context, "digest": digest(plan)} + assert validate_plan(envelope, context, tests, {"target.py"}) == plan + tool.write_bytes(b"\x7fELFafter") + with pytest.raises(ValueError, match="Native tools changed"): + validate_plan(envelope, context, tests, {"target.py"}) + + +@pytest.mark.parametrize("case", ["fixture", "child", "tracer"]) +def test_coverage_and_full_campaigns_agree_on_opaque_killers(tmp_path: Path, case: str) -> None: + (tmp_path / "target.py").write_text("def checked():\n return True\n") + source = { + "fixture": ( + "import pytest\nfrom target import checked\n" + "@pytest.fixture(scope='module')\n" + "def flag():\n return checked()\n" + "def test_weak(flag):\n assert isinstance(flag, bool)\n" + "def test_strong(flag):\n assert flag is True\n" + ), + "child": ( + "import subprocess, sys\nfrom target import checked\n" + "def test_weak():\n assert isinstance(checked(), bool)\n" + "def test_strong():\n subprocess.run([sys.executable, '-c', " + "'from target import checked; assert checked() is True'], check=True)\n" + ), + "tracer": ( + "import sys\nfrom target import checked\n" + "def test_weak():\n assert isinstance(checked(), bool)\n" + "def test_strong():\n previous = sys.gettrace()\n" + " try:\n sys.settrace(None)\n assert checked() is True\n" + " finally:\n sys.settrace(previous)\n" + ), + }[case] + (tmp_path / "test_target.py").write_text(source + "def test_unrelated():\n assert 1 == 1\n") + runner = Path(__file__).with_name("run_mutations.py") + baseline = {"pytest_gremlins": VERSION, "scope": {"target.py": "*"}, "exceptions": []} + outcomes = [] + for selection in ("coverage", "full"): + result = subprocess.run( # noqa: S603 + [ + sys.executable, + str(runner), + "--targets=target.py", + "--workers=2", + f"--test-selection={selection}", + "test_target.py", + ], + cwd=tmp_path, + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr + directory = tmp_path / "coverage/gremlins" + report = json.loads((directory / "gremlins.json").read_text()) + run = json.loads((directory / "run.json").read_text()) + assert check(tmp_path, report, run, baseline) == [] + outcomes.append({row["gremlin_id"]: row["status"] for row in report["results"]}) + assert set(outcomes[-1].values()) == {"zapped"} + if selection == "coverage": + assert all( + "test_target.py::test_unrelated" not in row["selected_tests"] + for row in report["results"] + ) + report["results"][0]["selected_tests"] = report["results"][0]["selected_tests"][:1] + with pytest.raises(ValueError, match="selection differs"): + check(tmp_path, report, run, baseline) + assert outcomes[0] == outcomes[1] + + +@pytest.mark.parametrize("shared", [False, True]) +def test_neutral_failure_prefix_must_pass_before_scoring(tmp_path: Path, shared: bool) -> None: + (tmp_path / "target.py").write_text("def checked():\n return True\n") + (tmp_path / "state.py").write_text("ready = False\n") + (tmp_path / "test_a_setup.py").write_text( + "import state\ndef test_initialize():\n state.ready = True\n" + ) + (tmp_path / "test_target.py").write_text( + "import state\nfrom target import checked\n" + "def test_checked():\n assert state.ready\n assert checked() is True\n" + ) + command = [ + sys.executable, + str(Path(__file__).with_name("run_mutations.py")), + "--targets=target.py", + "--workers=2", + ] + options = [] + if shared: + prepared = subprocess.run( # noqa: S603 + [*command, "--baseline-shard=1/1", "."], + cwd=tmp_path, + capture_output=True, + text=True, + check=False, + ) + assert prepared.returncode == 0, prepared.stdout + prepared.stderr + reports = tmp_path / "coverage/gremlins" + baselines = reports / "baselines" + baselines.mkdir() + for name in ("coverage-plan.json", "baseline-1-of-1.json"): + (reports / name).rename(baselines / name) + options = [f"--baselines={baselines}"] + result = subprocess.run( # noqa: S603 + [*command, *options, "."], + cwd=tmp_path, + capture_output=True, + text=True, + check=False, + ) + assert result.returncode != 0 + assert "Unmutated failure prefix failed" in result.stdout + result.stderr + assert not (tmp_path / "coverage/gremlins/run.json").exists() + assert not (tmp_path / "coverage/gremlins/progress.jsonl").exists() diff --git a/tests/test_mutation_gate.py b/tests/test_mutation_gate.py index e9809eb..f058ebb 100644 --- a/tests/test_mutation_gate.py +++ b/tests/test_mutation_gate.py @@ -40,6 +40,8 @@ def campaign(tmp_path: Path) -> tuple[dict[str, Any], dict[str, Any], dict[str, run = { "pytest_gremlins": VERSION, "runner": RUNNER, + "test_selection": "full", + "kill_confirmation": "baseline-orders", "shard": [1, 1], "sources": {"target.py": hashlib.sha256(source.encode()).hexdigest()}, } @@ -67,6 +69,12 @@ def test_rejects_skipped_or_invalid_instrumentation( (2, "pytest_gremlins", "1.9.0"), (1, "runner", "trailmark-full-pytest-v2"), (1, "runner", "trailmark-full-pytest-v3"), + (1, "runner", "trailmark-full-pytest-v4"), + (1, "runner", "trailmark-full-pytest-v5"), + (1, "runner", "trailmark-full-pytest-v6"), + (1, "runner", "trailmark-pytest-coverage-v7"), + (1, "runner", "trailmark-pytest-coverage-v8"), + (1, "kill_confirmation", "unchecked"), ], ) def test_rejects_previous_adapter_reports( @@ -94,6 +102,37 @@ def test_rejects_result_without_tests(tmp_path: Path, campaign: tuple) -> None: assert len(failures) == 1 and '"status": "no tests"' in failures[0] +@pytest.mark.parametrize("status", ["timeout", "error", "pardoned", "no tests"]) +def test_rejects_inconclusive_results_outside_reviewed_scope( + tmp_path: Path, campaign: tuple, status: str +) -> None: + report, run, baseline = campaign + baseline["scope"]["target.py"] = ["another_function"] + if status == "no tests": + report["results"][0]["selected_tests"] = [] + else: + report["results"][0]["status"] = status + report["summary"] = { + "total": len(report["results"]), + **Counter(row["status"] for row in report["results"]), + } + failures = check(tmp_path, report, run, baseline) + assert len(failures) == 1 and f'"status": "{status}"' in failures[0] + + +def test_survivors_outside_reviewed_scope_remain_informational( + tmp_path: Path, campaign: tuple +) -> None: + report, run, baseline = campaign + baseline["scope"]["target.py"] = ["another_function"] + report["results"][0]["status"] = "survived" + report["summary"] = { + "total": len(report["results"]), + **Counter(row["status"] for row in report["results"]), + } + assert check(tmp_path, report, run, baseline) == [] + + def test_requires_complete_inventory_even_if_summary_matches( tmp_path: Path, campaign: tuple ) -> None: diff --git a/tests/test_mutation_order.py b/tests/test_mutation_order.py index 37cfb7d..21e6843 100644 --- a/tests/test_mutation_order.py +++ b/tests/test_mutation_order.py @@ -18,6 +18,11 @@ ("tree_sitter_custom/verus/__init__.py", "test_verus_grammar.py"), ("parsers/rust/parser.py", "test_rust_parser.py"), ("parsers/rust/_scopes.py", "test_rust_local_items.py"), + ("parsers/lean/_syntax.py", "test_lean_parser.py"), + ("parsers/_declarations.py", "test_declaration_identity.py"), + ("parsers/c/_macros.py", "test_c_macros.py"), + ("parsers/fstar/_semantics.py", "test_fstar_parser.py"), + ("parsers/rego/parser.py", "test_rego_rule_references.py"), ("parsers/python/parser.py", "test_python_parser.py"), ("parsers/_common.py", "test_common_parser.py"), ("models/nodes.py", "test_models.py"), diff --git a/tests/test_mutation_runner.py b/tests/test_mutation_runner.py index a228792..74a2337 100644 --- a/tests/test_mutation_runner.py +++ b/tests/test_mutation_runner.py @@ -11,13 +11,96 @@ import pytest from pytest_gremlins.instrumentation.transformer import transform_source +from pytest_gremlins.parallel.exit_codes import COLLECTION_KILLING_TEST +from tests.mutation_bootstrap import record_source_collection_exits from tests.mutation_gate import check from tests.run_mutations import RUNNER, VERSION, parse_shard, select_shard pytestmark = pytest.mark.mutation_infrastructure +def _run_collection_control( + tmp_path: Path, source: str, conftest: str = "" +) -> subprocess.CompletedProcess[str]: + (tmp_path / "target.py").write_text(source) + (tmp_path / "test_target.py").write_text( + "from target import checked\ndef test_checked():\n assert checked() is True\n" + ) + if conftest: + (tmp_path / "conftest.py").write_text(conftest) + return subprocess.run( # noqa: S603 + [ + sys.executable, + str(Path(__file__).with_name("run_mutations.py")), + "--targets=target.py", + "--workers=2", + "test_target.py", + ], + cwd=tmp_path, + capture_output=True, + text=True, + check=False, + ) + + +def test_application_collection_exit_is_confirmed_as_a_kill(tmp_path: Path) -> None: + result = _run_collection_control( + tmp_path, + "import sys\nif __name__ == '__main__':\n sys.exit(2)\n" + "def checked():\n return True\n", + ) + assert result.returncode == 0, result.stdout + result.stderr + report = json.loads((tmp_path / "coverage/gremlins/gremlins.json").read_text()) + assert report["results"] + assert {row["status"] for row in report["results"]} == {"zapped"} + assert any(row.get("killing_test") == COLLECTION_KILLING_TEST for row in report["results"]) + + +@pytest.mark.parametrize( + ("hook", "exception"), + [ + ("pytest_collection_modifyitems", "SystemExit(2)"), + ("pytest_collection_modifyitems", "RuntimeError('controlled harness failure')"), + ("pytest_sessionfinish", "SystemExit(2)"), + ], +) +def test_harness_failures_remain_errors(tmp_path: Path, hook: str, exception: str) -> None: + result = _run_collection_control( + tmp_path, + "def checked():\n return True\n", + "import os\n" + f"def {hook}():\n" + " if os.environ.get('ACTIVE_GREMLIN'):\n" + f" raise {exception}\n", + ) + assert result.returncode == 0, result.stdout + result.stderr + report = json.loads((tmp_path / "coverage/gremlins/gremlins.json").read_text()) + assert report["results"] + assert {row["status"] for row in report["results"]} == {"error"} + + +def test_unmutated_collection_exit_does_not_produce_scores(tmp_path: Path) -> None: + result = _run_collection_control( + tmp_path, + "import os, sys\n" + "if os.environ.get('PYTEST_GREMLINS_SOURCES_FILE'):\n sys.exit(2)\n" + "def checked():\n return True\n", + ) + assert result.returncode != 0 + assert "Instrumented baseline failed" in result.stdout + result.stderr + assert not (tmp_path / "coverage/gremlins/run.json").exists() + assert not (tmp_path / "coverage/gremlins/progress.jsonl").exists() + + +def test_bootstrap_adapter_rejects_an_unrecognized_layout(tmp_path: Path) -> None: + bootstrap = tmp_path / "gremlin_bootstrap.py" + bootstrap.write_text("print('unrecognized bootstrap')\n") + with pytest.raises(pytest.UsageError, match="Revalidate"): + record_source_collection_exits(tmp_path) + assert bootstrap.read_text() == "print('unrecognized bootstrap')\n" + + @pytest.mark.parametrize("value", ["0/4", "5/4", "1/0", "-1/4", "1", "1/2/3", "one/4"]) def test_rejects_invalid_shard(value: str) -> None: with pytest.raises(argparse.ArgumentTypeError, match="INDEX/TOTAL"): @@ -107,12 +190,14 @@ def test_runner_executes_fixtures_parameters_and_package_mutations(tmp_path: Pat ) (tmp_path / "test_toy.py").write_text("""\ import coverage +import os import pytest from toy import checked, ignored, RESOURCE, VALUE @pytest.mark.parametrize(("value", "answer"), [(0, False), (1, True)], ids=["ZERO", "ONE"]) def test_strong(tmp_path, value, answer): - assert coverage.Coverage.current() is None + collecting = bool(os.environ.get("TRAILMARK_MUTATION_COVERAGE")) + assert (coverage.Coverage.current() is not None) == collecting assert tmp_path.is_dir() assert RESOURCE == "known resource" and VALUE == 7 assert checked(value) is answer @@ -167,7 +252,7 @@ def test_weak(tmp_path, value): assert {row["gremlin_id"]: row["status"] for row in progress} == { row["gremlin_id"]: row["status"] for row in results } - assert all(row["selected_test_count"] == 5 for row in progress) + assert all(0 < row["selected_test_count"] < 5 for row in progress) assert all(Path(row["file_path"]).name == "__init__.py" for row in progress) strong = [r for r in results if r["line_number"] == 5] weak = [r for r in results if r["line_number"] == 7] @@ -177,17 +262,19 @@ def test_weak(tmp_path, value): assert {r["status"] for r in strong} == {"zapped"} assert {r["status"] for r in delegated} == {"zapped"} assert {r["status"] for r in weak} == {"survived"} - assert all(len(r["selected_tests"]) == 5 for r in results) assert all( - "test_toy.py::test_strong[ZERO]" in r["selected_tests"] - and "test_toy.py::test_strong[ONE]" in r["selected_tests"] - and "test_integration.py::test_integration" in r["selected_tests"] - for r in results + r["selected_tests"] == ["test_toy.py::test_strong[ZERO]", "test_toy.py::test_strong[ONE]"] + for r in strong + ) + assert all(r["selected_tests"] == ["test_integration.py::test_integration"] for r in delegated) + assert all( + r["selected_tests"] == ["test_toy.py::test_weak[0]", "test_toy.py::test_weak[1]"] + for r in weak ) -@pytest.mark.parametrize("shard", ["1/1", "99/99"]) -def test_runner_rejects_order_dependent_baseline(tmp_path: Path, shard: str) -> None: +@pytest.mark.parametrize("partition", ["--shard=1/1", "--shard=99/99", "--baseline-shard=1/1"]) +def test_runner_rejects_order_dependent_baseline(tmp_path: Path, partition: str) -> None: (tmp_path / "target.py").write_text("def checked(value):\n return value > 0\n") (tmp_path / "state.py").write_text("ready = False\n") (tmp_path / "test_a_setup.py").write_text( @@ -202,7 +289,14 @@ def test_runner_rejects_order_dependent_baseline(tmp_path: Path, shard: str) -> progress.write_text("stale previous campaign\n") runner = Path(__file__).with_name("run_mutations.py") result = subprocess.run( # noqa: S603 - [sys.executable, str(runner), "--targets=target.py", f"--shard={shard}", "."], + [ + sys.executable, + str(runner), + "--targets=target.py", + "--test-selection=full", + partition, + ".", + ], cwd=tmp_path, capture_output=True, text=True, @@ -213,6 +307,103 @@ def test_runner_rejects_order_dependent_baseline(tmp_path: Path, shard: str) -> assert not (tmp_path / "coverage/gremlins/run.json").exists() progress = tmp_path / "coverage/gremlins/progress.jsonl" assert not progress.exists() or not progress.read_text() + assert not list((tmp_path / "coverage/gremlins").glob("baseline-*.json")) + + +@pytest.mark.parametrize("selection", ["full", "coverage"]) +def test_shared_baselines_preserve_mutant_results_and_reject_changed_tests( + tmp_path: Path, selection: str +) -> None: + for name in ("first", "second"): + (tmp_path / f"{name}.py").write_text("def checked(value):\n return value > 0\n") + (tmp_path / f"test_{name}.py").write_text( + f"from {name} import checked\n" + "def test_boundary():\n assert not checked(0)\n assert checked(1)\n" + ) + runner = Path(__file__).with_name("run_mutations.py") + reports = tmp_path / "coverage/gremlins" + shared = reports / "baselines" + shared.mkdir(parents=True) + executions = tmp_path.with_suffix(".executions.jsonl") + (tmp_path / "conftest.py").write_text( + "import json, os, sys\nfrom pathlib import Path\n" + "def pytest_runtest_call(item):\n" + f" with Path({str(executions)!r}).open('a') as stream:\n" + " stream.write(json.dumps({'argv': sys.argv, 'test': item.nodeid, " + "'instrumented': bool(os.environ.get('PYTEST_GREMLINS_SOURCES_FILE')), " + "'prefix': bool(os.environ.get('TRAILMARK_PREFIX_LIMIT')), " + "'mutant': bool(os.environ.get('ACTIVE_GREMLIN'))}) + '\\n')\n" + ) + + def run(*options: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( # noqa: S603 + [ + sys.executable, + str(runner), + "--targets=first.py,second.py", + f"--test-selection={selection}", + "--workers=2", + *options, + "test_first.py", + "test_second.py", + ], + cwd=tmp_path, + capture_output=True, + text=True, + check=False, + ) + + checked = [] + partitions = 1 if selection == "coverage" else 2 + for index in range(1, partitions + 1): + result = run(f"--baseline-shard={index}/{partitions}") + assert result.returncode == 0, result.stdout + result.stderr + receipt = reports / f"baseline-{index}-of-{partitions}.json" + checked.extend(json.loads(receipt.read_text())["checked"]) + receipt.rename(shared / receipt.name) + assert not (reports / "run.json").exists() + assert not (reports / "progress.jsonl").exists() + assert len(checked) == len(set(checked)) == partitions + calls = [json.loads(line) for line in executions.read_text().splitlines()] + assert len(calls) == 2 * partitions + assert all(call["instrumented"] for call in calls) + assert not any(call["mutant"] for call in calls) + if selection == "coverage": + (reports / "coverage-plan.json").rename(shared / "coverage-plan.json") + + combined = {} + for index in (1, 2): + executions.unlink() + result = run(f"--shard={index}/2", f"--baselines={shared}") + assert result.returncode == 0, result.stdout + result.stderr + assert f"Reusing validated instrumented baseline orders: {partitions}" in result.stdout + assert "Checking instrumented baseline order" not in result.stdout + calls = [json.loads(line) for line in executions.read_text().splitlines()] + assert all(call["instrumented"] for call in calls) + assert not any(Path(call["argv"][0]) == runner for call in calls) + assert all(call["mutant"] or call["prefix"] for call in calls) + assert "Checking " not in result.stdout + report = json.loads((reports / "gremlins.json").read_text()) + combined.update({row["gremlin_id"]: row["status"] for row in report["results"]}) + assert json.loads((reports / "run.json").read_text())["baseline_validation"] == "shared" + result = run() + assert result.returncode == 0, result.stdout + result.stderr + report = json.loads((reports / "gremlins.json").read_text()) + assert combined == {row["gremlin_id"]: row["status"] for row in report["results"]} + assert set(combined.values()) == {"zapped"} + + with (tmp_path / "test_second.py").open("a") as test: + test.write("\n# Edited after the baselines were validated.\n") + result = run("--shard=1/2", f"--baselines={shared}") + assert result.returncode != 0 + message = ( + "Invalid shared coverage selection" + if selection == "coverage" + else "Invalid shared mutation baselines" + ) + assert message in result.stdout + result.stderr + assert not (reports / "run.json").exists() + assert not (reports / "progress.jsonl").exists() def test_runner_instruments_spawned_children(tmp_path: Path) -> None: diff --git a/tests/test_proxies.py b/tests/test_proxies.py index 497207b..5142741 100644 --- a/tests/test_proxies.py +++ b/tests/test_proxies.py @@ -3,10 +3,11 @@ from __future__ import annotations from pathlib import Path +from unittest.mock import Mock, call import pytest -from trailmark.analysis.proxies import ensure_proxy_nodes +from trailmark.analysis.proxies import _callable_owner, ensure_proxy_nodes from trailmark.models.edges import CodeEdge, EdgeKind from trailmark.models.graph import CodeGraph from trailmark.models.nodes import CodeUnit, NodeKind, NodeOrigin, SourceLocation, TypeRef @@ -19,6 +20,15 @@ def _unit(node_id: str, name: str, kind: NodeKind = NodeKind.FUNCTION) -> CodeUn return CodeUnit(node_id, name, kind, _LOCATION) +def test_callable_owner_stops_before_revisiting_a_container() -> None: + graph = CodeGraph(nodes={name: _unit(name, name, NodeKind.CLASS) for name in ("A", "B")}) + owners = Mock(spec=dict) + # The path is work -> A -> B -> A. Revisiting A must not consume another lookup. + owners.get.side_effect = ["A", "B", "A"] + assert _callable_owner("work", graph, owners, {NodeKind.FUNCTION}) is None + assert owners.get.call_args_list == [call("work"), call("A"), call("B")] + + @pytest.mark.parametrize( ("outer", "inner", "expected"), [ diff --git a/tests/test_pyramid_includes.py b/tests/test_pyramid_includes.py index 22752b8..e9ca36c 100644 --- a/tests/test_pyramid_includes.py +++ b/tests/test_pyramid_includes.py @@ -1,5 +1,6 @@ from pathlib import Path +from tests.parse_work import count_work from trailmark.analysis._pyramid_includes import discover_pyramid_includes from trailmark.models.edges import EdgeKind from trailmark.query.api import QueryEngine @@ -43,7 +44,7 @@ def test_shadowed_or_custom_package_registrars_do_not_guess_relative_targets( "def unrelated():\n obj = unknown()\n obj.include('target')\n" ) (tmp_path / "target.py").write_text("def includeme(config): pass\n") - engine = QueryEngine.from_directory(str(tmp_path)) + engine, _ = count_work(lambda: QueryEngine.from_directory(str(tmp_path)), max_work=100_000) assert not any( dict(e.attributes).get("reference_context") == "pyramid_include" for e in engine._store._graph.edges diff --git a/tests/test_reference_literals.py b/tests/test_reference_literals.py index 0869ad8..d065a4f 100644 --- a/tests/test_reference_literals.py +++ b/tests/test_reference_literals.py @@ -20,6 +20,33 @@ def _values(tmp_path: Path, name: str, text: str) -> list[str]: return [ref.value for ref in reference_literals(_write(tmp_path, name, text))] +@pytest.mark.parametrize( + ("text", "quote", "expected"), + [("x", "", ("x", 1)), ("''", "'", ("'", 2)), (r"\n", '"', ("\n", 2))], +) +def test_yaml_flow_character_returns_the_next_unconsumed_index( + text: str, quote: str, expected: tuple[str, int] +) -> None: + assert _reference_literals._yaml_flow_char(text, 0, quote) == expected + + +@pytest.mark.parametrize(("text", "expected"), [("\n", " "), ("\n\n", "\n")]) +def test_yaml_flow_folding_distinguishes_one_break_from_an_empty_line( + text: str, expected: str +) -> None: + assert _reference_literals._yaml_fold(text, "") == expected + + +@pytest.mark.parametrize( + ("text", "expected"), + [("\n value", (3, 1)), ("\n \n\tvalue", (4, 2)), ("\n \n\t", (4, 2))], +) +def test_yaml_line_break_scanner_advances_to_content_or_end( + text: str, expected: tuple[int, int] +) -> None: + assert _reference_literals._yaml_skip_breaks(text, 0) == expected + + _GRAPHQL = r'''# comment "App\\Comment::nope" App\Hidden::nope """Type description "App\\Doc::nope" with \""" inside.""" type Query { diff --git a/tests/test_rego_rule_references.py b/tests/test_rego_rule_references.py index 6f54746..a04ec62 100644 --- a/tests/test_rego_rule_references.py +++ b/tests/test_rego_rule_references.py @@ -2,6 +2,7 @@ from pathlib import Path +from tests.parse_work import parse_work from trailmark.models.edges import EdgeKind from trailmark.parse import parse_file from trailmark.query.api import QueryEngine @@ -40,7 +41,7 @@ def test_rule_parameters_some_and_assignments_shadow_rule_names(tmp_path: Path) "quantified { some invalid; invalid == 1 }\n" ) - graph = parse_file(str(source), language="rego", strict=True) + graph, _ = parse_work(source, language="rego", max_work=100_000) assert not [edge for edge in graph.edges if edge.kind == EdgeKind.REFERENCES] diff --git a/tests/test_rocq_parser.py b/tests/test_rocq_parser.py index e5eb0b8..b7e2145 100644 --- a/tests/test_rocq_parser.py +++ b/tests/test_rocq_parser.py @@ -2,10 +2,21 @@ import pytest +from tests.parse_work import parse_work from trailmark.models.edges import EdgeKind from trailmark.parse import detect_languages, parse_directory, parse_file +def test_missing_import_stops_after_enclosing_namespaces(tmp_path: Path) -> None: + source = tmp_path / "Scoped.v" + source.write_text( + "Module Outer.\nRequire Import Missing.\nDefinition value := 0.\nEnd Outer.\n" + ) + graph, _ = parse_work(source, language="rocq", max_work=100_000) + value = next(node for node in graph.nodes.values() if node.name == "value") + assert dict(value.attributes)["qualified_name"] == "Scoped.Outer.value" + + def test_gallina_references_and_statement_roles() -> None: graph = parse_file(str(Path(__file__).parent / "fixtures/kat/rocq/taxonomy.v"), "rocq") names = {n.id: n.name for n in graph.nodes.values()} diff --git a/tests/test_rust_local_items.py b/tests/test_rust_local_items.py index c9c73c5..63f0ff0 100644 --- a/tests/test_rust_local_items.py +++ b/tests/test_rust_local_items.py @@ -3,6 +3,7 @@ from __future__ import annotations from pathlib import Path +from unittest.mock import patch import pytest @@ -13,6 +14,19 @@ from trailmark.query.api import QueryEngine +@pytest.mark.parametrize("macro", ["opaque", "crate::opaque"]) +def test_ordinary_macros_keep_nested_verus_opaque(tmp_path: Path, macro: str) -> None: + path = tmp_path / "ordinary.rs" + path.write_text(f"{macro}! {{ verus! {{ fn hidden() {{}} }} }}\nfn visible() {{}}\n") + parser = RustParser() + with patch.object(parser, "_parse_verus_block", return_value=None) as parse_verus: + graph = parser.parse_file(str(path)) + parse_verus.assert_not_called() + assert {node.id for node in graph.nodes.values() if node.kind == NodeKind.FUNCTION} == { + "ordinary:visible" + } + + @pytest.mark.parametrize("wrapper", [False, True]) @pytest.mark.parametrize( ("declaration", "call", "owner", "kind"), diff --git a/tests/test_test_policy.py b/tests/test_test_policy.py index d51fd4e..bd035f9 100644 --- a/tests/test_test_policy.py +++ b/tests/test_test_policy.py @@ -82,7 +82,12 @@ def test_policy_allows_product_limits_and_disabled_deadlines(source: str) -> Non def test_suite_has_no_test_timeouts_or_wall_clock_assertions() -> None: # These are opt-in measurement tools or the mutation executor, not tests. - measurement_tools = {"benchmark_analysis.py", "smoke_binary_projects.py", "run_mutations.py"} + measurement_tools = { + "benchmark_analysis.py", + "smoke_binary_projects.py", + "run_mutations.py", + "mutation_confirmation.py", + } violations = { path.name: controls for path in Path(__file__).parent.glob("*.py") @@ -96,3 +101,6 @@ def test_hypothesis_has_no_deadline_or_generation_speed_limit() -> None: assert defaults is not None assert defaults.deadline is None assert HealthCheck.too_slow in defaults.suppress_health_check + mutation = settings.get_profile("trailmark-mutation") + assert mutation.derandomize is True + assert mutation.database is None