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(health): pick a file's lead finding the same way on every run (#2872)

Raghav Chamadiya5d299052c8b3
diff --git a/packages/core/src/repowise/core/analysis/health/models.py b/packages/core/src/repowise/core/analysis/health/models.py
index 63ded3253..659c1dc96 100644
--- a/packages/core/src/repowise/core/analysis/health/models.py
+++ b/packages/core/src/repowise/core/analysis/health/models.py
@@ -90,12 +90,30 @@ def primary_finding(findings: Sequence[Any]) -> Any | None:
discrete = [
item for item in candidates if row_field(item, "biomarker_type") not in continuous
]
- return max(
+ # A total order: equal impacts are common (two biomarkers on one file can
+ # quantise to the same deduction), and a bare ``max`` let input order pick
+ # the lead, so two indexes of one tree disagreed. Severity breaks the tie
+ # first; the rest only makes it stable.
+ return min(
discrete or candidates,
- key=lambda item: float(row_field(item, "health_impact") or 0.0),
+ key=lambda item: (
+ -float(row_field(item, "health_impact") or 0.0),
+ _severity_rank(row_field(item, "severity")),
+ str(row_field(item, "biomarker_type") or ""),
+ row_field(item, "line_start") or 0,
+ str(row_field(item, "function_name") or ""),
+ ),
)
+def _severity_rank(severity: Any) -> int:
+ """Position in ``SEVERITY_ORDER`` (critical first); unknown sorts last."""
+ from .aggregation import SEVERITY_ORDER
+
+ value = str(severity or "")
+ return SEVERITY_ORDER.index(value) if value in SEVERITY_ORDER else len(SEVERITY_ORDER)
+
+
def split_by_origin(findings: Iterable[Any]) -> tuple[list[Any], list[Any]]:
"""Partition findings into ``(code_shape, history)``.
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
index cd955d57e..810df5146 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
@@ -287,7 +287,18 @@ async def finalize_refactoring_opportunities(
findings = list(
(
await session.execute(
- select(HealthFinding).where(HealthFinding.repository_id == repository_id)
+ # Ordered by the natural key: without it the rows came back in
+ # whichever index the planner chose, and the per-file finding
+ # id lists stored with each opportunity followed that order.
+ select(HealthFinding)
+ .where(HealthFinding.repository_id == repository_id)
+ .order_by(
+ HealthFinding.file_path,
+ HealthFinding.biomarker_type,
+ HealthFinding.line_start,
+ HealthFinding.function_name,
+ HealthFinding.public_id,
+ )
)
)
.scalars()
diff --git a/tests/unit/health/test_primary_and_magnitude.py b/tests/unit/health/test_primary_and_magnitude.py
index 07348d4d8..97e0789a0 100644
--- a/tests/unit/health/test_primary_and_magnitude.py
+++ b/tests/unit/health/test_primary_and_magnitude.py
@@ -7,9 +7,13 @@ from types import SimpleNamespace
from repowise.server.routers.code_health import _leads_by_file, _primary_and_magnitude
-def _f(path, biomarker, impact, reason=""):
+def _f(path, biomarker, impact, reason="", severity="medium"):
return SimpleNamespace(
- file_path=path, biomarker_type=biomarker, health_impact=impact, reason=reason
+ file_path=path,
+ biomarker_type=biomarker,
+ health_impact=impact,
+ reason=reason,
+ severity=severity,
)
@@ -22,7 +26,7 @@ FINDINGS = [
_f("b.py", "coverage_gradient", 0.9, "40% uncovered"),
# Advisory only: no lead, real zero magnitude.
_f("c.py", "assertion_free_test", 0.0, "no asserts"),
- # Null impact counts as zero; ties keep the first.
+ # Null impact counts as zero; a tie is decided by name, not input order.
_f("d.py", "god_object", None, "big"),
_f("d.py", "long_method", 0.1, "90 lines"),
_f("d.py", "complex_method", 0.1, "ccn 11"),
@@ -41,8 +45,8 @@ GOLDEN = {
},
"c.py": {"primary_biomarker": None, "primary_reason": None, "total_deduction": 0.0},
"d.py": {
- "primary_biomarker": "long_method",
- "primary_reason": "90 lines",
+ "primary_biomarker": "complex_method",
+ "primary_reason": "ccn 11",
"total_deduction": 0.2,
},
}
@@ -87,3 +91,19 @@ def test_primary_finding_prefers_code_shape_over_history() -> None:
history = _f("e.py", "change_entropy", 2.5, "changed with 25 files")
assert primary_finding([history, shaped]) is shaped
assert primary_finding([history]) is history
+
+
+def test_primary_finding_tie_does_not_depend_on_input_order() -> None:
+ """Equal impacts must not let row order pick the lead: two indexes of one
+ tree read the rows in different orders and disagreed on it."""
+ from repowise.core.analysis.health.models import primary_finding
+
+ cohesion = _f("f.java", "low_cohesion", 0.871, "lcom 0.9")
+ complex_ = _f("f.java", "complex_method", 0.871, "ccn 30")
+ assert primary_finding([cohesion, complex_]) is complex_
+ assert primary_finding([complex_, cohesion]) is complex_
+
+ # Severity breaks the tie before the name does.
+ severe = _f("f.java", "low_cohesion", 0.871, "lcom 0.9", severity="high")
+ assert primary_finding([complex_, severe]) is severe
+ assert primary_finding([severe, complex_]) is severe
diff --git a/tests/unit/server/test_refactoring_opportunities.py b/tests/unit/server/test_refactoring_opportunities.py
index b858b1a29..fafbe1be3 100644
--- a/tests/unit/server/test_refactoring_opportunities.py
+++ b/tests/unit/server/test_refactoring_opportunities.py
@@ -569,6 +569,44 @@ async def test_a_step_names_the_findings_its_cause_produced(client, app):
assert resolved["resolved"] is True
+async def test_lead_finding_ids_follow_the_findings_not_their_insert_order(client, app):
+ """Stored finding id lists must not depend on which index the planner reads."""
+ from sqlalchemy import select
+
+ from repowise.core.persistence.models import HealthFinding, RefactoringOpportunity
+
+ repo_id = await _repo(client)
+ path = "pkg/mod.py"
+ async with app.state.session_factory() as session:
+ await crud.save_health_findings(
+ session,
+ repo_id,
+ [_finding(path, function_name=name) for name in ("zeta", "alpha", "mid")],
+ )
+ await crud.save_refactoring_suggestions(session, repo_id, [_plan(path, "alpha")])
+ await crud.finalize_refactoring_opportunities(session, repo_id)
+ await session.commit()
+ by_function = {
+ row.function_name: row.public_id
+ for row in (
+ await session.execute(
+ select(HealthFinding).where(HealthFinding.repository_id == repo_id)
+ )
+ ).scalars()
+ }
+ details = json.loads(
+ (
+ await session.execute(
+ select(RefactoringOpportunity.details_json).where(
+ RefactoringOpportunity.repository_id == repo_id
+ )
+ )
+ ).scalar_one()
+ )
+ assert details["lead_finding_ids"] == [by_function[n] for n in ("alpha", "mid", "zeta")]
+
+
@pytest.mark.asyncio
async def test_the_detail_hands_back_structured_next_calls(client, app):
repo_id = await _seed(client, app, files=2)