"""Run pinned pure-backend mutation gates in a temporary copy of the checkout.""" from __future__ import annotations import argparse import ast import hashlib from importlib.metadata import version import json import os from pathlib import Path import re import shutil import subprocess import sys import tempfile ROOT = Path(__file__).resolve().parents[1] # The reviewed source inventory selects real implementations, never compatibility imports. MODULE_PATHS = { "search_words": "search/corpus/domain/words", "search_matching": "search/domain/matching", "data_formats": "search/corpus/domain/formats", "search_indexes": "search/corpus/infrastructure/indexes", "reader_identity": "reader/query/domain/identity", "cache_core": "shared/cache/core", "reader_index": "reader/catalog/domain/index", "reader_assets": "reader/catalog/domain/assets", "upstream_http": "shared/transport/upstream", "search_execution": "search/infrastructure/executor", "record_metadata": "search/corpus/domain/records", "search_filters": "search/domain/filters", "proxy_streams": "shared/transport/streams", "folder_tree": "search/corpus/domain/folder_tree", "search_projection": "search/domain/projection", "search_candidates": "search/domain/candidates", "search_bootstrap": "search/application/bootstrap", "search_browse": "search/domain/browse", "reader_archive": "reader/archive/domain/validation", } TOOL_VERSION = "3.8.1" SELECTED_TESTS = [ "test_ascii_cjk_and_punctuation_tokens_with_injected_segmenter", "test_all_cjk_inclusive_boundaries_are_independent_tokens", "test_file_match_missing_fields_and_fuzzy_source_contract", "test_file_field_is_checked_independently_of_repository", "test_vocabulary_order_is_stable_for_rebuilt_postings", "test_complete_file_token_uses_extension", "test_missing_file_and_folder_defaults_are_empty", "test_records_digest_uses_order_and_field_delimiters", ] MATCHING_TESTS = [ "test_matching_helpers_keep_wildcard_results_after_large_character_cache", "test_fuzzy_precheck_and_distance_are_bounded", "test_exact_and_wildcard_matchers_keep_unicode_and_newline_semantics", "test_star_only_matcher_accepts_empty_substring_without_scans", "test_mixed_wildcard_runs_match_python_dot_with_bounded_line_scans", "test_boundary_stars_preserve_case_newlines_and_literal_metacharacters", "test_boundary_stars_use_one_literal_scan_and_question_patterns_keep_nfa", "test_boundary_question_star_runs_match_regex_and_are_bounded", "test_boundary_question_star_long_fields_prefilter_mandatory_literals", "test_ordered_star_chunks_keep_line_and_unicode_semantics", "test_interior_stars_use_ordered_chunks_and_questions_keep_nfa", "test_question_only_fast_path_preserves_fixed_width_unicode_and_newlines", "test_question_long_fields_prefilter_mandatory_literals_without_changing_results", "test_wildcards_agree_with_independent_regular_expression_reference", "test_fuzzy_helpers_match_independent_distance_and_multiset_references", "test_wildcard_cache_keeps_repeated_characters_and_clears_at_limit", "test_wildcard_cache_reuses_literal_scans_across_matches", "test_fuzzy_match_stops_at_the_two_edit_work_bound", ] EXECUTION_TESTS = [ "test_report_close_failure_context_and_deduplication", "test_started_cancel_retains_real_worker_and_capacity_until_exit", "test_close_drains_queued_work_before_joining_worker", "test_check_is_safe_outside_an_executor_thread", "test_queued_cancellation_immediately_releases_capacity", "test_cancelled_search_can_release_the_worker_cooperatively", "test_background_executor_drains_before_context_exit", "test_completed_job_registers_a_callable_cleanup", "test_cancelling_background_wait_keeps_foreground_ownership", "test_background_jobs_wait_for_admitted_foreground_jobs", "test_active_cancellation_retains_slot_and_queued_cancellation_drops_work", "test_capacity_failure_and_recovery", "test_single_named_search_thread_and_real_millisecond_timings", "test_repeated_foreground_completion_does_not_leave_stale_owners", "test_close_waits_for_started_work_after_requester_cancels", "test_abandoned_failures_are_consumed_and_executor_recovers", "test_close_drains_failed_owned_job_before_shutting_down", "test_shutdown_joins_worker_and_constructor_sets_boolean_state", "test_close_rejects_missing_state_for_existing_close_task", "test_close_after_default_executor_shutdown", "test_close_does_not_wait_for_busy_default_executor", "test_shutdown_error_propagates_to_all_close_callers", "test_abandoned_close_failure_is_reported_once_and_retryable", "test_close_retries_after_shutdown_thread_start_failure", "test_shutdown_notification_ignores_cancelled_future", "test_shutdown_notification_tolerates_closed_loop", "test_shutdown_failure_logged_when_delivery_is_unavailable", "test_shutdown_join_does_not_block_event_loop", "test_cancelled_and_concurrent_close_keep_ownership_without_blocking_loop", ] SPECS: dict[str, tuple[str, list[str], list[str]]] = { "search_words": ("search/backend/test_search_words_contract.py", SELECTED_TESTS, []), "search_matching": ("search/backend/test_search_words_contract.py", MATCHING_TESTS, ["search_words.py"]), "data_formats": ("data/test_data_formats_contract.py", [], []), "search_indexes": ("search/backend/test_native_search_indexes.py", [], []), "reader_identity": ("reader/backend/test_reader_identity_contract.py", [], []), "cache_core": ("search/backend/test_cache_core_contract.py", [], []), "reader_index": ("reader/backend/test_reader_index_contract.py", [], []), "upstream_http": ("proxy/test_upstream_http.py", [], []), "search_execution": ("search/backend/test_search_execution.py", EXECUTION_TESTS, []), # records imports assets, which re-exports the upstream path pattern. "record_metadata": ("search/backend/test_record_metadata_contract.py", [], ["reader_assets.py", "upstream_http.py"]), "search_filters": ("search/backend/test_search_filters_mutation_contract.py", [], []), "proxy_streams": ("proxy/test_proxy_streams_contract.py", [], []), "folder_tree": ("search/backend/test_folder_tree_mutation_contract.py", [], []), "search_projection": ("search/backend/test_search_projection_mutation_contract.py", [], []), "search_candidates": ("search/backend/test_search_candidates_mutation_contract.py", [], ["search_indexes.py"]), "search_bootstrap": ("search/backend/test_search_bootstrap_mutation_contract.py", [], []), "search_browse": ("tests/search/backend/test_search_browse_mutation_contract.py".removeprefix("tests/"), [], []), "reader_archive": ("reader/backend/test_reader_archive_mutation_contract.py", [], []), } EMPTY_STATUSES = ("no_tests", "skipped", "suspicious", "timeout", "check_was_interrupted_by_user", "segfault") def generated_mutations(module: str, generated: str) -> dict[str, ast.FunctionDef | ast.AsyncFunctionDef]: """Inventory generated functions, including async methods inside classes.""" result: dict[str, ast.FunctionDef | ast.AsyncFunctionDef] = {} for node in ast.walk(ast.parse(generated)): if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and re.search(r"__mutmut_\d+$", node.name): key = f"backend.{module}.{node.name}" if key in result: raise ValueError(f"duplicate generated mutation: {key}") result[key] = node return result def mutation_errors(stats: dict[str, int], outcomes: dict[str, int], current_hashes: dict[str, str], reviewed: dict[str, dict[str, str]]) -> list[str]: errors: list[str] = [] required = ("total", "killed", "survived", *EMPTY_STATUSES) if any(type(stats.get(key)) is not int or stats[key] < 0 for key in required): return ["mutation statistics are missing or invalid"] if (stats.get("total", 0) <= 0 or stats.get("total") != len(outcomes) or stats.get("killed") != sum(code == 1 for code in outcomes.values()) or stats.get("survived") != sum(code == 0 for code in outcomes.values())): errors.append("mutation results are incomplete or contain unexpected outcomes") for status in EMPTY_STATUSES: if stats.get(status, 0): errors.append(f"mutation results contain {status}: {stats[status]}") survived = {key for key, code in outcomes.items() if code == 0} if any(type(code) is not int or code not in (0, 1) for code in outcomes.values()): errors.append("mutation outcomes contain errors or timeouts") for key in sorted(survived): entry = reviewed.get(key) if (not entry or not current_hashes.get(key) or entry.get("sha256") != current_hashes.get(key) or not entry.get("rationale")): errors.append(f"unreviewed surviving mutation: {key}") for key in sorted(set(reviewed) - survived): errors.append(f"stale equivalent-mutation review: {key}") return errors def mutation_diagnostics(outcomes: dict[str, int], durations: dict[str, float], estimates: dict[str, float]) -> dict[str, object]: """Keep names and timings when a gate fails; never reinterpret a result.""" failed = [ {"mutant": name, "exit_code": code, "seconds": durations.get(name), "estimated_seconds": estimates.get(name)} for name, code in sorted(outcomes.items()) if type(code) is not int or code not in (0, 1) ] measured = [(name, value) for name, value in durations.items() if isinstance(value, (int, float)) and value >= 0] slowest = [ {"mutant": name, "exit_code": outcomes.get(name), "seconds": value, "estimated_seconds": estimates.get(name)} for name, value in sorted(measured, key=lambda item: (-item[1], item[0]))[:10] ] return {"abnormal_outcomes": failed, "slowest": slowest} def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--module", choices=tuple(SPECS), default="search_words") module = parser.parse_args().module test_name, selected, dependencies = SPECS[module] module_path = MODULE_PATHS[module] source = ROOT / "backend" / f"{module_path}.py" test = ROOT / "tests" / test_name equivalent = ROOT / "quality/mutation-reviews" / f"mutation-equivalent-{module.replace('_', '-')}.json" review = json.loads(equivalent.read_text()) source_bytes = source.read_bytes() source_hash = hashlib.sha256(source_bytes).hexdigest() if (not isinstance(review, dict) or not isinstance(review.get("equivalent"), dict) or not isinstance(review.get("source_sha256"), str) or not re.fullmatch(r"[0-9a-f]{64}", review["source_sha256"])): print("Invalid mutation review metadata", file=sys.stderr) return 1 exemptions = review["equivalent"] # A source hash binds a permission to accept specific survivors. An empty # review grants no such permission; test the current bytes with zero survivors. if (version("mutmut") != TOOL_VERSION or review.get("tool") != f"mutmut {TOOL_VERSION}" or review.get("source") != f"backend/{module_path}.py" or (exemptions and review["source_sha256"] != source_hash)): print("Mutation equivalent review must match the exact source and tool version", file=sys.stderr) return 1 with tempfile.TemporaryDirectory(prefix=f"reader-{module}-mutation-") as directory: temp = Path(directory) (temp / "backend").mkdir() (temp / "tests").mkdir() def copy_module(name: str) -> None: relative = Path('backend') / (MODULE_PATHS[name] + '.py') destination = temp / relative destination.parent.mkdir(parents=True, exist_ok=True) if name == module: # Run exactly the bytes whose digest was checked and reported. destination.write_bytes(source_bytes) else: shutil.copyfile(ROOT / relative, destination) for parent in relative.parents: if parent == Path('.'): break shutil.copyfile(ROOT / parent / '__init__.py', temp / parent / '__init__.py') compatibility = Path('backend') / (name + '.py') if (ROOT / compatibility).is_file(): shutil.copyfile(ROOT / compatibility, temp / compatibility) copy_module(module) for dependency in dependencies: copy_module(Path(dependency).stem) target_test = temp / "tests" / test_name target_test.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(test, target_test) if module == "reader_identity": (temp / "tests/support").mkdir(parents=True, exist_ok=True) shutil.copyfile(ROOT / "tests/support/reader-contract-vectors.json", temp / "tests/support/reader-contract-vectors.json") if module == "record_metadata": fixture = Path("static/reader/core/reader-contract.js") (temp / fixture).parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(ROOT / fixture, temp / fixture) (temp / "tests/__init__.py").write_text("") test_class = "SearchExecutionTests" if module == "search_execution" else "SearchWordsContractTests" selections = ([f"tests/{test_name}::{test_class}::{name}" for name in selected] if selected else [f"tests/{test_name}::PythonSearchIndexTests" if module == "search_indexes" else f"tests/{test_name}"]) (temp / "pyproject.toml").write_text( '[tool.mutmut]\nsource_paths = ["backend/"]\n' + f'only_mutate = ["backend/{module_path}.py"]\n' + ('also_copy = ["static/"]\n' if module == "record_metadata" else '') + 'pytest_add_cli_args_test_selection = ' + json.dumps(selections) + '\n' + 'use_git_change_detection = false\nuse_setproctitle = false\n') env = os.environ.copy() env["PYTEST_DISABLE_PLUGIN_AUTOLOAD"] = "1" for args in (["run", "--max-children", "2"], ["export-cicd-stats"]): command = [sys.executable, "-B", "-m", "mutmut", *args] subprocess.run(command, cwd=temp, env=env, check=True, timeout=600) # noqa: S603 stats = json.loads((temp / "mutants/mutmut-cicd-stats.json").read_text()) meta = json.loads((temp / "mutants/backend" / f"{module_path}.py.meta").read_text()) generated = (temp / "mutants/backend" / f"{module_path}.py").read_text() functions = generated_mutations(module_path.replace("/", "."), generated) generated_keys = set(functions) hashes = {} for key, code in meta["exit_code_by_key"].items(): if code == 0 and key in functions: segment = ast.get_source_segment(generated, functions[key]) if segment is None: raise RuntimeError(f"missing generated source for {key}") hashes[key] = hashlib.sha256(segment.encode()).hexdigest() errors = mutation_errors(stats, meta["exit_code_by_key"], hashes, exemptions) if generated_keys != set(meta["exit_code_by_key"]): errors.append("generated mutant inventory does not match recorded outcomes") print(json.dumps({"tool": review["tool"], "source": review["source"], "source_sha256": source_hash, "test": test_name, "test_sha256": hashlib.sha256(test.read_bytes()).hexdigest(), **stats, "reviewed_equivalent_survivors": len(set(exemptions) & set(hashes))}, sort_keys=True)) if errors: print("Mutation failure diagnostics: " + json.dumps(mutation_diagnostics( meta["exit_code_by_key"], meta.get("durations_by_key", {}), meta.get("estimated_durations_by_key", {})), sort_keys=True), file=sys.stderr) print("\n".join(errors), file=sys.stderr) return 1 return 0 if __name__ == "__main__": raise SystemExit(main())