From 65df36c4c3b26b664d9bd2004b657ad214d19b59 Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Thu, 20 Aug 2026 11:28:27 -0700 Subject: [PATCH 1/6] feat(ci): scope mutation testing to the pull request diff The existing mutation workflow is manual and mutates a whole folder, which takes hours, so nothing about a pull request's own test quality gets checked before it merges. This adds the diff-scoped half, following Google's approach in "State of Mutation Testing at Google": mutate what the change touched, not the codebase. scripts/mutation_diff_scope.py reads the diff against the merge base, rewrites [tool.mutmut] so paths_to_mutate is the changed production files and tests_dir is the tests mirroring them, then emits mutant-name globs for the functions holding the changed lines. mutmut trampolines per function and per method, so that is the smallest unit it can be asked to run. The new workflow is advisory: results land in the job summary and an artifact, and nothing blocks a merge. A --max-functions cap bounds the worst case and prints what it dropped rather than truncating quietly. The report script now counts only the mutants a run actually executed, since a diff-scoped run leaves everything else at "not checked" and the old summary folded those into the score. --- .github/workflows/mutation-test-pr.yml | 158 +++++++++ .gitignore | 9 + scripts/mutation_diff_scope.py | 303 ++++++++++++++++++ scripts/mutation_report.py | 65 +++- .../test_litellm/test_mutation_diff_scope.py | 242 ++++++++++++++ 5 files changed, 762 insertions(+), 15 deletions(-) create mode 100644 .github/workflows/mutation-test-pr.yml create mode 100644 scripts/mutation_diff_scope.py create mode 100644 tests/test_litellm/test_mutation_diff_scope.py diff --git a/.github/workflows/mutation-test-pr.yml b/.github/workflows/mutation-test-pr.yml new file mode 100644 index 000000000000..b7ae605ccd66 --- /dev/null +++ b/.github/workflows/mutation-test-pr.yml @@ -0,0 +1,158 @@ +name: "Mutation Test (PR diff)" + +# Diff-scoped mutation testing, modeled on Google's "State of Mutation Testing +# at Google" (https://research.google/pubs/state-of-mutation-testing-at-google/): +# mutate only what the pull request changed, not the whole codebase. +# +# scripts/mutation_diff_scope.py rewrites [tool.mutmut] so paths_to_mutate is +# the changed production files and tests_dir is the tests mirroring them, then +# emits mutant-name globs for the functions containing the changed lines. +# +# Advisory only: the result is written to the job summary and uploaded as an +# artifact. Nothing here blocks a merge. + +on: + pull_request: + paths: + - "litellm/**.py" + - "scripts/mutation_diff_scope.py" + - ".github/workflows/mutation-test-pr.yml" + +permissions: + contents: read + +concurrency: + group: mutation-test-pr-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + mutation: + name: Mutate the diff + runs-on: ubuntu-latest + timeout-minutes: 20 + + steps: + - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 + with: + persist-credentials: false + # The scope script diffs HEAD against the merge base with the target + # branch, so the full history has to be present. + fetch-depth: 0 + + - name: Set up Python + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: "3.12" + + - name: Scope the run to the diff + id: scope + run: | + python scripts/mutation_diff_scope.py \ + --base "origin/${{ github.event.pull_request.base.ref }}" \ + --write-pyproject | tee mutmut-scope.log + + - name: Set up uv + if: steps.scope.outputs.has_scope == 'true' + uses: ./.github/actions/setup-uv-with-retries + with: + version: "0.10.9" + + - name: Cache uv dependencies + if: steps.scope.outputs.has_scope == 'true' + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: | + ~/.cache/uv + .venv + key: ${{ runner.os }}-uv-${{ hashFiles('uv.lock') }} + restore-keys: | + ${{ runner.os }}-uv- + + - name: Install dependencies + if: steps.scope.outputs.has_scope == 'true' + run: | + .github/scripts/uv_sync_with_retries.sh --frozen --group ci --group proxy-dev --extra google --extra proxy --extra semantic-router --extra saml + + - name: Cache Prisma binaries + if: steps.scope.outputs.has_scope == 'true' + uses: ./.github/actions/cache-prisma-binaries + + - name: Generate Prisma client + if: steps.scope.outputs.has_scope == 'true' + run: | + uv run --no-sync prisma generate --schema litellm/proxy/schema.prisma + + # See .github/workflows/mutation-test.yml for why these two steps exist: + # an editable install shadows the mutants/ sandbox, and pytest-retry + # crashes under mutmut's in-process pytest.main() call. + - name: Reinstall litellm non-editable (so mutants/ is not shadowed) + if: steps.scope.outputs.has_scope == 'true' + run: | + uv pip uninstall litellm + uv pip install . --no-deps + + - name: Remove pytest plugins that conflict with mutmut + if: steps.scope.outputs.has_scope == 'true' + run: | + uv pip uninstall pytest-retry || true + + - name: Run mutmut on the changed functions + if: steps.scope.outputs.has_scope == 'true' + continue-on-error: true + timeout-minutes: 10 + env: + PYTHONPATH: ${{ github.workspace }}/mutants + run: | + set -o pipefail + # mutants/ has to exist before mutmut starts: it is on PYTHONPATH, and Python + # caches a missing sys.path entry, so a directory created later is never searched. + mkdir -p mutants + GLOBS=() + while IFS= read -r glob || [ -n "$glob" ]; do + [ -n "$glob" ] && GLOBS+=("$glob") + done < mutmut-scope-globs.txt + uv run --no-sync --with mutmut==3.5.0 mutmut run "${GLOBS[@]}" 2>&1 | tee mutmut-run.log + + - name: Generate mutation report + if: always() && steps.scope.outputs.has_scope == 'true' + run: | + set +e + uv run --no-sync --with mutmut==3.5.0 mutmut export-cicd-stats > /dev/null 2>&1 + uv run --no-sync --with mutmut==3.5.0 mutmut results --all=true > mutmut-results.txt 2>&1 + uv run --no-sync python scripts/mutation_report.py + { + echo "## Mutation testing on this diff" + echo "" + echo '```' + cat mutmut-scope.log + echo '```' + echo "" + head -c 900000 mutation-report.md + } >> "$GITHUB_STEP_SUMMARY" + + - name: Report that nothing was in scope + if: steps.scope.outputs.has_scope != 'true' + run: | + { + echo "## Mutation testing on this diff" + echo "" + echo "No mutable production code changed, or no mirrored tests were found for it." + echo "" + echo '```' + cat mutmut-scope.log + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + + - name: Upload mutation artifacts + if: always() && steps.scope.outputs.has_scope == 'true' + uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1 + with: + name: mutmut-pr-${{ github.run_id }}-${{ github.run_attempt }} + path: | + mutation-report.md + mutmut-results.txt + mutmut-run.log + mutmut-scope.json + mutmut-scope.log + if-no-files-found: warn + retention-days: 14 diff --git a/.gitignore b/.gitignore index 201e02f2189e..cb1b21a9aef6 100644 --- a/.gitignore +++ b/.gitignore @@ -145,3 +145,12 @@ crash.*.log ui/litellm-dashboard/out/ litellm.log + +# mutation testing scratch (mutmut sandbox + diff-scope artifacts) +mutants/ +mutation-report.md +mutmut-results.txt +mutmut-run.log +mutmut-scope.json +mutmut-scope-globs.txt +mutmut-scope.log diff --git a/scripts/mutation_diff_scope.py b/scripts/mutation_diff_scope.py new file mode 100644 index 000000000000..4ccc77fceab8 --- /dev/null +++ b/scripts/mutation_diff_scope.py @@ -0,0 +1,303 @@ +#!/usr/bin/env python3 +"""Scope a mutmut run to the production code a pull request actually changed. + +mutmut reads its configuration only from ``[tool.mutmut]`` in ``pyproject.toml``, +and it filters which mutants to *execute* by fnmatch against mutant names. This +script bridges a git diff to both: + +1. It rewrites ``[tool.mutmut]`` so ``paths_to_mutate`` is the changed production + files and ``tests_dir`` is the test files that mirror them. +2. It emits mutant-name globs for the functions containing the changed lines, to + be passed as arguments to ``mutmut run``. + +mutmut installs its trampolines per top-level function and per class method, so a +changed line's enclosing function is the smallest unit it can execute. + +Usage: + python scripts/mutation_diff_scope.py --base origin/litellm_internal_staging +""" + +from __future__ import annotations + +import argparse +import ast +import json +import os +import re +import subprocess +import sys +import tomllib +from collections.abc import Iterable, Iterator, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Final + +REPO_ROOT: Final = Path(__file__).resolve().parent.parent +MUTATE_ROOTS: Final = ("litellm/",) +EXCLUDED_PREFIXES: Final = ( + "litellm/proxy/_experimental/", + "litellm/types/", +) +TEST_MIRROR_ROOT: Final = "tests/test_litellm" +# mutmut runs the selected tests from a `mutants/` sandbox. It copies tests/ itself, but a +# test that reaches back out to repo tooling (scripts/, .github/) fails to import there. +SANDBOX_COPIES: Final = ("litellm/", "scripts/", ".github/") +CLASS_NAME_SEPARATOR: Final = "ǁ" +HUNK_HEADER: Final = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@") +CONFIG_SECTION: Final = re.compile(r"^\[tool\.mutmut\]$.*?(?=^\[)", re.MULTILINE | re.DOTALL) + + +@dataclass(frozen=True, slots=True) +class ChangedFile: + path: str + lines: frozenset[int] + + +@dataclass(frozen=True, slots=True) +class TrampolineUnit: + """A function or method mutmut can address by name, and the lines it spans.""" + + mangled_name: str + start_line: int + end_line: int + + +@dataclass(frozen=True, slots=True) +class Scope: + files: tuple[ChangedFile, ...] + tests: tuple[str, ...] + globs: tuple[str, ...] + dropped_globs: tuple[str, ...] + + @property + def is_runnable(self) -> bool: + return bool(self.globs and self.tests) + + +def _git(root: Path, *args: str) -> str: + return subprocess.run(("git", *args), cwd=root, capture_output=True, text=True, check=True).stdout + + +def is_mutable_path(root: Path, path: str) -> bool: + return ( + path.endswith(".py") + and path.startswith(MUTATE_ROOTS) + and not path.startswith(EXCLUDED_PREFIXES) + and (root / path).is_file() + ) + + +def is_unit_test_path(root: Path, path: str) -> bool: + """Only the mirrored unit suite; tests/e2e needs a live proxy and cannot run in mutmut's sandbox.""" + return ( + path.startswith(f"{TEST_MIRROR_ROOT}/") + and path.endswith(".py") + and Path(path).name.startswith("test_") + and (root / path).is_file() + ) + + +def parse_unified_diff(root: Path, diff: str) -> tuple[ChangedFile, ...]: + """Map each changed production file to the post-image line numbers the diff touched.""" + + def touched_lines() -> Iterator[tuple[str, int]]: + current = "" + cursor = 0 + for line in diff.splitlines(): + if line.startswith("+++ b/"): + current = line[len("+++ b/") :] + elif (header := HUNK_HEADER.match(line)) is not None: + cursor = int(header.group(1)) + elif line.startswith("+") and not line.startswith("+++") and current: + yield current, cursor + cursor += 1 + + touched: Final = tuple(touched_lines()) + return tuple( + ChangedFile(path=path, lines=frozenset(line for other, line in touched if other == path)) + for path in sorted({path for path, _ in touched}) + if is_mutable_path(root, path) + ) + + +def changed_test_files(root: Path, diff: str) -> tuple[str, ...]: + return tuple( + sorted( + path + for line in diff.splitlines() + if line.startswith("+++ b/") and is_unit_test_path(root, path := line[len("+++ b/") :]) + ) + ) + + +def mapped_tests(root: Path, path: str) -> tuple[str, ...]: + """Find the tests mirroring a production file, per tests/test_litellm/readme.md.""" + relative: Final = Path(path).relative_to("litellm") + mirror_dir: Final = Path(TEST_MIRROR_ROOT) / relative.parent + named: Final = tuple(sorted(str(p.relative_to(root)) for p in (root / mirror_dir).glob(f"test_{relative.stem}*.py"))) + if named: + return named + return (str(mirror_dir),) if (root / mirror_dir).is_dir() else () + + +def trampoline_units(source: str) -> tuple[TrampolineUnit, ...]: + """Every unit mutmut trampolines: top-level functions and direct class methods.""" + tree: Final = ast.parse(source) + + def unit(node: ast.stmt, class_name: str | None) -> TrampolineUnit | None: + if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + return None + separator = CLASS_NAME_SEPARATOR + mangled = f"x{separator}{class_name}{separator}{node.name}" if class_name else f"x_{node.name}" + return TrampolineUnit( + mangled_name=mangled, + start_line=min((d.lineno for d in node.decorator_list), default=node.lineno), + end_line=node.end_lineno or node.lineno, + ) + + def walk() -> Iterator[TrampolineUnit]: + for statement in tree.body: + if (function := unit(statement, None)) is not None: + yield function + elif isinstance(statement, ast.ClassDef): + for member in statement.body: + if (method := unit(member, statement.name)) is not None: + yield method + + return tuple(walk()) + + +def module_name(path: str) -> str: + return path[: -len(".py")].replace(os.sep, ".").replace("/", ".") + + +def globs_for(root: Path, changed: ChangedFile) -> tuple[str, ...]: + try: + units = trampoline_units((root / changed.path).read_text(encoding="utf-8")) + except SyntaxError: + return () + module: Final = module_name(changed.path) + return tuple( + f"{module}.{unit.mangled_name}__mutmut_*" + for unit in units + if any(unit.start_line <= line <= unit.end_line for line in changed.lines) + ) + + +def build_scope(root: Path, base: str, max_functions: int) -> Scope: + merge_base: Final = _git(root, "merge-base", base, "HEAD").strip() + diff: Final = _git(root, "diff", "-U0", merge_base, "--", ".") + files: Final = parse_unified_diff(root, diff) + all_globs: Final = tuple(glob for changed in files for glob in globs_for(root, changed)) + tests: Final = tuple( + sorted({*(t for changed in files for t in mapped_tests(root, changed.path)), *changed_test_files(root, diff)}) + ) + return Scope( + files=files, + tests=tests, + globs=all_globs[:max_functions], + dropped_globs=all_globs[max_functions:], + ) + + +def render_config(scope: Scope, pytest_add_cli_args: Sequence[str]) -> str: + def toml_list(values: Iterable[str]) -> str: + return "[\n" + "".join(f' "{value}",\n' for value in values) + "]" + + return ( + "[tool.mutmut]\n" + f"paths_to_mutate = {toml_list(f.path for f in scope.files)}\n" + f"tests_dir = {toml_list(scope.tests)}\n" + f"also_copy = {toml_list(SANDBOX_COPIES)}\n" + # Gathering coverage costs an extra full run of the selected tests, and mutants on + # uncovered lines are cheap here: mutmut marks them "no tests" without running any. + "mutate_only_covered_lines = false\n" + f"pytest_add_cli_args = {toml_list(pytest_add_cli_args)}\n" + "\n" + ) + + +def rewrite_pyproject(root: Path, scope: Scope, pytest_add_cli_args: Sequence[str]) -> None: + pyproject: Final = root / "pyproject.toml" + original: Final = pyproject.read_text(encoding="utf-8") + if CONFIG_SECTION.search(original) is None: + raise SystemExit("Could not find a [tool.mutmut] section to replace in pyproject.toml") + pyproject.write_text( + CONFIG_SECTION.sub(lambda _: render_config(scope, pytest_add_cli_args), original, count=1), encoding="utf-8" + ) + + +def existing_pytest_cli_args(root: Path) -> tuple[str, ...]: + with open(root / "pyproject.toml", "rb") as handle: + section: Mapping[str, object] = tomllib.load(handle)["tool"]["mutmut"] + args: Final = section.get("pytest_add_cli_args", ()) + return tuple(str(arg) for arg in args) if isinstance(args, list) else () + + +def describe(scope: Scope, max_functions: int) -> str: + def section(title: str, values: Iterable[str]) -> Iterator[str]: + listed = tuple(values) + yield f"{title}: {len(listed)}" + yield from (f" {value}" for value in listed) + + lines: Final = ( + *section("changed production files", (f"{f.path} ({len(f.lines)} lines)" for f in scope.files)), + *section("test selection", scope.tests), + *section("functions to mutate", scope.globs), + *( + section(f"NOT mutated (over --max-functions={max_functions})", scope.dropped_globs) + if scope.dropped_globs + else () + ), + ) + return "\n".join(lines) + + +def emit_github_output(scope: Scope) -> None: + if (output := os.environ.get("GITHUB_OUTPUT")) is None: + return + with open(output, "a", encoding="utf-8") as handle: + handle.write(f"has_scope={'true' if scope.is_runnable else 'false'}\n") + handle.write(f"function_count={len(scope.globs)}\n") + + +def main(argv: Sequence[str]) -> int: + parser: Final = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--base", default="origin/litellm_internal_staging") + parser.add_argument("--max-functions", type=int, default=40) + parser.add_argument("--root", type=Path, default=REPO_ROOT) + parser.add_argument("--write-pyproject", action="store_true") + parser.add_argument("--globs-out", type=Path, default=None) + parser.add_argument("--json-out", type=Path, default=None) + args: Final = parser.parse_args(argv) + + root: Final = args.root.resolve() + scope: Final = build_scope(root, args.base, args.max_functions) + globs_out: Final = args.globs_out or root / "mutmut-scope-globs.txt" + json_out: Final = args.json_out or root / "mutmut-scope.json" + + globs_out.write_text("".join(f"{glob}\n" for glob in scope.globs), encoding="utf-8") + json_out.write_text( + json.dumps( + { + "files": [{"path": f.path, "lines": sorted(f.lines)} for f in scope.files], + "tests": list(scope.tests), + "globs": list(scope.globs), + "dropped_globs": list(scope.dropped_globs), + }, + indent=2, + ), + encoding="utf-8", + ) + print(describe(scope, args.max_functions)) + + if args.write_pyproject and scope.is_runnable: + rewrite_pyproject(root, scope, existing_pytest_cli_args(root)) + print("rewrote [tool.mutmut] in pyproject.toml for this diff") + + emit_github_output(scope) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/scripts/mutation_report.py b/scripts/mutation_report.py index a606e3f71cf3..86c1cf728b55 100644 --- a/scripts/mutation_report.py +++ b/scripts/mutation_report.py @@ -15,7 +15,9 @@ import ast import json +import os import re +import shlex import subprocess import sys import tomllib @@ -25,7 +27,11 @@ from textwrap import dedent ROOT = Path(__file__).resolve().parent.parent -MUTMUT_INVOCATION = ["uv", "run", "--no-sync", "--with", "mutmut==3.5.0", "mutmut"] +# Overridable so the report can be regenerated outside CI, where the project venv +# `uv run --no-sync` expects may not exist. +MUTMUT_INVOCATION = shlex.split( + os.environ.get("MUTMUT_CMD", "uv run --no-sync --with mutmut==3.5.0 mutmut") +) def load_mutmut_config() -> dict: @@ -33,16 +39,42 @@ def load_mutmut_config() -> dict: return tomllib.load(f)["tool"]["mutmut"] -def get_survivors() -> list[str]: +def get_results() -> list[tuple[str, str]]: + """Parse `mutmut results` into (mutant name, status) pairs. + + A diff-scoped run leaves every out-of-scope mutant at `not checked`, so + callers must drop that status before counting anything. + """ proc = subprocess.run( - [*MUTMUT_INVOCATION, "results"], capture_output=True, text=True, check=False + [*MUTMUT_INVOCATION, "results", "--all=true"], capture_output=True, text=True, check=False ) - survivors = [] + results = [] for line in proc.stdout.splitlines(): - m = re.match(r"\s*(\S+):\s*survived\s*$", line) + m = re.match(r"\s*(\S+):\s*(killed|survived|no tests|timeout|suspicious|skipped|not checked)\s*$", line) if m: - survivors.append(m.group(1)) - return survivors + results.append((m.group(1), m.group(2))) + return results + + +def summarize(results: list[tuple[str, str]]) -> dict | None: + """Count only the mutants this run actually executed.""" + checked = [status for _, status in results if status != "not checked"] + if not checked: + return None + return { + "total": len(checked), + **{ + key: sum(1 for status in checked if status == label) + for key, label in ( + ("killed", "killed"), + ("survived", "survived"), + ("no_tests", "no tests"), + ("skipped", "skipped"), + ("suspicious", "suspicious"), + ("timeout", "timeout"), + ) + }, + } def get_mutmut_show(mutant_name: str) -> str: @@ -399,15 +431,18 @@ def render(config: dict, survivors: list[str], stats: dict | None) -> str: def main() -> int: config = load_mutmut_config() - stats_file = ROOT / "mutants" / "mutmut-cicd-stats.json" - stats: dict | None = None - if stats_file.exists(): - try: - stats = json.loads(stats_file.read_text()) - except json.JSONDecodeError as exc: - print(f"warning: could not parse {stats_file}: {exc}", file=sys.stderr) + results = get_results() + stats = summarize(results) + + if stats is None: + stats_file = ROOT / "mutants" / "mutmut-cicd-stats.json" + if stats_file.exists(): + try: + stats = json.loads(stats_file.read_text()) + except json.JSONDecodeError as exc: + print(f"warning: could not parse {stats_file}: {exc}", file=sys.stderr) - survivors = get_survivors() + survivors = [name for name, status in results if status == "survived"] report = render(config, survivors, stats) out_path = ROOT / "mutation-report.md" diff --git a/tests/test_litellm/test_mutation_diff_scope.py b/tests/test_litellm/test_mutation_diff_scope.py new file mode 100644 index 000000000000..f6ae38a069b8 --- /dev/null +++ b/tests/test_litellm/test_mutation_diff_scope.py @@ -0,0 +1,242 @@ +"""Regression tests for the diff-scoped mutation testing gate. + +`.github/workflows/mutation-test-pr.yml` runs mutmut on pull requests, and the +only thing keeping that job inside a few minutes is `scripts/mutation_diff_scope.py` +narrowing mutmut down to what the diff touched. Two things have to hold, or the +job either burns hours or silently tests nothing: + +- The mutant-name globs must address the exact functions containing the changed + lines, spelled the way mutmut mangles them (`x_` for a module-level + function, `xǁǁ` for a method). A glob that matches nothing makes + mutmut abort; a glob that is too broad drags in unrelated functions. +- The test selection must stay inside `tests/test_litellm/`. `tests/e2e/` needs a + live proxy and cannot run inside mutmut's `mutants/` sandbox, so pulling one in + would fail the clean-test check and abort the run. + +These tests drive the real scope builder against a throwaway git repository laid +out like this one, so a regression shows up as the wrong mutmut invocation. +""" + +from __future__ import annotations + +import subprocess +import sys +import tomllib +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(REPO_ROOT / "scripts")) + +from mutation_diff_scope import ( # noqa: E402 + Scope, + build_scope, + render_config, + rewrite_pyproject, + trampoline_units, +) + +PYPROJECT = """\ +[project] +name = "litellm" + +[tool.mutmut] +paths_to_mutate = [ + "litellm/proxy/management_endpoints/", +] +tests_dir = [ + "tests/test_litellm/proxy/management_endpoints/", +] +pytest_add_cli_args = [ + "-p", "no:retry", +] + +[tool.coverage.run] +branch = true +""" + +ROUTER = '''\ +import functools + + +def _deployment_key(name: str) -> str: + return name.strip() + + +class Router: + def __init__(self, models: list[str]) -> None: + self.models = models + + @functools.cached_property + def get_model_list(self) -> list[str]: + return [m for m in self.models if m] + + async def acompletion(self, model: str) -> str: + return model +''' + +AUTH_CHECKS = '''\ +DEFAULT_ROLE = "user" + + +def can_call_model(model: str, allowed: list[str]) -> bool: + return model in allowed +''' + +TYPES = '''\ +def coerce(value: str) -> str: + return value +''' + + +def _run(root: Path, *args: str) -> None: + subprocess.run(("git", *args), cwd=root, check=True, capture_output=True) + + +def _write(root: Path, path: str, body: str) -> None: + target = root / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(body, encoding="utf-8") + + +@pytest.fixture +def repo(tmp_path: Path) -> Path: + root = tmp_path.resolve() + _run(root, "init", "-q", "-b", "base") + _run(root, "config", "user.email", "test@example.com") + _run(root, "config", "user.name", "test") + + _write(root, "pyproject.toml", PYPROJECT) + _write(root, "litellm/router.py", ROUTER) + _write(root, "litellm/proxy/auth/auth_checks.py", AUTH_CHECKS) + _write(root, "litellm/types/utils.py", TYPES) + _write(root, "tests/test_litellm/test_router.py", "def test_router(): pass\n") + _write(root, "tests/test_litellm/proxy/auth/test_auth_checks.py", "def test_auth(): pass\n") + _write(root, "tests/e2e/test_live_proxy.py", "def test_live(): pass\n") + + _run(root, "add", "-A") + _run(root, "commit", "-qm", "base") + _run(root, "checkout", "-q", "-b", "feature") + return root + + +def _commit(root: Path, message: str = "change") -> None: + _run(root, "add", "-A") + _run(root, "commit", "-qm", message) + + +def scope_of(root: Path, max_functions: int = 40) -> Scope: + return build_scope(root, "base", max_functions) + + +def test_changed_method_maps_to_its_mangled_mutant_glob(repo: Path) -> None: + """A line inside a class method must address that method, class-qualified.""" + _write(repo, "litellm/router.py", ROUTER.replace("if m]", "if m and m.strip()]")) + _commit(repo) + + assert scope_of(repo).globs == ("litellm.router.xǁRouterǁget_model_list__mutmut_*",) + + +def test_changed_module_level_function_uses_the_underscore_prefix(repo: Path) -> None: + """Module-level functions mangle to `x_`, not `xǁ...ǁ`.""" + _write(repo, "litellm/proxy/auth/auth_checks.py", AUTH_CHECKS.replace("model in allowed", "model.lower() in allowed")) + _commit(repo) + + assert scope_of(repo).globs == ("litellm.proxy.auth.auth_checks.x_can_call_model__mutmut_*",) + + +def test_touching_a_decorator_still_selects_the_decorated_function(repo: Path) -> None: + """mutmut mutates the whole decorated function, so its decorator lines belong to it.""" + _write(repo, "litellm/router.py", ROUTER.replace("@functools.cached_property", "@functools.cache")) + _commit(repo) + + assert scope_of(repo).globs == ("litellm.router.xǁRouterǁget_model_list__mutmut_*",) + + +def test_module_level_change_selects_no_function(repo: Path) -> None: + """mutmut only trampolines functions, so a module-level constant has nothing to run.""" + _write(repo, "litellm/proxy/auth/auth_checks.py", AUTH_CHECKS.replace('"user"', '"internal_user"')) + _commit(repo) + + scope = scope_of(repo) + assert scope.files, "the file must still register as changed" + assert scope.globs == () + assert scope.is_runnable is False + + +def test_type_definitions_are_never_mutated(repo: Path) -> None: + """litellm/types holds declarations; mutating them only produces noise.""" + _write(repo, "litellm/types/utils.py", TYPES.replace("return value", "return value.strip()")) + _commit(repo) + + assert scope_of(repo).files == () + + +def test_test_only_changes_produce_nothing_to_mutate(repo: Path) -> None: + _write(repo, "tests/test_litellm/test_router.py", "def test_router(): assert True\n") + _commit(repo) + + assert scope_of(repo).is_runnable is False + + +def test_test_selection_is_the_mirrored_file_plus_changed_unit_tests(repo: Path) -> None: + _write(repo, "litellm/router.py", ROUTER.replace("if m]", "if m and m.strip()]")) + _write(repo, "tests/test_litellm/proxy/auth/test_auth_checks.py", "def test_auth(): assert True\n") + _commit(repo) + + assert scope_of(repo).tests == ( + "tests/test_litellm/proxy/auth/test_auth_checks.py", + "tests/test_litellm/test_router.py", + ) + + +def test_e2e_tests_are_excluded_from_the_selection(repo: Path) -> None: + """tests/e2e needs a live proxy; including one aborts the run at mutmut's clean-test check.""" + _write(repo, "litellm/router.py", ROUTER.replace("if m]", "if m and m.strip()]")) + _write(repo, "tests/e2e/test_live_proxy.py", "def test_live(): assert True\n") + _commit(repo) + + assert "tests/e2e/test_live_proxy.py" not in scope_of(repo).tests + + +def test_max_functions_caps_the_run_and_reports_what_it_dropped(repo: Path) -> None: + """Silently truncating would read as full coverage of the diff.""" + _write(repo, "litellm/router.py", ROUTER.replace("return name.strip()", "return name.strip().lower()").replace("if m]", "if m and m.strip()]")) + _commit(repo) + + uncapped = scope_of(repo) + assert len(uncapped.globs) == 2 + + capped = scope_of(repo, max_functions=1) + assert len(capped.globs) == 1 + assert capped.dropped_globs == uncapped.globs[1:] + + +def test_rewritten_pyproject_scopes_mutmut_and_keeps_the_rest_of_the_file(repo: Path) -> None: + _write(repo, "litellm/router.py", ROUTER.replace("if m]", "if m and m.strip()]")) + _commit(repo) + + rewrite_pyproject(repo, scope_of(repo), ("-p", "no:retry")) + config = tomllib.loads((repo / "pyproject.toml").read_text(encoding="utf-8")) + + assert config["tool"]["mutmut"]["paths_to_mutate"] == ["litellm/router.py"] + assert config["tool"]["mutmut"]["tests_dir"] == ["tests/test_litellm/test_router.py"] + assert config["tool"]["mutmut"]["mutate_only_covered_lines"] is False + assert config["tool"]["mutmut"]["pytest_add_cli_args"] == ["-p", "no:retry"] + assert config["tool"]["coverage"]["run"]["branch"] is True + assert config["project"]["name"] == "litellm" + + +def test_render_config_copies_what_the_selected_tests_import(repo: Path) -> None: + """mutmut runs from mutants/; a test importing litellm or repo tooling needs those copied in.""" + rendered = render_config(Scope(files=(), tests=(), globs=(), dropped_globs=()), ()) + + assert tomllib.loads(rendered)["tool"]["mutmut"]["also_copy"] == ["litellm/", "scripts/", ".github/"] + + +def test_trampoline_units_skips_nested_functions(repo: Path) -> None: + """mutmut folds a nested def into its parent, so selecting it by name would match nothing.""" + source = "def outer():\n def inner():\n return 1\n\n return inner()\n" + + assert [unit.mangled_name for unit in trampoline_units(source)] == ["x_outer"] From a37c29bb01fb8384cfebd325fc72bf24cc749947 Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Thu, 20 Aug 2026 12:04:45 -0700 Subject: [PATCH 2/6] fix(ci): read the pull request base ref from env, not a template expansion --- .github/workflows/mutation-test-pr.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/mutation-test-pr.yml b/.github/workflows/mutation-test-pr.yml index b7ae605ccd66..72df97537c7b 100644 --- a/.github/workflows/mutation-test-pr.yml +++ b/.github/workflows/mutation-test-pr.yml @@ -46,9 +46,11 @@ jobs: - name: Scope the run to the diff id: scope + env: + BASE_REF: ${{ github.event.pull_request.base.ref }} run: | python scripts/mutation_diff_scope.py \ - --base "origin/${{ github.event.pull_request.base.ref }}" \ + --base "origin/$BASE_REF" \ --write-pyproject | tee mutmut-scope.log - name: Set up uv From cff28ea462eb868fbce2b66d120619b16ce5b4ce Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Thu, 20 Aug 2026 12:19:07 -0700 Subject: [PATCH 3/6] fix(ci): keep deletion-only diffs in scope and fail a mutation run that checked nothing --- .github/workflows/mutation-test-pr.yml | 4 + scripts/mutation_diff_scope.py | 14 +- scripts/mutation_report.py | 219 +++++++++++------- .../test_litellm/test_mutation_diff_scope.py | 40 +++- tests/test_litellm/test_mutation_report.py | 115 +++++++++ 5 files changed, 299 insertions(+), 93 deletions(-) create mode 100644 tests/test_litellm/test_mutation_report.py diff --git a/.github/workflows/mutation-test-pr.yml b/.github/workflows/mutation-test-pr.yml index 72df97537c7b..addfb6eed985 100644 --- a/.github/workflows/mutation-test-pr.yml +++ b/.github/workflows/mutation-test-pr.yml @@ -122,6 +122,7 @@ jobs: uv run --no-sync --with mutmut==3.5.0 mutmut export-cicd-stats > /dev/null 2>&1 uv run --no-sync --with mutmut==3.5.0 mutmut results --all=true > mutmut-results.txt 2>&1 uv run --no-sync python scripts/mutation_report.py + report_status=$? { echo "## Mutation testing on this diff" echo "" @@ -131,6 +132,9 @@ jobs: echo "" head -c 900000 mutation-report.md } >> "$GITHUB_STEP_SUMMARY" + # Surviving mutants stay advisory. A run that checked nothing is a broken job, + # and reporting that as a clean sweep is the one failure mode worth going red for. + exit $report_status - name: Report that nothing was in scope if: steps.scope.outputs.has_scope != 'true' diff --git a/scripts/mutation_diff_scope.py b/scripts/mutation_diff_scope.py index 4ccc77fceab8..694b4a9d4bb7 100644 --- a/scripts/mutation_diff_scope.py +++ b/scripts/mutation_diff_scope.py @@ -98,7 +98,13 @@ def is_unit_test_path(root: Path, path: str) -> bool: def parse_unified_diff(root: Path, diff: str) -> tuple[ChangedFile, ...]: - """Map each changed production file to the post-image line numbers the diff touched.""" + """Map each changed production file to the post-image line numbers the diff touched. + + Deleted lines have no post-image line of their own, so they are attributed to + the line they now follow: under ``-U0`` that is the hunk header's ``+`` start, + which is the surviving line directly above the deletion. Without this, removing + a guard clause would leave its function out of scope entirely. + """ def touched_lines() -> Iterator[tuple[str, int]]: current = "" @@ -108,9 +114,13 @@ def touched_lines() -> Iterator[tuple[str, int]]: current = line[len("+++ b/") :] elif (header := HUNK_HEADER.match(line)) is not None: cursor = int(header.group(1)) - elif line.startswith("+") and not line.startswith("+++") and current: + elif not current: + continue + elif line.startswith("+") and not line.startswith("+++"): yield current, cursor cursor += 1 + elif line.startswith("-") and not line.startswith("---"): + yield current, max(cursor, 1) touched: Final = tuple(touched_lines()) return tuple( diff --git a/scripts/mutation_report.py b/scripts/mutation_report.py index 86c1cf728b55..9238afd3d5ae 100644 --- a/scripts/mutation_report.py +++ b/scripts/mutation_report.py @@ -22,6 +22,7 @@ import sys import tomllib from collections import defaultdict +from dataclasses import dataclass from difflib import SequenceMatcher from pathlib import Path from textwrap import dedent @@ -32,6 +33,35 @@ MUTMUT_INVOCATION = shlex.split( os.environ.get("MUTMUT_CMD", "uv run --no-sync --with mutmut==3.5.0 mutmut") ) +# mutmut mangles a class method as `xǁǁ` and a module-level +# function as `x_`. +CLASS_NAME_SEPARATOR = "ǁ" +RESULT_LINE = re.compile( + r"\s*(\S+):\s*(killed|survived|no tests|timeout|suspicious|skipped|not checked)\s*$" +) +MUTANT_NAME = re.compile(r"^(?P.+)\.(?P[^.]+)__mutmut_(?P\d+)$") +COUNT_KEYS = ("killed", "survived", "no_tests", "skipped", "suspicious", "timeout", "segfault") + + +@dataclass(frozen=True) +class MutantName: + """A parsed mutmut mutant identifier.""" + + module: str + class_name: str | None + function: str + number: str + + @property + def mangled(self) -> str: + """The name mutmut gives the mutated function inside the trampoline file.""" + if self.class_name is None: + return f"x_{self.function}" + return f"x{CLASS_NAME_SEPARATOR}{self.class_name}{CLASS_NAME_SEPARATOR}{self.function}" + + @property + def qualified(self) -> str: + return f"{self.class_name}.{self.function}" if self.class_name else self.function def load_mutmut_config() -> dict: @@ -39,7 +69,7 @@ def load_mutmut_config() -> dict: return tomllib.load(f)["tool"]["mutmut"] -def get_results() -> list[tuple[str, str]]: +def get_results() -> tuple[tuple[str, str], ...]: """Parse `mutmut results` into (mutant name, status) pairs. A diff-scoped run leaves every out-of-scope mutant at `not checked`, so @@ -48,17 +78,13 @@ def get_results() -> list[tuple[str, str]]: proc = subprocess.run( [*MUTMUT_INVOCATION, "results", "--all=true"], capture_output=True, text=True, check=False ) - results = [] - for line in proc.stdout.splitlines(): - m = re.match(r"\s*(\S+):\s*(killed|survived|no tests|timeout|suspicious|skipped|not checked)\s*$", line) - if m: - results.append((m.group(1), m.group(2))) - return results + matches = (RESULT_LINE.match(line) for line in proc.stdout.splitlines()) + return tuple((m.group(1), m.group(2)) for m in matches if m is not None) -def summarize(results: list[tuple[str, str]]) -> dict | None: +def summarize(results: tuple[tuple[str, str], ...]) -> dict | None: """Count only the mutants this run actually executed.""" - checked = [status for _, status in results if status != "not checked"] + checked = tuple(status for _, status in results if status != "not checked") if not checked: return None return { @@ -87,19 +113,38 @@ def get_mutmut_show(mutant_name: str) -> str: return proc.stdout.strip() or "(mutmut show produced no output)" -def parse_mutant_name(name: str) -> tuple[str, str, str]: - """Parse `.x___mutmut_` -> (module, function, N). +def parse_mutant_name(name: str) -> MutantName: + """Parse a mutmut mutant identifier into its module, class, function and number. - mutmut prefixes mutated functions with `x_` (single underscore). For a - function named `foo`, mutants are `x_foo__mutmut_N`. For a function named - `_foo` (leading underscore), the mutant becomes `x__foo__mutmut_N` — so - the regex matches a single underscore after `x` and captures everything - (including any leading underscores) up to `__mutmut_`. + Module-level functions are `.x___mutmut_`; a + function named `_foo` becomes `x__foo__mutmut_N`, so everything after the + single `x_` prefix (leading underscores included) is the function name. + Class methods are `.xǁǁ__mutmut_`. + + An unrecognised name is returned verbatim as the function, so the report + still shows something addressable instead of dropping the mutant. """ - m = re.match(r"^(.+)\.x_(.+)__mutmut_(\d+)$", name) + m = MUTANT_NAME.match(name) if not m: - return name, name, "?" - return m.group(1), m.group(2), m.group(3) + return MutantName(module=name, class_name=None, function=name, number="?") + mangled = m.group("mangled") + if mangled.startswith(f"x{CLASS_NAME_SEPARATOR}"): + parts = mangled.split(CLASS_NAME_SEPARATOR) + if len(parts) == 3: + return MutantName( + module=m.group("module"), + class_name=parts[1], + function=parts[2], + number=m.group("number"), + ) + if mangled.startswith("x_"): + return MutantName( + module=m.group("module"), + class_name=None, + function=mangled[len("x_") :], + number=m.group("number"), + ) + return MutantName(module=name, class_name=None, function=name, number="?") def function_anchor(module_path: str, function_name: str) -> str: @@ -114,23 +159,32 @@ def module_to_file(module_path: str) -> Path | None: def find_function_in_file( - file_path: Path, function_name: str + file_path: Path, function_name: str, class_name: str | None = None ) -> tuple[int, int, str, list[int]] | None: - """Find a top-level or nested function by name; returns the first match. + """Find a function by name; returns the first match. Returns ``(start_line, end_line, source, all_match_lines)`` or ``None``. - ``all_match_lines`` is the start line of every function (any nesting - level) in the file with this name. When ``len(all_match_lines) > 1`` the - file defines the same name in multiple places (e.g., a module-level - helper and a class method) — mutmut's mutant identifier does not carry - class context, so we can't determine which definition was mutated. - Callers surface a disambiguation note in that case. + ``all_match_lines`` is the start line of every candidate definition. When + ``len(all_match_lines) > 1`` the file defines the same name in several + places and callers surface a disambiguation note. A mutant carrying class + context is matched against that class's own methods, which is normally + unambiguous. """ src = file_path.read_text() tree = ast.parse(src) + scopes = ( + [ + node + for node in ast.walk(tree) + if isinstance(node, ast.ClassDef) and node.name == class_name + ] + if class_name is not None + else [tree] + ) matches = [ node - for node in ast.walk(tree) + for scope in scopes + for node in ast.walk(scope) if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == function_name ] @@ -161,13 +215,11 @@ def _indent_of(line: str) -> str: return line[: len(line) - len(line.lstrip())] -def render_meta_style_mutant( - module_path: str, function_name: str, mutant_num: str -) -> str | None: +def render_meta_style_mutant(mutant: MutantName) -> str | None: """Render the mutated function with `# MUTANT START`/`# MUTANT END` delimiters. Reads `mutants/.py` (the trampoline file mutmut emits), finds - `x___mutmut_orig` and `x___mutmut_`, and renders the + `__mutmut_orig` and `__mutmut_`, and renders the mutated version with the lines that differ from `__mutmut_orig` wrapped in `# MUTANT START`/`# MUTANT END` comments — the format from Meta's ACH paper (arXiv 2501.12862, Table 1). @@ -179,7 +231,7 @@ def render_meta_style_mutant( Returns None if the trampoline file or either function cannot be found (the caller falls back to the unified diff). """ - trampoline = ROOT / "mutants" / Path(*module_path.split(".")).with_suffix(".py") + trampoline = ROOT / "mutants" / Path(*mutant.module.split(".")).with_suffix(".py") if not trampoline.exists(): return None @@ -190,8 +242,8 @@ def render_meta_style_mutant( return None file_lines = src.splitlines() - orig_def = f"x_{function_name}__mutmut_orig" - mutant_def = f"x_{function_name}__mutmut_{mutant_num}" + orig_def = f"{mutant.mangled}__mutmut_orig" + mutant_def = f"{mutant.mangled}__mutmut_{mutant.number}" orig_node = mutated_node = None for node in ast.walk(tree): @@ -211,8 +263,8 @@ def render_meta_style_mutant( # Rewrite the def line to use the original (non-trampolined) function name # so the agent sees the function as it appears in the source file. - orig_lines[0] = orig_lines[0].replace(orig_def, function_name, 1) - mutated_lines[0] = mutated_lines[0].replace(mutant_def, function_name, 1) + orig_lines[0] = orig_lines[0].replace(orig_def, mutant.function, 1) + mutated_lines[0] = mutated_lines[0].replace(mutant_def, mutant.function, 1) matcher = SequenceMatcher(a=orig_lines, b=mutated_lines) out: list[str] = [] @@ -254,11 +306,11 @@ def render_meta_style_mutant( return "\n".join(out) -def render(config: dict, survivors: list[str], stats: dict | None) -> str: - by_function: dict[tuple[str, str], list[tuple[str, str]]] = defaultdict(list) +def render(config: dict, survivors: tuple[str, ...], stats: dict | None) -> str: + by_function: dict[tuple[str, str | None, str], list[tuple[str, MutantName]]] = defaultdict(list) for survivor in survivors: - module_path, function_name, mutant_num = parse_mutant_name(survivor) - by_function[(module_path, function_name)].append((survivor, mutant_num)) + mutant = parse_mutant_name(survivor) + by_function[(mutant.module, mutant.class_name, mutant.function)].append((survivor, mutant)) out: list[str] = [] out.append("# Mutation Test Report") @@ -267,18 +319,7 @@ def render(config: dict, survivors: list[str], stats: dict | None) -> str: out.append("## Summary") out.append("") if stats: - total = stats.get("total", 0) or sum( - stats.get(k, 0) - for k in ( - "killed", - "survived", - "no_tests", - "skipped", - "suspicious", - "timeout", - "segfault", - ) - ) + total = stats.get("total", 0) or sum(stats.get(k, 0) for k in COUNT_KEYS) killed = stats.get("killed", 0) survived = stats.get("survived", 0) score = (killed / total * 100) if total else 0.0 @@ -292,28 +333,35 @@ def render(config: dict, survivors: list[str], stats: dict | None) -> str: out.append(f"- {k.replace('_', ' ').title()}: {v}") else: out.append(f"- Survivors found: **{len(survivors)}**") - out.append("- (mutmut-cicd-stats.json not available — full counts unavailable)") + out.append("- (no mutant results and no mutmut-cicd-stats.json)") out.append("") if not survivors: - out.append("**No surviving mutants — the test suite caught every mutation.**") + out.append( + "**No surviving mutants — the test suite caught every mutation.**" + if stats + else "**The mutation run produced no results at all. Treat this as a failed " + "run, not as a passing one: nothing was executed to survive.**" + ) out.append("") return "\n".join(out) out.append("## Surviving mutants by function") out.append("") - for (module_path, function_name), items in by_function.items(): - anchor = function_anchor(module_path, function_name) + for (module_path, class_name, function_name), items in by_function.items(): + qualified = items[0][1].qualified + anchor = function_anchor(module_path, qualified) out.append( - f"- [`{function_name}`](#{anchor}) — {len(items)} mutant" + f"- [`{qualified}`](#{anchor}) — {len(items)} mutant" f"{'s' if len(items) != 1 else ''} ({module_path})" ) out.append("") - for (module_path, function_name), items in by_function.items(): - anchor = function_anchor(module_path, function_name) + for (module_path, class_name, function_name), items in by_function.items(): + qualified = items[0][1].qualified + anchor = function_anchor(module_path, qualified) out.append(f'') - out.append(f"## `{module_path}.{function_name}`") + out.append(f"## `{module_path}.{qualified}`") out.append("") out.append(f"**Module:** `{module_path}`") @@ -326,7 +374,7 @@ def render(config: dict, survivors: list[str], stats: dict | None) -> str: rel = file_path.relative_to(ROOT) out.append(f"**File:** `{rel}`") out.append("") - found = find_function_in_file(file_path, function_name) + found = find_function_in_file(file_path, function_name, class_name) if found: start, end, fn_src, all_lines = found out.append(f"### Original function (lines {start}-{end})") @@ -336,11 +384,8 @@ def render(config: dict, survivors: list[str], stats: dict | None) -> str: out.append( f"> **Note:** {len(all_lines)} functions named " f"`{function_name}` are defined in this file at lines " - f"{line_list}. Showing the first match. mutmut's " - f"mutant identifier does not carry class context, so " - f"the body below may not correspond to the function " - f"that was actually mutated — verify manually before " - f"writing the killing test." + f"{line_list}. Showing the first match; verify it is the " + f"one that was mutated before writing the killing test." ) out.append("") out.append("```python") @@ -353,12 +398,10 @@ def render(config: dict, survivors: list[str], stats: dict | None) -> str: out.append(f"### Surviving mutations ({len(items)})") out.append("") - for i, (mutant_name, mutant_num) in enumerate(items, 1): + for i, (mutant_name, mutant) in enumerate(items, 1): out.append(f"#### Mutation {i} of {len(items)} — `{mutant_name}`") out.append("") - meta_style = render_meta_style_mutant( - module_path, function_name, mutant_num - ) + meta_style = render_meta_style_mutant(mutant) if meta_style is not None: out.append( "Mutated function (the bug is delimited by " @@ -428,21 +471,25 @@ def render(config: dict, survivors: list[str], stats: dict | None) -> str: return "\n".join(out) +def fallback_stats() -> dict | None: + """mutmut's own export, used when `mutmut results` could not be parsed.""" + stats_file = ROOT / "mutants" / "mutmut-cicd-stats.json" + if not stats_file.exists(): + return None + try: + exported = json.loads(stats_file.read_text()) + except json.JSONDecodeError as exc: + print(f"warning: could not parse {stats_file}: {exc}", file=sys.stderr) + return None + return exported if any(exported.get(key, 0) for key in COUNT_KEYS) else None + + def main() -> int: config = load_mutmut_config() results = get_results() - stats = summarize(results) - - if stats is None: - stats_file = ROOT / "mutants" / "mutmut-cicd-stats.json" - if stats_file.exists(): - try: - stats = json.loads(stats_file.read_text()) - except json.JSONDecodeError as exc: - print(f"warning: could not parse {stats_file}: {exc}", file=sys.stderr) - - survivors = [name for name, status in results if status == "survived"] + stats = summarize(results) or fallback_stats() + survivors = tuple(name for name, status in results if status == "survived") report = render(config, survivors, stats) out_path = ROOT / "mutation-report.md" @@ -451,6 +498,14 @@ def main() -> int: f"Wrote {out_path} ({len(survivors)} survivor" f"{'s' if len(survivors) != 1 else ''}, {len(report)} chars)" ) + if stats is None: + # Survivors are advisory, but a run that checked nothing is a broken run: + # reporting it as a clean sweep is how a crashed mutmut turns into a green PR. + print( + "error: mutmut reported no checked mutants; the run did not complete", + file=sys.stderr, + ) + return 1 return 0 diff --git a/tests/test_litellm/test_mutation_diff_scope.py b/tests/test_litellm/test_mutation_diff_scope.py index f6ae38a069b8..d72675720331 100644 --- a/tests/test_litellm/test_mutation_diff_scope.py +++ b/tests/test_litellm/test_mutation_diff_scope.py @@ -19,6 +19,7 @@ from __future__ import annotations +import importlib.util import subprocess import sys import tomllib @@ -26,16 +27,20 @@ import pytest -REPO_ROOT = Path(__file__).resolve().parents[2] -sys.path.insert(0, str(REPO_ROOT / "scripts")) - -from mutation_diff_scope import ( # noqa: E402 - Scope, - build_scope, - render_config, - rewrite_pyproject, - trampoline_units, +_REPO_ROOT = Path(__file__).resolve().parents[2] +_spec = importlib.util.spec_from_file_location( + "mutation_diff_scope", _REPO_ROOT / "scripts" / "mutation_diff_scope.py" ) +scope_module = importlib.util.module_from_spec(_spec) +# dataclasses resolves a frozen class's module through sys.modules at decoration time. +sys.modules[_spec.name] = scope_module +_spec.loader.exec_module(scope_module) + +Scope = scope_module.Scope +build_scope = scope_module.build_scope +render_config = scope_module.render_config +rewrite_pyproject = scope_module.rewrite_pyproject +trampoline_units = scope_module.trampoline_units PYPROJECT = """\ [project] @@ -154,6 +159,23 @@ def test_touching_a_decorator_still_selects_the_decorated_function(repo: Path) - assert scope_of(repo).globs == ("litellm.router.xǁRouterǁget_model_list__mutmut_*",) +def test_deletion_only_change_still_selects_the_function(repo: Path) -> None: + """Removing a guard clause changes behavior, so its function has to stay in scope.""" + guarded = AUTH_CHECKS.replace( + " return model in allowed\n", + " if not model:\n return False\n return model in allowed\n", + ) + _write(repo, "litellm/proxy/auth/auth_checks.py", guarded) + _commit(repo, "add the guard") + _run(repo, "checkout", "-q", "-b", "removal") + _write(repo, "litellm/proxy/auth/auth_checks.py", AUTH_CHECKS) + _commit(repo, "remove the guard") + + scope = build_scope(repo, "feature", 40) + + assert scope.globs == ("litellm.proxy.auth.auth_checks.x_can_call_model__mutmut_*",) + + def test_module_level_change_selects_no_function(repo: Path) -> None: """mutmut only trampolines functions, so a module-level constant has nothing to run.""" _write(repo, "litellm/proxy/auth/auth_checks.py", AUTH_CHECKS.replace('"user"', '"internal_user"')) diff --git a/tests/test_litellm/test_mutation_report.py b/tests/test_litellm/test_mutation_report.py new file mode 100644 index 000000000000..a6d7a55630f5 --- /dev/null +++ b/tests/test_litellm/test_mutation_report.py @@ -0,0 +1,115 @@ +"""Regression tests for the mutation report the PR job posts as its summary. + +The report is the only thing a reviewer reads, so two failures matter more than +the rest of the rendering: a run that executed nothing must not read as a clean +sweep, and a surviving mutant in a class method must resolve to that method +rather than to whatever else in the file shares its name. +""" + +from __future__ import annotations + +import importlib.util +import sys +from pathlib import Path + +_REPO_ROOT = Path(__file__).resolve().parents[2] +_spec = importlib.util.spec_from_file_location( + "mutation_report", _REPO_ROOT / "scripts" / "mutation_report.py" +) +report = importlib.util.module_from_spec(_spec) +# dataclasses resolves a frozen class's module through sys.modules at decoration time. +sys.modules[_spec.name] = report +_spec.loader.exec_module(report) + + +SOURCE = '''\ +def handle(payload: str) -> str: + return payload + + +class Router: + def handle(self, payload: str) -> str: + return payload.strip() +''' + + +def test_class_method_mutant_resolves_to_the_class_and_method(): + parsed = report.parse_mutant_name("litellm.router.xǁRouterǁ_get_client__mutmut_11") + + assert (parsed.module, parsed.class_name, parsed.function, parsed.number) == ( + "litellm.router", + "Router", + "_get_client", + "11", + ) + assert parsed.mangled == "xǁRouterǁ_get_client" + assert parsed.qualified == "Router._get_client" + + +def test_module_level_mutant_keeps_leading_underscores(): + parsed = report.parse_mutant_name( + "litellm.proxy.common_utils.x__is_user_team_admin__mutmut_2" + ) + + assert (parsed.class_name, parsed.function, parsed.mangled) == ( + None, + "_is_user_team_admin", + "x__is_user_team_admin", + ) + + +def test_unparseable_mutant_name_is_kept_verbatim(): + parsed = report.parse_mutant_name("not-a-mutant") + + assert parsed.function == "not-a-mutant" + assert parsed.number == "?" + + +def test_class_context_picks_the_method_over_the_module_level_twin(tmp_path: Path): + """Both definitions are named `handle`; only the class context tells them apart.""" + source = tmp_path / "router.py" + source.write_text(SOURCE, encoding="utf-8") + + method = report.find_function_in_file(source, "handle", "Router") + function = report.find_function_in_file(source, "handle", None) + + assert method is not None and "payload.strip()" in method[2] + assert method[3] == [6] + assert function is not None and "payload.strip()" not in function[2] + + +def test_summarize_ignores_mutants_the_run_never_checked(): + results = ( + ("mod.x_a__mutmut_1", "killed"), + ("mod.x_a__mutmut_2", "survived"), + ("mod.x_b__mutmut_1", "not checked"), + ) + + assert report.summarize(results) == { + "total": 2, + "killed": 1, + "survived": 1, + "no_tests": 0, + "skipped": 0, + "suspicious": 0, + "timeout": 0, + } + + +def test_summarize_returns_none_when_nothing_ran(): + assert report.summarize((("mod.x_a__mutmut_1", "not checked"),)) is None + + +def test_a_run_that_checked_nothing_is_not_reported_as_a_clean_sweep(): + """mutmut crashing must not render the same green summary as a killed-everything run.""" + rendered = report.render({}, (), None) + + assert "caught every mutation" not in rendered + assert "failed run" in rendered + + +def test_a_run_with_no_survivors_still_reports_the_clean_sweep(): + rendered = report.render({}, (), {"total": 3, "killed": 3, "survived": 0}) + + assert "caught every mutation" in rendered + assert "Mutation score: **100.0%**" in rendered From 5a4c1ad504784c6b95fde6c123db8522705c784a Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Thu, 20 Aug 2026 13:14:30 -0700 Subject: [PATCH 4/6] fix(ci): fail the mutation report when the run left in-scope mutants unchecked --- .github/workflows/mutation-test-pr.yml | 3 + scripts/mutation_report.py | 73 +++++++++++++++++++--- tests/test_litellm/test_mutation_report.py | 28 +++++++++ 3 files changed, 96 insertions(+), 8 deletions(-) diff --git a/.github/workflows/mutation-test-pr.yml b/.github/workflows/mutation-test-pr.yml index addfb6eed985..ed03136c040a 100644 --- a/.github/workflows/mutation-test-pr.yml +++ b/.github/workflows/mutation-test-pr.yml @@ -98,6 +98,9 @@ jobs: run: | uv pip uninstall pytest-retry || true + # mutmut catches an interrupt and still exits 0, so its exit code separates + # nothing. The report step is what decides: it fails when a mutant this run + # asked for was never checked. - name: Run mutmut on the changed functions if: steps.scope.outputs.has_scope == 'true' continue-on-error: true diff --git a/scripts/mutation_report.py b/scripts/mutation_report.py index 9238afd3d5ae..b9b476c421b0 100644 --- a/scripts/mutation_report.py +++ b/scripts/mutation_report.py @@ -24,10 +24,14 @@ from collections import defaultdict from dataclasses import dataclass from difflib import SequenceMatcher +from fnmatch import fnmatch from pathlib import Path from textwrap import dedent ROOT = Path(__file__).resolve().parent.parent +# Written by scripts/mutation_diff_scope.py: the mutant-name globs this run was +# asked to execute. Absent for a whole-folder run, which has no such contract. +SCOPE_GLOBS_FILE = ROOT / "mutmut-scope-globs.txt" # Overridable so the report can be regenerated outside CI, where the project venv # `uv run --no-sync` expects may not exist. MUTMUT_INVOCATION = shlex.split( @@ -82,6 +86,33 @@ def get_results() -> tuple[tuple[str, str], ...]: return tuple((m.group(1), m.group(2)) for m in matches if m is not None) +def scope_globs() -> tuple[str, ...]: + if not SCOPE_GLOBS_FILE.exists(): + return () + return tuple( + stripped + for line in SCOPE_GLOBS_FILE.read_text(encoding="utf-8").splitlines() + if (stripped := line.strip()) + ) + + +def unchecked_in_scope( + results: tuple[tuple[str, str], ...], globs: tuple[str, ...] +) -> tuple[str, ...]: + """In-scope mutants the run never got to. + + mutmut swallows an interrupt and still exits 0, so its exit code cannot tell a + finished run from one that was killed halfway. What the run was asked to do is + the only reliable contract: any requested mutant left at `not checked` means + the score below covers less than the diff does. + """ + return tuple( + name + for name, status in results + if status == "not checked" and any(fnmatch(name, glob) for glob in globs) + ) + + def summarize(results: tuple[tuple[str, str], ...]) -> dict | None: """Count only the mutants this run actually executed.""" checked = tuple(status for _, status in results if status != "not checked") @@ -306,7 +337,12 @@ def render_meta_style_mutant(mutant: MutantName) -> str | None: return "\n".join(out) -def render(config: dict, survivors: tuple[str, ...], stats: dict | None) -> str: +def render( + config: dict, + survivors: tuple[str, ...], + stats: dict | None, + unchecked: tuple[str, ...] = (), +) -> str: by_function: dict[tuple[str, str | None, str], list[tuple[str, MutantName]]] = defaultdict(list) for survivor in survivors: mutant = parse_mutant_name(survivor) @@ -334,16 +370,28 @@ def render(config: dict, survivors: tuple[str, ...], stats: dict | None) -> str: else: out.append(f"- Survivors found: **{len(survivors)}**") out.append("- (no mutant results and no mutmut-cicd-stats.json)") + if unchecked: + out.append(f"- Never checked: **{len(unchecked)}** of the mutants this run asked for") out.append("") - if not survivors: + if unchecked: out.append( - "**No surviving mutants — the test suite caught every mutation.**" - if stats - else "**The mutation run produced no results at all. Treat this as a failed " + f"**The run stopped early: {len(unchecked)} in-scope mutants were never " + "checked, so the score above covers less than the diff does. Treat this " + "as a failed run.**" + ) + out.append("") + elif not stats: + out.append( + "**The mutation run produced no results at all. Treat this as a failed " "run, not as a passing one: nothing was executed to survive.**" ) out.append("") + + if not survivors: + if stats and not unchecked: + out.append("**No surviving mutants — the test suite caught every mutation.**") + out.append("") return "\n".join(out) out.append("## Surviving mutants by function") @@ -489,8 +537,9 @@ def main() -> int: results = get_results() stats = summarize(results) or fallback_stats() + unchecked = unchecked_in_scope(results, scope_globs()) survivors = tuple(name for name, status in results if status == "survived") - report = render(config, survivors, stats) + report = render(config, survivors, stats, unchecked) out_path = ROOT / "mutation-report.md" out_path.write_text(report) @@ -498,14 +547,22 @@ def main() -> int: f"Wrote {out_path} ({len(survivors)} survivor" f"{'s' if len(survivors) != 1 else ''}, {len(report)} chars)" ) + # Survivors are advisory. A run that checked nothing, or stopped partway through + # what it was asked to check, is a broken run: reporting either as a clean sweep + # is how a crashed mutmut turns into a green pull request. if stats is None: - # Survivors are advisory, but a run that checked nothing is a broken run: - # reporting it as a clean sweep is how a crashed mutmut turns into a green PR. print( "error: mutmut reported no checked mutants; the run did not complete", file=sys.stderr, ) return 1 + if unchecked: + print( + f"error: {len(unchecked)} in-scope mutants were never checked; " + f"the run did not complete (first: {unchecked[0]})", + file=sys.stderr, + ) + return 1 return 0 diff --git a/tests/test_litellm/test_mutation_report.py b/tests/test_litellm/test_mutation_report.py index a6d7a55630f5..b93d1d7c9e7f 100644 --- a/tests/test_litellm/test_mutation_report.py +++ b/tests/test_litellm/test_mutation_report.py @@ -113,3 +113,31 @@ def test_a_run_with_no_survivors_still_reports_the_clean_sweep(): assert "caught every mutation" in rendered assert "Mutation score: **100.0%**" in rendered + + +def test_in_scope_mutants_left_unchecked_are_what_marks_a_run_unfinished(): + """A killed mutmut leaves the rest at `not checked`; only the requested ones count.""" + results = ( + ("litellm.router.xǁRouterǁpick__mutmut_1", "killed"), + ("litellm.router.xǁRouterǁpick__mutmut_2", "not checked"), + ("litellm.other.x_untouched__mutmut_1", "not checked"), + ) + + assert report.unchecked_in_scope(results, ("litellm.router.xǁRouterǁpick__mutmut_*",)) == ( + "litellm.router.xǁRouterǁpick__mutmut_2", + ) + assert report.unchecked_in_scope(results, ()) == () + + +def test_a_partial_run_is_not_reported_as_a_clean_sweep(): + """3 of 27 mutants killed is not a 100% score; it is a run that stopped early.""" + rendered = report.render( + {}, + (), + {"total": 3, "killed": 3, "survived": 0}, + ("litellm.router.xǁRouterǁpick__mutmut_4",), + ) + + assert "caught every mutation" not in rendered + assert "stopped early" in rendered + assert "Never checked: **1**" in rendered From 1584f6f14c43e379de47c51d6ef3043cb9fabaa2 Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Thu, 20 Aug 2026 13:36:28 -0700 Subject: [PATCH 5/6] fix(ci): drop deletions with no surviving line above them instead of blaming the next function --- scripts/mutation_diff_scope.py | 8 +++--- .../test_litellm/test_mutation_diff_scope.py | 25 +++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/scripts/mutation_diff_scope.py b/scripts/mutation_diff_scope.py index 694b4a9d4bb7..b03b7e23f9a2 100644 --- a/scripts/mutation_diff_scope.py +++ b/scripts/mutation_diff_scope.py @@ -103,7 +103,9 @@ def parse_unified_diff(root: Path, diff: str) -> tuple[ChangedFile, ...]: Deleted lines have no post-image line of their own, so they are attributed to the line they now follow: under ``-U0`` that is the hunk header's ``+`` start, which is the surviving line directly above the deletion. Without this, removing - a guard clause would leave its function out of scope entirely. + a guard clause would leave its function out of scope entirely. A deletion that + starts at the top of the file has no such line, and nothing above it to blame, + so it is dropped rather than charged to whatever moved up into its place. """ def touched_lines() -> Iterator[tuple[str, int]]: @@ -119,8 +121,8 @@ def touched_lines() -> Iterator[tuple[str, int]]: elif line.startswith("+") and not line.startswith("+++"): yield current, cursor cursor += 1 - elif line.startswith("-") and not line.startswith("---"): - yield current, max(cursor, 1) + elif line.startswith("-") and not line.startswith("---") and cursor >= 1: + yield current, cursor touched: Final = tuple(touched_lines()) return tuple( diff --git a/tests/test_litellm/test_mutation_diff_scope.py b/tests/test_litellm/test_mutation_diff_scope.py index d72675720331..91f1e99a8d59 100644 --- a/tests/test_litellm/test_mutation_diff_scope.py +++ b/tests/test_litellm/test_mutation_diff_scope.py @@ -176,6 +176,31 @@ def test_deletion_only_change_still_selects_the_function(repo: Path) -> None: assert scope.globs == ("litellm.proxy.auth.auth_checks.x_can_call_model__mutmut_*",) +def test_deleting_a_functions_last_statement_still_selects_it(repo: Path) -> None: + """The line above the deletion is the anchor, so a trailing deletion stays inside its function.""" + two_statements = AUTH_CHECKS.replace( + " return model in allowed\n", + " normalized = model.strip()\n return normalized in allowed\n", + ) + _write(repo, "litellm/proxy/auth/auth_checks.py", two_statements) + _commit(repo, "add a statement") + _run(repo, "checkout", "-q", "-b", "trailing-removal") + _write(repo, "litellm/proxy/auth/auth_checks.py", two_statements.replace(" return normalized in allowed\n", "")) + _commit(repo, "drop the return") + + scope = build_scope(repo, "feature", 40) + + assert scope.globs == ("litellm.proxy.auth.auth_checks.x_can_call_model__mutmut_*",) + + +def test_deleting_a_whole_function_does_not_drag_in_its_neighbour(repo: Path) -> None: + """Deleted code has nothing to mutate; charging it to whatever moved up would be noise.""" + _write(repo, "litellm/router.py", ROUTER[ROUTER.index("class Router:") :]) + _commit(repo) + + assert scope_of(repo).globs == () + + def test_module_level_change_selects_no_function(repo: Path) -> None: """mutmut only trampolines functions, so a module-level constant has nothing to run.""" _write(repo, "litellm/proxy/auth/auth_checks.py", AUTH_CHECKS.replace('"user"', '"internal_user"')) From e810dfa827179c1ea85fd694e75d8494c10bba14 Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Thu, 20 Aug 2026 16:50:44 -0700 Subject: [PATCH 6/6] fix(ci): stop the diff scope from selecting the whole unit suite Timing the gate against three real open pull requests turned up two ways the test selection went wide. A private module never matched its test file, since litellm/_redis.py globs test__redis*.py while the file is test_redis.py, and the miss fell through to the mirror directory. For a module at the top of litellm/ that directory is tests/test_litellm itself, so every mutant would have run the entire unit suite. The same fallback pulled all of tests/test_litellm/caching into a caching diff and picked up an unrelated order-dependent s3 test, which fails on an unmutated tree and aborts the run before a single mutant executes. Private modules now also try the underscore-stripped spelling, and the directory fallback stops at the mirror root instead of returning it. Overload stubs are deduplicated too: they repeat the implementation's name, so a touched signature asked for the same function three times and burned three slots of --max-functions. --- scripts/mutation_diff_scope.py | 20 +++++-- .../test_litellm/test_mutation_diff_scope.py | 60 +++++++++++++++++++ 2 files changed, 76 insertions(+), 4 deletions(-) diff --git a/scripts/mutation_diff_scope.py b/scripts/mutation_diff_scope.py index b03b7e23f9a2..89ba51a28295 100644 --- a/scripts/mutation_diff_scope.py +++ b/scripts/mutation_diff_scope.py @@ -143,13 +143,24 @@ def changed_test_files(root: Path, diff: str) -> tuple[str, ...]: def mapped_tests(root: Path, path: str) -> tuple[str, ...]: - """Find the tests mirroring a production file, per tests/test_litellm/readme.md.""" + """Find the tests mirroring a production file, per tests/test_litellm/readme.md. + + A private module drops its leading underscores on the way to a test name, so + ``litellm/_redis.py`` is covered by ``test_redis.py``. Missing that spelling used + to fall through to the directory, and for a module at the top of ``litellm/`` the + directory is the entire unit suite: every mutant would run all of it. + """ relative: Final = Path(path).relative_to("litellm") mirror_dir: Final = Path(TEST_MIRROR_ROOT) / relative.parent - named: Final = tuple(sorted(str(p.relative_to(root)) for p in (root / mirror_dir).glob(f"test_{relative.stem}*.py"))) + stems: Final = (relative.stem, relative.stem.lstrip("_")) + named: Final = tuple( + sorted({str(p.relative_to(root)) for stem in stems for p in (root / mirror_dir).glob(f"test_{stem}*.py")}) + ) if named: return named - return (str(mirror_dir),) if (root / mirror_dir).is_dir() else () + if mirror_dir == Path(TEST_MIRROR_ROOT) or not (root / mirror_dir).is_dir(): + return () + return (str(mirror_dir),) def trampoline_units(source: str) -> tuple[TrampolineUnit, ...]: @@ -200,7 +211,8 @@ def build_scope(root: Path, base: str, max_functions: int) -> Scope: merge_base: Final = _git(root, "merge-base", base, "HEAD").strip() diff: Final = _git(root, "diff", "-U0", merge_base, "--", ".") files: Final = parse_unified_diff(root, diff) - all_globs: Final = tuple(glob for changed in files for glob in globs_for(root, changed)) + # `@overload` stubs repeat their implementation's name, and mutmut mangles them all the same way. + all_globs: Final = tuple(dict.fromkeys(glob for changed in files for glob in globs_for(root, changed))) tests: Final = tuple( sorted({*(t for changed in files for t in mapped_tests(root, changed.path)), *changed_test_files(root, diff)}) ) diff --git a/tests/test_litellm/test_mutation_diff_scope.py b/tests/test_litellm/test_mutation_diff_scope.py index 91f1e99a8d59..b0dc51d79f0c 100644 --- a/tests/test_litellm/test_mutation_diff_scope.py +++ b/tests/test_litellm/test_mutation_diff_scope.py @@ -94,6 +94,35 @@ def coerce(value: str) -> str: return value ''' +REDIS = '''\ +def get_redis_client(url: str) -> str: + return url +''' + +OVERLOADED = '''\ +from typing import overload + + +@overload +def embedding( + model: str, + stream: bool, +) -> str: ... + + +@overload +def embedding( + model: str, +) -> str: ... + + +def embedding( + model: str, + stream: bool = False, +) -> str: + return model +''' + def _run(root: Path, *args: str) -> None: subprocess.run(("git", *args), cwd=root, check=True, capture_output=True) @@ -116,6 +145,11 @@ def repo(tmp_path: Path) -> Path: _write(root, "litellm/router.py", ROUTER) _write(root, "litellm/proxy/auth/auth_checks.py", AUTH_CHECKS) _write(root, "litellm/types/utils.py", TYPES) + _write(root, "litellm/_redis.py", REDIS) + _write(root, "litellm/_unmapped.py", REDIS) + _write(root, "litellm/main.py", OVERLOADED) + _write(root, "tests/test_litellm/test_redis.py", "def test_redis(): pass\n") + _write(root, "tests/test_litellm/test_main.py", "def test_main(): pass\n") _write(root, "tests/test_litellm/test_router.py", "def test_router(): pass\n") _write(root, "tests/test_litellm/proxy/auth/test_auth_checks.py", "def test_auth(): pass\n") _write(root, "tests/e2e/test_live_proxy.py", "def test_live(): pass\n") @@ -238,6 +272,32 @@ def test_test_selection_is_the_mirrored_file_plus_changed_unit_tests(repo: Path) ) +def test_private_module_maps_to_its_test_file_without_the_underscore(repo: Path) -> None: + """`litellm/_redis.py` is covered by `test_redis.py`, not `test__redis.py`.""" + _write(repo, "litellm/_redis.py", REDIS.replace("return url", "return url.strip()")) + _commit(repo) + + assert scope_of(repo).tests == ("tests/test_litellm/test_redis.py",) + + +def test_an_unmapped_top_level_module_never_selects_the_whole_unit_suite(repo: Path) -> None: + """Falling back to tests/test_litellm would run every unit test once per mutant.""" + _write(repo, "litellm/_unmapped.py", REDIS.replace("return url", "return url.strip()")) + _commit(repo) + + scope = scope_of(repo) + assert scope.globs, "the changed function still has to be reported" + assert scope.tests == () + + +def test_overloaded_function_is_requested_once(repo: Path) -> None: + """@overload stubs share the implementation's mangled name, so repeating it just burns the cap.""" + _write(repo, "litellm/main.py", OVERLOADED.replace(" model: str,", " model: str | None,")) + _commit(repo) + + assert scope_of(repo).globs == ("litellm.main.x_embedding__mutmut_*",) + + def test_e2e_tests_are_excluded_from_the_selection(repo: Path) -> None: """tests/e2e needs a live proxy; including one aborts the run at mutmut's clean-test check.""" _write(repo, "litellm/router.py", ROUTER.replace("if m]", "if m and m.strip()]"))