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.

fix(update): reuse persisted function-mod p80 in incremental hotspot gate (#1532)

Felix-Ayushe5c34a474c37
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index 420850f0d..fa3860d99 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -43,6 +43,7 @@ from repowise.core.reasoning import REASONING_MODES
from .incremental import (
_build_update_vector_store,
+ _load_stored_function_mod_p80,
_load_stored_git_meta,
_rebuild_graph_and_git,
_refresh_knowledge_graph,
@@ -1218,7 +1219,9 @@ def run_update(
# ``git_meta_map`` holds this run's changed files only; the dead-code
# analyzer scores confidence per file and would read every unchanged file
- # as "no commits" without the stored rows.
+ # as "no commits" without the stored rows. The stored function-mod p80
+ # keeps the hotspot gate repo-wide instead of derived from the changed
+ # subset (issue #1484).
partial_health_report, dead_code_report = _run_partial_analysis(
repo_path,
graph_builder,
@@ -1227,6 +1230,7 @@ def run_update(
file_diffs,
source_map,
stored_git_meta=_load_stored_git_meta(repo_path),
+ repo_function_mod_p80=_load_stored_function_mod_p80(repo_path),
)
# Partial health has consumed the per-file ``BlameIndex``; drop it before
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py b/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py
index 081f548a2..9527f3984 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py
@@ -158,6 +158,20 @@ def _load_stored_git_meta(repo_path: Any) -> dict[str, dict]:
return run_async(load_stored_git_meta(repo_path, log=console.print))
+def _load_stored_function_mod_p80(repo_path: Any) -> int | None:
+ """Repo-wide p80 of per-function modification counts from the blame rollup.
+
+ Delegates to :mod:`repowise.core.pipeline.incremental`. The incremental
+ health pass uses this so the Function Hotspot gate is scored against the
+ full repo, not the changed-files subset (issue #1484). Best-effort:
+ ``None`` when the rollup has not been persisted (or the store is
+ unreadable).
+ """
+ from repowise.core.pipeline.incremental import load_stored_function_mod_p80
+
+ return run_async(load_stored_function_mod_p80(repo_path, log=console.print))
+
+
def _run_partial_analysis(
repo_path: Any,
graph_builder: Any,
@@ -166,6 +180,7 @@ def _run_partial_analysis(
file_diffs: list,
source_map: dict[str, bytes] | None = None,
stored_git_meta: dict[str, dict] | None = None,
+ repo_function_mod_p80: int | None = None,
) -> tuple[Any, Any]:
"""Run partial code-health + repo-wide dead-code analysis.
@@ -185,5 +200,6 @@ def _run_partial_analysis(
file_diffs,
source_map=source_map,
stored_git_meta=stored_git_meta,
+ repo_function_mod_p80=repo_function_mod_p80,
log=console.print,
)
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 53c618933..8adf0f17c 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -359,6 +359,7 @@ class HealthAnalyzer:
*,
on_step: Any | None = None,
changed_files: set[str] | list[str] | None = None,
+ repo_function_mod_p80: int | None = None,
) -> HealthReport:
"""Analyze the configured parsed files.
@@ -368,6 +369,15 @@ class HealthAnalyzer:
files), but only files in *changed_files* contribute findings /
metrics. The caller is responsible for upserting (not replacing)
the result against the existing rows.
+
+ *repo_function_mod_p80* overrides the repo-wide 80th percentile of
+ per-function modification counts that gates the Function Hotspot
+ biomarker. On an incremental run ``walked`` holds only the changed
+ files, so deriving the percentile from it would bias the gate
+ toward churn-heavy subsets (issue #1484) — the caller should pass
+ the percentile computed over the full repo (from the persisted
+ ``git_function_blame`` rollup) instead. ``None`` (the default)
+ computes it from the walked set as before.
"""
cfg = config or {}
disabled: list[str] = list(cfg.get("disabled_biomarkers", ()))
@@ -437,7 +447,11 @@ class HealthAnalyzer:
if on_step:
on_step(pf.file_info.path)
- repo_fn_mod_p80 = _compute_repo_function_mod_p80(walked, self.git_meta_map)
+ repo_fn_mod_p80 = (
+ repo_function_mod_p80
+ if repo_function_mod_p80 is not None
+ else _compute_repo_function_mod_p80(walked, self.git_meta_map)
+ )
repo_dependents_p80 = _compute_repo_dependents_p80(self.parsed_files, self.graph)
repo_active_contributors = _compute_repo_active_contributors(self.git_meta_map)
@@ -522,6 +536,7 @@ class HealthAnalyzer:
on_step: Any | None = None,
changed_files: set[str] | list[str] | None = None,
max_workers: int | None = None,
+ repo_function_mod_p80: int | None = None,
) -> HealthReport:
"""Parallel variant of :meth:`analyze` for large repos.
@@ -534,6 +549,11 @@ class HealthAnalyzer:
Duplication still runs once up-front (cross-file by nature), and
the symbol-complexity write-back still runs on the main thread
so ORM objects don't cross thread boundaries unexpectedly.
+
+ *repo_function_mod_p80* overrides the repo-wide percentile that
+ gates the Function Hotspot biomarker (see :meth:`analyze`); on an
+ incremental run the caller passes the value computed over the full
+ repo so the gate is not biased by the changed-files subset.
"""
cfg = config or {}
disabled: list[str] = list(cfg.get("disabled_biomarkers", ()))
@@ -612,7 +632,11 @@ class HealthAnalyzer:
except Exception as exc:
log.debug("health_duplication_failed", error=str(exc))
dup_report = DuplicationReport()
- repo_fn_mod_p80 = _compute_repo_function_mod_p80(list(walked), self.git_meta_map)
+ repo_fn_mod_p80 = (
+ repo_function_mod_p80
+ if repo_function_mod_p80 is not None
+ else _compute_repo_function_mod_p80(list(walked), self.git_meta_map)
+ )
repo_dependents_p80 = _compute_repo_dependents_p80(self.parsed_files, self.graph)
repo_active_contributors = _compute_repo_active_contributors(self.git_meta_map)
diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.py
index 8d36881c9..835953a98 100644
--- a/packages/core/src/repowise/core/persistence/crud/git.py
+++ b/packages/core/src/repowise/core/persistence/crud/git.py
@@ -573,6 +573,25 @@ async def count_git_function_blame(session: AsyncSession, repository_id: str) ->
return int(result.scalar_one() or 0)
+async def get_git_function_mod_counts(session: AsyncSession, repository_id: str) -> list[int]:
+ """Return the persisted per-function modification counts for a repository.
+
+ The ``git_function_blame`` rollup is written during FULL-tier health
+ analysis (all modified functions on a full index; the changed subset on
+ an incremental one), so reading it back gives the repo-wide distribution
+ a fresh percentile can be computed from — the incremental health pass
+ reuses this instead of deriving the hotspot gate from the churn-heavy
+ changed-files subset (issue #1484).
+ """
+ result = await session.execute(
+ select(GitFunctionBlame.mod_count).where(
+ GitFunctionBlame.repository_id == repository_id,
+ GitFunctionBlame.mod_count > 0,
+ )
+ )
+ return [int(mod_count) for (mod_count,) in result.all()]
+
+
async def get_git_function_blame(
session: AsyncSession, repository_id: str, symbol_id: str
) -> GitFunctionBlame | None:
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index a9f8b105c..912531b2e 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -371,6 +371,56 @@ async def load_stored_git_meta(
return None
+async def load_stored_function_mod_p80(repo_path: Any, *, log: LogFn | None = None) -> int | None:
+ """Load the repo-wide p80 of per-function modification counts.
+
+ Computed from the persisted ``git_function_blame`` rollup, which a FULL
+ index writes for every modified function. The incremental health pass
+ reuses this value so the Function Hotspot gate is scored against the
+ full repo rather than the churn-heavy changed-files subset (issue
+ #1484) — a hotspot verdict then no longer flips when a full ``init``
+ is later replaced by an incremental ``update``.
+
+ Returns ``None`` when the store is unreadable, the repository row is
+ missing, or no blame rollup has been persisted (ESSENTIAL tier, or a
+ repo that has never been fully indexed) — callers fall back to the
+ walked-set computation in that case.
+ """
+ log = log or _noop_log
+ if not (Path(repo_path) / ".repowise" / "wiki.db").is_file():
+ return None
+ try:
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ )
+ from repowise.core.persistence.crud import (
+ get_git_function_mod_counts,
+ get_repository_by_path,
+ )
+ from repowise.core.persistence.database import resolve_db_url
+
+ engine = create_engine(resolve_db_url(repo_path))
+ try:
+ async with get_session(create_session_factory(engine)) as session:
+ repo = await get_repository_by_path(session, str(repo_path))
+ if repo is None:
+ return None
+ counts = await get_git_function_mod_counts(session, repo.id)
+ finally:
+ await engine.dispose()
+ if not counts:
+ return None
+ # Same inclusive-lower p80 as the in-memory path — do not reimplement.
+ from repowise.core.analysis.health.engine import _percentile_p80
+
+ return _percentile_p80(counts)
+ except Exception as exc:
+ log(f"[yellow]Stored function-mod percentile unavailable: {exc}[/yellow]")
+ return None
+
+
def run_partial_analysis(
repo_path: Any,
graph_builder: Any,
@@ -380,6 +430,7 @@ def run_partial_analysis(
*,
source_map: dict[str, bytes] | None = None,
stored_git_meta: dict[str, dict] | None = None,
+ repo_function_mod_p80: int | None = None,
log: LogFn | None = None,
) -> tuple[Any, Any]:
"""Run partial code-health + repo-wide dead-code analysis.
@@ -400,6 +451,13 @@ def run_partial_analysis(
entries as a repo-wide aggregate, so widening it there would silently move
health scores (the same reason the idle-decay rows are kept out of it).
+ *repo_function_mod_p80* is the repo-wide 80th percentile of per-function
+ modification counts, loaded from the persisted ``git_function_blame``
+ rollup (see :func:`load_stored_function_mod_p80`). It is passed through to
+ the health analyzer so the Function Hotspot gate is scored against the full
+ repo instead of this run's changed-files subset (issue #1484). ``None``
+ makes the analyzer fall back to deriving it from the walked files.
+
``None`` means the store could not be read, which is different from an
empty mapping and narrows what the resulting report is allowed to
overwrite. See ``load_stored_git_meta``.
@@ -431,7 +489,9 @@ def run_partial_analysis(
else None
)
partial_health_report = _health_analyzer.analyze(
- _analyzer_config, changed_files=_health_changed
+ _analyzer_config,
+ changed_files=_health_changed,
+ repo_function_mod_p80=repo_function_mod_p80,
)
log(
f"Health analysis (partial): [cyan]{len(_health_changed)} files[/cyan], "
diff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.py
index 8309561c5..36b2fcc3b 100644
--- a/packages/core/src/repowise/core/workspace/update.py
+++ b/packages/core/src/repowise/core/workspace/update.py
@@ -429,9 +429,16 @@ async def _incremental_repo_update(
# covers the changed files only, so every other file would be scored
# against an empty dict — which reads as "no commits in 90 days" and puts
# the whole repo on the 0.7 / safe-to-delete rung of the confidence ladder.
- from ..pipeline.incremental import load_stored_git_meta
+ from ..pipeline.incremental import (
+ load_stored_function_mod_p80,
+ load_stored_git_meta,
+ )
stored_git_meta = await load_stored_git_meta(repo_path, log=_log.info)
+ # Repo-wide p80 from the persisted blame rollup, so the partial health
+ # pass scores the Function Hotspot gate against the full repo instead of
+ # this run's changed-files subset (issue #1484).
+ stored_function_mod_p80 = await load_stored_function_mod_p80(repo_path, log=_log.info)
partial_health_report, dead_code_report = run_partial_analysis(
repo_path,
@@ -441,6 +448,7 @@ async def _incremental_repo_update(
file_diffs,
source_map=source_map,
stored_git_meta=stored_git_meta,
+ repo_function_mod_p80=stored_function_mod_p80,
log=_log.info,
)
diff --git a/tests/unit/health/test_incremental_p80_override.py b/tests/unit/health/test_incremental_p80_override.py
new file mode 100644
index 000000000..d40dfd1fa
--- /dev/null
+++ b/tests/unit/health/test_incremental_p80_override.py
@@ -0,0 +1,85 @@
+"""Regression tests for issue #1484: the Function Hotspot gate must be scored
+against the full-repo p80 even on incremental runs.
+
+On an incremental run ``walked``/``target_files`` holds only the changed files,
+so deriving ``repo_function_mod_p80`` from them biases the gate toward the
+churn-heavy subset (e.g. full-repo ``[1,2,2,3,4,4,5]`` → p80=4 but changed
+subset ``[4,4,5]`` → p80=5), which flips a file's hotspot verdict between
+``init`` and ``update``. The incremental caller now loads the persisted
+full-repo percentile (``git_function_blame`` rollup) and passes it in as an
+override.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from repowise.core.analysis.health.engine import HealthAnalyzer
+
+
+def _parsed_file(path: str) -> SimpleNamespace:
+ return SimpleNamespace(
+ file_info=SimpleNamespace(
+ path=path,
+ language="python",
+ abs_path=f"/tmp/{path}",
+ is_test=False,
+ ),
+ symbols=[],
+ )
+
+
+class _CaptureEvaluator(HealthAnalyzer):
+ """Engine whose ``_evaluate_file`` records the p80 override instead of
+ doing real biomarker work."""
+
+ def __init__(self, *args, **kwargs) -> None:
+ super().__init__(*args, **kwargs)
+ self.captured_p80s: list[int | None] = []
+
+ def _evaluate_file(self, *args, **kwargs):
+ self.captured_p80s.append(kwargs.get("repo_function_mod_p80"))
+ pf = args[0]
+ return SimpleNamespace(file_path=pf.file_info.path, nloc=0, score=10.0), [], []
+
+
+def test_incremental_analyze_uses_override_not_walked_subset():
+ """``analyze(changed_files=..., repo_function_mod_p80=X)`` must hand the
+ override to the per-file evaluation, not the value derived from the
+ changed subset (issue #1484)."""
+ eng = _CaptureEvaluator(
+ graph=None,
+ git_meta_map={
+ "src/a.py": {},
+ "src/b.py": {},
+ },
+ parsed_files=[_parsed_file("src/a.py"), _parsed_file("src/b.py")],
+ )
+ eng.analyze(changed_files=["src/a.py"], repo_function_mod_p80=4)
+ assert eng.captured_p80s and eng.captured_p80s == [4]
+
+
+def test_full_analyze_still_derives_p80_from_walked():
+ """A full run (no ``changed_files``) keeps deriving the percentile from the
+ walked set — the override is only an incremental-run input."""
+ eng = _CaptureEvaluator(
+ graph=None,
+ git_meta_map={"src/a.py": {}},
+ parsed_files=[_parsed_file("src/a.py")],
+ )
+ eng.analyze()
+ # No blame index on any walked file → p80 is None (the "no signal"
+ # outcome), proving the default computation path still ran.
+ assert eng.captured_p80s and eng.captured_p80s == [None]
+
+
+def test_analyze_async_forwards_override():
+ import asyncio
+
+ eng = _CaptureEvaluator(
+ graph=None,
+ git_meta_map={"src/a.py": {}},
+ parsed_files=[_parsed_file("src/a.py")],
+ )
+ asyncio.run(eng.analyze_async(changed_files=["src/a.py"], repo_function_mod_p80=4))
+ assert eng.captured_p80s and eng.captured_p80s == [4]
diff --git a/tests/unit/persistence/test_git_function_blame_crud.py b/tests/unit/persistence/test_git_function_blame_crud.py
index 9a8ac400f..8226ed8fb 100644
--- a/tests/unit/persistence/test_git_function_blame_crud.py
+++ b/tests/unit/persistence/test_git_function_blame_crud.py
@@ -9,6 +9,7 @@ from repowise.core.persistence.crud import (
delete_git_function_blame,
get_git_function_blame,
get_git_function_blames,
+ get_git_function_mod_counts,
upsert_git_function_blame_bulk,
)
from tests.unit.persistence.helpers import insert_repo
@@ -94,3 +95,26 @@ async def test_delete_git_function_blame(async_session) -> None:
await delete_git_function_blame(async_session, repo.id)
await async_session.commit()
assert await count_git_function_blame(async_session, repo.id) == 0
+
+
+async def test_get_git_function_mod_counts_excludes_zero(async_session) -> None:
+ repo = await insert_repo(async_session)
+ await upsert_git_function_blame_bulk(
+ async_session,
+ repo.id,
+ [
+ _row("a.py::foo", mods=1),
+ _row("a.py::bar", mods=4),
+ _row("a.py::baz", mods=4),
+ _row("b.py::qux", mods=5),
+ _row("c.py::nope", mods=0),
+ ],
+ )
+ await async_session.commit()
+
+ counts = await get_git_function_mod_counts(async_session, repo.id)
+ # The persisted rollup only carries functions with mod_count > 0; the
+ # loader that computes the repo-wide p80 from these must not let a zero
+ # row into the distribution (matches the in-memory computation).
+ assert sorted(counts) == [1, 4, 4, 5]
diff --git a/tests/unit/pipeline/test_load_stored_function_mod_p80.py b/tests/unit/pipeline/test_load_stored_function_mod_p80.py
new file mode 100644
index 000000000..7ae543f63
--- /dev/null
+++ b/tests/unit/pipeline/test_load_stored_function_mod_p80.py
@@ -0,0 +1,109 @@
+"""``load_stored_function_mod_p80`` reads the persisted per-function blame
+rollup and returns the repo-wide p80 the incremental health pass reuses, so the
+Function Hotspot gate is not biased by the changed-files subset (issue #1484).
+"""
+
+from __future__ import annotations
+
+from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+)
+from repowise.core.persistence.crud import (
+ get_repository_by_path,
+ upsert_git_function_blame_bulk,
+)
+from repowise.core.persistence.database import init_db, resolve_db_url
+from repowise.core.pipeline.incremental import load_stored_function_mod_p80
+
+
+def _row(symbol_id: str, *, mods: int) -> dict:
+ path, _, name = symbol_id.partition("::")
+ return {
+ "symbol_id": symbol_id,
+ "file_path": path,
+ "function_name": name,
+ "start_line": 1,
+ "end_line": 10,
+ "line_count": 10,
+ "mod_count": mods,
+ "recent_mod_count": 1,
+ "median_author_time": 1_700_000_000,
+ "owner_name": "Ann",
+ "owner_email": "ann@x",
+ "owner_line_pct": 0.7,
+ }
+
+
+async def _seed(repo_path, rows: list[dict]) -> None:
+ engine = create_engine(resolve_db_url(repo_path))
+ try:
+ await init_db(engine)
+ async with get_session(create_session_factory(engine)) as session:
+ repo = await get_repository_by_path(session, str(repo_path))
+ if repo is None:
+ from repowise.core.persistence.crud import upsert_repository
+
+ repo = await upsert_repository(
+ session,
+ name="loader-test",
+ local_path=str(repo_path),
+ url="https://example.test/loader",
+ )
+ await session.commit()
+ await upsert_git_function_blame_bulk(session, repo.id, rows)
+ await session.commit()
+ finally:
+ await engine.dispose()
+
+
+async def test_loader_computes_full_repo_p80(tmp_path):
+ """Full-repo distribution [1,2,2,3,4,4,5] → p80=4 (the issue's example).
+ The changed-files subset [4,4,5] would give 5; the loader must answer 4."""
+ repo_path = tmp_path / "repo"
+ repo_path.mkdir()
+ await _seed(
+ repo_path,
+ [
+ _row("a.py::f1", mods=1),
+ _row("a.py::f2", mods=2),
+ _row("a.py::f3", mods=2),
+ _row("b.py::f4", mods=3),
+ _row("c.py::f5", mods=4),
+ _row("c.py::f6", mods=4),
+ _row("c.py::f7", mods=5),
+ ],
+ )
+
+ assert await load_stored_function_mod_p80(repo_path) == 4
+
+
+async def test_loader_no_store_returns_none(tmp_path):
+ """Reading must never conjure a store, and an absent rollup is unknown."""
+ assert await load_stored_function_mod_p80(tmp_path) is None
+ assert not (tmp_path / ".repowise").exists()
+
+
+async def test_loader_empty_rollup_returns_none(tmp_path):
+ """No persisted blame rows (ESSENTIAL tier / never full-indexed) → None,
+ so the analyzer falls back to the walked-set computation."""
+ repo_path = tmp_path / "repo"
+ repo_path.mkdir()
+ engine = create_engine(resolve_db_url(repo_path))
+ try:
+ await init_db(engine)
+ async with get_session(create_session_factory(engine)) as session:
+ from repowise.core.persistence.crud import upsert_repository
+
+ await upsert_repository(
+ session,
+ name="loader-test",
+ local_path=str(repo_path),
+ url="https://example.test/loader",
+ )
+ await session.commit()
+ finally:
+ await engine.dispose()
+
+ assert await load_stored_function_mod_p80(repo_path) is None