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(serving): read paths skip the schema reconcile, heavy imports and unused test lookups (#3279)
Raghav Chamadiyae7b0b270ceb8
diff --git a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py b/packages/cli/src/repowise/cli/commands/dead_code_cmd.pyindex c2ac18109..d03fbd67a 100644--- a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py+++ b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py@@ -64,7 +64,7 @@ async def _read_stored(repo_path: Path, config: dict) -> DeadCodeReport | None:from repowise.core.persistence.crud import finding_data_from_row, get_dead_code_findings- async with repo_index_session(repo_path, reconcile=False) as opened:+ async with repo_index_session(repo_path) as opened:if opened is None:return Nonesession, repo_id = openeddiff --git a/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py b/packages/cli/src/repowise/cli/commands/doc_drift_cmd.pyindex 610806438..89a8c2df8 100644--- a/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py+++ b/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py@@ -87,7 +87,7 @@ async def _index_symbol_names(root: Path) -> frozenset[str] | None:from repowise.core.persistence.crud import get_symbol_names- async with repo_index_session(root, reconcile=False) as opened:+ async with repo_index_session(root) as opened:if opened is None:return Nonesession, repo_id = openeddiff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.pyindex c812a008d..ac4db646e 100644--- a/packages/cli/src/repowise/cli/helpers.py+++ b/packages/cli/src/repowise/cli/helpers.py@@ -283,22 +283,34 @@ def get_db_url_for_repo(repo_path: Path) -> str:return resolve_db_url(repo_path)+STALE_INDEX_MESSAGE = (+ "This index was written by an older version of repowise; run `repowise update`."+)+++class StaleIndexError(click.ClickException):+ """The store lacks a table or column this version reads, and could not be repaired."""++ def __init__(self) -> None:+ super().__init__(STALE_INDEX_MESSAGE)++@contextlib.asynccontextmanager-async def repo_index_session(- root: Path, *, reconcile: bool = True-) -> AsyncIterator[tuple[AsyncSession, str] | None]:- """Open the repo-local store, yielding ``(session, repo_id)`` or ``None``.-- A scoring or scanning command must never fail because the index is absent,- stale or locked, so every storage error yields ``None`` instead.- ``reconcile=False`` skips the schema reconcile, so a caller that only reads- writes nothing to the store.+async def repo_index_session(root: Path) -> AsyncIterator[tuple[AsyncSession, str] | None]:+ """Open the repo-local store for reading, yielding ``(session, repo_id)`` or ``None``.++ A scoring or scanning command must never fail because the index is absent+ or locked, so every storage error yields ``None`` instead. The schema is+ reconciled only when a catalogue read finds it behind the models: the+ reconcile costs a read command 0.3 s and writes to the store, so a current+ store skips it. A store still behind after it raises :class:`StaleIndexError`,+ since every answer read from it would be missing what it lacks."""from sqlalchemy.exc import SQLAlchemyErrorfrom repowise.core.persistence import create_engine, create_session_factory, get_sessionfrom repowise.core.persistence.crud import get_repository_by_path- from repowise.core.persistence.database import has_db_store+ from repowise.core.persistence.database import has_db_store, schema_behind# The configured store, which may live outside the repo (REPOWISE_DB_URL).if not has_db_store(root):@@ -310,10 +322,12 @@ async def repo_index_session(opened: tuple[AsyncSession, str] | None = Nonetry:url = get_db_url_for_repo(root)- if reconcile:- await reconcile_schema_best_effort(url)engine = create_engine(url)stack.push_async_callback(engine.dispose)+ if await schema_behind(engine):+ await reconcile_schema_best_effort(url)+ if await schema_behind(engine):+ raise StaleIndexErrorfactory = create_session_factory(engine)session = await stack.enter_async_context(get_session(factory))repo = await get_repository_by_path(session, str(root))@@ -341,8 +355,9 @@ async def reconcile_schema_best_effort(db_url: str) -> None:have gained since, and the ORM then fails with a raw ``no such column`` onthe first query — which for a read command means every read. ``init_db``back-fills those columns in place and is idempotent, so the CLI pairs it- with ``create_engine`` everywhere it opens a store, the way the MCP server,- the workspace registry and the FastAPI app already do in their lifespans.+ with ``create_engine`` where a command opens a store, the way the MCP+ server, the workspace registry and the FastAPI app already do in their+ lifespans. :func:`repo_index_session` runs it only on a store found behind.Opportunistic, not a precondition, which is the part worth having in oneplace. Reconciling needs a write, and a store can be read-only ordiff --git a/packages/core/src/repowise/core/analysis/dead_code/__init__.py b/packages/core/src/repowise/core/analysis/dead_code/__init__.pyindex a41ced2ef..d279e1277 100644--- a/packages/core/src/repowise/core/analysis/dead_code/__init__.py+++ b/packages/core/src/repowise/core/analysis/dead_code/__init__.py@@ -28,7 +28,9 @@ Internal layout (Phase 1 refactor):from __future__ import annotations-from .analyzer import DeadCodeAnalyzer+from typing import TYPE_CHECKING++from ...lazy_exports import lazy_exportsfrom .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReportfrom .risk_factors import (RISK_CAP_CONFIDENCE,@@ -38,6 +40,13 @@ from .risk_factors import (risk_evidence,)+if TYPE_CHECKING:+ from .analyzer import DeadCodeAnalyzer++# The analyzer pulls in ingestion (~0.8 s); the persistence layer imports+# this package for its models on every CLI command and never runs it.+__getattr__, __dir__ = lazy_exports(__name__, {"DeadCodeAnalyzer": ".analyzer"}, globals())+__all__ = ["RISK_CAP_CONFIDENCE","SAFE_CONFIDENCE_THRESHOLD",diff --git a/packages/core/src/repowise/core/ingestion/__init__.py b/packages/core/src/repowise/core/ingestion/__init__.pyindex 375d79f70..5815aba0a 100644--- a/packages/core/src/repowise/core/ingestion/__init__.py+++ b/packages/core/src/repowise/core/ingestion/__init__.py@@ -10,8 +10,11 @@ ChangeDetector — git-based change detection + symbol rename detectionLANGUAGE_CONFIGS — dict of per-language configuration"""-from .change_detector import AffectedPages, ChangeDetector, FileDiff, SymbolDiff, SymbolRename-from .graph import GraphBuilder+from __future__ import annotations++from typing import TYPE_CHECKING++from ..lazy_exports import lazy_exportsfrom .models import (EXTENSION_TO_LANGUAGE,CallReceiver,@@ -28,9 +31,35 @@ from .models import (SymbolKind,compute_content_hash,)-from .parser import LANGUAGE_CONFIGS, ASTParser, LanguageConfig, parse_file-from .traverser import FileTraverser, TraversalStats, is_candidate_source_path-from .tsconfig_resolver import TsconfigResolver, wire_tsconfig_resolver++if TYPE_CHECKING:+ from .change_detector import AffectedPages, ChangeDetector, FileDiff, SymbolDiff, SymbolRename+ from .graph import GraphBuilder+ from .parser import LANGUAGE_CONFIGS, ASTParser, LanguageConfig, parse_file+ from .traverser import FileTraverser, TraversalStats, is_candidate_source_path+ from .tsconfig_resolver import TsconfigResolver, wire_tsconfig_resolver++# Loaded on first use: the graph builder alone pulls in networkx (~0.8 s), and+# importing any ``ingestion.*`` submodule runs this file, so every read path+# that only wants the models or the language registry paid for the parser.+__getattr__, __dir__ = lazy_exports(+ __name__,+ {+ **dict.fromkeys(+ ("AffectedPages", "ChangeDetector", "FileDiff", "SymbolDiff", "SymbolRename"),+ ".change_detector",+ ),+ "GraphBuilder": ".graph",+ **dict.fromkeys(+ ("LANGUAGE_CONFIGS", "ASTParser", "LanguageConfig", "parse_file"), ".parser"+ ),+ **dict.fromkeys(+ ("FileTraverser", "TraversalStats", "is_candidate_source_path"), ".traverser"+ ),+ **dict.fromkeys(("TsconfigResolver", "wire_tsconfig_resolver"), ".tsconfig_resolver"),+ },+ globals(),+)__all__ = ["EXTENSION_TO_LANGUAGE",diff --git a/packages/core/src/repowise/core/ingestion/resolvers/context.py b/packages/core/src/repowise/core/ingestion/resolvers/context.pyindex c1e967cae..365555e8e 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/context.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/context.py@@ -6,11 +6,14 @@ import jsonimport shlexfrom dataclasses import dataclass, fieldfrom pathlib import Path-from typing import Any+from typing import TYPE_CHECKING, Any-import networkx as nximport structlog+if TYPE_CHECKING:+ # An annotation only: networkx costs ~0.7 s to import on a read path.+ import networkx as nx+log = structlog.get_logger(__name__)diff --git a/packages/core/src/repowise/core/lazy_exports.py b/packages/core/src/repowise/core/lazy_exports.pynew file mode 100644index 000000000..55387a34e--- /dev/null+++ b/packages/core/src/repowise/core/lazy_exports.py@@ -0,0 +1,32 @@+"""Package exports that load their submodule on first use (PEP 562)."""++from __future__ import annotations++from collections.abc import Callable, Mapping+from importlib import import_module+from typing import Any+++def lazy_exports(+ package: str, exports: Mapping[str, str], namespace: dict[str, Any]+) -> tuple[Callable[[str], Any], Callable[[], list[str]]]:+ """``(__getattr__, __dir__)`` for *package*, whose *exports* map a name to+ the relative submodule defining it.++ A name is imported when first read and then cached in *namespace* (the+ package's ``globals()``), so later reads skip the hook; ``dir()`` lists+ the lazy names alongside the loaded ones.+ """++ def getattr_(name: str) -> Any:+ module = exports.get(name)+ if module is None:+ raise AttributeError(f"module {package!r} has no attribute {name!r}")+ value = getattr(import_module(module, package), name)+ namespace[name] = value+ return value++ def dir_() -> list[str]:+ return sorted({*namespace, *exports})++ return getattr_, dir_diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/actions.py b/packages/core/src/repowise/core/persistence/crud/analysis/actions.pyindex 39ce9dd6c..85f504251 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/actions.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/actions.py@@ -248,7 +248,9 @@ async def _test_map(session: AsyncSession, repo_id: str, files: dict[str, FileFaasync def _fix_first(session: AsyncSession, repo_id: str) -> dict[str, Any]:- return {"fix_first": (await load_fix_first(session, repo_id, limit=FIX_FIRST_ACTIONS)).items}+ # An action names the item and links to its full read; it carries no tests.+ queue = await load_fix_first(session, repo_id, limit=FIX_FIRST_ACTIONS, verify=False)+ return {"fix_first": queue.items}async def _secrets(session: AsyncSession, repo_id: str, files: dict[str, FileFacts]) -> dict:diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py b/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.pyindex 01c30f249..cf525de2e 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py@@ -528,10 +528,13 @@ async def load_fix_first(limit: int | None = DEFAULT_LIMIT,scope: str = "production",item_id: str | None = None,+ verify: bool = True,) -> FixFirstQueue:"""The Fix-first queue for one repository, from its stored analysis.``item_id`` keeps only that item, at its rank, for a lookup by id.+ ``verify=False`` leaves a plan-less finding's tests unresolved, for a+ caller that never shows them: that read is most of a cold build.The full queue is built once per store write and every ``limit`` and idis a slice of it: the reads are the same whatever is kept, and writing@@ -543,14 +546,17 @@ async def load_fix_first(scope,await _stamp(session, repository_id),)- key = (*base, limit, item_id)+ key = (*base, verify, limit, item_id)queue = _cached(key)if queue is not None:return queue- full = _cached((*base, None, None))+ # A verified queue answers an unverified ask too; never the reverse.+ full = _cached((*base, True, None, None)) or _cached((*base, verify, None, None))if full is None:- full = await _build(session, repository_id, limit=None, scope=scope, item_id=None)- _remember((*base, None, None), full)+ full = await _build(+ session, repository_id, limit=None, scope=scope, item_id=None, verify=verify+ )+ _remember((*base, verify, None, None), full)queue = full if key[-2:] == (None, None) else queue_view(full, limit=limit, item_id=item_id)_remember(key, queue)return queue@@ -590,6 +596,7 @@ async def _build(limit: int | None,scope: str,item_id: str | None,+ verify: bool = True,) -> FixFirstQueue:refactoring = _decoded(await _refactoring(session, repository_id))performance = _decoded(await _performance(session, repository_id))@@ -617,7 +624,7 @@ async def _build(basis=await _basis(session, repository_id),hot_cuts=await _hot_cuts(session, repository_id),symbol_lines=await _symbol_lines(session, repository_id, performance),- validate=await _finding_validator(session, repository_id, findings),+ validate=await _finding_validator(session, repository_id, findings) if verify else None,)diff --git a/packages/core/src/repowise/core/persistence/database.py b/packages/core/src/repowise/core/persistence/database.pyindex 9351077a6..c85947b5f 100644--- a/packages/core/src/repowise/core/persistence/database.py+++ b/packages/core/src/repowise/core/persistence/database.py@@ -165,6 +165,7 @@ __all__ = ["get_session","init_db","resolve_db_url",+ "schema_behind",]DB_FILENAME = "wiki.db"@@ -681,3 +682,28 @@ async def init_db(engine: AsyncEngine) -> None:from repowise.core.persistence.search import PAGE_FTS_DDLawait conn.execute(text(PAGE_FTS_DDL))+++async def schema_behind(engine: AsyncEngine) -> bool:+ """Whether a table or column the models declare is missing from the store.++ One catalogue read, so a reader can skip the reconcile ``init_db`` runs and+ pay for it only on a store an older repowise wrote. SQLite only; another+ backend is migrated by Alembic and reads as current.+ """+ if engine.dialect.name != "sqlite":+ return False+ async with engine.connect() as conn:+ rows = await conn.execute(+ text(+ "SELECT m.name, p.name FROM sqlite_master AS m "+ "JOIN pragma_table_info(m.name) AS p WHERE m.type = 'table'"+ )+ )+ live: dict[str, set[str]] = {}+ for table, column in rows:+ live.setdefault(table, set()).add(column)+ return any(+ not {c.name for c in table.columns} <= live.get(name, set())+ for name, table in Base.metadata.tables.items()+ )diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py b/packages/server/src/repowise/server/mcp_server/tool_overview/tool.pyindex ff17d23ce..ef0e21cfc 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py@@ -2,9 +2,12 @@from __future__ import annotations+import asyncio+from collections.abc import Awaitablefrom typing import Anyfrom sqlalchemy import select+from sqlalchemy.pool import StaticPoolfrom repowise.core.persistence.crud import code_file_rowsfrom repowise.core.persistence.database import get_session@@ -99,7 +102,7 @@ async def get_overview(repo: str | None = None, include: list[str] | None = Noneasync with get_session(ctx.session_factory) as session:repository = await _get_repo(session)result = await _repo_overview(- session, repository, exclude_spec, set(include or []), collector+ session, ctx.session_factory, repository, exclude_spec, set(include or []), collector)# Made once per session, so this is where the full scope that every@@ -111,25 +114,34 @@ async def get_overview(repo: str | None = None, include: list[str] | None = Noneasync def _repo_overview(session: Any,+ session_factory: Any,repository: Any,exclude_spec: Any,want: set[str],collector: OmissionCollector,) -> dict[str, Any]:- """Every single-repo block, in payload order; empty optional blocks are left out."""- overview_page = await _load_overview_page(session, repository)- module_pages = await _load_module_pages(session, repository, collector)- entry_point_ids = await _resolve_entry_point_ids(session, repository, exclude_spec)- all_git = await _load_git_rows(session, repository, exclude_spec)- architecture = await _build_architecture(session, repository)- dependencies = await _build_package_dependencies(session, repository, exclude_spec)- if dependencies:- architecture = {**architecture, "dependencies": dependencies}- code_health = await _build_code_health(session, repository)- next_actions, next_actions_reason = await _build_next_actions(session, repository)- requested = await _requested_blocks(session, repository, exclude_spec, all_git, want)- sections, outline = await _load_outline(session, repository, want, collector)+ """Every single-repo block, in payload order; empty optional blocks are left out.++ Code health and the next actions are the slow reads and need nothing else+ here, so each runs on its own read session while the rest is read.+ """+ slow = _slow_reads(session, session_factory, repository)+ try:+ overview_page = await _load_overview_page(session, repository)+ module_pages = await _load_module_pages(session, repository, collector)+ entry_point_ids = await _resolve_entry_point_ids(session, repository, exclude_spec)+ all_git = await _load_git_rows(session, repository, exclude_spec)+ architecture = await _build_architecture(session, repository)+ dependencies = await _build_package_dependencies(session, repository, exclude_spec)+ if dependencies:+ architecture = {**architecture, "dependencies": dependencies}+ requested = await _requested_blocks(session, repository, exclude_spec, all_git, want)+ sections, outline = await _load_outline(session, repository, want, collector)+ except BaseException:+ await _abandon(slow)+ raisecontent_md, content_hint = _overview_content(overview_page, "content" in want)+ code_health, (next_actions, next_actions_reason) = await slowresult: dict[str, Any] = {"title": _resolve_title(overview_page, repository),@@ -180,6 +192,45 @@ async def _repo_overview(return result+def _slow_reads(session: Any, session_factory: Any, repository: Any) -> Awaitable[Any]:+ """``(code health, next actions)``: started now on their own sessions, or,+ on a store whose sessions share one connection, read later on *session*."""+ if not _own_connections(session_factory):+ return _in_turn(session, repository)++ async def apart(build: Any) -> Any:+ async with get_session(session_factory) as own:+ return await build(own, repository)++ return asyncio.gather(apart(_build_code_health), apart(_build_next_actions))+++async def _in_turn(session: Any, repository: Any) -> tuple[Any, Any]:+ return (+ await _build_code_health(session, repository),+ await _build_next_actions(session, repository),+ )+++async def _abandon(slow: Any) -> None:+ """Stop the slow reads when the rest failed, so no task outlives the call."""+ if isinstance(slow, asyncio.Future):+ slow.cancel()+ await asyncio.gather(slow, return_exceptions=True)+ else:+ slow.close() # an in-turn read that never started+++def _own_connections(session_factory: Any) -> bool:+ """Whether each session gets its own connection, so two can read at once.++ A ``StaticPool`` (in-memory SQLite) hands every session the same one, where+ their savepoints would collide.+ """+ bind = session_factory.kw.get("bind")+ return bind is not None and not isinstance(bind.sync_engine.pool, StaticPool)++_OUTLINE_HINT = ("The stored page tree — the same outline the web app and the ""editor extension render. Every 'section' in this response "diff --git a/packages/server/src/repowise/server/services/refactoring_health.py b/packages/server/src/repowise/server/services/refactoring_health.pyindex 60e201d12..2e858afe3 100644--- a/packages/server/src/repowise/server/services/refactoring_health.py+++ b/packages/server/src/repowise/server/services/refactoring_health.py@@ -240,7 +240,7 @@ class RefactoringHealthService:Upgrade path: store the eligibility on the opportunity row at indextime and filter on the column."""- queue = await load_fix_first(self._session, self._repository_id, limit=0)+ queue = await load_fix_first(self._session, self._repository_id, limit=0, verify=False)reasons = queue.refactoring_reasonsmatched = await refactoring_opportunity_ids(self._session, self._repository_id, **filtersdiff --git a/tests/unit/cli/test_repo_index_session.py b/tests/unit/cli/test_repo_index_session.pynew file mode 100644index 000000000..6c7819a4c--- /dev/null+++ b/tests/unit/cli/test_repo_index_session.py@@ -0,0 +1,99 @@+"""``repo_index_session`` reconciles the schema only when the store is behind."""++from __future__ import annotations++import asyncio+from pathlib import Path++import pytest++from repowise.cli import helpers+++def store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, str]:+ """A current store with one repository row: ``(root, repo_id)``."""+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+ )++ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)+ root = tmp_path.resolve()+ (root / ".repowise").mkdir()++ async def seed() -> str:+ engine = create_engine(f"sqlite+aiosqlite:///{_db(root).as_posix()}")+ try:+ await init_db(engine)+ async with get_session(create_session_factory(engine)) as session:+ repo = await upsert_repository(session, name="r", local_path=str(root))+ await session.commit()+ return repo.id+ finally:+ await engine.dispose()++ return root, asyncio.run(seed())+++def _db(root: Path) -> Path:+ return root / ".repowise" / "wiki.db"+++def _drop_a_column(root: Path) -> None:+ """The store an older repowise wrote: one column the models declare is absent."""+ import sqlite3++ with sqlite3.connect(_db(root)) as conn:+ conn.execute("ALTER TABLE health_file_metrics DROP COLUMN analyzed_commit")+++def _read(root: Path) -> str | None:+ async def go() -> str | None:+ async with helpers.repo_index_session(root) as opened:+ return None if opened is None else opened[1]++ return asyncio.run(go())+++def _count_reconciles(monkeypatch: pytest.MonkeyPatch, *, repair: bool) -> list[str]:+ calls: list[str] = []+ real = helpers.reconcile_schema_best_effort++ async def counting(url: str) -> None:+ calls.append(url)+ if repair:+ await real(url)++ monkeypatch.setattr(helpers, "reconcile_schema_best_effort", counting)+ return calls+++def test_a_current_store_opens_without_a_reconcile(store, monkeypatch) -> None:+ root, repo_id = store+ calls = _count_reconciles(monkeypatch, repair=True)+ assert _read(root) == repo_id+ assert calls == []+++def test_a_store_missing_a_column_is_reconciled_once(store, monkeypatch) -> None:+ root, repo_id = store+ _drop_a_column(root)+ calls = _count_reconciles(monkeypatch, repair=True)+ assert _read(root) == repo_id+ assert len(calls) == 1+ # Repaired in place, so the next read pays nothing.+ assert _read(root) == repo_id+ assert len(calls) == 1+++def test_a_store_the_reconcile_cannot_repair_names_the_fix(store, monkeypatch) -> None:+ root, _ = store+ _drop_a_column(root)+ _count_reconciles(monkeypatch, repair=False)+ with pytest.raises(helpers.StaleIndexError, match="run `repowise update`"):+ _read(root)diff --git a/tests/unit/persistence/test_crud_import_cost.py b/tests/unit/persistence/test_crud_import_cost.pynew file mode 100644index 000000000..6d8087bf9--- /dev/null+++ b/tests/unit/persistence/test_crud_import_cost.py@@ -0,0 +1,52 @@+"""The read paths' imports must not load the parser or the graph builder.++Every CLI read command imports the analysis CRUD layer; the dead-code analyzer+and the ingestion package's eager re-exports once made that import pull in+networkx and the tree-sitter parser, about two seconds before any query ran.+"""++from __future__ import annotations++import subprocess+import sys++import pytest++HEAVY = (+ "networkx",+ "repowise.core.ingestion.graph",+ "repowise.core.ingestion.parser",+ "repowise.core.analysis.dead_code.analyzer",+)+++ ("module", "heavy"),+ [+ ("repowise.core.persistence.crud.analysis.actions", HEAVY),+ ("repowise.cli.commands.health_cmd.persist", HEAVY),+ # The MCP server is one long-lived process whose graph tools use+ # networkx; it must still not load the parser or the dead-code pass.+ ("repowise.server.mcp_server.tool_overview.tool", HEAVY[1:]),+ ],+)+def test_a_read_path_loads_no_parser_or_graph(module: str, heavy: tuple[str, ...]) -> None:+ probe = f"import sys, {module}; print(sorted(m for m in {heavy!r} if m in sys.modules))"+ out = subprocess.run(+ [sys.executable, "-c", probe], capture_output=True, text=True, check=True+ ).stdout+ assert out.strip() == "[]"+++def test_lazy_names_resolve_and_are_listed() -> None:+ from repowise.core import ingestion+ from repowise.core.analysis import dead_code+ from repowise.core.analysis.dead_code.analyzer import DeadCodeAnalyzer+ from repowise.core.ingestion.graph import GraphBuilder++ assert {"GraphBuilder", "FileTraverser"} <= set(dir(ingestion))+ assert ingestion.GraphBuilder is GraphBuilder+ assert dead_code.DeadCodeAnalyzer is DeadCodeAnalyzer+ assert "DeadCodeAnalyzer" in dir(dead_code)+ with pytest.raises(AttributeError):+ _ = ingestion.NoSuchNamediff --git a/tests/unit/persistence/test_fix_first_loader.py b/tests/unit/persistence/test_fix_first_loader.pyindex a24e81323..a7bebc0d5 100644--- a/tests/unit/persistence/test_fix_first_loader.py+++ b/tests/unit/persistence/test_fix_first_loader.py@@ -320,3 +320,31 @@ def test_json_text_renders_for_both_dialects() -> None:query = select(json_text(column("details_json"), "actionability_reason"))assert "json_extract(details_json" in str(query.compile(dialect=sqlite.dialect()))assert "CAST(details_json AS JSON) ->>" in str(query.compile(dialect=postgresql.dialect()))+++async def test_an_unverified_read_skips_the_test_lookup(async_session, monkeypatch) -> None:+ """The actions view never shows tests, so it must not pay for resolving them.++ The verified queue, once built, answers an unverified read too.+ """+ from repowise.core.persistence.crud.analysis import fix_first as loader++ rid = await seed_fix_first(async_session)+ loader.clear_fix_first_cache()+ calls = 0+ original = loader._finding_validator++ async def counting(*args, **kwargs):+ nonlocal calls+ calls += 1+ return await original(*args, **kwargs)++ monkeypatch.setattr(loader, "_finding_validator", counting)+ bare = await load_fix_first(async_session, rid, verify=False)+ assert calls == 0+ assert [i.id for i in bare.items] == [i.id for i in (await load_fix_first(async_session, rid)).items]+ assert calls == 1+ assert (await load_fix_first(async_session, rid, limit=None, verify=False)).items == (+ await load_fix_first(async_session, rid, limit=None)+ ).items+ assert calls == 1diff --git a/tests/unit/server/mcp/test_overview_next_actions.py b/tests/unit/server/mcp/test_overview_next_actions.pyindex d264c894e..58fe713dd 100644--- a/tests/unit/server/mcp/test_overview_next_actions.py+++ b/tests/unit/server/mcp/test_overview_next_actions.py@@ -107,3 +107,91 @@ def test_budget_sheds_the_block_before_the_protected_ones():order = contract.shed_orderassert order.index("next_actions.quarter.actions[]") < order.index("next_actions")assert "next_actions" not in contract.protected++++def _factory(url: str):+ from sqlalchemy.ext.asyncio import async_sessionmaker++ from repowise.core.persistence import create_engine++ return async_sessionmaker(create_engine(url))+++def _record(monkeypatch, gate=None):+ """Stand-ins for the two slow blocks that note the session each read on."""+ from repowise.server.mcp_server.tool_overview import tool++ seen: dict = {}++ async def code_health(session, _repo):+ seen["code_health"] = session+ if gate is not None:+ await gate.wait() # finishes only if next_actions runs meanwhile+ return {"average_health": 7.0}++ async def next_actions(session, _repo):+ seen["next_actions"] = session+ if gate is not None:+ gate.set()+ return {}, None++ monkeypatch.setattr(tool, "_build_code_health", code_health)+ monkeypatch.setattr(tool, "_build_next_actions", next_actions)+ return seen+++async def test_on_a_file_store_the_slow_blocks_read_together_on_their_own_sessions(+ tmp_path, monkeypatch+):+ import asyncio++ from repowise.server.mcp_server.tool_overview.tool import _slow_reads++ seen = _record(monkeypatch, gate=asyncio.Event())+ caller = object()+ slow = _slow_reads(caller, _factory(f"sqlite+aiosqlite:///{(tmp_path / 'w.db').as_posix()}"), None)+ health, actions = await asyncio.wait_for(slow, timeout=10)++ assert health == {"average_health": 7.0} and actions == ({}, None)+ assert seen["code_health"] is not caller and seen["next_actions"] is not caller+ assert seen["code_health"] is not seen["next_actions"]+++async def test_on_a_shared_connection_they_read_in_turn_on_the_callers_session(monkeypatch):+ from repowise.server.mcp_server.tool_overview.tool import _slow_reads++ seen = _record(monkeypatch)+ caller = object()+ slow = _slow_reads(caller, _factory("sqlite+aiosqlite:///:memory:"), None)+ assert seen == {}, "nothing reads before the caller's own reads are done"+ await slow+ assert seen == {"code_health": caller, "next_actions": caller}+++async def test_a_failed_overview_leaves_no_slow_read_running(tmp_path, monkeypatch):+ import asyncio++ from repowise.server.mcp_server.tool_overview.tool import _abandon, _slow_reads++ _record(monkeypatch, gate=asyncio.Event())+ from repowise.server.mcp_server.tool_overview import tool++ async def stuck(session, _repo):+ await asyncio.Event().wait()++ monkeypatch.setattr(tool, "_build_next_actions", stuck)+ before = asyncio.all_tasks()+ slow = _slow_reads(object(), _factory(f"sqlite+aiosqlite:///{(tmp_path / 'w.db').as_posix()}"), None)+ await asyncio.sleep(0)+ await _abandon(slow)++ assert slow.done()+ assert asyncio.all_tasks() <= before+ # The fallback is a coroutine that never started; abandoning closes it.+ lazy = _slow_reads(object(), _factory("sqlite+aiosqlite:///:memory:"), None)+ await _abandon(lazy)+ assert lazy.cr_frame is None