From 256a57693c0fc109fda84daae536f1d5e0fe46e1 Mon Sep 17 00:00:00 2001 From: Scott Arciszewski <147527775+tob-scott-a@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:05:01 -0500 Subject: [PATCH 1/5] Add candidate mutation test pool and parity audits --- .github/workflows/mutation-audit.yml | 64 ++++++ .github/workflows/mutation.yml | 40 +++- .gitignore | 2 +- AGENTS.md | 4 + CONTRIBUTING.md | 46 +++++ pyproject.toml | 1 + tests/benchmark_mutations.py | 191 ++++++++++++++++++ tests/compare_mutations.py | 172 ++++++++++++++++ tests/mutation_bootstrap.py | 3 + tests/mutation_confirmation.py | 5 + tests/mutation_gate.py | 18 +- tests/mutation_inventory.py | 27 +++ tests/run_mutations.py | 65 +++++- tests/test_aiken_parser.py | 6 + tests/test_audit_regressions.py | 60 ++++++ tests/test_augment.py | 19 ++ tests/test_bash_nested_bindings.py | 3 + tests/test_bash_parser.py | 5 + tests/test_binary_commit_validation.py | 6 + tests/test_binary_import.py | 10 + tests/test_binary_models.py | 30 +++ tests/test_binary_oracles.py | 3 + tests/test_binary_snapshots.py | 2 + tests/test_c_binding_contracts.py | 5 + tests/test_c_block_splices.py | 1 + tests/test_c_callback_forms.py | 1 + tests/test_c_conditional_recovery.py | 1 + tests/test_c_conditional_trivia.py | 1 + tests/test_c_followup.py | 15 ++ tests/test_c_function_references.py | 5 + tests/test_c_header_budgets.py | 1 + tests/test_c_lookup_controls.py | 1 + tests/test_c_macro_budgets.py | 1 + tests/test_c_macro_conditions.py | 1 + tests/test_c_macro_rejections.py | 1 + tests/test_c_macro_splices.py | 1 + tests/test_c_macros.py | 1 + tests/test_c_nested_declarators.py | 1 + tests/test_c_parser.py | 14 ++ tests/test_c_recovery_locations.py | 1 + tests/test_c_review_regressions.py | 3 + tests/test_c_source_recovery.py | 5 + tests/test_c_typedef_casts.py | 4 + tests/test_c_visibility_macros.py | 2 + tests/test_cairo_parser.py | 17 ++ tests/test_cairo_qualified_calls.py | 4 + tests/test_cairo_self_calls.py | 4 + tests/test_callable_binding_boundaries.py | 26 +++ tests/test_callable_references.py | 28 +++ tests/test_circom_grammar.py | 2 + tests/test_circom_parser.py | 11 + tests/test_cli.py | 16 ++ tests/test_cli_parser.py | 2 + tests/test_common_parser.py | 20 ++ tests/test_cpp_block_macros.py | 8 + tests/test_cpp_cast_receivers.py | 5 + tests/test_cpp_declaration_markers.py | 7 + tests/test_cpp_export_markers.py | 2 + tests/test_cpp_header_discovery.py | 3 + tests/test_cpp_parser.py | 20 ++ tests/test_csharp_optional_overloads.py | 7 + tests/test_csharp_parser.py | 21 ++ tests/test_csharp_static_calls.py | 9 + tests/test_dafny_callback_sites.py | 6 + tests/test_dafny_parser.py | 17 ++ tests/test_dafny_proof_continuations.py | 1 + tests/test_dart_parser.py | 14 ++ tests/test_dart_return_receivers.py | 8 + tests/test_declaration_identity.py | 5 + tests/test_detector_tags.py | 12 ++ tests/test_diagram_script.py | 27 +++ tests/test_diff.py | 20 ++ tests/test_directory_linking.py | 7 + tests/test_dispatch_resolution.py | 3 + tests/test_docs.py | 8 + tests/test_ecmascript_construction_sites.py | 7 + tests/test_ecmascript_import_scaling.py | 1 + .../test_ecmascript_imported_constructors.py | 3 + tests/test_ecmascript_named_imports.py | 4 + tests/test_elysia_entrypoints.py | 12 ++ tests/test_entrypoint_discovery.py | 10 + tests/test_entrypoint_exports.py | 12 ++ tests/test_entrypoint_ownership.py | 7 + tests/test_entrypoints.py | 43 ++++ tests/test_erlang_parser.py | 17 ++ tests/test_exceptions.py | 23 +++ tests/test_final_parser_followups.py | 17 ++ tests/test_followup_bindings.py | 6 + tests/test_followup_diagnostics.py | 4 + tests/test_followup_frontends.py | 10 + tests/test_formal_common.py | 10 + tests/test_formal_recovery_offsets.py | 1 + tests/test_fstar_application_sites.py | 3 + tests/test_fstar_parenthesized_heads.py | 2 + tests/test_fstar_parser.py | 18 ++ tests/test_go_parser.py | 14 ++ tests/test_go_receivers.py | 3 + tests/test_graph_oracles.py | 3 + tests/test_haskell_parser.py | 17 ++ tests/test_hidden_apis.py | 4 + tests/test_inherited_method_binding.py | 5 + tests/test_java_anonymous_inheritance.py | 6 + tests/test_java_parser.py | 11 + tests/test_javascript_parser.py | 10 + tests/test_julia_inbounds.py | 4 + tests/test_julia_parser.py | 10 + tests/test_kat_cli.py | 1 + tests/test_kat_diagram.py | 5 + tests/test_kat_parsers.py | 1 + tests/test_kotlin_overload_arity.py | 5 + tests/test_kotlin_parser.py | 10 + tests/test_lean_parser.py | 15 ++ tests/test_lean_regressions.py | 7 + tests/test_lookup_oracle.py | 2 + tests/test_lua_parser.py | 9 + tests/test_lua_table_bindings.py | 5 + tests/test_masm_grammar.py | 2 + tests/test_masm_parser.py | 15 ++ tests/test_models.py | 7 + tests/test_mutation_comparison.py | 156 ++++++++++++++ tests/test_native_binary.py | 23 +++ tests/test_native_grammar.py | 11 + tests/test_new_language_parsers.py | 7 + tests/test_objc_enum_macros.py | 4 + tests/test_objc_ivar_receivers.py | 7 + tests/test_objc_nullability.py | 3 + tests/test_objc_parser.py | 10 + tests/test_parse_api.py | 2 + tests/test_parser_edge_cases.py | 6 + tests/test_path_glob.py | 2 + tests/test_perl_parser.py | 5 + tests/test_php_callables.py | 6 + tests/test_php_parser.py | 17 ++ tests/test_php_templates.py | 3 + tests/test_polyglot.py | 2 + tests/test_powershell_parser.py | 5 + tests/test_preanalysis.py | 11 + tests/test_proverif_parser.py | 11 + tests/test_proxies.py | 7 + tests/test_proxy_properties.py | 2 + tests/test_pyramid_includes.py | 4 + tests/test_python_decorator_bindings.py | 20 ++ tests/test_python_import_resolution.py | 7 + tests/test_python_module_initialization.py | 6 + tests/test_python_parser.py | 15 ++ tests/test_python_walrus_bindings.py | 2 + tests/test_query.py | 30 +++ tests/test_query_edge_cases.py | 2 + tests/test_r_parser.py | 5 + tests/test_receiver_index.py | 2 + tests/test_recovery.py | 5 + tests/test_reference_literals.py | 17 ++ tests/test_rego_index_grammar.py | 1 + tests/test_rego_rule_references.py | 5 + tests/test_release_followups.py | 10 + tests/test_repository_links.py | 3 + tests/test_resolution.py | 3 + tests/test_rocq_parser.py | 14 ++ tests/test_round2_bindings.py | 7 + tests/test_round2_frontends.py | 9 + tests/test_round3_bindings.py | 3 + tests/test_round3_c.py | 3 + tests/test_round3_frontends.py | 2 + tests/test_round3_python.py | 3 + tests/test_round3_robustness.py | 1 + tests/test_round4_bindings.py | 3 + tests/test_round4_c.py | 4 + tests/test_round4_frontends.py | 2 + tests/test_round4_python.py | 2 + tests/test_round5_bindings.py | 3 + tests/test_round5_ecmascript.py | 2 + tests/test_round5_python.py | 1 + tests/test_ruby_inline_visibility.py | 1 + tests/test_ruby_literal_aliases.py | 8 + tests/test_ruby_parser.py | 14 ++ tests/test_rust_local_items.py | 16 ++ tests/test_rust_macro_templates.py | 8 + tests/test_rust_parser.py | 11 + tests/test_rust_verus_regressions.py | 17 ++ tests/test_sarif_locations.py | 3 + tests/test_snapshots.py | 23 +++ tests/test_solidity_call_spans.py | 1 + tests/test_solidity_modifier_calls.py | 6 + tests/test_solidity_parser.py | 12 ++ tests/test_solidity_state.py | 7 + tests/test_source_policy.py | 9 + tests/test_sql_parser.py | 9 + tests/test_sql_routine_boundaries.py | 4 + tests/test_storage.py | 25 +++ tests/test_swift_parser.py | 12 ++ tests/test_tamarin_parser.py | 11 + tests/test_test_policy.py | 1 + tests/test_tlaplus_local_definitions.py | 5 + tests/test_tlaplus_parser.py | 8 + tests/test_tlaplus_proofs.py | 5 + tests/test_typescript_parser.py | 13 ++ tests/test_vb_grammar.py | 5 + tests/test_vb_parser.py | 5 + tests/test_whyml_application_sites.py | 3 + tests/test_whyml_parser.py | 11 + tests/test_zig_parser.py | 8 + 201 files changed, 2309 insertions(+), 17 deletions(-) create mode 100644 .github/workflows/mutation-audit.yml create mode 100644 tests/benchmark_mutations.py create mode 100644 tests/compare_mutations.py create mode 100644 tests/mutation_inventory.py create mode 100644 tests/test_mutation_comparison.py diff --git a/.github/workflows/mutation-audit.yml b/.github/workflows/mutation-audit.yml new file mode 100644 index 00000000..57528153 --- /dev/null +++ b/.github/workflows/mutation-audit.yml @@ -0,0 +1,64 @@ +name: Mutation pool parity + +on: + schedule: + - cron: '0 6 * * 1' + workflow_dispatch: + pull_request: + branches: [main] + paths: + - '.github/workflows/mutation*.yml' + - 'tests/*mutation*.py' + - 'tests/conftest.py' + - 'tests/parse_work.py' + - 'tests/test_test_policy.py' + - 'pyproject.toml' + - 'uv.lock' + +permissions: + contents: read + +jobs: + reference: + uses: ./.github/workflows/mutation.yml + with: + test-group: full + test-selection: full + test-order: collection + full-source: true + candidate: + uses: ./.github/workflows/mutation.yml + with: + test-group: fast + test-selection: coverage + full-source: true + compare: + name: Preserve every full-pool kill + needs: [reference, candidate] + runs-on: ubuntu-latest + 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: npm ci + - run: uv sync --locked --all-groups --extra binary + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: mutation-report-*-full-shard-* + path: coverage/parity/full + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: mutation-report-*-fast-shard-* + path: coverage/parity/fast + - run: uv run --locked python -m tests.compare_mutations coverage/parity/full coverage/parity/fast > coverage/parity/comparison.json + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: mutation-pool-comparison + path: coverage/parity/comparison.json diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml index 5a3bee1b..8a578c7d 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -6,15 +6,41 @@ on: pull_request: branches: [main] workflow_dispatch: + inputs: + test-group: + type: choice + options: [full, fast] + default: full + test-selection: + type: choice + options: [coverage, full] + default: coverage + workflow_call: + inputs: + test-group: + type: string + default: full + test-selection: + type: string + default: coverage + test-order: + type: string + default: component + full-source: + type: boolean + default: false concurrency: - group: mutation-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + group: mutation-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}-${{ inputs.test-group || 'full' }}-${{ inputs.test-selection || 'coverage' }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} permissions: contents: read env: + MUTATION_TEST_GROUP: ${{ inputs.test-group || 'full' }} + MUTATION_TEST_SELECTION: ${{ inputs.test-selection || 'coverage' }} + MUTATION_TEST_ORDER: ${{ inputs.test-order || 'component' }} PYTHONHASHSEED: "0" TRAILMARK_REQUIRE_BINARY_TOOLS: "1" TRAILMARK_LLVM_OBJDUMP: /usr/bin/llvm-objdump @@ -38,6 +64,7 @@ jobs: id: scope env: PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} + FULL_SOURCE: ${{ inputs.full-source }} run: | reviewed=false if [[ "$GITHUB_EVENT_NAME" == pull_request ]]; then @@ -47,6 +74,7 @@ jobs: reviewed=false fi fi + if [[ "$FULL_SOURCE" == true ]]; then reviewed=false; fi echo "reviewed=$reviewed" >> "$GITHUB_OUTPUT" baselines: @@ -73,11 +101,11 @@ jobs: 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" + uv run --locked --extra binary python -m tests.run_mutations "${scope[@]}" --test-group="$MUTATION_TEST_GROUP" --test-selection="$MUTATION_TEST_SELECTION" --test-order="$MUTATION_TEST_ORDER" --baseline-shard="$BASELINE_SHARD" - name: Upload validated baselines uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: mutation-baseline + name: mutation-baseline-${{ env.MUTATION_TEST_GROUP }} overwrite: true path: | coverage/gremlins/baseline-*.json @@ -114,13 +142,13 @@ jobs: - run: uv sync --locked --all-groups --extra binary - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: - name: mutation-baseline + name: mutation-baseline-${{ env.MUTATION_TEST_GROUP }} 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 + uv run --locked --extra binary python -m tests.run_mutations "${scope[@]}" --test-group="$MUTATION_TEST_GROUP" --test-selection="$MUTATION_TEST_SELECTION" --test-order="$MUTATION_TEST_ORDER" --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" @@ -135,7 +163,7 @@ jobs: if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: mutation-report-${{ github.sha }}-shard-${{ matrix.shard }} + name: mutation-report-${{ github.sha }}-${{ env.MUTATION_TEST_GROUP }}-shard-${{ matrix.shard }} overwrite: true path: coverage/gremlins/ if-no-files-found: error diff --git a/.gitignore b/.gitignore index 63144330..a7bd80b7 100644 --- a/.gitignore +++ b/.gitignore @@ -14,7 +14,7 @@ mutants/ src/trailmark/tree_sitter_custom/**/*.so src/trailmark/tree_sitter_custom/**/*.pyd .gremlins_cache/ -coverage/gremlins/ +coverage/ # Keep raw audit reports, probes, and validation logs local. /docs/audits/ /pr-audits/ diff --git a/AGENTS.md b/AGENTS.md index d02724b0..f3b01a82 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -137,3 +137,7 @@ Do not enable `TRAILMARK_UPDATE_SNAPSHOTS` during CI or mutation testing. `test_query.py`, plus focused parser/analysis/doc regression tests. - Update `README.md` and the matching regression tests if adding or changing user-facing API. + +The candidate `mutation_fast` pool is opt-in with `--test-group=fast`; the full +pool stays the default until complete parity and a 20% median wall-time saving +are measured. See CONTRIBUTING.md for comparisons and weekly/release audits. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3ff2ddeb..db94afc6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -201,6 +201,52 @@ followed by the relevant test files. Snapshot updates (`TRAILMARK_UPDATE_SNAPSHOTS=1`) are disabled during CI and mutation runs; do not enable them there. +### Mutation test pools + +The candidate fast pool marks existing tests with `pytest.mark.mutation_fast`. +Tests stay in their original modules and ordinary CI continues to run every test. +The full pool remains the default until the release acceptance campaign proves +zero lost kills and at least 20% lower median end-to-end wall time. + +```bash +uv run pytest -q -m mutation_fast tests/ +uv run python -m tests.run_mutations --test-group=fast --workers=4 --report-dir=coverage/fast +uv run python -m tests.mutation_gate --report-dir=coverage/fast + +# Unfiltered reference: test pool and coverage selection are independent controls. +uv run python -m tests.run_mutations --test-group=full --test-selection=full --test-order=collection --report-dir=coverage/reference +uv run python -m tests.compare_mutations coverage/reference coverage/fast + +# Complete application inventory, three serialized repetitions per configuration. +# Configure the native tool paths listed above before starting this long benchmark. +uv run python -m tests.benchmark_mutations --workers=4 --repeat=3 --output-dir=coverage/pool-benchmark +``` + +Report directories must be distinct for independent campaigns; put them under +ignored `coverage/` or outside the checkout. Comparisons require the exact source +checkout that produced the reports. They reconstruct the complete mutation inventory, +validate disjoint shard coverage and matching inputs, reject inconclusive outcomes, +and report each outcome difference rather than comparing percentages alone. +The benchmark includes clean baselines, instrumented coverage preparation, +collection, mutation execution, confirmations, and report validation. It includes +plain unsharded pytest-gremlins only as a measurement reference; normal mutation +work must use the repository runner. Result caching is disabled in these comparisons. + +The seed pool comes from the v0.9.1 campaign's recorded failing-test witnesses. +These witnesses are candidates, not evidence that each test kills independently. +Keep integration tests and collection import witnesses that provide unique kills. +When an audit loses a kill, restore the relevant existing test to the marked pool +or add a small behavioral regression, then rerun the comparison. Do not expand +equivalent-mutant exceptions or narrow the mutated application to repair parity. +Timing measurements belong in the benchmark, never in correctness assertions. + +`mutation-audit.yml` compares an unfiltered full-pool campaign with the fast pool +weekly on Monday at 06:00 UTC and for mutation-infrastructure pull requests. +Run its manual trigger against each release candidate as well. Each pool uses +32 mutation shards and its own matching baseline. Once acceptance permits the +routine fast-pool default, retain these full-pool audits and restore every lost +kill before accepting a failed audit. + ## Audit artifacts Keep implementations, minimized behavioral regressions, and concise decisions in diff --git a/pyproject.toml b/pyproject.toml index b62c5031..af84e332 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -96,6 +96,7 @@ known-third-party = ["coverage"] [tool.pytest.ini_options] testpaths = ["tests"] markers = [ + "mutation_fast: candidate mutation pool; parity and performance must be audited", "mutation_infrastructure: validate the runner once in its clean baseline", "binary_tools: integration checks requiring the binary extra and native host tools", ] diff --git a/tests/benchmark_mutations.py b/tests/benchmark_mutations.py new file mode 100644 index 00000000..08845e4f --- /dev/null +++ b/tests/benchmark_mutations.py @@ -0,0 +1,191 @@ +"""Measure mutation pools end to end; never use elapsed time as a pytest assertion.""" + +from __future__ import annotations + +import argparse +import gzip +import json +import os +import shutil +import statistics +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +from tests.compare_mutations import compare, load_campaign +from tests.mutation_controls import input_fingerprint + + +def archive_report(directory: Path) -> None: + """Keep full test selections while avoiding multi-gigabyte duplicate reports.""" + path = directory / "gremlins.json" + with path.open("rb") as source, gzip.open(path.with_suffix(".json.gz"), "wb") as destination: + shutil.copyfileobj(source, destination) + path.unlink() + + +def benchmark(output: Path, *, repeat: int, workers: int) -> dict[str, Any]: + """Run one unfiltered reference and alternating, uncached unsharded measurements.""" + root = Path.cwd() + output = output.resolve() + if output.is_relative_to(root) and not output.is_relative_to(root / "coverage"): + raise ValueError("Put benchmark output outside the checkout or under coverage/") + output.mkdir(parents=True, exist_ok=False) + os.environ["TRAILMARK_MUTATION_TESTING"] = "1" + os.environ["TRAILMARK_REQUIRE_BINARY_TOOLS"] = "1" + if os.environ.get("PYTEST_ADDOPTS"): + raise ValueError("Unset PYTEST_ADDOPTS for the controlled benchmark") + fingerprint = input_fingerprint(root) + timings: list[dict[str, Any]] = [] + + def execute(command: list[str], destination: Path) -> float: + started = time.perf_counter() + with destination.open("w") as log: + completed = subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=False) # noqa: S603 + if completed.returncode: + raise ValueError(f"Benchmark command failed; see {destination}") + if input_fingerprint(root) != fingerprint: + raise ValueError("Benchmark inputs changed") + return time.perf_counter() - started + + def campaign(name: str, *, group: str, selection: str = "coverage") -> Path: + directory = output / name + command = [ + sys.executable, + "-m", + "tests.run_mutations", + f"--test-group={group}", + f"--test-selection={selection}", + f"--workers={workers}", + f"--report-dir={directory}", + ] + if selection == "full": + command.append("--test-order=collection") + execute(command, output / f"{name}.log") + return directory + + reference = campaign("reference", group="full", selection="full") + _, reference_rows = load_campaign(reference) + archive_report(reference) + for iteration in range(repeat): + order = ("full", "fast", "stock") if iteration % 2 == 0 else ("stock", "fast", "full") + for group in order: + name = f"{iteration + 1}-{group}" + print(f"Measuring {name}", flush=True) + clean = [ + sys.executable, + "-m", + "pytest", + "-q", + "tests", + "-m", + "mutation_fast and not mutation_infrastructure" + if group == "fast" + else "not mutation_infrastructure", + ] + clean_seconds = execute(clean, output / f"{name}-clean.log") + started = time.perf_counter() + if group != "stock": + directory = campaign(name, group=group) + comparison = compare(reference, directory) + (output / f"{name}-comparison.json").write_text( + json.dumps(comparison, indent=2) + "\n" + ) + if comparison["lost_kills"]: + raise ValueError(f"Lost kills in {name}; inspect its comparison report") + archive_report(directory) + else: + directory = output / name + command = [ + *clean, + "--gremlins", + "--gremlin-executor=subprocess", + f"--gremlin-workers={workers}", + "--gremlin-targets=src/trailmark", + "--gremlin-report=json", + f"--gremlins-html-dir={directory}", + ] + execute(command, output / f"{name}.log") + # The pinned plugin hardcodes its JSON path independently of html-dir. + directory.mkdir(parents=True, exist_ok=True) + shutil.copyfile( + root / "coverage/gremlins/gremlins.json", directory / "gremlins.json" + ) + stock = json.loads((directory / "gremlins.json").read_text()) + by_id = {row["gremlin_id"]: row for row in stock["results"]} + if len(by_id) != len(reference_rows) or set(by_id) != { + row["gremlin_id"] for row in reference_rows.values() + }: + raise ValueError("Stock mutation inventory differs") + # Persist stock outcomes for a comparison after every arm has finished. + (output / f"{name}-outcomes.json").write_text( + json.dumps({key: row["status"] for key, row in by_id.items()}) + "\n" + ) + archive_report(directory) + (root / "coverage/gremlins/gremlins.json").unlink() + timings.append( + { + "repeat": iteration + 1, + "group": group, + "clean_baseline_seconds": clean_seconds, + "campaign_and_validation_seconds": time.perf_counter() - started, + "total_seconds": clean_seconds + time.perf_counter() - started, + } + ) + (output / "timings.json").write_text(json.dumps(timings, indent=2) + "\n") + _, candidate_rows = load_campaign(output / f"{iteration + 1}-fast") + fast_by_id = {row["gremlin_id"]: row for row in candidate_rows.values()} + stock_rows = json.loads((output / f"{iteration + 1}-stock-outcomes.json").read_text()) + differences = [ + {"gremlin_id": key, "stock": status, "fast": fast_by_id[key]["status"]} + for key, status in stock_rows.items() + if status != fast_by_id[key]["status"] + ] + (output / f"{iteration + 1}-stock-comparison.json").write_text( + json.dumps(differences, indent=2) + "\n" + ) + if any(row["stock"] == "zapped" and row["fast"] != "zapped" for row in differences): + raise ValueError("Fast pool lost a stock-plugin kill") + medians = { + group: statistics.median(row["total_seconds"] for row in timings if row["group"] == group) + for group in ("full", "fast", "stock") + } + pairs = [ + {row["group"]: row["total_seconds"] for row in timings if row["repeat"] == index} + for index in range(1, repeat + 1) + ] + reduction = 1 - medians["fast"] / medians["full"] + return { + "inputs": fingerprint, + "workers": workers, + "repeat": repeat, + "median_seconds": medians, + "reduction": reduction, + "release_eligible": repeat >= 3 + and workers == 4 + and reduction >= 0.20 + and all(pair["fast"] < pair["full"] for pair in pairs), + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--repeat", type=int, default=3) + parser.add_argument("--workers", type=int, default=4) + args = parser.parse_args() + if args.repeat < 1 or args.workers < 1: + parser.error("Repeat and workers must be positive") + try: + result = benchmark(args.output_dir, repeat=args.repeat, workers=args.workers) + except (OSError, ValueError, KeyError, TypeError) as exc: + parser.exit(1, f"Mutation benchmark failed: {exc}\n") + (args.output_dir / "summary.json").write_text(json.dumps(result, indent=2) + "\n") + print(json.dumps(result, indent=2)) + return int(not result["release_eligible"]) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/compare_mutations.py b/tests/compare_mutations.py new file mode 100644 index 00000000..21428d8c --- /dev/null +++ b/tests/compare_mutations.py @@ -0,0 +1,172 @@ +"""Compare complete mutation campaigns without treating missing evidence as success.""" + +from __future__ import annotations + +import argparse +import gzip +import hashlib +import json +from collections import Counter +from pathlib import Path +from typing import Any + +from pytest_gremlins.instrumentation.transformer import transform_source + +from tests.mutation_inventory import inventory + + +def read_report(path: Path) -> Any: + """Accept archived reports without requiring a second uncompressed copy.""" + if path.exists(): + return json.loads(path.read_text()) + with gzip.open(path.with_suffix(path.suffix + ".gz"), "rt") as source: + return json.load(source) + + +def load_campaign(directory: Path) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]: + """Load one campaign, or a complete set of its disjoint shard directories.""" + paths = ( + [directory] + if (directory / "run.json").is_file() + else sorted(path.parent for path in directory.rglob("run.json")) + ) + if not paths: + raise ValueError("Missing campaign reports") + context = None + shards = set() + results = {} + total_shards = 0 + for path in paths: + run = json.loads((path / "run.json").read_text()) + index, count = run["shard"] + if not 1 <= index <= count or (index, count) in shards: + raise ValueError("Duplicate or invalid campaign shard") + shards.add((index, count)) + total_shards = count + current = { + key: run[key] + for key in ( + "inputs", + "sources", + "targets", + "tests", + "runner", + "pytest_gremlins", + "test_order", + "test_selection", + "test_group", + "workers", + "kill_confirmation", + ) + } + if context is not None and current != context: + raise ValueError("Mismatched campaign shards") + context = current + if run["baseline_validation"] not in {"local", "shared"} or run[ + "kill_confirmation" + ] not in {"baseline-orders", "failure-prefix"}: + raise ValueError("Missing validated baseline or confirmation") + report = read_report(path / "gremlins.json") + inventory = json.loads((path / "inventory.json").read_text()) + rows = report["results"] + by_id = {row["gremlin_id"]: row for row in rows} + expected = {row["gremlin_id"]: row for row in inventory} + if ( + len(by_id) != len(rows) + or len(expected) != len(inventory) + or by_id.keys() != expected.keys() + or report.get("skipped_files") + ): + raise ValueError("Incomplete or duplicate mutation inventory") + counts = Counter(row["status"] for row in rows) + if report["summary"]["total"] != len(rows) or any( + report["summary"].get(status, 0) != count for status, count in counts.items() + ): + raise ValueError("Inconsistent mutation summary") + for identifier, row in by_id.items(): + if row["status"] not in {"zapped", "survived"} or not row["selected_tests"]: + raise ValueError("Inconclusive mutation outcome") + detail = expected[identifier] + fingerprint = detail["fingerprint"] + if fingerprint in results: + raise ValueError("Duplicate mutation fingerprint") + results[fingerprint] = { + **detail, + "status": row["status"], + "killing_test": row.get("killing_test"), + } + if shards != {(index, total_shards) for index in range(1, total_shards + 1)}: + raise ValueError("Incomplete campaign shards") + assert context is not None + return context, results + + +def compare( + reference: Path, + candidate: Path, + *, + root: Path | None = None, + require_full_reference: bool = True, +) -> dict[str, Any]: + """Report every difference, rejecting incomparable sources and test inputs.""" + before, full = load_campaign(reference) + after, fast = load_campaign(candidate) + for key in ("inputs", "sources", "targets", "tests", "runner", "pytest_gremlins", "workers"): + if before[key] != after[key]: + raise ValueError(f"Incomparable campaign {key}") + if require_full_reference and ( + before["test_group"] != "full" or before["test_selection"] != "full" + ): + raise ValueError("Reference must use the full test pool without coverage filtering") + if full.keys() != fast.keys() or not full: + raise ValueError("Campaign mutation inventories differ or are empty") + root = (root or Path.cwd()).resolve() + mutations = [] + for name, expected_hash in before["sources"].items(): + path = (root / name).resolve() + if ( + not path.is_relative_to(root) + or hashlib.sha256(path.read_bytes()).hexdigest() != expected_hash + ): + raise ValueError(f"Missing or changed campaign source: {name}") + discovered, _ = transform_source(path.read_text(), str(path)) + mutations.extend(discovered) + actual = {row["fingerprint"] for row in inventory(mutations, root)} + if actual != full.keys(): + raise ValueError("Campaign inventory does not match application sources") + differences = [ + { + "fingerprint": key, + "path": row["path"], + "function": row["function"], + "line": row["line"], + "reference": row["status"], + "candidate": fast[key]["status"], + } + for key, row in sorted(full.items()) + if row["status"] != fast[key]["status"] + ] + return { + "mutants": len(full), + "reference_kills": sum(row["status"] == "zapped" for row in full.values()), + "candidate_kills": sum(row["status"] == "zapped" for row in fast.values()), + "lost_kills": sum(row["reference"] == "zapped" for row in differences), + "differences": differences, + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("reference", type=Path) + parser.add_argument("candidate", type=Path) + args = parser.parse_args() + try: + result = compare(args.reference, args.candidate) + except (OSError, ValueError, KeyError, TypeError) as exc: + parser.exit(1, f"Mutation comparison failed: {exc}\n") + print(json.dumps(result, indent=2)) + return int(bool(result["lost_kills"])) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/mutation_bootstrap.py b/tests/mutation_bootstrap.py index 3c91187c..15a0df23 100644 --- a/tests/mutation_bootstrap.py +++ b/tests/mutation_bootstrap.py @@ -81,6 +81,7 @@ def record_test_execution(directory: Path) -> None: def __init__(self): self.started = [] self.failed = False + self.failures = [] self.stopped = False self.limit = int(os.environ.get('TRAILMARK_PREFIX_LIMIT', '0')) @@ -90,6 +91,7 @@ def pytest_runtest_logstart(self, nodeid): def pytest_runtest_logreport(self, report): if report.failed: self.failed = True + self.failures.append({'test': report.nodeid, 'phase': report.when}) @pytest.hookimpl(wrapper=True, tryfirst=True) def pytest_runtest_protocol(self, item): @@ -111,6 +113,7 @@ def pytest_runtest_protocol(self, item): if destination: with open(destination + '.tmp', 'w') as output: json.dump({'tests': execution.started, 'failed': execution.failed, + 'failures': execution.failures, 'stopped': execution.stopped, 'exit_code': int(exit_code)}, output) os.replace(destination + '.tmp', destination) """ diff --git a/tests/mutation_confirmation.py b/tests/mutation_confirmation.py index aa6cb066..74879640 100644 --- a/tests/mutation_confirmation.py +++ b/tests/mutation_confirmation.py @@ -52,6 +52,7 @@ def __init__(self, workers: int, output: Path, *, checked_orders: bool = False) self.output = output self.checked_orders = checked_orders self.pending: list[_PendingKill] = [] + self.witnesses: dict[str, dict[str, str]] = {} def defer( self, @@ -79,6 +80,9 @@ def flush(self, session: plugin.GremlinSession, record: _Recorder) -> None: try: evidence = _read_execution(_execution_path(directory, gremlin.gremlin_id)) executions[gremlin.gremlin_id] = evidence + failures = evidence.get("failures", []) + if failures: + self.witnesses[gremlin.gremlin_id] = failures[0] except (OSError, ValueError): evidence = None output.write( @@ -91,6 +95,7 @@ def flush(self, session: plugin.GremlinSession, record: _Recorder) -> None: ), "failed": evidence["failed"] if evidence else None, "exit_code": evidence["exit_code"] if evidence else None, + "failure": self.witnesses.get(gremlin.gremlin_id), } ) + "\n" diff --git a/tests/mutation_gate.py b/tests/mutation_gate.py index 1b8970c6..5d5420a3 100644 --- a/tests/mutation_gate.py +++ b/tests/mutation_gate.py @@ -130,10 +130,13 @@ def _validate_versions(run: dict[str, Any], baseline: dict[str, Any]) -> None: raise ValueError("Report lacks validated pytest failure confirmation") -def _validate_test_selection(root: Path, report: dict[str, Any], run: dict[str, Any]) -> None: +def _validate_test_selection( + root: Path, report: dict[str, Any], run: dict[str, Any], report_dir: Path | None = None +) -> None: if run["test_selection"] == "full": return - envelope = json.loads((root / "coverage/gremlins/coverage-plan.json").read_text()) + directory = report_dir if report_dir is not None else root / "coverage/gremlins" + envelope = json.loads((directory / "coverage-plan.json").read_text()) expected = { key: run[key] for key in ( @@ -147,6 +150,7 @@ def _validate_test_selection(root: Path, report: dict[str, Any], run: dict[str, ) } expected["addopts"] = envelope["context"]["addopts"] + expected["test_group"] = run.get("test_group", "full") expected["coverage_plan"] = run["selection_plan"] tests = envelope["plan"]["tests"] plan = validate_plan(envelope, expected, tests, set(run["sources"])) @@ -238,12 +242,13 @@ def check( baseline: dict[str, Any], *, shard: tuple[int, int] = (1, 1), + report_dir: Path | None = None, ) -> list[str]: _validate_versions(run, baseline) 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) + _validate_test_selection(root, report, run, report_dir) inconclusive = [ { "path": row["file_path"], @@ -280,13 +285,14 @@ def check( def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--shard", type=parse_shard, default=(1, 1)) + parser.add_argument("--report-dir", type=Path, default=Path("coverage/gremlins")) args = parser.parse_args() root = Path.cwd() try: - report = json.loads((root / "coverage/gremlins/gremlins.json").read_text()) - run = json.loads((root / "coverage/gremlins/run.json").read_text()) + report = json.loads((args.report_dir / "gremlins.json").read_text()) + run = json.loads((args.report_dir / "run.json").read_text()) baseline = json.loads((root / "tests/mutation_baseline.json").read_text()) - failures = check(root, report, run, baseline, shard=args.shard) + failures = check(root, report, run, baseline, shard=args.shard, report_dir=args.report_dir) except (OSError, ValueError, KeyError, TypeError) as exc: print(f"Mutation gate failed: {exc}", file=sys.stderr) return 1 diff --git a/tests/mutation_inventory.py b/tests/mutation_inventory.py new file mode 100644 index 00000000..7bed0c1c --- /dev/null +++ b/tests/mutation_inventory.py @@ -0,0 +1,27 @@ +"""Stable mutation identities shared by comparison and execution reports.""" + +from __future__ import annotations + +import ast +from pathlib import Path +from typing import Any + +from pytest_gremlins.instrumentation.gremlin import Gremlin + + +def inventory(gremlins: list[Gremlin], root: Path) -> list[dict[str, Any]]: + """Describe every assigned mutation using its source rather than its ordinal ID.""" + from tests.mutation_gate import describe, functions_in + + sources = {} + result = [] + for gremlin in gremlins: + path = Path(gremlin.file_path).resolve() + if path not in sources: + source = path.read_text() + tree = ast.parse(source) + sources[path] = source, (tree, list(functions_in(tree))) + source, context = sources[path] + detail = describe(gremlin, source, path.relative_to(root.resolve()).as_posix(), context) + result.append({"gremlin_id": gremlin.gremlin_id, **detail}) + return result diff --git a/tests/run_mutations.py b/tests/run_mutations.py index cf66c980..d8a169e5 100644 --- a/tests/run_mutations.py +++ b/tests/run_mutations.py @@ -14,8 +14,10 @@ import os import subprocess import sys +import time from collections import defaultdict from collections.abc import Callable, Sequence +from dataclasses import replace from importlib.metadata import version from pathlib import Path from typing import Any @@ -39,7 +41,7 @@ from tests.mutation_order import prioritize_tests, relative_node_ids VERSION = "1.14.3" -RUNNER = "trailmark-pytest-coverage-v9" +RUNNER = "trailmark-pytest-coverage-v10" def parse_shard(value: str) -> tuple[int, int]: @@ -74,6 +76,8 @@ def _arguments() -> argparse.Namespace: ) parser.add_argument("--test-order", choices=["component", "collection"], default="component") parser.add_argument("--test-selection", choices=["coverage", "full"], default="coverage") + parser.add_argument("--test-group", choices=["fast", "full"], default="full") + parser.add_argument("--report-dir", type=Path, default=Path("coverage/gremlins")) controls = parser.add_mutually_exclusive_group() controls.add_argument( "--baseline-shard", @@ -87,6 +91,10 @@ def _arguments() -> argparse.Namespace: ) parser.add_argument("tests", nargs="*", default=["tests"]) args = parser.parse_args() + destination = args.report_dir.resolve() + root = Path.cwd().resolve() + if destination.is_relative_to(root) and not destination.is_relative_to(root / "coverage"): + parser.error("Report directories must be under coverage/ or outside the checkout") if args.workers < 1: parser.error("--workers must be positive") if version("pytest-gremlins") != VERSION: @@ -146,6 +154,7 @@ def _check_instrumented_orders( "tests": args.tests, "test_order": args.test_order, "test_selection": args.test_selection, + "test_group": args.test_group, "addopts": session.preserved_addopts, } if args.test_selection == "coverage": @@ -218,9 +227,11 @@ def write_and_check( raise pytest.UsageError(f"Mutation instrumentation skipped files: {unwritable}") record_source_collection_exits(directory) record_test_execution(directory) + started = time.perf_counter() receipts.append( _check_instrumented_orders(directory, instrumented_asts, args, fingerprint, plans) ) + args.timings["instrumented_preparation_seconds"] = time.perf_counter() - started return directory return write_and_check @@ -230,6 +241,12 @@ class _RequireCompleteInstrumentation: def __init__(self, args: argparse.Namespace) -> None: self.args = args self.empty_shard = False + self.inventory: list[dict[str, Any]] = [] + self.started = time.perf_counter() + + @pytest.hookimpl(tryfirst=True) + def pytest_collection_modifyitems(self) -> None: + self.args.timings["collection_and_startup_seconds"] = time.perf_counter() - self.started @pytest.hookimpl(trylast=True) def pytest_collection_finish(self) -> None: @@ -243,6 +260,9 @@ def pytest_collection_finish(self) -> None: if self.args.baseline_shard: session.enabled = False selected = select_shard(session.gremlins, self.args.shard) + from tests.mutation_inventory import inventory + + self.inventory = inventory(selected, Path.cwd()) self.empty_shard = bool(session.gremlins) and not selected session.gremlins = selected @@ -266,6 +286,7 @@ def _run_campaign( cache_result = plugin._cache_gremlin_result dispatch = plugin._dispatch_mutation_run selections: dict[str, list[str]] = {} + confirmed: dict[str, plugin.GremlinResult] = {} def record_confirmed_result( gremlin: Gremlin, @@ -275,6 +296,10 @@ def record_confirmed_result( ) -> None: # Native collection/timeout checks and our failure-prefix checks have # finished before a result reaches this publication point. + witness = controls.witnesses.get(gremlin.gremlin_id) + if witness is not None: + result = replace(result, killing_test=witness["test"]) + confirmed[gremlin.gremlin_id] = result cache_result(gremlin, selected_tests, result, session) with (report_dir / "progress.jsonl").open("a") as progress: progress.write( @@ -287,6 +312,8 @@ def record_confirmed_result( "status": result.status.value, "selected_test_count": len(result.selected_tests), "execution_time_ms": result.execution_time_ms, + "killing_test": result.killing_test, + "failure_phase": witness["phase"] if witness else None, } ) + "\n" @@ -304,9 +331,13 @@ def record_result( def dispatch_and_confirm( session: pytest.Session, gremlin_session: plugin.GremlinSession ) -> list[plugin.GremlinResult]: + started = time.perf_counter() results = dispatch(session, gremlin_session) + args.timings["mutation_execution_seconds"] = time.perf_counter() - started + started = time.perf_counter() controls.flush(gremlin_session, record_confirmed_result) - return results + args.timings["confirmation_seconds"] = time.perf_counter() - started + return [confirmed.get(result.gremlin.gremlin_id, result) for result in results] def uncached_tests(gremlin: Gremlin, session: plugin.GremlinSession) -> list[str]: tests = list(session.test_node_ids) @@ -333,6 +364,16 @@ def reuse_coverage(session: plugin.GremlinSession, rootdir: Path) -> None: if args.test_selection == "coverage": print("Reusing coverage from the validated baseline", flush=True) + def write_json( + score: plugin.MutationScore, + rootdir: Path, + *, + skipped_files: dict[str, str] | None = None, + ) -> Path: + destination = report_dir / "gremlins.json" + plugin.JsonReporter().write_report(score, destination, skipped_files=skipped_files) + return destination + instrumentation = _RequireCompleteInstrumentation(args) with ( patch.object( @@ -345,13 +386,18 @@ def reuse_coverage(session: plugin.GremlinSession, rootdir: Path) -> None: 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), + patch.object(plugin, "_write_json_report", side_effect=write_json), ): result = pytest.main( [ "-q", *args.tests, "-m", - "not mutation_infrastructure", + ( + "mutation_fast and not mutation_infrastructure" + if args.test_group == "fast" + else "not mutation_infrastructure" + ), "--gremlins", "--gremlin-executor=subprocess", *(["--gremlin-no-coverage-filter"] if args.test_selection == "full" else []), @@ -362,6 +408,10 @@ def reuse_coverage(session: plugin.GremlinSession, rootdir: Path) -> None: ], plugins=[instrumentation], ) + if result == 0 and not args.baseline_shard: + (report_dir / "inventory.json").write_text( + json.dumps(instrumentation.inventory, indent=2) + "\n" + ) 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" @@ -370,9 +420,11 @@ def reuse_coverage(session: plugin.GremlinSession, rootdir: Path) -> None: def main() -> int: + started = time.perf_counter() args = _arguments() + args.timings = {} os.environ["TRAILMARK_MUTATION_TESTING"] = "1" - report_dir = Path("coverage/gremlins") + report_dir = args.report_dir report_dir.mkdir(parents=True, exist_ok=True) for name in ( "run.json", @@ -381,6 +433,7 @@ def main() -> int: "coverage-plan.json", "prefix-summary.json", "executions.jsonl", + "inventory.json", ): (report_dir / name).unlink(missing_ok=True) receipt_path = None @@ -412,11 +465,15 @@ def main() -> int: "inputs": fingerprint, "test_order": args.test_order, "test_selection": args.test_selection, + "test_group": args.test_group, + "workers": args.workers, "selection_plan": plans[0]["digest"] if plans else None, "shard": args.shard, "targets": args.targets, "sources": hashes, "tests": args.tests, + "wall_seconds": time.perf_counter() - started, + "timings": args.timings, "baseline_validation": "shared" if args.baselines is not None else "local", "kill_confirmation": ( "baseline-orders" if args.test_selection == "full" else "failure-prefix" diff --git a/tests/test_aiken_parser.py b/tests/test_aiken_parser.py index 50a8d00a..8d717269 100644 --- a/tests/test_aiken_parser.py +++ b/tests/test_aiken_parser.py @@ -21,6 +21,7 @@ def _source(tmp_path: Path, text: str) -> Path: return path +@pytest.mark.mutation_fast @pytest.mark.parametrize( ("owner", "expected"), [("sample", "sample:run"), ("sample:validator", "sample:validator.run")] ) @@ -29,6 +30,7 @@ def test_callable_ids_keep_the_module_and_lexical_owner(owner: str, expected: st assert extractor.child_id(owner, "run") == expected +@pytest.mark.mutation_fast def test_types_signatures_imports_and_branches(tmp_path: Path) -> None: path = _source( tmp_path, @@ -62,6 +64,7 @@ def test_types_signatures_imports_and_branches(tmp_path: Path) -> None: ) +@pytest.mark.mutation_fast @pytest.mark.parametrize( "purpose", ["mint", "spend", "withdraw", "publish", "vote", "propose", "else"] ) @@ -83,6 +86,7 @@ def test_handlers_are_reachable_entrypoints(tmp_path: Path, purpose: str) -> Non assert engine.entrypoint_paths_to("helper") +@pytest.mark.mutation_fast def test_pipeline_calls_once_per_stage(tmp_path: Path) -> None: path = _source( tmp_path, "fn first(x) { x } fn second(x, y) { x } fn f(x) { x |> first |> second(1) }" @@ -95,6 +99,7 @@ def test_pipeline_calls_once_per_stage(tmp_path: Path) -> None: ] +@pytest.mark.mutation_fast def test_callback_and_import_do_not_bind_to_namesakes(tmp_path: Path) -> None: _source( tmp_path, @@ -141,6 +146,7 @@ def test_sibling_validator_handlers_stay_distinct(tmp_path: Path) -> None: } +@pytest.mark.mutation_fast def test_parse_errors_warn(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: path = tmp_path / "broken.ak" path.write_text("validator broken { spend(") diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 4e68ff5c..17dbd57d 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -28,6 +28,7 @@ FIXTURES = Path(__file__).parent / "fixtures" / "audit" +@pytest.mark.mutation_fast def test_proto_nested_fields_and_public_import() -> None: graph = parse_file(str(FIXTURES / "proto/cases/schema.proto"), "proto") for owner in ("Request", "Response"): @@ -48,6 +49,7 @@ def test_proto_nested_fields_and_public_import() -> None: assert not any(e.kind == EdgeKind.CALLS for e in graph.edges) +@pytest.mark.mutation_fast def test_graphql_effective_roots() -> None: engine = QueryEngine.from_directory( str(FIXTURES / "graphql/explicit_roots"), language="graphql" @@ -60,6 +62,7 @@ def test_graphql_effective_roots() -> None: } +@pytest.mark.mutation_fast def test_graphql_wrapped_type_dependencies() -> None: graph = parse_file(str(FIXTURES / "graphql/signatures/schema.graphql"), "graphql") wrapped = [ @@ -77,6 +80,7 @@ def test_graphql_wrapped_type_dependencies() -> None: ) +@pytest.mark.mutation_fast @pytest.mark.parametrize("mode", ["single", "split"]) def test_graphql_extensions(mode: str) -> None: graph = parse_directory(str(FIXTURES / "graphql/extensions" / mode), "graphql") @@ -85,6 +89,7 @@ def test_graphql_extensions(mode: str) -> None: assert not any(edge.kind == EdgeKind.CALLS for edge in graph.edges) +@pytest.mark.mutation_fast @pytest.mark.parametrize("artifact", [{"index": 0}, {"uri": "app.py", "uriBaseId": "SRC"}]) def test_sarif_run_locations_bind_correct_source(tmp_path: Path, artifact: dict) -> None: graph = CodeGraph(root_path=str(tmp_path)) @@ -123,6 +128,7 @@ def test_sarif_run_locations_bind_correct_source(tmp_path: Path, artifact: dict) assert set(graph.annotations) == {"lib"} +@pytest.mark.mutation_fast def test_thrift_file_identity_and_signature_types() -> None: graph = parse_directory(str(FIXTURES / "thrift/identity"), "thrift") requests = [unit for unit in graph.nodes.values() if unit.name == "Request"] @@ -155,6 +161,7 @@ def test_thrift_file_identity_and_signature_types() -> None: ) +@pytest.mark.mutation_fast @pytest.mark.parametrize("case", ["contract", "contract_inline", "impl_self"]) def test_sway_implemented_abi_entrypoints(case: str) -> None: engine = QueryEngine.from_directory(str(FIXTURES / "sway" / case), language="sway") @@ -162,6 +169,7 @@ def test_sway_implemented_abi_entrypoints(case: str) -> None: assert engine.entrypoint_paths_to("sink") +@pytest.mark.mutation_fast def test_sway_generic_impl_owners() -> None: graph = parse_directory(str(FIXTURES / "sway/generic"), "sway") assert "main:get" not in graph.nodes @@ -175,6 +183,7 @@ def test_sway_generic_impl_owners() -> None: } == {f"main:{sink}"} +@pytest.mark.mutation_fast def test_func_method_variants_and_lexical_callbacks() -> None: graph = parse_file(str(FIXTURES / "func/methods.fc"), "func") @@ -200,6 +209,7 @@ def callees(name: str) -> set[str]: assert sum(edge.target_id == "methods:helper" for edge in scoped_edges) == 1 +@pytest.mark.mutation_fast def test_func_semantic_getters_and_reserved_handlers() -> None: engine = QueryEngine.from_directory(str(FIXTURES / "func"), language="func") ids = {row["node_id"] for row in engine.attack_surface()} @@ -207,6 +217,7 @@ def test_func_semantic_getters_and_reserved_handlers() -> None: assert "constructs:get_private" not in ids +@pytest.mark.mutation_fast @pytest.mark.parametrize( "language,name,source", [("python", "bad.py", "def broken(:\n pass\n"), ("c", "bad.c", "int f() { return 1 }\n")], @@ -255,6 +266,7 @@ def test_cli_strict_analysis( assert "Incomplete source analysis" in output.err +@pytest.mark.mutation_fast @pytest.mark.parametrize("directory", [False, True]) def test_python_callable_ownership_and_shadowing(tmp_path: Path, directory: bool) -> None: path = tmp_path / "owned.py" @@ -307,6 +319,7 @@ def static(self, cls): pass assert [p.name for p in graph.nodes["owned:C.static"].parameters] == ["self", "cls"] +@pytest.mark.mutation_fast @pytest.mark.parametrize("language,extension", [("javascript", ".js"), ("typescript", ".ts")]) def test_ecmascript_nested_callable_ownership( tmp_path: Path, language: str, extension: str @@ -334,6 +347,7 @@ def test_ecmascript_nested_callable_ownership( assert not graph.parse_diagnostics +@pytest.mark.mutation_fast def test_typescript_tsx_and_interface_signatures() -> None: graph = parse_file(str(FIXTURES / "typescript/tsx/case.tsx"), "typescript", strict=True) calls = {(e.source_id, e.target_id) for e in graph.edges if e.kind == EdgeKind.CALLS} @@ -345,6 +359,7 @@ def test_typescript_tsx_and_interface_signatures() -> None: assert member.type_parameters[0].name == "U" +@pytest.mark.mutation_fast def test_typescript_receiver_invalidations() -> None: graph = parse_directory(str(FIXTURES / "typescript/receivers"), "typescript") calls = [e for e in graph.edges if e.kind == EdgeKind.CALLS] @@ -365,6 +380,7 @@ def _calls(graph: CodeGraph, source: str) -> list[str]: return [e.target_id for e in graph.edges if e.source_id == source and e.kind == EdgeKind.CALLS] +@pytest.mark.mutation_fast def test_sql_identity_body_ownership_and_identifier_matching() -> None: graph = parse_directory(str(FIXTURES / "sql/identities"), "sql") overloads = [n for n in graph.nodes.values() if n.name == "lookup"] @@ -403,6 +419,7 @@ def test_sql_identity_body_ownership_and_identifier_matching() -> None: assert ("z_views:app.mixed_distinct", 'a_tables:app."MiXeD"') not in dependencies +@pytest.mark.mutation_fast def test_r_binding_order_mutation_and_quoted_syntax() -> None: graph = parse_file(str(FIXTURES / "r/scope/main.R"), "r") calls = [e for e in graph.edges if e.source_id == "main:main" and e.kind == EdgeKind.CALLS] @@ -415,6 +432,7 @@ def test_r_binding_order_mutation_and_quoted_syntax() -> None: assert engine.paths_between("main:main", "main:helper") == [] +@pytest.mark.mutation_fast def test_miden_invocation_kinds_qualified_names_and_entrypoints() -> None: graph = parse_directory(str(FIXTURES / "masm/qualified"), "masm") assert "client:check" not in _calls(graph, "client:caller") @@ -431,6 +449,7 @@ def test_miden_invocation_kinds_qualified_names_and_entrypoints() -> None: assert {row["node_id"] for row in engine.attack_surface()} == {"library:api", "program:begin"} +@pytest.mark.mutation_fast def test_zig_identifiers_signatures_and_destructured_binding_guard() -> None: graph = parse_file(str(FIXTURES / "zig/quoted.zig"), "zig") assert _calls(graph, "quoted:main") == [ @@ -450,6 +469,7 @@ def test_zig_identifiers_signatures_and_destructured_binding_guard() -> None: assert graph.nodes[calls[0]].kind == NodeKind.PROXY +@pytest.mark.mutation_fast def test_aiken_labels_and_deferred_captures() -> None: graph = parse_directory(str(FIXTURES / "aiken/labels"), "aiken") assert [p.name for p in graph.nodes["sample:another"].parameters] == ["helper"] @@ -460,6 +480,7 @@ def test_aiken_labels_and_deferred_captures() -> None: assert _calls(graph, "sample:passed") == ["sample:receives"] +@pytest.mark.mutation_fast def test_lua_local_assignments_and_environment() -> None: graph = parse_directory(str(FIXTURES / "lua/lexical"), "lua") assert all( @@ -471,6 +492,7 @@ def test_lua_local_assignments_and_environment() -> None: assert "environment:helper" not in _calls(graph, "environment:main") +@pytest.mark.mutation_fast @pytest.mark.parametrize("case", ["quoted_eval", "escaped_eval", "quoted_source", "quoted_unset"]) def test_bash_static_command_words_invalidate_bindings(case: str) -> None: graph = parse_directory(str(FIXTURES / "bash/cases" / case), "bash") @@ -479,6 +501,7 @@ def test_bash_static_command_words_invalidate_bindings(case: str) -> None: assert "./library.bash" in graph.dependencies +@pytest.mark.mutation_fast def test_bash_coproc_and_time_ownership() -> None: graph = parse_file(str(FIXTURES / "bash/cases/coproc/sample.sh"), "bash", strict=True) assert graph.nodes["sample:main"].location.end_line == 8 @@ -487,6 +510,7 @@ def test_bash_coproc_and_time_ownership() -> None: assert _calls(graph, "sample:main").count("sample:helper") == 2 +@pytest.mark.mutation_fast def test_go_generics_signatures_and_package_boundaries() -> None: graph = parse_directory(str(FIXTURES / "go"), "go") assert _calls(graph, "features:genericCaller") == ["features:identity"] @@ -517,12 +541,14 @@ def test_rust_impl_bodies_remain_distinct(case: str) -> None: assert graph.nodes[_calls(graph, method.id)[0]].name in {"first_sink", "second_sink"} +@pytest.mark.mutation_fast def test_rust_2024_exports() -> None: engine = QueryEngine.from_directory(str(FIXTURES / "rust/ffi2024"), language="rust") names = {row["node_id"].split(":")[-1] for row in engine.attack_surface()} assert {"hidden_export", "rust_abi_export", "signature_control"} <= names +@pytest.mark.mutation_fast def test_cairo_module_ownership_and_embedded_abi() -> None: graph = parse_directory(str(FIXTURES / "cairo/core/src"), "cairo") assert _calls(graph, "lib:local.caller") == ["lib:local.helper"] @@ -546,6 +572,7 @@ def test_cairo_module_ownership_and_embedded_abi() -> None: } +@pytest.mark.mutation_fast def test_php_namespace_and_callable_ownership() -> None: graph = parse_file(str(FIXTURES / "php/namespaces.php"), "php", strict=True) for namespace in ("Alpha", "Beta"): @@ -569,6 +596,7 @@ def test_php_namespace_and_callable_ownership() -> None: assert "call_forms:Base.parentAction" in calls +@pytest.mark.mutation_fast def test_perl_package_context_defaults_and_bare_calls() -> None: graph = parse_directory(str(FIXTURES / "perl/fixtures/qualified_body"), "perl") assert _calls(graph, "qualified_body:Beta.main") == ["qualified_body:Alpha.helper"] @@ -591,6 +619,7 @@ def test_powershell_mutators_keep_stale_functions_unresolved(case: str) -> None: ) +@pytest.mark.mutation_fast def test_powershell_callback_signatures_and_header_defaults() -> None: graph = parse_directory(str(FIXTURES / "powershell/parameters"), "powershell") for name, annotation in (("Invoke-Work", "string"), ("Invoke-Header", "int")): @@ -613,6 +642,7 @@ def test_powershell_callback_signatures_and_header_defaults() -> None: assert _calls(graph, callback.id) == ["sample:Get-Default"] +@pytest.mark.mutation_fast def test_vb_field_and_property_shadows() -> None: graph = parse_directory(str(FIXTURES / "vb/field_shadow"), "vb") assert "sample:Sink.Execute" not in _calls(graph, "sample:App.Run") @@ -627,6 +657,7 @@ def test_vb_field_and_property_shadows() -> None: assert dict(graph.nodes[f"sample:App.Value.{accessor}"].attributes)["vb_shared"] is True +@pytest.mark.mutation_fast def test_vb_array_declarators_retain_main_entrypoint() -> None: engine = QueryEngine.from_directory(str(FIXTURES / "vb/array_main"), language="vb") assert engine.entrypoint_paths_to("sample:App.Helper") == [ @@ -636,6 +667,7 @@ def test_vb_array_declarators_retain_main_entrypoint() -> None: assert graph.nodes["sample:App.Main"].parameters[0].type_ref == TypeRef("String()") +@pytest.mark.mutation_fast def test_julia_destructuring_quotes_and_callable_methods(tmp_path: Path) -> None: engine = QueryEngine.from_directory( str(FIXTURES / "julia/cases/destructuring"), language="julia" @@ -665,6 +697,7 @@ def test_julia_destructuring_quotes_and_callable_methods(tmp_path: Path) -> None assert graph.nodes["case:Handler.__call__"].parameters[0] == Parameter("h", TypeRef("Handler")) +@pytest.mark.mutation_fast def test_c_indirect_calls_and_tag_namespaces() -> None: graph = parse_directory(str(FIXTURES / "c/shadowing"), "c") for name in ("dispatch", "explicit_indirect", "local_shadow"): @@ -681,6 +714,7 @@ def test_c_indirect_calls_and_tag_namespaces() -> None: assert target != f"{module}:{name}" +@pytest.mark.mutation_fast def test_solidity_call_options_and_declaration_arguments() -> None: graph = parse_directory(str(FIXTURES / "solidity/call_options"), "solidity") calls = [e for e in graph.edges if e.kind == EdgeKind.CALLS] @@ -699,6 +733,7 @@ def test_solidity_call_options_and_declaration_arguments() -> None: ] +@pytest.mark.mutation_fast def test_cpp_namespace_identity_and_deferred_ownership(tmp_path: Path) -> None: graph = parse_directory(str(FIXTURES / "cpp/namespace_scope"), "cpp") for namespace in ("alpha", "beta"): @@ -728,6 +763,7 @@ def test_cpp_namespace_identity_and_deferred_ownership(tmp_path: Path) -> None: assert "case:Holder.callback" not in _calls(graph, f"case:{name}") +@pytest.mark.mutation_fast def test_csharp_namespaces_shadowing_and_call_forms() -> None: graph = parse_directory(str(FIXTURES / "c_sharp/fixtures"), "c_sharp") for namespace, method in (("First", "FirstOnly"), ("Second", "SecondOnly")): @@ -745,6 +781,7 @@ def test_csharp_namespaces_shadowing_and_call_forms() -> None: assert graph.nodes[_calls(graph, f"{prefix}.Nullable")[0]].kind == NodeKind.PROXY +@pytest.mark.mutation_fast def test_java_deferred_owners_explicit_construction_and_servlets(tmp_path: Path) -> None: graph = parse_directory(str(FIXTURES / "java/ownership"), "java") for name in ("deferred", "local", "anonymous"): @@ -770,6 +807,7 @@ def test_java_deferred_owners_explicit_construction_and_servlets(tmp_path: Path) assert {e["node_id"] for e in engine.attack_surface()} == {"Servlets:Web.doGet"} +@pytest.mark.mutation_fast def test_swift_extensions_scopes_and_deferred_bodies(tmp_path: Path) -> None: graph = parse_directory(str(FIXTURES / "swift/extensions"), "swift") assert graph.nodes["probe:Service"].kind == NodeKind.STRUCT @@ -793,6 +831,7 @@ def test_swift_extensions_scopes_and_deferred_bodies(tmp_path: Path) -> None: ) +@pytest.mark.mutation_fast def test_kotlin_nested_companions_and_local_owners() -> None: graph = parse_directory(str(FIXTURES / "kotlin/fixtures"), "kotlin") _assert_deferred_reachable(graph, "Ownership:caller") @@ -806,6 +845,7 @@ def test_kotlin_nested_companions_and_local_owners() -> None: assert "Ownership:Outer.Companion.main" in {e["node_id"] for e in engine.attack_surface()} +@pytest.mark.mutation_fast def test_objc_selectors_dispatch_identity_and_blocks() -> None: graph = parse_directory(str(FIXTURES / "objc/fixtures/selectors"), "objc") assert _calls(graph, "Selectors:Worker.+touch") == ["Selectors:class_sink"] @@ -833,6 +873,7 @@ def test_objc_selectors_dispatch_identity_and_blocks() -> None: assert _calls(graph, block.id) == ["Blocks:callback_sink"] +@pytest.mark.mutation_fast def test_dart_constructors_arrows_and_lexical_binding() -> None: graph = parse_file(str(FIXTURES / "dart/constructors.dart"), "dart", strict=True) constructors = [n for n in graph.nodes.values() if dict(n.attributes).get("dart_constructor")] @@ -854,6 +895,7 @@ def test_dart_constructors_arrows_and_lexical_binding() -> None: _assert_deferred_reachable(graph, "binding:deferred") +@pytest.mark.mutation_fast def test_circom_include_visibility_discard_and_main_arguments(tmp_path: Path) -> None: graph = parse_directory(str(FIXTURES / "circom/includes"), "circom") assert set(_calls(graph, "circuit:Root")) == {"lib.child:Child", "lib.child:width"} @@ -871,6 +913,7 @@ def test_circom_include_visibility_discard_and_main_arguments(tmp_path: Path) -> assert all(target not in {"a:Child", "b:Child"} for target in _calls(graph, "root:main")) +@pytest.mark.mutation_fast def test_move_qualified_generics_callbacks_and_modules() -> None: graph = parse_directory(str(FIXTURES / "move/bindings"), "move") assert _calls(graph, "caller:0x42::caller:run").count("caller:0x42::caller:transfer") == 1 @@ -898,6 +941,7 @@ def test_move_qualified_generics_callbacks_and_modules() -> None: ) +@pytest.mark.mutation_fast def test_move_entrypoint_modifiers_and_generic_comparison_control(tmp_path: Path) -> None: engine = QueryEngine.from_directory(str(FIXTURES / "move/entrypoints"), language="move") assert {row["node_id"].rsplit(":", 1)[-1] for row in engine.attack_surface()} == { @@ -914,6 +958,7 @@ def test_move_entrypoint_modifiers_and_generic_comparison_control(tmp_path: Path assert _calls(graph, "nested:0x1::test:run") == ["nested:0x1::test:id"] +@pytest.mark.mutation_fast def test_tact_static_member_binding_and_receiver_signatures() -> None: graph = parse_file(str(FIXTURES / "tact/binding/wallet.tact"), "tact") targets = _calls(graph, "wallet:Wallet.receive") @@ -928,6 +973,7 @@ def test_tact_static_member_binding_and_receiver_signatures() -> None: assert graph.nodes["wallet:Wallet.current"].return_type == TypeRef("Int") +@pytest.mark.mutation_fast @pytest.mark.parametrize( "case,package", [("repeated", "repeated"), ("cross_clause", "crossclause")] ) @@ -951,6 +997,7 @@ def test_rego_else_and_head_calls_stay_with_clause() -> None: assert _calls(graph, clause) == ["multibody:helper"] +@pytest.mark.mutation_fast @pytest.mark.parametrize( "language,path", [ @@ -969,6 +1016,7 @@ def test_unsupported_syntax_reports_diagnostics_and_strict_rejects( parse_file(str(FIXTURES / path), language, strict=True) +@pytest.mark.mutation_fast def test_ruby_owners_vcalls_and_entrypoint_visibility() -> None: graph = parse_file(str(FIXTURES / "ruby/fixtures/namespaces.rb"), "ruby") assert { @@ -998,6 +1046,7 @@ def test_ruby_owners_vcalls_and_entrypoint_visibility() -> None: assert not any(target.endswith(":item") for target in _calls(graph, "modern:iterate")) +@pytest.mark.mutation_fast def test_erlang_arity_exports_specs_and_qualified_calls() -> None: graph = parse_file(str(FIXTURES / "erlang/arity/arity_demo.erl"), "erlang") assert _calls(graph, "arity_demo:choose/0") == ["arity_demo:zero_sink/0"] @@ -1019,6 +1068,7 @@ def test_erlang_arity_exports_specs_and_qualified_calls() -> None: assert not engine.paths_between("caller:dynamic/2", "local_target:hit/0") +@pytest.mark.mutation_fast def test_erlang_closure_creation_capture_and_target_evaluation() -> None: graph = parse_file(str(FIXTURES / "erlang/closures/closure_demo.erl"), "erlang") for source in ("capture/0", "remote_capture/0"): @@ -1032,6 +1082,7 @@ def test_erlang_closure_creation_capture_and_target_evaluation() -> None: assert "closure_demo:maker/0" in _calls(graph, "closure_demo:factory_call/0") +@pytest.mark.mutation_fast def test_haskell_lexical_owners_binding_and_call_syntax() -> None: engine = QueryEngine.from_directory(str(FIXTURES / "haskell/fixtures"), language="haskell") graph = parse_directory(str(FIXTURES / "haskell/fixtures"), "haskell") @@ -1053,6 +1104,7 @@ def test_haskell_lexical_owners_binding_and_call_syntax() -> None: assert all(target.startswith("proxy.") for target in _calls(graph, "Syntax:viaDollar")) +@pytest.mark.mutation_fast def test_go_directory_linking_respects_package_even_in_polyglot(tmp_path: Path) -> None: (tmp_path / "app.go").write_text("package app\nfunc Run() { missing() }") (tmp_path / "other_test.go").write_text("package app_test\nfunc missing() {}") @@ -1072,6 +1124,7 @@ def test_skipped_verus_reports_structured_diagnostic(tmp_path: Path) -> None: parse_file(str(path), "rust", strict=True) +@pytest.mark.mutation_fast def test_solidity_inherited_callable_storage_blocks_free_binding(tmp_path: Path) -> None: (tmp_path / "base.sol").write_text( "contract Base { function() internal work; function helper() internal {} }" @@ -1086,6 +1139,7 @@ def test_solidity_inherited_callable_storage_blocks_free_binding(tmp_path: Path) assert any("$binding.work" in target for target in _calls(graph, "child:Child.run")) +@pytest.mark.mutation_fast def test_sql_replacement_signature_excludes_default_and_normalizes_schema(tmp_path: Path) -> None: path = tmp_path / "replace.sql" path.write_text( @@ -1108,6 +1162,7 @@ def test_sql_replacement_signature_excludes_default_and_normalizes_schema(tmp_pa assert routine.parameters[0].type_ref == TypeRef("integer") +@pytest.mark.mutation_fast @pytest.mark.parametrize( "artifact", [ @@ -1136,6 +1191,7 @@ def test_sarif_invalid_bases_and_indices_remain_unmatched(tmp_path: Path, artifa assert not graph.annotations +@pytest.mark.mutation_fast @pytest.mark.parametrize("definition", ["struct same;", "struct same { int value; };"]) def test_c_tag_collision_retains_both_containment_edges(tmp_path: Path, definition: str) -> None: source = tmp_path / "tag.c" @@ -1151,6 +1207,7 @@ def test_c_tag_collision_retains_both_containment_edges(tmp_path: Path, definiti assert {"tag:same", function.id} <= children +@pytest.mark.mutation_fast def test_ruby_named_visibility_is_local_to_its_class(tmp_path: Path) -> None: (tmp_path / "nested.rb").write_text( "class Outer < ApplicationController\n def show; end\n" @@ -1160,6 +1217,7 @@ def test_ruby_named_visibility_is_local_to_its_class(tmp_path: Path) -> None: assert {row["node_id"] for row in engine.attack_surface()} == {"nested:Outer.Inner.show"} +@pytest.mark.mutation_fast def test_static_namespace_linking_keeps_file_local_visibility(tmp_path: Path) -> None: (tmp_path / "owner.cpp").write_text( "namespace Util { static void local() {} static void remote() {} }\n" @@ -1171,6 +1229,7 @@ def test_static_namespace_linking_keeps_file_local_visibility(tmp_path: Path) -> assert "owner:Util.remote" not in _calls(graph, "other:other") +@pytest.mark.mutation_fast def test_cross_file_linking_go_same_package_and_python_import(tmp_path: Path) -> None: (tmp_path / "app.go").write_text("package app\nfunc Run() { helper() }") (tmp_path / "helper.go").write_text("package app\nfunc helper() {}") @@ -1184,6 +1243,7 @@ def test_cross_file_linking_go_same_package_and_python_import(tmp_path: Path) -> assert _calls(graph, "app:run") == ["pkg.helper:helper"] +@pytest.mark.mutation_fast @pytest.mark.parametrize("kind,blocked", [(EdgeKind.CALLS, True), (EdgeKind.READS, False)]) def test_rust_alias_resolution_preserves_blocked_and_noncall_edges( tmp_path: Path, kind: EdgeKind, blocked: bool diff --git a/tests/test_augment.py b/tests/test_augment.py index 089e3fab..f671cc46 100644 --- a/tests/test_augment.py +++ b/tests/test_augment.py @@ -77,13 +77,16 @@ def _write_json(tmp_path: Any, name: str, data: dict[str, Any]) -> str: class TestNormalizePath: + @pytest.mark.mutation_fast def test_relative_path(self) -> None: assert _normalize_path("src/handler.py", _ROOT) == "src/handler.py" + @pytest.mark.mutation_fast def test_absolute_path(self) -> None: result = _normalize_path("/project/src/handler.py", _ROOT) assert result == "src/handler.py" + @pytest.mark.mutation_fast def test_file_uri(self) -> None: result = _normalize_path( "file:///project/src/handler.py", @@ -105,6 +108,7 @@ def test_absolute_path_outside_root(self) -> None: class TestFindOverlappingNodes: + @pytest.mark.mutation_fast def test_exact_match(self) -> None: graph = _build_graph() nodes = _find_overlapping_nodes(graph, "src/handler.py", 10, 30) @@ -116,6 +120,7 @@ def test_partial_overlap(self) -> None: assert "mod:func_a" in nodes assert "mod:func_b" in nodes + @pytest.mark.mutation_fast def test_no_overlap(self) -> None: graph = _build_graph() nodes = _find_overlapping_nodes(graph, "src/handler.py", 51, 60) @@ -123,6 +128,7 @@ def test_no_overlap(self) -> None: ids = [n for n in nodes if "func" in n] assert ids == [] + @pytest.mark.mutation_fast def test_wrong_file(self) -> None: graph = _build_graph() nodes = _find_overlapping_nodes(graph, "src/other.py", 10, 30) @@ -186,6 +192,7 @@ def _sarif_result( class TestAugmentFromSarif: + @pytest.mark.mutation_fast def test_matches_finding_to_node(self, tmp_path: Any) -> None: graph = _build_graph() store = GraphStore(graph) @@ -205,6 +212,7 @@ def test_matches_finding_to_node(self, tmp_path: Any) -> None: assert result["matched_findings"] == 1 assert result["unmatched_findings"] == 0 + @pytest.mark.mutation_fast def test_annotation_format(self, tmp_path: Any) -> None: graph = _build_graph() store = GraphStore(graph) @@ -361,6 +369,7 @@ def _weaudit_entry( class TestAugmentFromWeaudit: + @pytest.mark.mutation_fast def test_matches_finding_with_line_conversion( self, tmp_path: Any, @@ -379,6 +388,7 @@ def test_matches_finding_with_line_conversion( result = augment_from_weaudit(store, path) assert result["matched_findings"] == 1 + @pytest.mark.mutation_fast def test_finding_annotation_kind(self, tmp_path: Any) -> None: graph = _build_graph() store = GraphStore(graph) @@ -393,6 +403,7 @@ def test_finding_annotation_kind(self, tmp_path: Any) -> None: anns = graph.annotations.get("mod:func_a", []) assert any(a.kind == AnnotationKind.FINDING for a in anns) + @pytest.mark.mutation_fast def test_note_annotation_kind(self, tmp_path: Any) -> None: graph = _build_graph() store = GraphStore(graph) @@ -427,6 +438,7 @@ def test_source_includes_author(self, tmp_path: Any) -> None: anns = graph.annotations.get("mod:func_a", []) assert any(a.source == "weaudit:alice" for a in anns) + @pytest.mark.mutation_fast def test_severity_subgraphs(self, tmp_path: Any) -> None: graph = _build_graph() store = GraphStore(graph) @@ -455,6 +467,7 @@ def test_severity_subgraphs(self, tmp_path: Any) -> None: assert "weaudit:low" in result["subgraphs_created"] assert "weaudit:findings" in result["subgraphs_created"] + @pytest.mark.mutation_fast def test_description_format(self, tmp_path: Any) -> None: graph = _build_graph() store = GraphStore(graph) @@ -489,6 +502,7 @@ def test_resolved_entries_included(self, tmp_path: Any) -> None: class TestClearAugmented: + @pytest.mark.mutation_fast def test_clear_sarif(self, tmp_path: Any) -> None: graph = _build_graph() store = GraphStore(graph) @@ -524,6 +538,7 @@ def test_clear_removes_subgraphs(self, tmp_path: Any) -> None: clear_augmented(store, "sarif") assert not any(k.startswith("sarif:") for k in graph.subgraphs) + @pytest.mark.mutation_fast def test_reaugment_idempotent(self, tmp_path: Any) -> None: graph = _build_graph() store = GraphStore(graph) @@ -546,6 +561,7 @@ def test_reaugment_idempotent(self, tmp_path: Any) -> None: # ── QueryEngine integration ────────────────────────────────────────── +@pytest.mark.mutation_fast @pytest.mark.parametrize("source", ["sarif", "weaudit"]) @pytest.mark.parametrize("replace_existing", [None, False, True]) def test_multiple_finding_imports_apply_replacement_policy( @@ -574,6 +590,7 @@ def test_multiple_finding_imports_apply_replacement_policy( assert set(graph["subgraphs"][severity_subgraph]) == expected +@pytest.mark.mutation_fast @pytest.mark.parametrize("source", ["sarif", "weaudit"]) @pytest.mark.parametrize("replace_existing", [False, True]) @pytest.mark.parametrize("failure", ["missing", "malformed_json", "invalid_record"]) @@ -614,6 +631,7 @@ def test_failed_finding_import_preserves_existing_graph( assert engine.findings() == findings_before +@pytest.mark.mutation_fast @pytest.mark.parametrize("source", ["sarif", "weaudit"]) @pytest.mark.parametrize("root_kind", ["dot", "relative", "absolute"]) @pytest.mark.parametrize("language", ["python", "auto"]) @@ -741,6 +759,7 @@ def test_findings_method(self, tmp_path: Any) -> None: assert "findings" in findings[0] assert findings[0]["findings"][0]["kind"] == "finding" + @pytest.mark.mutation_fast def test_findings_filter_by_kind(self, tmp_path: Any) -> None: graph = _build_graph() engine = QueryEngine.from_graph(graph) diff --git a/tests/test_bash_nested_bindings.py b/tests/test_bash_nested_bindings.py index 5b03d904..2e484a7b 100644 --- a/tests/test_bash_nested_bindings.py +++ b/tests/test_bash_nested_bindings.py @@ -24,6 +24,7 @@ def _helpers(tmp_path: Path, source: str) -> tuple[CodeGraph, list[CodeEdge]]: return graph, calls +@pytest.mark.mutation_fast def test_nested_helper_definition_dominates_its_call(tmp_path: Path) -> None: graph, calls = _helpers(tmp_path, "outer() {\n helper() { :; }\n helper\n}\n") call = next(edge for edge in calls if edge.source_id == "nested:outer") @@ -32,6 +33,7 @@ def test_nested_helper_definition_dominates_its_call(tmp_path: Path) -> None: assert call.confidence == EdgeConfidence.INFERRED +@pytest.mark.mutation_fast @pytest.mark.parametrize("alias", ["alias helper=other", "alias ${CMD:-x}=other"]) def test_later_alias_cannot_rewrite_an_already_parsed_function_body( tmp_path: Path, alias: str @@ -41,6 +43,7 @@ def test_later_alias_cannot_rewrite_an_already_parsed_function_body( assert call.target_id == "nested:outer.helper" +@pytest.mark.mutation_fast @pytest.mark.parametrize( "body", [ diff --git a/tests/test_bash_parser.py b/tests/test_bash_parser.py index b8a57cf9..5f4485cd 100644 --- a/tests/test_bash_parser.py +++ b/tests/test_bash_parser.py @@ -19,6 +19,7 @@ def _file(tmp_path: Path, source: str) -> Path: return path +@pytest.mark.mutation_fast def test_script_functions_substitutions_and_ownership(tmp_path: Path) -> None: path = _file( tmp_path, @@ -36,6 +37,7 @@ def test_script_functions_substitutions_and_ownership(tmp_path: Path) -> None: assert any(e.source_id == "sample: