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
perf(change-risk): serve a repeated committed range from a per-process cache (#4209)
Raghav Chamadiya004cf426a70e
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/cache.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/cache.pynew file mode 100644index 000000000..f36d3c83d--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/cache.py@@ -0,0 +1,162 @@+"""The committed-range change-risk cache: one scoring per range and index state.++A revspec names commits, so the score, the delta and every block are fixed+once the revisions, the request's filters, the index and the few live inputs+the blocks read (riskignore, repo config, coverage ingests, branch tips) are.+A repeat call or a ``finding_id`` drill-down is then served from here instead+of rerunning the comparison. Uncommitted work is never cached: its revspec is+``None`` and its content moves without any of those changing.+"""++from __future__ import annotations++import asyncio+import hashlib+import subprocess+from collections import OrderedDict+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++#: Scored ranges kept per process; each holds its delta and served payloads.+_CAPACITY = 16++_TRANSIENT = frozenset({"unavailable", "timeout"})+++@dataclass+class Scored:+ """One scored range: its ref and delta, and each payload served for it.++ Callers only read ``delta``; it is shared, not copied.+ """++ ref: str+ delta: Any+ payloads: dict[str, tuple[dict, list[str] | None]] = field(default_factory=dict)+++_SCORED: OrderedDict[str, Scored] = OrderedDict()+++def lookup(key: str | None) -> Scored | None:+ if key is None:+ return None+ hit = _SCORED.get(key)+ if hit is not None:+ _SCORED.move_to_end(key)+ return hit+++def remember(key: str | None, ref: str, delta: Any) -> Scored | None:+ """Keep *delta* for *key*, or ``None`` when the call is not cacheable."""+ # A failed or timed-out comparison may succeed next time, so it is not kept.+ if key is None or getattr(delta, "status", None) in _TRANSIENT:+ return None+ entry = _SCORED.get(key)+ if entry is None:+ entry = _SCORED[key] = Scored(ref, delta)+ _SCORED.move_to_end(key)+ while len(_SCORED) > _CAPACITY:+ _SCORED.popitem(last=False)+ return entry+++def payload_key(include: list[str] | None) -> str:+ return repr(sorted(include or ()))+++async def cache_key(+ ctx: Any,+ revspec: str | None,+ extensions: list[str] | None,+ exclude_patterns: list[str] | None,+ include_paths: tuple[str, ...],+ baseline: int,+) -> str | None:+ """The range's cache identity, or ``None`` when this call must not be cached."""+ from repowise.server.mcp_server import _state++ # Workspace mode joins other repositories' indexes into the tests block.+ # Ceiling: those members' index states are not in the key, so the cache+ # stays off there; adding each member's state key is the upgrade.+ if not revspec or _state._registry is not None:+ return None+ root = str(Path(ctx.path).resolve())+ live = await asyncio.to_thread(_live_inputs, root, revspec)+ if live is None:+ return None+ parts = (+ root,+ revspec,+ *live,+ repr(tuple(extensions or ())),+ repr(tuple(exclude_patterns or ())),+ repr(include_paths),+ str(baseline),+ await _index_inputs(ctx),+ )+ return hashlib.sha256("\x00".join(parts).encode("utf-8")).hexdigest()+++def _live_inputs(root: str, revspec: str) -> tuple[str, ...] | None:+ """The resolved revisions and the checkout inputs the blocks read, or ``None``."""+ from repowise.core import git_refs+ from repowise.core.analysis.change_risk.service import riskignore_patterns+ from repowise.core.analysis.git_cli import split_revspec+ from repowise.core.repo_config import health_rules_fingerprint++ parts = split_revspec(revspec)+ sides = (parts[0], parts[2]) if parts else (revspec, f"{revspec}^1")+ shas = [git_refs.resolve(root, side) for side in sides]+ head = git_refs.resolve(root, "HEAD") or ""+ # A root commit has no parent; any other unresolvable side is git's error to report.+ if not shas[0] or (parts and not shas[1]):+ return None+ try:+ tips = subprocess.run(+ ["git", "for-each-ref", "--format=%(objectname) %(refname)"],+ cwd=root,+ capture_output=True,+ stdin=subprocess.DEVNULL,+ timeout=10,+ check=True,+ ).stdout+ except (OSError, subprocess.SubprocessError):+ return None+ return (+ *shas,+ head,+ hashlib.sha256(tips).hexdigest(),+ repr(riskignore_patterns(root)),+ health_rules_fingerprint(root),+ )+++async def _index_inputs(ctx: Any) -> str:+ """The index state and the newest coverage ingest; ``""`` without an index."""+ from sqlalchemy import func, select+ from sqlalchemy.exc import SQLAlchemyError++ from repowise.core.persistence.database import get_session+ from repowise.core.persistence.models import CoverageIngest+ from repowise.server.mcp_server import tool_change_risk as _pkg+ from repowise.server.mcp_server._index_state import index_state_key++ session_factory = getattr(ctx, "session_factory", None)+ if session_factory is None:+ return ""+ try:+ async with get_session(session_factory) as session:+ repository = await _pkg._get_repo(session)+ # An ingest writes no index stamp, so its own row is the signal.+ newest, count = (+ await session.execute(+ select(func.max(CoverageIngest.ingested_at), func.count()).where(+ CoverageIngest.repository_id == repository.id+ )+ )+ ).one()+ except (LookupError, SQLAlchemyError):+ return ""+ return f"{index_state_key(repository)}|{newest or ''}|{count}"diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.pyindex fa8b6ba25..8b7b43dfd 100644--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.py+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.py@@ -3,6 +3,7 @@from __future__ import annotationsimport asyncio+import copyimport shutilimport subprocessimport time@@ -22,6 +23,7 @@ from repowise.server.mcp_server._helpers import (attach_ignored_arguments,)+from . import cache as _cachefrom .branches import _branch_overlap_block, _independent_changes_blockfrom .changed import _changed_in_scope, _push_changefrom .cross_repo import _cross_repo_block@@ -152,6 +154,10 @@ async def _attach_branch_blocks(return await _independent_changes_block(ctx, changed, collector, revspec)+#: ``_meta`` keys a cached payload keeps; the rest is rebuilt on every serve.+_CARRIED_META = frozenset({"omitted", "recovery_unavailable"})++@mcp.tool(surface_order=60,artifact_type="change_risk",@@ -204,6 +210,13 @@ async def get_change_risk(ctx = await _pkg._resolve_repo_context(repo)started = time.perf_counter()includes = _path_patterns(include_paths)+ key = await _cache.cache_key(ctx, revspec, extensions, exclude_patterns, includes, baseline)+ hit = _cache.lookup(key)+ if hit is not None and finding_id is not None:+ return _drill_down({"ref": hit.ref}, hit.delta, finding_id, revspec)+ stored = hit.payloads.get(_cache.payload_key(include)) if hit is not None else None+ if stored is not None:+ return await _served(ctx, stored, started)result, error = await _score_change(ctx.path, revspec, extensions, exclude_patterns, includes, baseline)@@ -266,6 +279,7 @@ async def get_change_risk(raisedelta = await delta_taskawait _attach_health_references(ctx, delta)+ scored_entry = _cache.remember(key, payload["ref"], delta)if finding_id is not None:return _drill_down(payload, delta, finding_id, revspec)payload["diff_shape"] = _diff_shape_sentence(payload, diagnostics)@@ -301,9 +315,32 @@ async def get_change_risk()attach_ignored_arguments(payload, ignored)collector.attach(payload)+ if scored_entry is not None:+ scored_entry.payloads[_cache.payload_key(include)] = (+ copy.deepcopy(payload),+ sorted(changed) or None,+ )return payload+async def _served(ctx: Any, stored: tuple[dict, list[str] | None], started: float) -> dict:+ """A cached payload with its ``_meta`` rebuilt, since freshness reads the live checkout."""+ payload, targets = stored+ out = copy.deepcopy(payload)+ # Omission refs belong to the stored blocks, so they carry over.+ kept = {k: v for k, v in out.get("_meta", {}).items() if k in _CARRIED_META}+ out["_meta"] = {+ **_pkg._build_meta(+ timing_ms=(time.perf_counter() - started) * 1000,+ repository=await _repository(ctx),+ targets=targets,+ extra={"source": "live_git", "cached": True},+ ),+ **kept,+ }+ return out++async def _nothing_to_score(ctx: Any, ref: str, scored: dict[str, Any], started: float) -> dict:"""An empty diff, reported as one rather than scored.diff --git a/tests/unit/server/mcp/conftest.py b/tests/unit/server/mcp/conftest.pyindex fee3b4d06..bcf973466 100644--- a/tests/unit/server/mcp/conftest.py+++ b/tests/unit/server/mcp/conftest.py@@ -796,3 +796,13 @@ def _no_omission_writes_outside_a_test_repo(monkeypatch, tmp_path):# misses the read.monkeypatch.setattr(store_module, "default_store_path", resolve)monkeypatch.setattr(collector, "default_store_path", resolve)++[email protected](autouse=True)+def _fresh_change_risk_cache(monkeypatch):+ """Each test scores its ranges itself; a cached payload would hide its patches."""+ from collections import OrderedDict++ from repowise.server.mcp_server.tool_change_risk import cache++ monkeypatch.setattr(cache, "_SCORED", OrderedDict())diff --git a/tests/unit/server/mcp/test_change_risk.py b/tests/unit/server/mcp/test_change_risk.pyindex 6205541a7..aceb07f70 100644--- a/tests/unit/server/mcp/test_change_risk.py+++ b/tests/unit/server/mcp/test_change_risk.py@@ -831,3 +831,80 @@ async def test_evidence_for_a_stored_change_is_its_kept_record(tmp_path, monkeypdegraded = await module.get_change_risk("HEAD", baseline=0, include=["evidence"])owners = {i["kind"]: i for i in degraded["evidence"]["items"]}["owners"]assert "database is locked" in owners["details"][0]["reason"]+++async def test_a_scored_range_is_reused_until_its_inputs_move(tmp_path, monkeypatch) -> None:+ from datetime import UTC, datetime++ from sqlalchemy import update++ from repowise.core.persistence.models import Repository++ repo = tmp_path / "repo"+ repo.mkdir()+ _git(["init", "-q"], repo)+ _commit(repo, {"src/app.py": "def f():\n return 1\n"}, "chore: seed")+ _commit(repo, {"src/app.py": "def f():\n return 2\n"}, "feat: two")+ factory = await _factory_with_repo(None, head_commit=_sha(repo))+ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")+ scores: list[str | None] = []+ real = module.score_live_change++ def _counting(path, revspec=None, **kwargs):+ scores.append(revspec)+ return real(path, revspec, **kwargs)++ async def _context(_: str | None) -> SimpleNamespace:+ return SimpleNamespace(path=str(repo), session_factory=factory)++ monkeypatch.setattr(module, "_resolve_repo_context", _context)+ monkeypatch.setattr(module, "score_live_change", _counting)++ first = await module.get_change_risk("HEAD~1..HEAD", baseline=0)+ again = await module.get_change_risk("HEAD~1..HEAD", baseline=0)+ assert len(scores) == 1 and again["_meta"]["cached"] is True+ assert set(again["_meta"]) - {"cached"} == set(first["_meta"])+ assert {k: v for k, v in again.items() if k != "_meta"} == {+ k: v for k, v in first.items() if k != "_meta"+ }+ # A drill-down of the range just scored, known id or not, reads the kept delta.+ missing = await module.get_change_risk("HEAD~1..HEAD", baseline=0, finding_id="nope")+ assert "error" in missing and len(scores) == 1+ # Other filters are another question.+ await module.get_change_risk("HEAD~1..HEAD", baseline=0, extensions=[".py"])+ assert len(scores) == 2++ async with factory() as session:+ await session.execute(update(Repository).values(updated_at=datetime.now(UTC)))+ await session.commit()+ await module.get_change_risk("HEAD~1..HEAD", baseline=0)+ assert len(scores) == 3++ _commit(repo, {"src/app.py": "def f():\n return 3\n"}, "feat: three")+ await module.get_change_risk("HEAD~1..HEAD", baseline=0)+ assert len(scores) == 4+++async def test_uncommitted_work_is_never_served_from_the_cache(tmp_path, monkeypatch) -> None:+ repo = tmp_path / "repo"+ repo.mkdir()+ _git(["init", "-q"], repo)+ _commit(repo, {"src/app.py": "value = 1\n"}, "chore: seed")+ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")+ scores: list[str | None] = []+ real = module.score_live_change++ def _counting(path, revspec=None, **kwargs):+ scores.append(revspec)+ return real(path, revspec, **kwargs)++ async def _context(_: str | None) -> SimpleNamespace:+ return SimpleNamespace(path=str(repo))++ monkeypatch.setattr(module, "_resolve_repo_context", _context)+ monkeypatch.setattr(module, "score_live_change", _counting)+ (repo / "src" / "app.py").write_text("value = 2\n", encoding="utf-8")+ await module.get_change_risk(baseline=0)+ second = await module.get_change_risk(baseline=0)++ assert scores == [None, None] and "cached" not in second["_meta"]