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(hooks): read the index with stdlib sqlite3 on the three lookups that never needed the ORM (#1297)

Raghav Chamadiya7c037e9215b7
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/fast_lookup.py b/packages/cli/src/repowise/cli/commands/augment_cmd/fast_lookup.py
new file mode 100644
index 000000000..fbd09830a
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/fast_lookup.py
@@ -0,0 +1,135 @@
+"""Read-only stdlib-``sqlite3`` twins of the three hot hook index lookups.
+
+Why this exists rather than the ORM the rest of the codebase uses: in a fresh
+hook process, ``import repowise.core.persistence`` costs ~958ms on this
+machine, against 17ms to build the engine and 34ms to run the query. The three
+call sites that use this module (the flood digest's PageRank ordering,
+triage's symbol + PageRank pair, the widened rescue's exact-name lookup) are
+plain SELECTs over two tables. They never used the MCP retrieval stack and
+already hand-write their own selects, so paying that import buys them nothing.
+
+The zero-result rescue deliberately does **not** use this module: 45% of its
+queries fall through to ``FullTextSearch``, which is genuinely shared code
+doing real work. No FTS5 is hand-rolled here and no part of the retrieval
+stack is replaced.
+
+Everything here is read-only and fails soft. :func:`connect` returns ``None``
+whenever the fast path is not provably safe, and every caller falls back to
+the ORM path rather than to silence, so schema drift degrades to today's
+behaviour instead of losing the surface.
+"""
+
+from __future__ import annotations
+
+import os
+import sqlite3
+from pathlib import Path
+
+#: The env vars ``resolve_db_url`` honours, copied from
+#: ``repowise.core.persistence.database.DB_ENV_VARS`` rather than imported:
+#: importing that module runs the persistence package ``__init__``, which is
+#: the second this module exists to avoid. If that tuple ever grows, this one
+#: has to grow with it; the cost of missing it is a slow query, not a wrong
+#: answer, because an unrecognised URL still lands on the ORM.
+_DB_ENV_VARS = ("REPOWISE_DB_URL", "REPOWISE_DATABASE_URL")
+
+#: SQLAlchemy compiles ``ilike()`` on SQLite to
+#: ``lower(col) LIKE lower(?) ESCAPE '\\'``. The queries below spell that out
+#: verbatim so the ported semantics are identical rather than merely similar.
+#: ``escape_like`` is the same function as ``persistence.sql.escape_like``,
+#: duplicated for the same import reason as above.
+_LIKE_ESCAPE = "\\"
+
+
+def escape_like(value: str) -> str:
+ """Escape LIKE metacharacters; twin of ``persistence.sql.escape_like``."""
+ return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+
+
+def connect(repo_path: Path) -> sqlite3.Connection | None:
+ """Read-only connection to the repo's ``wiki.db``, or None for the ORM.
+
+ ``None`` whenever a DB env var is set: ``resolve_db_url`` honours
+ ``REPOWISE_DB_URL`` / ``REPOWISE_DATABASE_URL``, so a hosted or postgres
+ setup must not be handed a local file path and silently find nothing. A
+ sqlite override lands here too, taking the ORM path rather than growing
+ URL parsing for a case no hook has; the ceiling on that shortcut is one
+ slow query, and lifting it is a URL parse away.
+
+ Callers must check the file exists first when a missing index means
+ "stay silent" rather than "use the ORM": the two entry points differ.
+ """
+ if any(os.environ.get(name) for name in _DB_ENV_VARS):
+ return None
+ db_path = repo_path / ".repowise" / "wiki.db"
+ if not db_path.exists():
+ return None
+ try:
+ return sqlite3.connect(
+ f"file:{db_path.as_posix()}?mode=ro", uri=True, timeout=1
+ )
+ except sqlite3.Error:
+ return None
+
+
+def repo_id(conn: sqlite3.Connection, repo_path: Path) -> str | None:
+ """The indexed repository id for *repo_path*, or None if it has no row.
+
+ Matches ``get_repository_by_path``: exact equality against the stored
+ ``local_path``, spelled with ``str(repo_path)`` as every writer does.
+ """
+ row = conn.execute(
+ "SELECT id FROM repositories WHERE local_path = ?", (str(repo_path),)
+ ).fetchone()
+ return row[0] if row else None
+
+
+def pagerank(
+ conn: sqlite3.Connection, repository_id: str, paths: list[str]
+) -> dict[str, float]:
+ """PageRank by node id for the file nodes among *paths*."""
+ if not paths:
+ return {}
+ placeholders = ",".join("?" * len(paths))
+ rows = conn.execute(
+ "SELECT node_id, pagerank FROM graph_nodes "
+ "WHERE repository_id = ? AND node_type = 'file' "
+ f"AND node_id IN ({placeholders})",
+ (repository_id, *paths),
+ ).fetchall()
+ return {node_id: pr or 0.0 for node_id, pr in rows if node_id}
+
+
+def symbols_matching(
+ conn: sqlite3.Connection, repository_id: str, paths: list[str], needle: str
+) -> list[tuple[str, str]]:
+ """``(file_path, name)`` for symbols in *paths* whose name contains *needle*."""
+ if not paths:
+ return []
+ placeholders = ",".join("?" * len(paths))
+ return conn.execute(
+ "SELECT file_path, name FROM wiki_symbols "
+ f"WHERE repository_id = ? AND file_path IN ({placeholders}) "
+ f"AND lower(name) LIKE lower(?) ESCAPE '{_LIKE_ESCAPE}'",
+ (repository_id, *paths, f"%{escape_like(needle)}%"),
+ ).fetchall()
+
+
+def symbols_named(
+ conn: sqlite3.Connection, repository_id: str, names: list[str], limit: int
+) -> list[tuple[str, str, str, int]]:
+ """``(name, kind, file_path, start_line)`` for symbols named exactly *names*.
+
+ Case-sensitive, like the ``IN`` it replaces: SQLite compares TEXT with
+ BINARY collation unless a column says otherwise, and neither the ORM path
+ nor this one asks for NOCASE. The widened rescue depends on that, since it
+ generates its case variants explicitly.
+ """
+ if not names:
+ return []
+ placeholders = ",".join("?" * len(names))
+ return conn.execute(
+ "SELECT name, kind, file_path, start_line FROM wiki_symbols "
+ f"WHERE repository_id = ? AND name IN ({placeholders}) LIMIT ?",
+ (repository_id, *names, limit),
+ ).fetchall()
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/search.py b/packages/cli/src/repowise/cli/commands/augment_cmd/search.py
index 8cec76276..0fa36ac10 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/search.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/search.py
@@ -21,8 +21,10 @@ and are not billed to the savings ledger; only the *served* digest
from __future__ import annotations
+import sqlite3
from pathlib import Path
+from . import fast_lookup
from ._shared import HookResult, _extract_output_text, _find_repo_root
# NOTE: repowise.core.persistence.sql is imported inside _rescue/_triage, not
@@ -32,6 +34,10 @@ from ._shared import HookResult, _extract_output_text, _find_repo_root
# a search was paying the whole bill. Both users are already async functions
# that defer their sqlalchemy imports; this is the same rule applied one line
# further. Keep it deferred.
+#
+# The three lookups that no longer need it at all go through ``fast_lookup``,
+# which is stdlib ``sqlite3`` only and therefore safe at module scope. Every
+# fast path here falls back to the ORM one below it, never to silence.
# Tunables — fixed thresholds keep the fire pattern predictable across
# repos. If these ever need to vary, derive them from indexed-row counts
@@ -141,11 +147,13 @@ def _handle_search_post(
if not matched:
return HookResult()
- import asyncio
+ enrichment = _fast_search_enrich(repo_path, pattern, mode, result_count, matched)
+ if enrichment is _ORM:
+ import asyncio
- enrichment = asyncio.run(
- _search_enrich(repo_path, pattern, mode, result_count, matched)
- )
+ enrichment = asyncio.run(
+ _search_enrich(repo_path, pattern, mode, result_count, matched)
+ )
if enrichment:
_log_search_firing(repo_path, session_id, mode, enrichment)
return HookResult(context=enrichment or None)
@@ -287,15 +295,17 @@ def _grep_flood_digest(repo_path: Path, output_text: str) -> str | None:
# One or two files: the raw output is already navigable.
return None
- file_order = None
- ranked_by_graph = False
- try:
- import asyncio
-
- file_order = asyncio.run(_pagerank_file_order(repo_path, list(groups.keys())))
- ranked_by_graph = file_order is not None
- except Exception:
+ paths = list(groups.keys())
+ file_order = _fast_pagerank_file_order(repo_path, paths)
+ if file_order is _ORM:
file_order = None
+ try:
+ import asyncio
+
+ file_order = asyncio.run(_pagerank_file_order(repo_path, paths))
+ except Exception:
+ file_order = None
+ ranked_by_graph = file_order is not None
if file_order is None:
file_order = sorted(groups, key=lambda p: -len(groups[p]))
@@ -394,14 +404,118 @@ async def _pagerank_file_order(repo_path: Path, paths: list[str]) -> list[str] |
finally:
await engine.dispose()
- if not rows:
+ return _order_by_pagerank(paths, normalized, dict(rows))
+
+
+def _order_by_pagerank(
+ paths: list[str], normalized: dict[str, str], by_node: dict[str, float]
+) -> list[str] | None:
+ """Grep-spelled *paths*, PageRank first, unranked tail in grep order.
+
+ Shared by both lookup paths so the ordering cannot drift between them.
+ """
+ if not by_node:
return None
- rank = {normalized[node_id]: pr or 0.0 for node_id, pr in rows if node_id in normalized}
+ rank = {
+ normalized[node_id]: pr or 0.0
+ for node_id, pr in by_node.items()
+ if node_id in normalized
+ }
ranked = sorted(rank, key=lambda p: -rank[p])
rest = [p for p in paths if p not in rank]
return ranked + rest
+# ---------------------------------------------------------------------------
+# Fast path: the same three lookups without the persistence import
+# ---------------------------------------------------------------------------
+
+#: "The fast path could not answer this; run the ORM query." Distinct from
+#: ``None``, which is a real answer meaning "stay silent", and the reason
+#: these helpers cannot just return ``None`` on failure: that would turn a
+#: missing table into a silently dropped surface.
+_ORM = object()
+
+
+def _wiki_db_exists(repo_path: Path) -> bool:
+ """Whether this repo has a local index at all.
+
+ Both ORM entry points bail out before their sqlalchemy imports on this
+ check, so the fast path has to answer "no index" the same way, with
+ silence, not with a fallback that pays the import to learn the same thing.
+ """
+ return (repo_path / ".repowise" / "wiki.db").exists()
+
+
+def _fast_pagerank_file_order(repo_path: Path, paths: list[str]) -> list[str] | None | object:
+ """``_pagerank_file_order`` over stdlib sqlite3. ``_ORM`` to fall back."""
+ if not _wiki_db_exists(repo_path):
+ return None
+ conn = fast_lookup.connect(repo_path)
+ if conn is None:
+ return _ORM
+ try:
+ repository_id = fast_lookup.repo_id(conn, repo_path)
+ if repository_id is None:
+ return None
+ normalized = _as_node_ids(repo_path, paths)
+ by_node = fast_lookup.pagerank(conn, repository_id, list(normalized))
+ return _order_by_pagerank(paths, normalized, by_node)
+ except sqlite3.Error:
+ return _ORM
+ finally:
+ conn.close()
+
+
+def _fast_search_enrich(
+ repo_path: Path,
+ pattern: str,
+ mode: str,
+ result_count: int,
+ matched: dict[str, int] | None,
+) -> str | None | object:
+ """Triage and the widened rescue without the ORM. ``_ORM`` to fall back.
+
+ The zero-result rescue is not served here on purpose: 45% of its queries
+ fall through to ``FullTextSearch``, so it stays on the shared retrieval
+ code and pays the import it actually uses.
+ """
+ if mode not in ("triage", "rescue_wide") or not matched:
+ return _ORM
+ clean = _clean_pattern(pattern)
+ if not clean:
+ return None
+ if not _wiki_db_exists(repo_path):
+ return None
+ conn = fast_lookup.connect(repo_path)
+ if conn is None:
+ return _ORM
+ try:
+ repository_id = fast_lookup.repo_id(conn, repo_path)
+ if repository_id is None:
+ return None
+ if mode == "triage":
+ if len(matched) < 2:
+ return None
+ paths = _triage_candidates(matched)
+ symbol_names: dict[str, list[str]] = {}
+ for file_path, name in fast_lookup.symbols_matching(
+ conn, repository_id, paths, clean
+ ):
+ if file_path and name:
+ symbol_names.setdefault(file_path, []).append(name)
+ pagerank = fast_lookup.pagerank(conn, repository_id, paths)
+ return _triage_text(pattern, result_count, matched, symbol_names, pagerank)
+ rows = fast_lookup.symbols_named(
+ conn, repository_id, sorted(_name_variants(clean)), _RESCUE_EXACT_FETCH
+ )
+ return _rescue_wide_text(pattern, clean, matched, rows)
+ except sqlite3.Error:
+ return _ORM
+ finally:
+ conn.close()
+
+
def _looks_like_path_lookup(pattern: str) -> bool:
"""Heuristic: pattern is a literal file path, not a search concept.
@@ -576,8 +690,6 @@ async def _search_enrich(
matched: dict[str, int] | None = None,
) -> str | None:
"""Run the rescue or triage query against the wiki and format output."""
- import re
-
from repowise.core.persistence import (
create_engine,
create_session_factory,
@@ -602,7 +714,7 @@ async def _search_enrich(
return None
repo_id = repo.id
- clean = re.sub(r"[^\w./_-]", "", pattern).strip("./")
+ clean = _clean_pattern(pattern)
if mode == "rescue":
return await _rescue(session, engine, repo_id, pattern, clean)
@@ -687,25 +799,12 @@ async def _rescue(
.limit(_RESCUE_TOP_N if matched is None else _RESCUE_EXACT_FETCH)
)
rows = (await session.execute(sym_stmt)).all()
+ if matched is not None:
+ return _rescue_wide_text(pattern, clean, matched, rows)
if rows:
- # Rank: prefer exact-token-equal matches; then shortest name (most
- # specific). All ties broken by file path lex order for stability.
- def _rank(row):
- name = (row[0] or "").lower()
- return (name not in lowered, len(name), row[2] or "")
-
- rows = sorted(rows, key=_rank)[:_RESCUE_TOP_N]
+ rows = _rescue_rank(rows, lowered)
first = rows[0]
line = f":{first[3]}" if first[3] else ""
- if matched is not None:
- if (first[2] or "") in matched:
- # The agent already has this file. Nothing new to say.
- return None
- return (
- f"[repowise] `{pattern}` matched {len(matched)} "
- f"file{'s' if len(matched) != 1 else ''}, but not {first[2]}{line}, "
- f"where indexed {first[1]} `{first[0]}` is defined."
- )
extras = ""
if len(rows) > 1:
extras = f" (+{len(rows) - 1} more)"
@@ -714,9 +813,6 @@ async def _rescue(
f"{first[1]} `{first[0]}` in {first[2]}{line}{extras}"
)
- if matched is not None:
- return None
-
# Fall back to FTS on wiki content. Only return if the FTS row actually
# points at a code page (file/module/api), not a generic doc page.
fts = FullTextSearch(engine)
@@ -794,8 +890,7 @@ async def _triage(
# it. Emitting there would be pure cost.
return None
- # Widest floods first-cut by match count. See _TRIAGE_MAX_CANDIDATES.
- paths = sorted(matched, key=lambda p: (-matched[p], p))[:_TRIAGE_MAX_CANDIDATES]
+ paths = _triage_candidates(matched)
sym_stmt = select(WikiSymbol.file_path, WikiSymbol.name).where(
WikiSymbol.repository_id == repo_id,
@@ -817,11 +912,48 @@ async def _triage(
for node_id, pr in (await session.execute(pr_stmt)).all()
if node_id
}
+ return _triage_text(pattern, result_count, matched, symbol_names, pagerank)
+
+
+# ---------------------------------------------------------------------------
+# Pure ranking and formatting, shared by the ORM and sqlite3 paths
+# ---------------------------------------------------------------------------
+#
+# Everything below takes rows and returns text. Both lookup paths run the same
+# two queries and then land here, so a ported query can change what it costs
+# but not what it says.
+
+
+def _clean_pattern(pattern: str) -> str:
+ """The pattern reduced to a symbol-ish token for index lookups."""
+ import re
+
+ return re.sub(r"[^\w./_-]", "", pattern).strip("./")
+
+
+def _triage_candidates(matched: dict[str, int]) -> list[str]:
+ """Matched files the ranker considers, widest floods first-cut by count.
+
+ See :data:`_TRIAGE_MAX_CANDIDATES`; also the parameter list of both index
+ queries, so the cut has to happen before either of them runs.
+ """
+ return sorted(matched, key=lambda p: (-matched[p], p))[:_TRIAGE_MAX_CANDIDATES]
+
+
+def _triage_text(
+ pattern: str,
+ result_count: int,
+ matched: dict[str, int],
+ symbol_names: dict[str, list[str]],
+ pagerank: dict[str, float],
+) -> str | None:
+ """Fuse the three legs and render triage's block, or None to stay silent."""
if not symbol_names and not pagerank:
# The index knows nothing about any matched file. Re-listing the
# grep's own top files back at it is not worth the tokens.
return None
+ paths = _triage_candidates(matched)
legs = [
paths,
_coverage_order(pattern, paths, symbol_names),
@@ -841,6 +973,44 @@ async def _triage(
return "\n".join(lines)
+def _rescue_rank(rows: list, lowered: set[str]) -> list:
+ """Best rescue candidates first, capped at :data:`_RESCUE_TOP_N`.
+
+ Prefer exact-token-equal matches; then the shortest name, as the most
+ specific; ties broken by file path lex order so the answer is stable
+ across query plans.
+ """
+
+ def _key(row):
+ name = (row[0] or "").lower()
+ return (name not in lowered, len(name), row[2] or "")
+
+ return sorted(rows, key=_key)[:_RESCUE_TOP_N]
+
+
+def _rescue_wide_text(
+ pattern: str, clean: str, matched: dict[str, int], rows: list
+) -> str | None:
+ """The widened rescue's line, or None when it has nothing new to say.
+
+ The gate is a set difference, not a count: the top exact-name match has to
+ live in a file the grep did *not* return. See :func:`_rescue`.
+ """
+ if not rows:
+ return None
+ rows = _rescue_rank(rows, {v.lower() for v in _name_variants(clean)})
+ first = rows[0]
+ if (first[2] or "") in matched:
+ # The agent already has this file. Nothing new to say.
+ return None
+ line = f":{first[3]}" if first[3] else ""
+ return (
+ f"[repowise] `{pattern}` matched {len(matched)} "
+ f"file{'s' if len(matched) != 1 else ''}, but not {first[2]}{line}, "
+ f"where indexed {first[1]} `{first[0]}` is defined."
+ )
+
+
def _rrf(legs: list[list[str]]) -> dict[str, float]:
"""Reciprocal Rank Fusion over ranked lists: ``sum(1/(rank + k))``.
diff --git a/tests/unit/cli/test_augment_fast_lookup.py b/tests/unit/cli/test_augment_fast_lookup.py
new file mode 100644
index 000000000..c6022a1c2
--- /dev/null
+++ b/tests/unit/cli/test_augment_fast_lookup.py
@@ -0,0 +1,201 @@
+"""The stdlib-sqlite3 lookups against a real wiki.db, and their fallbacks.
+
+Every behavioural test here is an *equivalence* test: it runs the fast path
+and the ORM path over the same database and asserts the two produce the same
+string. That is the only property the port is allowed to have. The speed is
+measured elsewhere; what these pin is that nothing else moved, including the
+two case-sensitivity semantics that differ between the queries (`IN` is
+case-sensitive, `ilike` is not) and the three ways the fast path is required
+to hand the work back to the ORM.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+import pytest
+
+from repowise.cli.commands.augment_cmd import fast_lookup
+from repowise.cli.commands.augment_cmd.search import (
+ _ORM,
+ _fast_pagerank_file_order,
+ _fast_search_enrich,
+ _pagerank_file_order,
+ _search_enrich,
+)
+
+MATCHED = {"src/a.py": 3, "src/b.py": 1}
+
+
+async def _build(repo_path: Path, symbols: list[tuple[str, str, str, int]]) -> None:
+ """A real indexed repo: one repository row, symbols, and file nodes."""
+ from repowise.core.persistence import (
+ GraphNode,
+ WikiSymbol,
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_repository,
+ )
+
+ db_path = repo_path / ".repowise" / "wiki.db"
+ db_path.parent.mkdir(parents=True, exist_ok=True)
+ engine = create_engine(f"sqlite+aiosqlite:///{db_path.as_posix()}")
+ try:
+ await init_db(engine)
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ repo = await upsert_repository(session, name="repo", local_path=str(repo_path))
+ for name, kind, file_path, start_line in symbols:
+ session.add(
+ WikiSymbol(
+ repository_id=repo.id,
+ file_path=file_path,
+ symbol_id=f"{file_path}::{name}",
+ name=name,
+ qualified_name=name,
+ kind=kind,
+ start_line=start_line,
+ )
+ )
+ for node_id, pagerank in (("src/a.py", 0.9), ("src/b.py", 0.1)):
+ session.add(
+ GraphNode(
+ repository_id=repo.id,
+ node_id=node_id,
+ node_type="file",
+ pagerank=pagerank,
+ )
+ )
+ finally:
+ await engine.dispose()
+
+
+def indexed_repo(tmp_path) -> Path:
+ """A repo whose index defines ``parseYaml`` in a file grep did not match."""
+ asyncio.run(
+ _build(
+ tmp_path,
+ [
+ ("parse_yaml", "function", "src/b.py", 42),
+ ("parseYaml", "function", "src/other.py", 10),
+ ],
+ )
+ )
+ return tmp_path
+
+
+def _orm(repo_path: Path, pattern: str, mode: str, matched: dict[str, int]) -> str | None:
+ return asyncio.run(_search_enrich(repo_path, pattern, mode, 40, matched))
+
+
+class TestEquivalence:
+ def test_triage_says_what_the_orm_says(self, indexed_repo: Path) -> None:
+ fast = _fast_search_enrich(indexed_repo, "parse_yaml", "triage", 40, MATCHED)
+ assert fast is not _ORM
+ assert fast == _orm(indexed_repo, "parse_yaml", "triage", MATCHED)
+ assert fast is not None
+
+ def test_widened_rescue_says_what_the_orm_says(self, indexed_repo: Path) -> None:
+ fast = _fast_search_enrich(indexed_repo, "parse_yaml", "rescue_wide", 5, MATCHED)
+ assert fast == _orm(indexed_repo, "parse_yaml", "rescue_wide", MATCHED)
+ assert fast == (
+ "[repowise] `parse_yaml` matched 2 files, but not src/other.py:10, "
+ "where indexed function `parseYaml` is defined."
+ )
+
+ def test_pagerank_order_matches_the_orm(self, indexed_repo: Path) -> None:
+ paths = ["src/b.py", "src/a.py"]
+ fast = _fast_pagerank_file_order(indexed_repo, paths)
+ assert fast == asyncio.run(_pagerank_file_order(indexed_repo, paths))
+ assert fast == ["src/a.py", "src/b.py"]
+
+ def test_zero_result_rescue_is_never_served_here(self, indexed_repo: Path) -> None:
+ """It keeps the ORM: 45% of its queries fall through to FTS."""
+ assert _fast_search_enrich(indexed_repo, "parse_yaml", "rescue", 0, None) is _ORM
+
+
+class TestFallsBackToTheOrm:
+ def test_a_configured_db_url_is_not_a_local_file(
+ self, indexed_repo: Path, monkeypatch
+ ) -> None:
+ """The one way a naive version breaks in production.
+
+ ``resolve_db_url`` honours these, so a hosted or postgres setup must
+ reach the ORM rather than quietly read a stale local sqlite file.
+ """
+ for var in ("REPOWISE_DB_URL", "REPOWISE_DATABASE_URL"):
+ monkeypatch.setenv(var, "postgresql://user@host/db")
+ assert _fast_search_enrich(indexed_repo, "parse_yaml", "triage", 40, MATCHED) is _ORM
+ assert _fast_pagerank_file_order(indexed_repo, ["src/a.py"]) is _ORM
+ monkeypatch.delenv(var)
+
+ def test_schema_drift_degrades_to_todays_behaviour(self, tmp_path: Path) -> None:
+ """A wiki.db without the tables must not lose the surface."""
+ (tmp_path / ".repowise").mkdir()
+ (tmp_path / ".repowise" / "wiki.db").write_bytes(b"")
+ assert _fast_search_enrich(tmp_path, "parse_yaml", "triage", 40, MATCHED) is _ORM
+ assert _fast_pagerank_file_order(tmp_path, ["src/a.py"]) is _ORM
+
+ def test_no_index_is_silence_not_a_fallback(self, tmp_path: Path) -> None:
+ """No wiki.db: the ORM would import a second to answer None."""
+ (tmp_path / ".repowise").mkdir()
+ assert _fast_search_enrich(tmp_path, "parse_yaml", "triage", 40, MATCHED) is None
+ assert _fast_pagerank_file_order(tmp_path, ["src/a.py"]) is None
+
+ def test_unindexed_repo_row_is_silence(self, tmp_path: Path) -> None:
+ """The db exists and is well-formed, but describes another checkout."""
+ asyncio.run(_build(tmp_path, [("parse_yaml", "function", "src/b.py", 42)]))
+ elsewhere = tmp_path / "nested"
+ (elsewhere / ".repowise").mkdir(parents=True)
+ (elsewhere / ".repowise" / "wiki.db").write_bytes(
+ (tmp_path / ".repowise" / "wiki.db").read_bytes()
+ )
+ assert _fast_search_enrich(elsewhere, "parse_yaml", "triage", 40, MATCHED) is None
+
+
+class TestCaseSemantics:
+ """The ported queries differ from each other, and both had to survive."""
+
+ def test_exact_name_lookup_stays_case_sensitive(self, indexed_repo: Path) -> None:
+ """``IN`` compares TEXT with BINARY collation; the rescue relies on it.
+
+ Its variants are generated case by case, so a case-insensitive match
+ would make every variant fire on every other one.
+ """
+ conn = fast_lookup.connect(indexed_repo)
+ assert conn is not None
+ try:
+ repo_id = fast_lookup.repo_id(conn, indexed_repo)
+ assert fast_lookup.symbols_named(conn, repo_id, ["parseYaml"], 8)
+ assert fast_lookup.symbols_named(conn, repo_id, ["PARSEYAML"], 8) == []
+ finally:
+ conn.close()
+
+ def test_name_contains_lookup_stays_case_insensitive(self, indexed_repo: Path) -> None:
+ """``ilike`` compiles to ``lower(name) LIKE lower(?)``; triage needs that."""
+ conn = fast_lookup.connect(indexed_repo)
+ assert conn is not None
+ try:
+ repo_id = fast_lookup.repo_id(conn, indexed_repo)
+ paths = ["src/b.py", "src/other.py"]
+ assert fast_lookup.symbols_matching(conn, repo_id, paths, "PARSE_YAML")
+ assert fast_lookup.symbols_matching(conn, repo_id, paths, "yaml")
+ finally:
+ conn.close()
+
+ def test_like_metacharacters_are_escaped(self, indexed_repo: Path) -> None:
+ """``_`` is a wildcard unescaped, and it is in most Python names."""
+ conn = fast_lookup.connect(indexed_repo)
+ assert conn is not None
+ try:
+ repo_id = fast_lookup.repo_id(conn, indexed_repo)
+ # parse_yaml is indexed; parseXyaml is not, and only an unescaped
+ # underscore would let this pattern reach it.
+ assert fast_lookup.symbols_matching(conn, repo_id, ["src/b.py"], "parse_yaml")
+ assert fast_lookup.symbols_matching(conn, repo_id, ["src/b.py"], "parsexyaml") == []
+ finally:
+ conn.close()
diff --git a/tests/unit/cli/test_augment_hook_perf.py b/tests/unit/cli/test_augment_hook_perf.py
index 3e454dd4a..29effae44 100644
--- a/tests/unit/cli/test_augment_hook_perf.py
+++ b/tests/unit/cli/test_augment_hook_perf.py
@@ -208,6 +208,76 @@ def test_a_read_in_a_repo_that_did_not_opt_in_imports_nothing_heavy(tmp_path: Pa
assert state["forgone"] == [rel], "the probe did not reach the counterfactual"
+def _indexed_search_repo(tmp_path: Path) -> Path:
+ """A repo the Grep hook will take all the way to a triage emission.
+
+ Three tables, spelled as the fast lookups read them: the repository row
+ they resolve the id from, the symbols the coverage leg needs, and the file
+ nodes the PageRank leg needs. Written with stdlib sqlite3 for the same
+ reason the hook now reads it that way.
+ """
+ repo = tmp_path / "repo"
+ (repo / ".repowise").mkdir(parents=True)
+ con = sqlite3.connect(repo / ".repowise" / "wiki.db")
+ con.execute("CREATE TABLE repositories (id TEXT, local_path TEXT)")
+ con.execute("INSERT INTO repositories VALUES ('r1', ?)", (str(repo),))
+ con.execute(
+ "CREATE TABLE wiki_symbols (repository_id TEXT, file_path TEXT, name TEXT, "
+ "kind TEXT, start_line INTEGER)"
+ )
+ con.execute(
+ "INSERT INTO wiki_symbols VALUES ('r1', 'src/b.py', 'parse_yaml', 'function', 42)"
+ )
+ con.execute(
+ "CREATE TABLE graph_nodes (repository_id TEXT, node_id TEXT, node_type TEXT, "
+ "pagerank REAL)"
+ )
+ for node_id, pagerank in (("src/a.py", 0.9), ("src/b.py", 0.1)):
+ con.execute("INSERT INTO graph_nodes VALUES ('r1', ?, 'file', ?)", (node_id, pagerank))
+ con.commit()
+ con.close()
+ return repo
+
+
+def test_a_triage_that_queries_the_index_imports_nothing_heavy(tmp_path: Path) -> None:
+ """The surface that *does* reach the index, on the same cheap graph.
+
+ Triage queried the wiki through the ORM, so a firing cost ~1.1s of cold
+ ``repowise.core.persistence`` import against 34ms of query. It now runs on
+ stdlib sqlite3. This is the guard that keeps it there, and unlike the
+ silent-invocation test above it can only pass by actually emitting.
+ """
+ repo = _indexed_search_repo(tmp_path)
+ content = "\n".join(
+ f"src/{'a' if i % 2 else 'b'}.py:{i}:parse_yaml(x)" for i in range(1, 21)
+ )
+ payload = {
+ "hook_event_name": "PostToolUse",
+ "tool_name": "Grep",
+ "tool_input": {"pattern": "parse_yaml"},
+ "tool_response": {"mode": "content", "content": content, "numLines": 20},
+ "cwd": str(repo),
+ "session_id": "perf",
+ }
+ code = (
+ "import sys, json, io; "
+ f"sys.stdin = io.StringIO({json.dumps(payload)!r}); "
+ "from repowise.cli.commands.augment_cmd import _run_augment; "
+ "_run_augment(client=None); "
+ f"heavy = sorted(m for m in sys.modules if m.startswith({_HEAVY_PREFIXES!r})); "
+ "print('\\n'.join(heavy), file=sys.stderr)"
+ )
+ out = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True,
+ check=True,
+ env=_fake_home(tmp_path),
+ )
+ assert "Most likely relevant" in out.stdout, "the probe did not reach a triage emission"
+ assert out.stderr.strip() == "", f"a triage emission pulled in:\n{out.stderr}"
+
+
def test_a_silent_invocation_imports_nothing_heavy(tmp_path: Path) -> None:
"""A payload the hook has nothing to say about must stay on the cheap path."""
code = (
diff --git a/tests/unit/cli/test_augment_search.py b/tests/unit/cli/test_augment_search.py
index 7c9209b17..769250e42 100644
--- a/tests/unit/cli/test_augment_search.py
+++ b/tests/unit/cli/test_augment_search.py
@@ -3,9 +3,12 @@
The hook is designed to be silent on the common case (focused search
already returned what the agent wanted) and only speak up when it can
add information the raw result didn't carry. These tests pin the
-boundary cases of the decision tree without hitting the wiki — the
-``_search_enrich`` async path is mocked because it requires a real
-wiki.db, and is exercised end-to-end in integration tests instead.
+boundary cases of the decision tree without hitting the wiki.
+
+``_fast_search_enrich`` is the mocked seam because it is the one every
+mode reaches first, including the zero-result rescue it declines to serve
+and hands straight back to the ORM. Both lookup paths need a real wiki.db
+and are exercised end-to-end in integration tests instead.
"""
from __future__ import annotations
@@ -335,12 +338,12 @@ def _call(tool_name, pattern, output_text, cwd):
class TestDecisionTree:
def test_skip_when_pattern_is_path(self, repowise_cwd) -> None:
- with patch.object(augment_cmd.search, "_search_enrich") as enrich:
+ with patch.object(augment_cmd.search, "_fast_search_enrich") as enrich:
assert _call("Grep", "src/foo.py", "src/foo.py:1: x", repowise_cwd) is None
enrich.assert_not_called()
def test_skip_when_no_pattern(self, repowise_cwd) -> None:
- with patch.object(augment_cmd.search, "_search_enrich") as enrich:
+ with patch.object(augment_cmd.search, "_fast_search_enrich") as enrich:
assert (
_handle_search_post(
tool_name="Grep",
@@ -362,7 +365,7 @@ class TestDecisionTree:
Before the widened rescue this test passed anyway, on the focused-set
skip below rather than on the branch it names.
"""
- with patch.object(augment_cmd.search, "_search_enrich") as enrich:
+ with patch.object(augment_cmd.search, "_fast_search_enrich") as enrich:
with patch.object(augment_cmd.search, "_find_repo_root", return_value=None):
assert _call("Grep", "auth", "src/a.py:1: hit", tmp_path) is None
enrich.assert_not_called()
@@ -376,10 +379,9 @@ class TestDecisionTree:
"""
output = "\n".join(f"src/file{i}.py:1: hit" for i in range(5))
sentinel = object()
- with (
- patch.object(augment_cmd.search, "_search_enrich", return_value=sentinel) as enrich,
- patch("asyncio.run", side_effect=lambda coro: (coro.close(), sentinel)[1]),
- ):
+ with patch.object(
+ augment_cmd.search, "_fast_search_enrich", return_value=sentinel
+ ) as enrich:
_call("Grep", "parse_yaml", output, repowise_cwd)
args = enrich.call_args_list[0].args
assert args[2] == "rescue_wide"
@@ -398,7 +400,7 @@ class TestDecisionTree:
query off the common path: it runs before any wiki lookup.
"""
output = "\n".join(f"src/file{i}.py:1: hit" for i in range(5))
- with patch.object(augment_cmd.search, "_search_enrich") as enrich:
+ with patch.object(augment_cmd.search, "_fast_search_enrich") as enrich:
assert _call("Grep", pattern, output, repowise_cwd) is None
enrich.assert_not_called()
@@ -411,7 +413,7 @@ class TestDecisionTree:
parse gate rather than passing on the cheaper one above it.
"""
output = "\n".join(f"unstructured line {i}" for i in range(5))
- with patch.object(augment_cmd.search, "_search_enrich") as enrich:
+ with patch.object(augment_cmd.search, "_fast_search_enrich") as enrich:
assert _call("Grep", "parse_yaml", output, repowise_cwd) is None
enrich.assert_not_called()
@@ -426,14 +428,15 @@ class TestDecisionTree:
def test_rescue_mode_on_true_zero_results(self, repowise_cwd, tool_output) -> None:
"""A positively-identified zero + concept query → rescue mode."""
sentinel = object()
- with patch.object(augment_cmd.search, "_search_enrich", return_value=sentinel) as enrich:
- with patch("asyncio.run", side_effect=lambda coro: (coro.close(), sentinel)[1]):
- _handle_search_post(
- tool_name="Grep",
- tool_input={"pattern": "parse_yaml"},
- tool_output=tool_output,
- cwd=str(repowise_cwd),
- )
+ with patch.object(
+ augment_cmd.search, "_fast_search_enrich", return_value=sentinel
+ ) as enrich:
+ _handle_search_post(
+ tool_name="Grep",
+ tool_input={"pattern": "parse_yaml"},
+ tool_output=tool_output,
+ cwd=str(repowise_cwd),
+ )
(call_args,) = enrich.call_args_list
kwargs = call_args.kwargs or {}
args = call_args.args
@@ -448,10 +451,9 @@ class TestDecisionTree:
text claims there was no literal match at all.
"""
sentinel = object()
- with (
- patch.object(augment_cmd.search, "_search_enrich", return_value=sentinel) as enrich,
- patch("asyncio.run", side_effect=lambda coro: (coro.close(), sentinel)[1]),
- ):
+ with patch.object(
+ augment_cmd.search, "_fast_search_enrich", return_value=sentinel
+ ) as enrich:
_handle_search_post(
tool_name="Grep",
tool_input={"pattern": "distill_savings"},
@@ -470,7 +472,7 @@ class TestDecisionTree:
],
)
def test_unknown_shape_skips_never_rescues(self, repowise_cwd, tool_output) -> None:
- with patch.object(augment_cmd.search, "_search_enrich") as enrich:
+ with patch.object(augment_cmd.search, "_fast_search_enrich") as enrich:
result = _handle_search_post(
tool_name="Grep",
tool_input={"pattern": "parse_yaml"},
@@ -491,7 +493,7 @@ class TestDecisionTree:
)
def test_zero_match_rescue_skipped_when_irrelevant(self, repowise_cwd, tool_input) -> None:
"""Regex patterns and single non-code-file scopes never rescue."""
- with patch.object(augment_cmd.search, "_search_enrich") as enrich:
+ with patch.object(augment_cmd.search, "_fast_search_enrich") as enrich:
result = _handle_search_post(
tool_name="Grep",
tool_input=tool_input,
@@ -507,9 +509,10 @@ class TestDecisionTree:
big = "\n".join(f"src/file{i}.py:1: hit" for i in range(_TRIAGE_THRESHOLD + 5))
sentinel = object()
- with patch.object(augment_cmd.search, "_search_enrich", return_value=sentinel) as enrich:
- with patch("asyncio.run", side_effect=lambda coro: (coro.close(), sentinel)[1]):
- _call("Grep", "auth", big, repowise_cwd)
+ with patch.object(
+ augment_cmd.search, "_fast_search_enrich", return_value=sentinel
+ ) as enrich:
+ _call("Grep", "auth", big, repowise_cwd)
call_args = enrich.call_args_list[0]
args = call_args.args
kwargs = call_args.kwargs or {}
@@ -546,9 +549,10 @@ class TestFloodDigest:
def test_few_files_fall_through_to_triage(self, repowise_cwd) -> None:
"""A flood concentrated in 1-2 files is already navigable — no digest."""
sentinel = "triaged"
- with patch.object(augment_cmd.search, "_search_enrich", return_value=sentinel) as enrich:
- with patch("asyncio.run", side_effect=lambda coro: (coro.close(), sentinel)[1]):
- out = _call("Grep", "auth", _flood(files=2, per_file=40), repowise_cwd)
+ with patch.object(
+ augment_cmd.search, "_fast_search_enrich", return_value=sentinel
+ ) as enrich:
+ out = _call("Grep", "auth", _flood(files=2, per_file=40), repowise_cwd)
assert out == sentinel
assert enrich.called
@@ -561,7 +565,7 @@ class TestFloodDigest:
hook says nothing.
"""
big = "\n".join(f"line {i} of something unstructured" for i in range(60))
- with patch.object(augment_cmd.search, "_search_enrich") as enrich:
+ with patch.object(augment_cmd.search, "_fast_search_enrich") as enrich:
assert _call("Grep", "auth", big, repowise_cwd) is None
enrich.assert_not_called()