From 78f7f329452bfef9054179fb98a36afc69760fac Mon Sep 17 00:00:00 2001 From: Martin Thoma Date: Sun, 29 Nov 2026 13:41:39 +0100 Subject: [PATCH] Speed up trampolines by reading os.environ once per call In the stats run, every call of a mutated function went through three os.environ lookups: get_mutant_under_test() checked "MUTANT_UNDER_TEST" in os.environ and then read it, and the stats branch read and parsed MUTMUT_DEPENDENCY_DEPTH. It also rebuilt the qualified name of the function with an f-string and mangled_name_from_mutant_name(). An os.environ lookup encodes the key and decodes the value, so for a function in an inner loop this costs more than the function itself. On main (1cce413), now that #651 gets pypdf past the import, the stats run on pypdf fails because of it: test_lzw_decoder_large_stream_performance makes 2.0 M trampolined calls and has a 15 s pytest-timeout. Profiled, 6.0 M os.environ lookups were the largest single cost of the stats run. The test passes in 1.5 s without mutmut and took 18.9 s in the stats run, so the timeout ended the run. Changes: - get_mutant_under_test() reads MUTANT_UNDER_TEST once. The environment still wins over the process-local value, as before. - run_stats_collection() sets the dependency tracking depth with the new set_dependency_tracking_depth(), which keeps it in process-local state and still mirrors it into MUTMUT_DEPENDENCY_DEPTH. The trampoline reads the environment only when the depth was not set in the process. - Each trampoline builds the qualified name of its function on its first call in the stats run and keeps it. Co-Authored-By: Claude Opus 5.5 --- src/mutmut/__main__.py | 4 +- src/mutmut/mutation/trampoline.py | 40 ++++++++++++- tests/mutation/test_trampoline.py | 95 +++++++++++++++++++++++++++++++ 3 files changed, 134 insertions(+), 5 deletions(-) diff --git a/src/mutmut/__main__.py b/src/mutmut/__main__.py index db4bbf75..f016ba34 100644 --- a/src/mutmut/__main__.py +++ b/src/mutmut/__main__.py @@ -52,6 +52,7 @@ from mutmut.mutation.file_mutation import MutatedFile from mutmut.mutation.file_mutation import filter_mutants_with_type_checker from mutmut.mutation.file_mutation import mutate_file_contents +from mutmut.mutation.trampoline import set_dependency_tracking_depth from mutmut.mutation.trampoline import set_mutant_under_test from mutmut.runners.harness import CollectTestsFailedException from mutmut.runners.harness import PytestRunner @@ -402,8 +403,7 @@ def run_stats_collection(runner: MutantRunner, tests: Iterable[str] | None = Non set_mutant_under_test("stats") os.environ["PY_IGNORE_IMPORTMISMATCH"] = "1" - depth = config().dependency_tracking_depth - os.environ["MUTMUT_DEPENDENCY_DEPTH"] = str(depth) + set_dependency_tracking_depth(config().dependency_tracking_depth) start_cpu_time = process_time() with CatchOutput(spinner_title="Running stats") as output_catcher: diff --git a/src/mutmut/mutation/trampoline.py b/src/mutmut/mutation/trampoline.py index dac20317..926cbd47 100644 --- a/src/mutmut/mutation/trampoline.py +++ b/src/mutmut/mutation/trampoline.py @@ -51,13 +51,40 @@ def get_mutant_under_test() -> str: If the key is missing (for example after ``patch.dict(..., clear=True)``), fall back to the process-local copy set by ``set_mutant_under_test``. """ - if "MUTANT_UNDER_TEST" in os.environ: + # The trampoline calls this on every call of a mutated function, so read os.environ once. + try: return os.environ["MUTANT_UNDER_TEST"] + except KeyError: + pass if _mutant_under_test is not None: return _mutant_under_test return "" +# Process-local copy of the dependency tracking depth of the stats run, so the trampoline +# does not read and parse ``MUTMUT_DEPENDENCY_DEPTH`` on every call. +_dependency_tracking_depth: int | None = None + + +def set_dependency_tracking_depth(depth: int | None) -> None: + """Record the dependency tracking depth of the stats run in process-local state. + + ``None`` clears it so the trampoline falls back to ``os.environ``. An int value is + also mirrored into ``MUTMUT_DEPENDENCY_DEPTH`` for processes that do not inherit it. + """ + global _dependency_tracking_depth + _dependency_tracking_depth = depth + if depth is not None: + os.environ["MUTMUT_DEPENDENCY_DEPTH"] = str(depth) + + +def get_dependency_tracking_depth() -> int: + """Return the dependency tracking depth of the stats run, -1 for no limit.""" + if _dependency_tracking_depth is not None: + return _dependency_tracking_depth + return int(os.environ.get("MUTMUT_DEPENDENCY_DEPTH", "-1")) + + def get_class_attribute(owner: Any, name: str) -> Any: """Return ``owner.name`` without calling a ``__getattribute__`` of the metaclass. @@ -82,7 +109,12 @@ def mutmut_mutated(decorated_func: Callable[P, R]) -> Callable[P, R]: or to the currently active mutated method. """ + # The qualified name of the original function, built on the first call in the stats run. + # It cannot be built here: the mutants dict is filled after the function is defined. + orig_qual_name: str | None = None + def trampoline(*args: P.args, **kwargs: P.kwargs) -> R: + nonlocal orig_qual_name # orig_func is the non-mutated implementation. # we do not use `decorated_func` directly, # because using the func via SomeClass.foo makes it easier for classmethod wrapping @@ -104,9 +136,11 @@ def trampoline(*args: P.args, **kwargs: P.kwargs) -> R: ) if mutant_under_test == "stats": - orig_qual_name = f"{orig_func.__module__}.{mangled_name_from_mutant_name(orig_func.__name__)}" + if orig_qual_name is None: + orig = mutants_dict["_mutmut_orig"] + orig_qual_name = f"{orig.__module__}.{mangled_name_from_mutant_name(orig.__name__)}" caller_name, depth = MutmutCallStack.get() - max_depth = int(os.environ.get("MUTMUT_DEPENDENCY_DEPTH", "-1")) + max_depth = get_dependency_tracking_depth() if max_depth == -1 or depth < max_depth: record_trampoline_hit(orig_qual_name, caller=caller_name) token = MutmutCallStack.set((orig_qual_name, depth + 1)) diff --git a/tests/mutation/test_trampoline.py b/tests/mutation/test_trampoline.py index 06b1f429..e06b371a 100644 --- a/tests/mutation/test_trampoline.py +++ b/tests/mutation/test_trampoline.py @@ -6,12 +6,15 @@ import asyncio import inspect import os +from unittest.mock import Mock from unittest.mock import patch import pytest from typing_extensions import Self +import mutmut.mutation.trampoline from mutmut.mutation.trampoline import get_mutant_under_test +from mutmut.mutation.trampoline import set_dependency_tracking_depth from mutmut.mutation.trampoline import set_mutant_under_test from mutmut.mutation.trampoline import wrap_in_trampoline @@ -457,3 +460,95 @@ def test_trampoline_classmethod_baseclass_original(self, monkeypatch): assert type(SomeNumberChild.add_zero(123)) is SomeNumberChild, "Should use the subclass" # assert type(SomeNumberChild(1).add_zero(123)) is SomeNumberChild, 'Should use the subclass' # assert SomeNumberChild.add_zero(123).number == 123, 'Should use the subclass' + + +mutants_return_value = {} +mutants_call_return_value = {} + + +@wrap_in_trampoline(mutants_return_value) +def return_value(a: int) -> int: + return a + + +def x_return_value__mutmut_orig(a: int) -> int: + return a + + +@wrap_in_trampoline(mutants_call_return_value) +def call_return_value(a: int) -> int: + return return_value(a) + + +def x_call_return_value__mutmut_orig(a: int) -> int: + return return_value(a) + + +mutants_return_value["_mutmut_orig"] = x_return_value__mutmut_orig +mutants_call_return_value["_mutmut_orig"] = x_call_return_value__mutmut_orig + + +class TestStatsRun: + @pytest.fixture + def recorded_hits(self, monkeypatch): + """Run the trampolines in stats mode and collect the hits they record.""" + hits = [] + monkeypatch.setattr( + mutmut.mutation.trampoline, + "record_trampoline_hit", + lambda name, caller=None: hits.append(name), + ) + monkeypatch.setenv("MUTANT_UNDER_TEST", "stats") + # set_dependency_tracking_depth() writes os.environ, which monkeypatch restores afterwards + monkeypatch.setenv("MUTMUT_DEPENDENCY_DEPTH", "-1") + yield hits + set_dependency_tracking_depth(None) + + def test_dependency_tracking_depth_set_in_process_limits_hits(self, recorded_hits): + """ + The stats run records only calls up to the dependency tracking depth given to set_dependency_tracking_depth(). + + A call at depth 1 (return_value called by call_return_value) is not recorded with depth 1. + """ + set_dependency_tracking_depth(1) + assert call_return_value(2) == 2 + assert recorded_hits == [f"{__name__}.x_call_return_value"] + + recorded_hits.clear() + set_dependency_tracking_depth(-1) + assert call_return_value(2) == 2 + assert recorded_hits == [f"{__name__}.x_call_return_value", f"{__name__}.x_return_value"] + + def test_dependency_tracking_depth_falls_back_to_env(self, recorded_hits, monkeypatch): + """ + The stats run reads the dependency tracking depth from MUTMUT_DEPENDENCY_DEPTH when it was not set in process. + """ + set_dependency_tracking_depth(None) + monkeypatch.setenv("MUTMUT_DEPENDENCY_DEPTH", "1") + assert call_return_value(2) == 2 + assert recorded_hits == [f"{__name__}.x_call_return_value"] + + def test_qualified_name_is_built_once_per_trampoline(self, recorded_hits, monkeypatch): + """ + The stats run builds the qualified name of a trampolined function on its first call only. + + A function in an inner loop runs millions of times in one test. + """ + mutants = {} + + @wrap_in_trampoline(mutants) + def return_value_once(a: int) -> int: + return a + + def x_return_value_once__mutmut_orig(a: int) -> int: + return a + + mutants["_mutmut_orig"] = x_return_value_once__mutmut_orig + mangle = Mock(wraps=mutmut.mutation.trampoline.mangled_name_from_mutant_name) + monkeypatch.setattr(mutmut.mutation.trampoline, "mangled_name_from_mutant_name", mangle) + + for _ in range(3): + assert return_value_once(2) == 2 + + assert recorded_hits == [f"{__name__}.x_return_value_once"] * 3 + assert mangle.call_count == 1