Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(tests): batch the IN lists of test-reachability edge reads (#3933)

Laentir Valetov80d88c58a127
diff --git a/packages/core/src/repowise/core/analysis/test_reachability.py b/packages/core/src/repowise/core/analysis/test_reachability.py
index 8c1a97e16..9377f0f05 100644
--- a/packages/core/src/repowise/core/analysis/test_reachability.py
+++ b/packages/core/src/repowise/core/analysis/test_reachability.py
@@ -942,27 +942,34 @@ async def _imported_names(
session: AsyncSession, repo_id: str, targets: list[str]
) -> list[tuple[str, str, frozenset[str]]]:
"""``(importer, imported file, names)`` for every import edge into *targets*."""
- params: dict[str, Any] = {"repo_id": repo_id}
- tgt = _in_clause("p", targets, params)
- ets = _in_clause("e", sorted(FILE_DEPENDENCY_EDGE_TYPES), params)
- rows = await session.execute(
- text(
- "SELECT source_node_id, target_node_id, imported_names_json FROM graph_edges "
- "WHERE repository_id = :repo_id "
- f"AND target_node_id IN ({tgt}) AND edge_type IN ({ets})"
- ),
- params,
- )
+ shared: dict[str, Any] = {"repo_id": repo_id}
+ ets = _in_clause("e", sorted(FILE_DEPENDENCY_EDGE_TYPES), shared)
+ targets = list(dict.fromkeys(targets))
out = []
- for source, target, names_json in rows:
- try:
- names = json.loads(names_json or "[]")
- except (TypeError, ValueError):
- names = []
- out.append((source, target, frozenset(n for n in names if isinstance(n, str))))
+ for start in range(0, len(targets), _IN_BATCH):
+ params = dict(shared)
+ tgt = _in_clause("p", targets[start : start + _IN_BATCH], params)
+ rows = await session.execute(
+ text(
+ "SELECT source_node_id, target_node_id, imported_names_json FROM graph_edges "
+ "WHERE repository_id = :repo_id "
+ f"AND target_node_id IN ({tgt}) AND edge_type IN ({ets})"
+ ),
+ params,
+ )
+ out.extend((source, target, _names_of(names_json)) for source, target, names_json in rows)
return out
+def _names_of(names_json: str | None) -> frozenset[str]:
+ """The names an import edge records; unreadable JSON records none."""
+ try:
+ names = json.loads(names_json or "[]")
+ except (TypeError, ValueError):
+ return frozenset()
+ return frozenset(n for n in names if isinstance(n, str))
+
+
@dataclass(frozen=True)
class ImportGraph:
"""Every file-dependency edge, reversed (``{file: files depending on it}``), read once.
@@ -1128,24 +1135,34 @@ def _in_clause(prefix: str, values: list[str], params: dict[str, Any]) -> str:
return ",".join(f":{prefix}{i}" for i in range(len(values)))
+#: Values one ``IN`` list binds. SQLite refuses a statement with more variables
+#: than SQLITE_MAX_VARIABLE_NUMBER (999 before 3.32, 32766 after), and the lists
+#: below are a change's files or every file and symbol of a repository.
+_IN_BATCH = 500
+
+
async def _edges_from(
session: AsyncSession, repo_id: str, sources: list[str], edge_types: list[str]
) -> list[tuple[str, str]]:
"""``(source, target)`` pairs leaving *sources* along *edge_types*."""
- if not sources:
- return []
- params: dict[str, Any] = {"repo_id": repo_id}
- src = _in_clause("s", sources, params)
- ets = _in_clause("e", edge_types, params)
- rows = await session.execute(
- text(
- "SELECT DISTINCT source_node_id, target_node_id FROM graph_edges "
- "WHERE repository_id = :repo_id "
- f"AND source_node_id IN ({src}) AND edge_type IN ({ets})"
- ),
- params,
- )
- return [(s, t) for s, t in rows]
+ shared: dict[str, Any] = {"repo_id": repo_id}
+ ets = _in_clause("e", edge_types, shared)
+ out: list[tuple[str, str]] = []
+ # Each source is in one batch only, so a pair is distinct across batches too.
+ sources = list(dict.fromkeys(sources))
+ for start in range(0, len(sources), _IN_BATCH):
+ params = dict(shared)
+ src = _in_clause("s", sources[start : start + _IN_BATCH], params)
+ rows = await session.execute(
+ text(
+ "SELECT DISTINCT source_node_id, target_node_id FROM graph_edges "
+ "WHERE repository_id = :repo_id "
+ f"AND source_node_id IN ({src}) AND edge_type IN ({ets})"
+ ),
+ params,
+ )
+ out.extend((s, t) for s, t in rows)
+ return out
async def _edges_into(
@@ -1162,27 +1179,31 @@ async def _edges_into(
loading every row, and the two walks should not disagree about how they read
it.
"""
- if not targets:
- return []
- params: dict[str, Any] = {"repo_id": repo_id}
- tgt = _in_clause("p", targets, params)
- ets = _in_clause("e", edge_types, params)
+ shared: dict[str, Any] = {"repo_id": repo_id}
+ ets = _in_clause("e", edge_types, shared)
origin_filter = ""
if excluded_origins:
# NULL means the row predates the vocabulary, not "unknown", so it has
# to survive the filter, and a bare NOT IN would drop it.
- bad = _in_clause("o", sorted(excluded_origins), params)
+ bad = _in_clause("o", sorted(excluded_origins), shared)
origin_filter = f" AND (resolution_origin IS NULL OR resolution_origin NOT IN ({bad}))"
- rows = await session.execute(
- text(
- "SELECT DISTINCT source_node_id, target_node_id FROM graph_edges "
- "WHERE repository_id = :repo_id "
- f"AND target_node_id IN ({tgt}) AND edge_type IN ({ets}){origin_filter}"
- f"{_LEGACY_CONFTEST_FILTER}"
- ),
- params,
- )
- return [(s, t) for s, t in rows]
+ out: list[tuple[str, str]] = []
+ # Each target is in one batch only, so a pair is distinct across batches too.
+ targets = list(dict.fromkeys(targets))
+ for start in range(0, len(targets), _IN_BATCH):
+ params = dict(shared)
+ tgt = _in_clause("p", targets[start : start + _IN_BATCH], params)
+ rows = await session.execute(
+ text(
+ "SELECT DISTINCT source_node_id, target_node_id FROM graph_edges "
+ "WHERE repository_id = :repo_id "
+ f"AND target_node_id IN ({tgt}) AND edge_type IN ({ets}){origin_filter}"
+ f"{_LEGACY_CONFTEST_FILTER}"
+ ),
+ params,
+ )
+ out.extend((s, t) for s, t in rows)
+ return out
def rank_tests(target: str, tests: Collection[str]) -> list[str]:
diff --git a/tests/unit/persistence/test_test_reachability_walk.py b/tests/unit/persistence/test_test_reachability_walk.py
index 909abb14d..46068f453 100644
--- a/tests/unit/persistence/test_test_reachability_walk.py
+++ b/tests/unit/persistence/test_test_reachability_walk.py
@@ -19,6 +19,8 @@ from repowise.core.analysis.test_reachability import (
ReachDistance,
call_graph_from_db,
call_graph_from_graph,
+ direct_dependents,
+ direct_importers,
imported_names_by_test,
reach_into_symbols,
)
@@ -749,3 +751,60 @@ async def test_reached_files_are_walked_once_per_index_state(async_session, monk
assert first == second == frozenset({"src/a.py"})
assert loads == 1
+
+
+async def test_reads_over_more_files_than_one_statement_can_bind(async_session):
+ """A repository-wide read binds a variable per file or symbol, past what one
+ SQLite statement accepts (SQLITE_MAX_VARIABLE_NUMBER, 32766)."""
+ repo = await insert_repo(async_session)
+ await _seed(
+ async_session,
+ repo.id,
+ nodes={"tests/test_a.py": True, "src/a.py": False, "src/b.py": False},
+ edges=[
+ ("tests/test_a.py", "src/a.py", "imports"),
+ ("src/b.py", "src/a.py", "imports"),
+ *_calls("tests/test_a.py", "src/b.py"),
+ ],
+ )
+ files = [f"src/gone_{i}.py" for i in range(40_000)] + ["src/a.py", "src/b.py"]
+ assert await direct_importers(async_session, repo.id, files) == {
+ "tests/test_a.py",
+ "src/b.py",
+ }
+ assert await direct_dependents(async_session, repo.id, files) == {
+ "src/a.py": {"tests/test_a.py", "src/b.py"},
+ "src/b.py": {"tests/test_a.py"},
+ }
+ names = await imported_names_by_test(async_session, repo.id, files, {"tests/test_a.py"})
+ assert names == {"src/a.py": {"tests/test_a.py": frozenset()}}
+
+
+async def test_a_node_listed_twice_across_batches_reads_its_edges_once(async_session):
+ """A repeated input landing in two batches must not repeat its pairs: one
+ ``IN`` list matches a node once however often it is listed."""
+ from repowise.core.analysis.test_reachability import (
+ _IN_BATCH,
+ _edges_from,
+ _edges_into,
+ _imported_names,
+ )
+
+ repo = await insert_repo(async_session)
+ await _seed(
+ async_session,
+ repo.id,
+ nodes={"tests/test_a.py": True, "src/a.py": False},
+ edges=[("tests/test_a.py", "src/a.py", "imports")],
+ )
+ padding = [f"src/gone_{i}.py" for i in range(_IN_BATCH)]
+ into = await _edges_into(
+ async_session, repo.id, ["src/a.py", *padding, "src/a.py"], ["imports"], frozenset()
+ )
+ assert into == [("tests/test_a.py", "src/a.py")]
+ out = await _edges_from(
+ async_session, repo.id, ["tests/test_a.py", *padding, "tests/test_a.py"], ["imports"]
+ )
+ assert 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())]