Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(tests): rank reaching tests by distance before the per-target cap (#4321)
Raghav Chamadiyaee8f79ab61d7
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.pyindex e6da37844..a46e64489 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py@@ -35,7 +35,7 @@ from repowise.core.analysis.test_reachability import (MAX_TESTS_PER_TARGET,ReachDistance,ReachedBy,- rank_tests,+ rank_reaching,)from repowise.core.code_origin import ship_rankfrom repowise.core.test_paths import is_test_support_path, names_test_for, paired_test_names@@ -1465,7 +1465,7 @@ def _expand_scopes(path: str, reached: ReachedBy, expanded: list[str]) -> Reachefound = reached.all_tests or tuple(reached.tests)if tuple(expanded) == tuple(found):return reached- ranked = rank_tests(path, expanded)+ ranked = rank_reaching(path, expanded, reach=reached.reach)return dataclasses.replace(reached,tests=ranked[:MAX_TESTS_PER_TARGET],diff --git a/packages/core/src/repowise/core/analysis/test_impact.py b/packages/core/src/repowise/core/analysis/test_impact.pyindex 0c315ca2a..169b3624a 100644--- a/packages/core/src/repowise/core/analysis/test_impact.py+++ b/packages/core/src/repowise/core/analysis/test_impact.py@@ -8,6 +8,7 @@ from an empty recommendation population.from __future__ import annotations+import sysfrom collections import defaultdictfrom collections.abc import Collection, Iterable, Mapping, Sequencefrom typing import Any@@ -16,7 +17,7 @@ from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.health.coverage.freshness import coverage_freshness-from repowise.core.analysis.test_reachability import MAX_TESTS_PER_TARGET, rank_tests+from repowise.core.analysis.test_reachability import MAX_TESTS_PER_TARGET, rank_reachingfrom repowise.core.analysis.test_selection import expand_test_scopesfrom repowise.core.exclusion import is_excludedfrom repowise.core.persistence.models import Repository@@ -60,15 +61,6 @@ _FRESHNESS_REASONS: dict[str, str | None] = {}-def _recommendation_sort_key(row: dict[str, Any]) -> tuple[int, int, str, str]:- return (- -len(row["source_files"]),- _BASIS_ORDER[row["basis"]],- row["repository"],- row["test_id"],- )--async def analyze_test_impact(session: AsyncSession,repository_id: str,@@ -169,7 +161,11 @@ async def _read_inferred(reached_by_file = {}inference_error = type(exc).__name__inferred = {- path: {"tests": list(reached.all_tests or reached.tests), "via": reached.via}+ path: {+ "tests": list(reached.all_tests or reached.tests),+ "via": reached.via,+ "reach": reached.reach,+ }for path, reached in reached_by_file.items()}if inference_error is None:@@ -215,10 +211,11 @@ def assemble_test_impact(when *coverage_summary* reports pairs. *inferred_by_file* maps a changed pathto ``{"tests": [...], "via": tier}``, both keys required, with ``tests`` theuncapped list (``ReachedBy.all_tests``, not the display-capped ``tests``), and- ``narrowed`` true when a reached conftest was already resolved to its tests;- paths outside *changed_files* are ignored. That list is used as the walk- found it, except where a scope file expanded (below). *coverage_summary* carries- ``pair_count``, ``test_count``, ``source_file_count``, ``ingested_at``,+ ``narrowed`` true when a reached conftest was already resolved to its tests,+ and optional ``reach`` (``ReachedBy.reach``); paths outside *changed_files*+ are ignored. That list is used in the walk's order, except where a scope+ file expanded (below), and inferred recommendations keep that order.+ *coverage_summary* carries ``pair_count``, ``test_count``, ``source_file_count``, ``ingested_at``,``source_format`` and ``ingested_commit_sha``. The ``*_error`` argumentsare the exception type names of a failed read; each marks the analysis degraded.*changed_files* is filtered by *exclude_spec* here too.@@ -289,6 +286,8 @@ def assemble_test_impact(inferred_tests_by_file: dict[str, list[str]] = {path: [] for path in changed}evidence: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list)test_files: dict[tuple[str, str], set[str]] = defaultdict(set)+ # Each inferred test's best place in a walk's ranked list (rank_reaching).+ walk_order: dict[tuple[str, str], int] = {}summary = coverage_summarymap_present = summary.get("pair_count", 0) > 0@@ -335,10 +334,14 @@ def assemble_test_impact(if reached.get("narrowed") or expanded != list(reached["tests"]):# A root conftest stands for every test in the repository: rank the# expansion nearest-first and keep the walk's own per-target cap.- kept_tests = rank_tests(path, kept_tests)[:MAX_TESTS_PER_TARGET]- for test_id in kept_tests:+ kept_tests = rank_reaching(+ path, kept_tests, reach=reached.get("reach"), changed=changed+ )+ kept_tests = kept_tests[:MAX_TESTS_PER_TARGET]+ for place, test_id in enumerate(kept_tests):inferred_tests_by_file[path].append(test_id)key = (repository_id, test_id)+ walk_order[key] = min(walk_order.get(key, place), place)test_files[key].add(test_id)detail = {"basis": "inferred",@@ -373,7 +376,15 @@ def assemble_test_impact("evidence": details,})- recommendations.sort(key=_recommendation_sort_key)+ recommendations.sort(+ key=lambda row: (+ -len(row["source_files"]),+ _BASIS_ORDER[row["basis"]],+ row["repository"],+ walk_order.get((row["repository_id"], row["test_id"]), sys.maxsize),+ row["test_id"],+ )+ )matched_files = sum(bool(tests) for tests in measured_tests_by_file.values())coverage_reason: str | Nonediff --git a/packages/core/src/repowise/core/analysis/test_reachability.py b/packages/core/src/repowise/core/analysis/test_reachability.pyindex ac9121a2d..d609efa18 100644--- a/packages/core/src/repowise/core/analysis/test_reachability.py+++ b/packages/core/src/repowise/core/analysis/test_reachability.py@@ -148,7 +148,8 @@ over data already in the database.from __future__ import annotationsimport json-from collections.abc import Collection, Mapping+import sys+from collections.abc import Collection, Iterable, Mappingfrom dataclasses import dataclassfrom pathlib import PurePosixPathfrom typing import Any, Literal, NamedTuple, TypeAlias@@ -211,7 +212,7 @@ __all__ = ["imported_names_by_test","load_import_graph","load_test_files",- "rank_tests",+ "rank_reaching","reach_into_symbols","tests_matching_by_name","tests_reaching",@@ -238,8 +239,7 @@ class ReachedBy:``total`` is how many the walk actually found, before``MAX_TESTS_PER_TARGET`` trimmed ``tests``. A surface that prints``len(tests)`` as the answer is stating a cap as a measurement. The cut keeps- the test named for the target and its directory neighbours first- (:func:`rank_tests`). Carry the total and say the bound.+ the closest tests (:func:`rank_reaching`). Carry the total and say the bound."""tests: list[str]@@ -517,7 +517,7 @@ async def tests_reaching_through_helpers(reached.setdefault(target, set()).update(tests)out: dict[str, ReachedBy] = {}for target, tests in reached.items():- ordered = tuple(rank_tests(target, tests))+ ordered = tuple(rank_reaching(target, tests, changed=targets))out[target] = ReachedBy(list(ordered[:MAX_TESTS_PER_TARGET]), "import-graph", len(ordered), ordered)@@ -699,12 +699,13 @@ async def tests_reaching_by_tier(return {}out: dict[str, ReachedBy] = {}+ # The targets are usually a change's files; a test among them leads every list.if call_depth >= 1:found = await _call_reaching(session, repo_id, seeds, test_files, call_depth, symbol_seeds=symbol_seeds, avoid=avoid)for seed, reach in found.items():- ordered = tuple(rank_tests(seed.split("::", 1)[0], reach))+ ordered = tuple(rank_reaching(seed, reach, reach=reach, changed=seeds))out[seed] = ReachedBy(list(ordered[:MAX_TESTS_PER_TARGET]), "call-graph", len(ordered), ordered, reach)@@ -715,7 +716,10 @@ async def tests_reaching_by_tier(session, repo_id, unanswered, test_files, import_depth, import_graph)for seed, tests in found.items():- ordered = tuple(rank_tests(seed.split("::", 1)[0], tests))+ # A test importing the target itself, not a file on the way to it.+ file = seed.split("::", 1)[0]+ direct = {t for t, via in entries[seed].items() if file in via}+ ordered = tuple(rank_reaching(seed, tests, direct=direct, changed=seeds))out[seed] = ReachedBy(list(ordered[:MAX_TESTS_PER_TARGET]),"import-graph",@@ -1206,15 +1210,41 @@ async def _edges_into(return out-def rank_tests(target: str, tests: Collection[str]) -> list[str]:- """*tests* with the one named for *target* first, then by how much of its directory- path each mirrors, so a capped list keeps the test most likely to exercise it."""- names = paired_test_names(target)- dirs = set(target.split("/")[:-1])+def rank_reaching(+ target: str,+ tests: Iterable[str],+ *,+ reach: Mapping[str, ReachDistance] | None = None,+ direct: Collection[str] = frozenset(),+ changed: Collection[str] = frozenset(),+) -> list[str]:+ """*tests* reaching *target*, the likeliest to exercise it first. Cap after this.++ In turn: a test in *changed* (the change edits it), fewer call hops+ (*reach*; a test without one sorts after every test with one), a test in+ *direct* (it imports or calls *target* itself), more of the test's+ functions at that distance, then by name: the test named for *target*,+ the one mirroring more of its directories, and the path. Targets, tests+ and *changed* may be ``path::name`` ids; every key reads the file part.+ """+ path_of = target.split("::", 1)[0]+ names = paired_test_names(path_of)+ dirs = set(path_of.split("/")[:-1])+ reach = reach or {}+ edited = {c.split("::", 1)[0] for c in changed}- def key(test: str) -> tuple[bool, int, str]:+ def key(test: str) -> tuple[bool, int, bool, int, bool, int, str]:path = test.split("::", 1)[0]- return path.rsplit("/", 1)[-1] not in names, -len(dirs & set(path.split("/")[:-1])), test+ distance = reach.get(test) or reach.get(path)+ return (+ path not in edited,+ distance.hops if distance else sys.maxsize,+ test not in direct and path not in direct,+ -distance.callers if distance else 0,+ path.rsplit("/", 1)[-1] not in names,+ -len(dirs & set(path.split("/")[:-1])),+ test,+ )return sorted(tests, key=key)@@ -1231,7 +1261,7 @@ def tests_matching_by_name(targets: list[str], test_files: Collection[str]) -> dby_name.setdefault(path.rsplit("/", 1)[-1], []).append(path)out: dict[str, ReachedBy] = {}for target in targets:- found = rank_tests(+ found = rank_reaching(target, [path for name in paired_test_names(target) for path in by_name.get(name, ())])if found:diff --git a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py b/packages/server/src/repowise/server/routers/code_health/coverage_routes.pyindex 27717d246..93f8b929b 100644--- a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py+++ b/packages/server/src/repowise/server/routers/code_health/coverage_routes.py@@ -343,7 +343,7 @@ async def health_tests_reaching("reached": True,"tests": reached.tests,"via": reached.via,- # The walk's own count, which ``tests`` may be a trimmed alphabetical+ # The walk's own count, which ``tests`` may be a ranked, trimmed# slice of. Without it a caller renders the cap as the answer."total": total,"truncated": total > len(reached.tests),diff --git a/tests/unit/analysis/test_assemble_test_impact.py b/tests/unit/analysis/test_assemble_test_impact.pyindex 3305cef43..2e8132018 100644--- a/tests/unit/analysis/test_assemble_test_impact.py+++ b/tests/unit/analysis/test_assemble_test_impact.py@@ -128,3 +128,42 @@ def test_nothing_changed() -> None:impact = assemble_test_impact([], {}, {}, {}, repository_id="r1")assert impact["files"] == []assert impact["coverage"]["reason"] == "no_changed_files"+++def test_inferred_recommendations_keep_the_walk_order() -> None:+ """The walk ranked closest first; the recommendations do not re-sort by name."""+ impact = assemble_test_impact(+ ["src/a.py"],+ {},+ {"src/a.py": {"tests": ["tests/z/test_near.py", "tests/a/test_far.py"], "via": "call-graph"}},+ {},+ repository_id="r1",+ )+ assert [r["test_id"] for r in impact["recommendations"]] == [+ "tests/z/test_near.py",+ "tests/a/test_far.py",+ ]+++def test_an_expanded_scope_ranks_by_the_walk_distance() -> None:+ from repowise.core.analysis.test_reachability import ReachDistance++ impact = assemble_test_impact(+ ["src/core.py"],+ {},+ {+ "src/core.py": {+ "tests": ["conftest.py", "tests/z/test_near.py"],+ "via": "call-graph",+ "reach": {"tests/z/test_near.py": ReachDistance(1, 1)},+ }+ },+ {},+ repository_id="r1",+ repository_test_files={"conftest.py", "tests/a/test_core.py", "tests/z/test_near.py"},+ )+ assert impact["files"][0]["inferred_tests"] == ["tests/a/test_core.py", "tests/z/test_near.py"]+ assert [r["test_id"] for r in impact["recommendations"]] == [+ "tests/z/test_near.py",+ "tests/a/test_core.py",+ ]diff --git a/tests/unit/analysis/test_test_reachability.py b/tests/unit/analysis/test_test_reachability.pyindex cd3d9da90..833d07c90 100644--- a/tests/unit/analysis/test_test_reachability.py+++ b/tests/unit/analysis/test_test_reachability.py@@ -14,10 +14,13 @@ import pytestfrom repowise.core.analysis.test_reachability import (DEFAULT_CALL_DEPTH,+ MAX_TESTS_PER_TARGET,CallGraphView,+ ReachDistance,call_graph_from_graph,files_reached_by_tests,files_with_paired_tests,+ rank_reaching,)@@ -217,3 +220,80 @@ def test_a_name_match_holds_through_a_barrel_or_when_the_graph_is_silent() -> Noassert files_with_paired_tests(None, {"src/lonely.py"}, {"tests/test_lonely.py"}) == {"src/lonely.py"}+++# ---------------------------------------------------------------------------+# rank_reaching: the order a capped reverse list keeps+# ---------------------------------------------------------------------------+++def test_rank_puts_a_test_the_change_edits_first() -> None:+ reach = {"tests/test_far.py": ReachDistance(3, 1), "tests/test_near.py": ReachDistance(1, 1)}+ ranked = rank_reaching(+ "src/a.py", reach, reach=reach, changed={"src/a.py", "tests/test_far.py::test_x"}+ )+ assert ranked == ["tests/test_far.py", "tests/test_near.py"]+++def test_rank_puts_fewer_hops_before_more_callers_and_names() -> None:+ reach = {+ "tests/test_a.py": ReachDistance(3, 9),+ "tests/zz/test_b.py": ReachDistance(1, 1),+ "tests/test_mid.py": ReachDistance(2, 1),+ }+ assert rank_reaching("src/a.py", reach, reach=reach) == [+ "tests/zz/test_b.py",+ "tests/test_mid.py",+ "tests/test_a.py",+ ]+++def test_rank_puts_a_test_without_a_distance_after_every_measured_one() -> None:+ reach = {"tests/zz/test_far.py": ReachDistance(5, 1)}+ assert rank_reaching("src/a.py", ["tests/test_a.py", "tests/zz/test_far.py"], reach=reach) == [+ "tests/zz/test_far.py",+ "tests/test_a.py",+ ]+++def test_rank_puts_a_direct_importer_before_a_transitive_one() -> None:+ tests = ["tests/test_a.py", "tests/zz/test_direct.py"]+ assert rank_reaching("src/a.py", tests, direct={"tests/zz/test_direct.py"}) == [+ "tests/zz/test_direct.py",+ "tests/test_a.py",+ ]+++def test_rank_breaks_a_hop_tie_by_callers() -> None:+ reach = {"tests/test_a.py": ReachDistance(2, 1), "tests/zz/test_b.py": ReachDistance(2, 4)}+ assert rank_reaching("src/a.py", reach, reach=reach) == [+ "tests/zz/test_b.py",+ "tests/test_a.py",+ ]+++def test_rank_falls_back_to_the_name_then_the_path() -> None:+ tests = ["tests/zz/test_b.py", "tests/test_other.py", "tests/zz/test_a.py", "src/test_x.py"]+ # Named for the target first, then directory overlap with it, then path.+ assert rank_reaching("src/x.py", tests) == [+ "src/test_x.py",+ "tests/test_other.py",+ "tests/zz/test_a.py",+ "tests/zz/test_b.py",+ ]+++def test_rank_reads_the_file_part_of_symbol_targets_and_test_ids() -> None:+ reach = {"tests/test_a.py": ReachDistance(1, 1), "tests/test_b.py": ReachDistance(2, 1)}+ ranked = rank_reaching(+ "src/a.py::run", ["tests/test_b.py::t", "tests/test_a.py::t"], reach=reach+ )+ assert ranked == ["tests/test_a.py::t", "tests/test_b.py::t"]+++def test_a_cap_after_rank_keeps_the_closest_tests() -> None:+ """A hub's direct tests sort after many path-earlier far ones by name alone."""+ reach = {f"tests/a/test_{i:03}.py": ReachDistance(3, 1) for i in range(MAX_TESTS_PER_TARGET)}+ reach["tests/z/test_direct.py"] = ReachDistance(1, 1)+ kept = rank_reaching("src/hub.py", reach, reach=reach)[:MAX_TESTS_PER_TARGET]+ assert kept[0] == "tests/z/test_direct.py"diff --git a/tests/unit/health/test_paired_test_basenames.py b/tests/unit/health/test_paired_test_basenames.pyindex 47963dddb..9826b363a 100644--- a/tests/unit/health/test_paired_test_basenames.py+++ b/tests/unit/health/test_paired_test_basenames.py@@ -171,9 +171,9 @@ def test_name_match_tier_finds_tests_named_for_a_target_anywhere():def test_unnamed_tests_rank_by_the_directories_they_share_with_the_target():- from repowise.core.analysis.test_reachability import rank_tests+ from repowise.core.analysis.test_reachability import rank_reaching- ranked = rank_tests("pkg/a/b/mod.py", ["pkg/x/test_other.py", "pkg/a/b/test_sibling.py"])+ ranked = rank_reaching("pkg/a/b/mod.py", ["pkg/x/test_other.py", "pkg/a/b/test_sibling.py"])assert ranked == ["pkg/a/b/test_sibling.py", "pkg/x/test_other.py"]diff --git a/tests/unit/persistence/golden/test_impact.json b/tests/unit/persistence/golden/test_impact.jsonindex a9acad32b..b4e0af095 100644--- a/tests/unit/persistence/golden/test_impact.json+++ b/tests/unit/persistence/golden/test_impact.json@@ -654,7 +654,7 @@"evidence": [{"basis": "inferred",- "source_file": "src/inferred.py",+ "source_file": "src/both.py","source_format": null,"via": "import-graph"}@@ -662,10 +662,10 @@"repository": "<bare>","repository_id": "<bare>","source_files": [- "src/inferred.py"+ "src/both.py"],- "test_file": "tests/excluded/test_hidden.py",- "test_id": "tests/excluded/test_hidden.py"+ "test_file": "tests/test_both_inferred.py",+ "test_id": "tests/test_both_inferred.py"},{"bases": [@@ -675,7 +675,7 @@"evidence": [{"basis": "inferred",- "source_file": "src/both.py",+ "source_file": "src/inferred.py","source_format": null,"via": "import-graph"}@@ -683,10 +683,10 @@"repository": "<bare>","repository_id": "<bare>","source_files": [- "src/both.py"+ "src/inferred.py"],- "test_file": "tests/test_both_inferred.py",- "test_id": "tests/test_both_inferred.py"+ "test_file": "tests/test_inferred.py",+ "test_id": "tests/test_inferred.py"},{"bases": [@@ -706,8 +706,8 @@"source_files": ["src/inferred.py"],- "test_file": "tests/test_inferred.py",- "test_id": "tests/test_inferred.py"+ "test_file": "tests/excluded/test_hidden.py",+ "test_id": "tests/excluded/test_hidden.py"}],"recommendations_by_primary_basis": {@@ -1207,7 +1207,7 @@"evidence": [{"basis": "inferred",- "source_file": "src/inferred.py",+ "source_file": "src/both.py","source_format": null,"via": "import-graph"}@@ -1215,10 +1215,10 @@"repository": "<stale>","repository_id": "<stale>","source_files": [- "src/inferred.py"+ "src/both.py"],- "test_file": "tests/excluded/test_hidden.py",- "test_id": "tests/excluded/test_hidden.py"+ "test_file": "tests/test_both_inferred.py",+ "test_id": "tests/test_both_inferred.py"},{"bases": [@@ -1228,7 +1228,7 @@"evidence": [{"basis": "inferred",- "source_file": "src/both.py",+ "source_file": "src/inferred.py","source_format": null,"via": "import-graph"}@@ -1236,10 +1236,10 @@"repository": "<stale>","repository_id": "<stale>","source_files": [- "src/both.py"+ "src/inferred.py"],- "test_file": "tests/test_both_inferred.py",- "test_id": "tests/test_both_inferred.py"+ "test_file": "tests/test_inferred.py",+ "test_id": "tests/test_inferred.py"},{"bases": [@@ -1259,8 +1259,8 @@"source_files": ["src/inferred.py"],- "test_file": "tests/test_inferred.py",- "test_id": "tests/test_inferred.py"+ "test_file": "tests/excluded/test_hidden.py",+ "test_id": "tests/excluded/test_hidden.py"}],"recommendations_by_primary_basis": {diff --git a/tests/unit/persistence/test_test_reachability_walk.py b/tests/unit/persistence/test_test_reachability_walk.pyindex 507b5fb54..54ad70e12 100644--- a/tests/unit/persistence/test_test_reachability_walk.py+++ b/tests/unit/persistence/test_test_reachability_walk.py@@ -808,3 +808,64 @@ async def test_a_node_listed_twice_across_batches_reads_its_edges_once(async_sesassert out == [("tests/test_a.py", "src/a.py")]names = await _imported_names(async_session, repo.id, ["src/a.py", *padding, "src/a.py"])assert names == [("tests/test_a.py", "src/a.py", frozenset())]+++async def test_the_capped_list_keeps_the_closest_tests_and_a_changed_test(+ async_session, monkeypatch+):+ """Ranked before the cap: a direct caller survives many path-earlier far ones,+ and a test that is itself a target leads."""+ from repowise.core.analysis import test_reachability as tr++ monkeypatch.setattr(tr, "MAX_TESTS_PER_TARGET", 2)+ far = [f"tests/a/test_far_{i}.py" for i in range(3)]+ edges = [+ ("src/hub.py", "src/hub.py::run", "defines"),+ ("src/mid.py", "src/mid.py::go", "defines"),+ ("src/mid.py::go", "src/hub.py::run", "calls"),+ *_calls("tests/z/test_direct.py", "src/hub.py"),+ ]+ for test in [*far, "tests/z/test_edited.py"]:+ edges += [+ (test, f"{test}::test_it", "defines"),+ (f"{test}::test_it", "src/mid.py::go", "calls"),+ ]+ tests = [*far, "tests/z/test_direct.py", "tests/z/test_edited.py"]+ repo = await insert_repo(async_session)+ await _seed(+ async_session,+ repo.id,+ nodes={**dict.fromkeys(tests, True), "src/hub.py": False, "src/mid.py": False},+ edges=edges,+ )+ found = await by_tier(async_session, repo.id, ["src/hub.py"])+ assert found["src/hub.py"].tests == ["tests/z/test_direct.py", far[0]]+ assert found["src/hub.py"].total == 5++ found = await by_tier(async_session, repo.id, ["src/hub.py", "tests/z/test_edited.py"])+ assert found["src/hub.py"].tests == ["tests/z/test_edited.py", "tests/z/test_direct.py"]+++async def test_the_import_tier_keeps_a_direct_importer_before_the_cap(async_session, monkeypatch):+ from repowise.core.analysis import test_reachability as tr++ monkeypatch.setattr(tr, "MAX_TESTS_PER_TARGET", 1)+ repo = await insert_repo(async_session)+ await _seed(+ async_session,+ repo.id,+ nodes={+ "tests/a/test_via_facade.py": True,+ "tests/z/test_direct.py": True,+ "src/api.py": False,+ "src/core.py": False,+ },+ edges=[+ ("tests/a/test_via_facade.py", "src/api.py", "imports"),+ ("src/api.py", "src/core.py", "imports"),+ ("tests/z/test_direct.py", "src/core.py", "imports"),+ ],+ )+ found = await by_tier(async_session, repo.id, ["src/core.py"], call_depth=0, import_depth=2)+ assert found["src/core.py"].tests == ["tests/z/test_direct.py"]+ assert found["src/core.py"].total == 2diff --git a/tests/unit/server/mcp/test_change_risk.py b/tests/unit/server/mcp/test_change_risk.pyindex eed84d6f4..352990930 100644--- a/tests/unit/server/mcp/test_change_risk.py+++ b/tests/unit/server/mcp/test_change_risk.py@@ -451,6 +451,71 @@ async def test_impacted_tests_falls_back_to_the_graph_without_a_map(tmp_path, moassert it["summary"] == "1 test(s) to run for this change, every test file there is."+async def test_a_test_file_the_change_edits_leads_the_inferred_run_list(tmp_path, monkeypatch):+ """Twelve broad tests import both changed sources; the one test file the+ change edits imports one. It still leads, inside the ten shown."""+ from repowise.core.persistence.models import GraphEdge, GraphNode++ repo = tmp_path / "repo"+ repo.mkdir()+ _git(["init", "-q"], repo)+ generic = [f"tests/test_aaa_generic_{i:02}.py" for i in range(12)]+ edited = "tests/test_duplication.py"+ _commit(+ repo,+ {+ "src/dup.py": "a\n",+ "src/tok.py": "a\n",+ edited: "from src import dup\n",+ **dict.fromkeys(generic, "from src import dup, tok\n"),+ },+ "chore: seed",+ )+ _commit(+ repo,+ {"src/dup.py": "a\nb\n", "src/tok.py": "a\nb\n", edited: "from src import dup\n\n"},+ "feat: edit",+ )++ factory = await _factory_with_repo(None, head_commit=_sha(repo, "HEAD~1"))+ async with factory() as s:+ for path in (*generic, edited, "src/dup.py", "src/tok.py"):+ is_test = path.startswith("tests/")+ s.add(+ GraphNode(+ repository_id="repo1",+ node_id=path,+ node_type="file",+ is_test=is_test,+ always_run_reason="" if is_test else None,+ )+ )+ imports = [(edited, "src/dup.py")]+ imports += [(t, src) for t in generic for src in ("src/dup.py", "src/tok.py")]+ for source, target in imports:+ s.add(+ GraphEdge(+ repository_id="repo1",+ source_node_id=source,+ target_node_id=target,+ edge_type="imports",+ )+ )+ await s.commit()++ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")++ async def _context(_: str | None) -> SimpleNamespace:+ return SimpleNamespace(path=str(repo), session_factory=factory)++ monkeypatch.setattr(module, "_resolve_repo_context", _context)+ it = (await module.get_change_risk(baseline=0))["impacted_tests"]++ assert it["basis"] == "inferred"+ assert it["tests_to_run"][0] == edited+ assert len(it["tests_to_run"]) == 10++@pytest.mark.parametrize(("files", "summary"),[