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.

perf(mcp): run test selection off the event loop and reuse it per change (#4208)

Raghav Chamadiya819b6d35becf
diff --git a/packages/server/src/repowise/server/mcp_server/_test_selection.py b/packages/server/src/repowise/server/mcp_server/_test_selection.py
index 12b198122..4c1d69560 100644
--- a/packages/server/src/repowise/server/mcp_server/_test_selection.py
+++ b/packages/server/src/repowise/server/mcp_server/_test_selection.py
@@ -12,8 +12,11 @@ each test is in it, and which evidence decided each changed file.
from __future__ import annotations
import asyncio
+import hashlib
+import subprocess
import threading
-from dataclasses import dataclass
+from collections import OrderedDict
+from dataclasses import astuple, dataclass
from pathlib import Path
from typing import Any
@@ -49,6 +52,11 @@ class _Flight:
#: the cancel flag, and a second one would only add to them.
_IN_FLIGHT: dict[str, _Flight] = {}
+#: Finished selections keyed on (repository, change, index state, config), so a
+#: repeated get_change_risk or get_risk for the same change reuses one.
+_DONE: OrderedDict[tuple, tuple] = OrderedDict()
+_DONE_CAPACITY = 16
+
class SelectionUnavailableError(Exception):
"""No selection could be made; ``status`` and the message say why."""
@@ -77,6 +85,10 @@ async def select_change_tests(
except (RepoConfigError, ValueError) as exc:
raise SelectionUnavailableError("config_invalid", f"tests config is invalid: {exc}") from exc
key = str(Path(repo_path).resolve())
+ done_key = await _done_key(key, session_factory, change, config)
+ if done_key is not None and done_key in _DONE:
+ _DONE.move_to_end(done_key)
+ return _DONE[done_key]
loop = asyncio.get_running_loop()
deadline = loop.time() + SELECTION_TIMEOUT_SECONDS
flight = await _flight_for(
@@ -99,7 +111,67 @@ async def select_change_tests(
f"Selecting tests took over {SELECTION_TIMEOUT_SECONDS:.0f} s; run "
"`repowise impacted-tests` for this change.",
)
- return flight.task.result()
+ selected = flight.task.result()
+ # A checkout edited while the selection read it is not cached under the old stamp.
+ if done_key is not None and done_key == await _done_key(key, session_factory, change, config):
+ _DONE[done_key] = selected
+ while len(_DONE) > _DONE_CAPACITY:
+ _DONE.popitem(last=False)
+ return selected
+
+
+async def _done_key(key: str, session_factory: Any, change: Any, config: Any) -> tuple | None:
+ """The cache identity of this selection, or ``None`` when it cannot be cached."""
+ from repowise.core.persistence.database import get_session
+ from repowise.server.mcp_server._helpers import _get_repo
+ from repowise.server.mcp_server._index_state import index_state_key
+
+ if session_factory is None:
+ return None
+ try:
+ async with get_session(session_factory) as session:
+ index = index_state_key(await _get_repo(session))
+ except Exception:
+ return None
+ # A committed head pins what the selection reads; without one it reads the
+ # live checkout, so the tree's state joins the key.
+ tree = "" if change.head else await asyncio.to_thread(_tree_stamp, key)
+ if tree is None:
+ return None
+ return (key, _change_identity(change), index, tree, repr(config))
+
+
+def _change_identity(change: Any) -> str:
+ """A digest of everything in *change*, order-independent where it is a set."""
+ rows = [
+ (path, sorted(diff.new_lines), *astuple(diff)[2:])
+ for path, diff in sorted(change.files.items())
+ ]
+ raw = repr((change.base, change.head, change.label, sorted(change.deleted), rows))
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()
+
+
+def _tree_stamp(root: str) -> str | None:
+ """What the checkout's dirty paths are and when each last changed; ``None`` when git fails."""
+ try:
+ out = subprocess.run(
+ ["git", "status", "--porcelain", "-z", "--untracked-files=all"],
+ cwd=root,
+ capture_output=True,
+ stdin=subprocess.DEVNULL,
+ timeout=10,
+ check=True,
+ ).stdout
+ except (OSError, subprocess.SubprocessError):
+ return None
+ digest = hashlib.sha256(out)
+ for entry in out.split(b"\0"):
+ try:
+ stat = (Path(root) / entry[3:].decode("utf-8", "replace")).stat()
+ except (OSError, ValueError):
+ continue
+ digest.update(f"{stat.st_mtime_ns}:{stat.st_size}".encode())
+ return digest.hexdigest()
async def _flight_for(key: str, change: Any, deadline: float, start: Any) -> _Flight:
@@ -142,6 +214,31 @@ def _release(key: str, flight: _Flight) -> None:
async def _select(
repo_path: Any, session_factory: Any, change: Any, config: Any, cancel: threading.Event
+) -> tuple:
+ """Run the selection on a worker thread with its own event loop.
+
+ The selection is mostly pure-Python CPU work, which on the server's loop
+ would hold every other call's queries until it finished. A pooled
+ engine's connections belong to the loop that opened them, so only an
+ engine that opens one per checkout (``NullPool``, as every file SQLite
+ store uses) moves off the loop.
+ """
+ if not _loop_agnostic(session_factory):
+ return await _select_here(repo_path, session_factory, change, config, cancel)
+ return await asyncio.to_thread(
+ asyncio.run, _select_here(repo_path, session_factory, change, config, cancel)
+ )
+
+
+def _loop_agnostic(session_factory: Any) -> bool:
+ from sqlalchemy.pool import NullPool
+
+ bind = getattr(session_factory, "kw", {}).get("bind")
+ return isinstance(getattr(getattr(bind, "sync_engine", None), "pool", None), NullPool)
+
+
+async def _select_here(
+ repo_path: Any, session_factory: Any, change: Any, config: Any, cancel: threading.Event
) -> tuple:
from repowise.core.analysis.test_collection import read_checkout, select_for_change
from repowise.core.analysis.test_ranking import ordered, rank_change
diff --git a/tests/unit/server/mcp/test_change_test_selection.py b/tests/unit/server/mcp/test_change_test_selection.py
index 9aa246551..651a8b1f3 100644
--- a/tests/unit/server/mcp/test_change_test_selection.py
+++ b/tests/unit/server/mcp/test_change_test_selection.py
@@ -50,19 +50,20 @@ async def _index(
edges: list[tuple[str, str, str]] = (),
coverage: list | None = None,
measured_at: str | None = None,
+ db_file: Path | None = None,
):
"""An index built at *base*: file nodes (``True`` test, ``str`` always-run reason), edges."""
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
- from sqlalchemy.pool import StaticPool
+ from sqlalchemy.pool import NullPool, StaticPool
from repowise.core.persistence.crud import save_test_coverage
from repowise.core.persistence.database import init_db
from repowise.core.persistence.models import GraphEdge, GraphNode, Repository
engine = create_async_engine(
- "sqlite+aiosqlite:///:memory:",
+ f"sqlite+aiosqlite:///{db_file.as_posix()}" if db_file else "sqlite+aiosqlite:///:memory:",
connect_args={"check_same_thread": False},
- poolclass=StaticPool,
+ poolclass=NullPool if db_file else StaticPool,
)
await init_db(engine)
factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
@@ -451,3 +452,51 @@ async def test_both_tools_list_tests_in_the_selections_run_order(tmp_path, monke
order = ["tests/test_z.py", "tests/test_status.py", "tests/test_walks.py"]
assert it["tests_to_run"] == order and list(it["why"]) == order
assert directive["tests_to_run"] == order
+
+
+async def test_a_repeated_selection_is_reused_until_the_tree_or_index_moves(
+ tmp_path, monkeypatch
+) -> None:
+ import threading
+ from collections import OrderedDict
+
+ from sqlalchemy import update
+
+ from repowise.core.persistence.models import Repository
+ from repowise.server.mcp_server import _test_selection
+
+ repo, base = _repo(tmp_path, _STATUS)
+ factory = await _index(
+ base,
+ {"src/status.py": False, "tests/test_status.py": True},
+ db_file=tmp_path / "wiki.db",
+ )
+ threads: list[int] = []
+ real = _test_selection._select_here
+
+ async def _recording(*args, **kwargs):
+ threads.append(threading.get_ident())
+ return await real(*args, **kwargs)
+
+ monkeypatch.setattr(_test_selection, "_select_here", _recording)
+ monkeypatch.setattr(_test_selection, "_DONE", OrderedDict())
+
+ async def _select() -> tuple:
+ change = _test_selection.files_change(repo, ["src/status.py"])
+ return await _test_selection.select_change_tests(repo, factory, change)
+
+ first = await _select()
+ assert await _select() is first
+ # The selection ran on a worker thread, off the server's loop.
+ assert threads == [threads[0]] and threads[0] != threading.get_ident()
+
+ (repo / "src" / "status.py").write_text("def status():\n return 2\n", encoding="utf-8")
+ dirty = await _select()
+ assert dirty is not first and len(threads) == 2
+ assert await _select() is dirty
+
+ async with factory() as session:
+ await session.execute(update(Repository).values(head_commit="moved"))
+ await session.commit()
+ assert await _select() is not dirty and len(threads) == 3