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(update): scan new commits' health outside the write transaction and pick up the ones a budget skipped (#3525)
Raghav Chamadiya054af8edf3c7
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.pyindex 37b4a2500..311d38e79 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py@@ -1409,6 +1409,11 @@ async def _persist_full_update_async("Configuration rebuild did not update every dependent store; ""the previous fingerprint was retained so the next update retries.")+ # The transaction commits as the block exits.+ if timings is not None:+ timings.start("persist.commit")+ if timings is not None:+ timings.stop("persist.commit")# FTS outside the transaction — rebuildable, and its writer manages# its own connection state.@@ -1460,6 +1465,13 @@ async def _persist_full_update_async(_skip("Deferred vector cleanup", exc)if require_config_rebuild_success:raise++ # After the transaction, so the scan never holds the write lock, and on+ # every update, so a backlog an earlier budget left drains.+ from repowise.core.pipeline.commit_health import refresh_commit_health_after_update++ with timed(timings, "persist.commit_health"):+ await refresh_commit_health_after_update(sf, repo_id, str(repo_path))return total_pagesfinally:await engine.dispose()diff --git a/packages/core/src/repowise/core/pipeline/commit_health.py b/packages/core/src/repowise/core/pipeline/commit_health.pyindex 31bba879a..2771c908d 100644--- a/packages/core/src/repowise/core/pipeline/commit_health.py+++ b/packages/core/src/repowise/core/pipeline/commit_health.py@@ -1,9 +1,10 @@"""Keep the per-commit health delta rows current, for both index paths.-One entry point, :func:`refresh_commit_health`, used by the full index and by-the incremental update. The difference between them is only which shas they-hand over; everything else — what is already scanned, what the budget allows,-how the rows are written — is the same decision and lives here once.+Two entry points share one scan: :func:`refresh_commit_health` for the full+index, inside its transaction, and :func:`refresh_commit_health_after_update`+for the incremental update, after its transaction. What is already scanned,+what the budget allows and how the rows are written is the same decision and+lives here once.The scan is bounded on purpose — see ``change_health.commit_scan`` for theper-file cost that forces it. A full index seeds the most recent@@ -12,6 +13,13 @@ per-file cost that forces it. A full index seeds the most recenttake about half an hour. Everything older has no row, which the commit sheetrenders as "not analysed" rather than "nothing found", and updates extend thecovered window one push at a time.++An update scans after its persist transaction has committed, never inside it:+the scan is minutes of CPU at worst, and holding SQLite's write lock that long+blocks every other writer (the post-commit hook's next update, MCP writes). It+also scans the newest commits in the store rather than only the ones it just+captured, so a commit an earlier update's budget did not reach is picked up by+a later one instead of staying "not analysed" until a full index."""from __future__ import annotations@@ -32,6 +40,13 @@ DEFAULT_COMMIT_LIMIT = 150#: order of magnitude with diff size, so a count alone bounds nothing.DEFAULT_BUDGET_SECONDS = 300.0+#: Wall clock one update may spend. An update runs on every commit through the+#: post-commit hook, so it gets a fifth of the full index's budget. A commit+#: costs ~5 s on this repository under load (~2 s idle), so this covers about a+#: dozen commits per run, a normal push in one update, and a longer gap drains+#: over the next few updates instead of stalling one for five minutes.+UPDATE_BUDGET_SECONDS = 60.0+def _env_number(name: str, default: float) -> float:"""Read a non-negative numeric override; ignore anything unparseable."""@@ -49,8 +64,8 @@ def commit_limit() -> int:return int(_env_number("REPOWISE_COMMIT_HEALTH_COMMITS", DEFAULT_COMMIT_LIMIT))-def budget_seconds() -> float:- return _env_number("REPOWISE_COMMIT_HEALTH_BUDGET_SECONDS", DEFAULT_BUDGET_SECONDS)+def budget_seconds(default: float = DEFAULT_BUDGET_SECONDS) -> float:+ return _env_number("REPOWISE_COMMIT_HEALTH_BUDGET_SECONDS", default)def recent_shas(commit_rows: list[dict] | None) -> list[str]:@@ -77,17 +92,16 @@ async def _pending_shas(return [sha for sha in shas if sha not in done][:limit]-async def _scan_and_store(- session: Any, repo_id: str, repo_path: str, pending: list[str], budget: float-) -> dict[str, int]:+async def _scan(repo_path: str, pending: list[str], budget: float) -> Any:from repowise.core.analysis.change_health.commit_scan import scan_commits- from repowise.core.persistence.crud import upsert_commit_health_bulkscan = await asyncio.to_thread(scan_commits, repo_path, pending, budget_seconds=budget)- if scan.delta_rows:- await upsert_commit_health_bulk(session, repo_id, scan.delta_rows, scan.finding_rows)if scan.exhausted_budget:logger.info("commit_health_budget_exhausted", scanned=scan.scanned, budget=budget)+ return scan+++def _stats(pending: list[str], scan: Any) -> dict[str, int]:return {"candidates": len(pending),"scanned": scan.scanned,@@ -97,6 +111,17 @@ async def _scan_and_store(}+async def _scan_and_store(+ session: Any, repo_id: str, repo_path: str, pending: list[str], budget: float+) -> dict[str, int]:+ from repowise.core.persistence.crud import upsert_commit_health_bulk++ scan = await _scan(repo_path, pending, budget)+ if scan.delta_rows:+ await upsert_commit_health_bulk(session, repo_id, scan.delta_rows, scan.finding_rows)+ return _stats(pending, scan)++async def refresh_commit_health(session: Any,repo_id: str,@@ -138,3 +163,55 @@ async def refresh_commit_health(except Exception as exc:logger.debug("commit_health_refresh_failed", error=str(exc))return nothing+++async def refresh_commit_health_after_update(+ session_factory: Any,+ repo_id: str,+ repo_path: str,+ *,+ budget: float | None = None,+) -> dict[str, int]:+ """The update's scan, run once its persist transaction has committed.++ Reads the window, scans with no session open, then writes the rows in a+ transaction of their own, so the write lock is held for the write and not+ for the scan. The window is the newest :data:`DEFAULT_COMMIT_LIMIT` commits+ in the store, the same window a full index seeds, newest first: the commits+ a reader opens first are covered first, and a backlog older than the window+ is not chased.++ Never raises, and touches nothing the update already committed.+ """+ from repowise.core.persistence import get_session+ from repowise.core.persistence.crud import get_git_commits, upsert_commit_health_bulk++ limit = commit_limit()+ nothing = dict.fromkeys(("candidates", "scanned", "skipped", "stored", "findings"), 0)+ if limit <= 0:+ return nothing+ try:+ async with get_session(session_factory) as session:+ window = [+ row.sha+ for row in await get_git_commits(session, repo_id, limit=limit, sort="date")+ ]+ if not window:+ return nothing+ pending = await _pending_shas(session, repo_id, repo_path, window, limit)+ if not pending:+ return nothing+ scan = await _scan(+ repo_path,+ pending,+ budget_seconds(UPDATE_BUDGET_SECONDS) if budget is None else budget,+ )+ if scan.delta_rows:+ async with get_session(session_factory) as session:+ await upsert_commit_health_bulk(+ session, repo_id, scan.delta_rows, scan.finding_rows+ )+ return _stats(pending, scan)+ except Exception as exc:+ logger.debug("commit_health_refresh_failed", error=str(exc))+ return nothingdiff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex fae4f9bb5..ee6ac2ee0 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -1481,14 +1481,9 @@ async def persist_incremental_commits(if file_rows:await upsert_git_commit_files_bulk(session, repo_id, file_rows)- # What the new commits did to health. An update is a handful of commits, so- # this is seconds; the same budget still applies if a long gap made it many.- with timed(timings, "persist.commits.health"):- from .commit_health import recent_shas, refresh_commit_health-- await refresh_commit_health(- session, repo_id, str(repo_path), recent_shas(rows)- )+ # What the new commits did to health is scanned by the caller once this+ # transaction commits (commit_health.refresh_commit_health_after_update):+ # the scan can take minutes and must not hold the write lock.with timed(timings, "persist.commits.experience"):await reconcile_commit_experience(session, repo_id, indexer)@@ -2290,6 +2285,18 @@ async def persist_incremental_index(degraded=degraded,timings=timings,)+ # The transaction commits as the block exits.+ if timings is not None:+ timings.start("persist.commit")+ if timings is not None:+ timings.stop("persist.commit")++ # Every update, not only those with git changes: a backlog an earlier+ # budget left drains here, and an empty window costs one query.+ from repowise.core.pipeline.commit_health import refresh_commit_health_after_update++ with timed(timings, "persist.commit_health"):+ await refresh_commit_health_after_update(sf, repo_id, str(repo_path))# After the session closes: on SQLite the full-text index shares the# database file, so writing to it while the session holds a write lockdiff --git a/tests/unit/persistence/test_commit_health_after_update.py b/tests/unit/persistence/test_commit_health_after_update.pynew file mode 100644index 000000000..1c26d1e96--- /dev/null+++ b/tests/unit/persistence/test_commit_health_after_update.py@@ -0,0 +1,231 @@+"""An update scans commit health after its write transaction, and catches up.++The scan can run for minutes. Inside the persist transaction it held SQLite's+write lock for all of it, blocking every other writer, and it only looked at+the commits the update had just captured, so a commit its budget missed was+never scanned again until a full index.+"""++from __future__ import annotations++import sqlite3+from datetime import UTC, datetime, timedelta+from pathlib import Path++import pytest++import repowise.core.analysis.change_health.commit_scan as scan_mod+import repowise.core.pipeline.incremental as incremental_mod+from repowise.core.analysis.change_health.commit_scan import (+ CommitHealthScan,+ current_fingerprint,+)+from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+)+from repowise.core.persistence.crud import get_commit_health, upsert_git_commits_bulk+from repowise.core.pipeline.commit_health import (+ DEFAULT_BUDGET_SECONDS,+ UPDATE_BUDGET_SECONDS,+ refresh_commit_health,+ refresh_commit_health_after_update,+)+from repowise.core.pipeline.incremental import persist_incremental_index+from tests.unit.persistence.helpers import insert_repo++_BASE = datetime(2026, 1, 1, tzinfo=UTC)+#: Oldest first; committed_at grows with the index.+_SHAS = [f"{i:040x}" for i in range(5)]+++def _commit_rows() -> list[dict]:+ return [+ {"sha": sha, "subject": sha[-1], "committed_at": _BASE + timedelta(hours=i)}+ for i, sha in enumerate(_SHAS)+ ]+++def _delta_row(sha: str, repo_path: str) -> dict:+ return {"sha": sha, "status": "available", **current_fingerprint(repo_path)}+++def _scanner(repo_path: str, per_run: int | None = None, seen: list | None = None):+ """A scan that covers at most *per_run* commits, as a spent budget would."""++ def scan(path, shas, *, budget_seconds=0.0, **_kwargs):+ if seen is not None:+ seen.append((list(shas), budget_seconds))+ done = shas if per_run is None else shas[:per_run]+ return CommitHealthScan(+ delta_rows=[_delta_row(sha, repo_path) for sha in done],+ scanned=len(done),+ exhausted_budget=len(done) < len(shas),+ )++ return scan+++def repo(tmp_path: Path, monkeypatch) -> Path:+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)+ monkeypatch.delenv("REPOWISE_COMMIT_HEALTH_BUDGET_SECONDS", raising=False)+ (tmp_path / ".repowise").mkdir()+ return tmp_path+++def _capture_commits(monkeypatch) -> None:+ """Stand in for the git walk: the update captures these commit rows."""++ async def capture(session, repo_id, repo_path, *, timings=None):+ await upsert_git_commits_bulk(session, repo_id, _commit_rows())++ monkeypatch.setattr(incremental_mod, "persist_incremental_commits", capture)+++async def _persist(repo: Path) -> None:+ await persist_incremental_index(+ repo,+ object(),+ {"src/a.py": {"file_path": "src/a.py"}},+ None,+ None,+ ["src/a.py"],+ log=lambda _msg: None,+ degraded=[],+ )+++async def _stored_shas(repo: Path) -> set[str]:+ engine = create_engine(f"sqlite+aiosqlite:///{repo / '.repowise' / 'wiki.db'}")+ try:+ async with get_session(create_session_factory(engine)) as session:+ repo_row = await upsert_repository(session, name=repo.name, local_path=str(repo))+ return {+ sha+ for sha in _SHAS+ if await get_commit_health(session, repo_row.id, sha) is not None+ }+ finally:+ await engine.dispose()+++async def test_update_scans_with_the_write_lock_free(repo, monkeypatch) -> None:+ """Another writer can take the lock mid-scan, and sees the update's rows."""+ _capture_commits(monkeypatch)+ observed: dict = {}+ inner = _scanner(str(repo))++ def scan(path, shas, **kwargs):+ conn = sqlite3.connect(repo / ".repowise" / "wiki.db", timeout=0)+ try:+ conn.execute("BEGIN IMMEDIATE") # raises "database is locked" if held+ conn.rollback()+ observed["committed"] = conn.execute("SELECT count(*) FROM git_commits").fetchone()[0]+ finally:+ conn.close()+ return inner(path, shas, **kwargs)++ monkeypatch.setattr(scan_mod, "scan_commits", scan)++ await _persist(repo)++ assert observed["committed"] == len(_SHAS)+ assert await _stored_shas(repo) == set(_SHAS)+++async def test_a_failed_scan_leaves_the_persist_committed(repo, monkeypatch) -> None:+ _capture_commits(monkeypatch)++ def boom(*_args, **_kwargs):+ raise RuntimeError("scan blew up")++ monkeypatch.setattr(scan_mod, "scan_commits", boom)++ await _persist(repo)++ conn = sqlite3.connect(repo / ".repowise" / "wiki.db")+ try:+ assert conn.execute("SELECT count(*) FROM git_commits").fetchone()[0] == len(_SHAS)+ finally:+ conn.close()+ assert await _stored_shas(repo) == set()+++async def test_an_update_with_no_git_changes_still_drains_the_backlog(+ repo, monkeypatch+) -> None:+ """Empty git maps capture nothing new, but earlier skipped commits get scanned."""+ _capture_commits(monkeypatch)+ monkeypatch.setattr(scan_mod, "scan_commits", _scanner(str(repo), 0))+ await _persist(repo)+ assert await _stored_shas(repo) == set()++ monkeypatch.setattr(scan_mod, "scan_commits", _scanner(str(repo)))+ await persist_incremental_index(+ repo, object(), {}, None, None, [], log=lambda _msg: None, degraded=[]+ )++ assert await _stored_shas(repo) == set(_SHAS)+++async def test_commits_a_budget_skipped_are_scanned_by_the_next_update(+ repo, monkeypatch+) -> None:+ engine = create_engine(f"sqlite+aiosqlite:///{repo / '.repowise' / 'wiki.db'}")+ await init_db(engine)+ sf = create_session_factory(engine)+ try:+ async with get_session(sf) as session:+ repo_id = (await insert_repo(session)).id+ await upsert_git_commits_bulk(session, repo_id, _commit_rows())+ seen: list = []+ monkeypatch.setattr(scan_mod, "scan_commits", _scanner(str(repo), 2, seen))++ first = await refresh_commit_health_after_update(sf, repo_id, str(repo))+ second = await refresh_commit_health_after_update(sf, repo_id, str(repo))+ third = await refresh_commit_health_after_update(sf, repo_id, str(repo))++ newest_first = list(reversed(_SHAS))+ assert seen[0][0] == newest_first+ assert seen[1][0] == newest_first[2:]+ assert seen[2][0] == newest_first[4:]+ assert [first["stored"], second["stored"], third["stored"]] == [2, 2, 1]+ # Nothing left: a fourth update does not scan at all.+ assert (await refresh_commit_health_after_update(sf, repo_id, str(repo)))[+ "candidates"+ ] == 0+ assert len(seen) == 3+ finally:+ await engine.dispose()+++async def test_update_budget_is_smaller_than_the_full_index(repo, monkeypatch) -> None:+ assert UPDATE_BUDGET_SECONDS < DEFAULT_BUDGET_SECONDS+ engine = create_engine(f"sqlite+aiosqlite:///{repo / '.repowise' / 'wiki.db'}")+ await init_db(engine)+ sf = create_session_factory(engine)+ try:+ async with get_session(sf) as session:+ repo_id = (await insert_repo(session)).id+ await upsert_git_commits_bulk(session, repo_id, _commit_rows())+ seen: list = []+ monkeypatch.setattr(scan_mod, "scan_commits", _scanner(str(repo), 0, seen))++ await refresh_commit_health_after_update(sf, repo_id, str(repo))+ async with get_session(sf) as session:+ await refresh_commit_health(session, repo_id, str(repo), list(_SHAS))+ monkeypatch.setenv("REPOWISE_COMMIT_HEALTH_BUDGET_SECONDS", "7")+ await refresh_commit_health_after_update(sf, repo_id, str(repo))++ assert [budget for _shas, budget in seen] == [+ UPDATE_BUDGET_SECONDS,+ DEFAULT_BUDGET_SECONDS,+ 7.0,+ ]+ finally:+ await engine.dispose()