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(refactoring): resolve opportunities left open by an older plan model (#2904)

Raghav Chamadiya55f3cdc7520a
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.py
index cbbb701f9..925cdf1f4 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
@@ -32,6 +32,7 @@ from repowise.core.analysis.finding_registry import excluded_types
from repowise.core.analysis.health.fix_first import DEFAULT_LIMIT, FixFirstQueue, build_fix_first
from repowise.core.analysis.health.fix_first.build import MIN_WORTH, hot_cut, hot_cut_offset
from repowise.core.analysis.health.perf.opportunity_rank import DEFAULT_QUEUE_STATES
+from repowise.core.analysis.health.refactoring.identity import REFACTORING_MODEL_VERSION
from repowise.core.analysis.health.rows import detail_map
from repowise.core.analysis.health.scoring import history_biomarkers
@@ -247,7 +248,11 @@ async def _refactoring(session: AsyncSession, repo_id: str) -> list[Any]:
o.status,
case((o.recoverable_health >= MIN_WORTH, o.details_json)).label("details_json"),
)
- .where(o.repository_id == repo_id, o.status == "open")
+ .where(
+ o.repository_id == repo_id,
+ o.status == "open",
+ o.refactoring_model_version == REFACTORING_MODEL_VERSION,
+ )
.order_by(o.rank_position)
)
)
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 7a90dacd8..e328140d3 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
@@ -18,7 +18,7 @@ from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any
-from sqlalchemy import Select, func, select
+from sqlalchemy import Select, func, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from ....test_paths import is_test_related_path
@@ -447,10 +447,9 @@ async def _reconcile_opportunities(
await session.execute(
select(RefactoringOpportunity).where(
RefactoringOpportunity.repository_id == repository_id,
- # Rows an older model minted are left exactly as they are:
- # their keys can never be composed again, so reading them
- # only to re-resolve them would grow this read for the life
- # of the repository.
+ # Rows an older model minted can never be composed again;
+ # they are retired below without being read, so this read
+ # does not grow for the life of the repository.
RefactoringOpportunity.refactoring_model_version
== REFACTORING_MODEL_VERSION,
)
@@ -489,6 +488,19 @@ async def _reconcile_opportunities(
if key not in seen and row.status not in _DECIDED_STATUSES:
row.status = "resolved"
row.updated_at = now
+ # Same rule for every row an older model minted, in one statement. Left
+ # open, they kept serving beside the current model's rows after a model
+ # bump, even though the plans they were folded from were already resolved.
+ await session.execute(
+ update(RefactoringOpportunity)
+ .where(
+ RefactoringOpportunity.repository_id == repository_id,
+ RefactoringOpportunity.refactoring_model_version != REFACTORING_MODEL_VERSION,
+ RefactoringOpportunity.status.not_in(tuple(_DECIDED_STATUSES)),
+ )
+ .values(status="resolved", updated_at=now)
+ .execution_options(synchronize_session=False)
+ )
await session.flush()
@@ -543,11 +555,17 @@ def _predicate(rule: Any, value: Any) -> Any:
def _opportunity_filters(repository_id: str, **params: Any) -> list[Any]:
- """The ``WHERE`` for *params*, built from the serving layer's filter table."""
+ """The ``WHERE`` for *params*, built from the serving layer's filter table.
+
+ Only the current model's rows are served: an older model's ids are never
+ composed again, so a row of one is history, not queue.
+ """
+ from ....analysis.health.refactoring.identity import REFACTORING_MODEL_VERSION
from ....analysis.health.refactoring.serving import active_filters
return [
RefactoringOpportunity.repository_id == repository_id,
+ RefactoringOpportunity.refactoring_model_version == REFACTORING_MODEL_VERSION,
*(_predicate(rule, value) for rule, value in active_filters(params)),
]
diff --git a/packages/server/src/repowise/server/services/refactoring_health.py b/packages/server/src/repowise/server/services/refactoring_health.py
index 45f731746..7fd7e3624 100644
--- a/packages/server/src/repowise/server/services/refactoring_health.py
+++ b/packages/server/src/repowise/server/services/refactoring_health.py
@@ -24,6 +24,7 @@ from typing import Any
from sqlalchemy import or_, select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.health.refactoring.identity import REFACTORING_MODEL_VERSION
from repowise.core.analysis.health.refactoring.serving import (
RefactoringQuery,
directive_from_summary,
@@ -369,6 +370,8 @@ class RefactoringHealthService:
.where(
RefactoringOpportunity.repository_id == self._repository_id,
RefactoringOpportunity.status == "open",
+ RefactoringOpportunity.refactoring_model_version
+ == REFACTORING_MODEL_VERSION,
RefactoringOpportunity.file_path == file_path,
)
.limit(5)
diff --git a/tests/unit/health/test_refactoring_serving.py b/tests/unit/health/test_refactoring_serving.py
index 7e3ab34b4..fff4fcf8c 100644
--- a/tests/unit/health/test_refactoring_serving.py
+++ b/tests/unit/health/test_refactoring_serving.py
@@ -275,13 +275,14 @@ _FILTERS: list[dict[str, Any]] = [
def _seed_rows(repository_id: str) -> list[Any]:
+ from repowise.core.analysis.health.refactoring.identity import REFACTORING_MODEL_VERSION
from repowise.core.persistence.models import RefactoringOpportunity
return [
RefactoringOpportunity(
repository_id=repository_id,
opportunity_id=f"refop_{i}",
- refactoring_model_version=1,
+ refactoring_model_version=REFACTORING_MODEL_VERSION,
rank_position=i,
queue_position=_QUEUE[i],
rank_score=1.0 / (i + 1),
diff --git a/tests/unit/persistence/test_fix_first_loader.py b/tests/unit/persistence/test_fix_first_loader.py
index 7878d67d1..f04dfeb8d 100644
--- a/tests/unit/persistence/test_fix_first_loader.py
+++ b/tests/unit/persistence/test_fix_first_loader.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import json
from repowise.core.analysis.health.fix_first import build_fix_first
+from repowise.core.analysis.health.refactoring.identity import REFACTORING_MODEL_VERSION
from repowise.core.persistence.crud.analysis.fix_first import load_fix_first
from repowise.core.persistence.models import (
GitMetadata,
@@ -42,7 +43,12 @@ async def seed_fix_first(session, rid: str | None = None) -> str:
in_degree=m["dependents"]))
session.add_all(HealthFinding(repository_id=rid, **_with_json(f, "details")) for f in FINDINGS)
session.add_all(
- RefactoringOpportunity(repository_id=rid, **_with_json(r, "details")) for r in REFACTORING
+ RefactoringOpportunity(
+ repository_id=rid,
+ refactoring_model_version=REFACTORING_MODEL_VERSION,
+ **_with_json(r, "details"),
+ )
+ for r in REFACTORING
)
session.add_all(
PerformanceOpportunity(repository_id=rid, **_with_json(p, "details")) for p in PERFORMANCE
diff --git a/tests/unit/server/test_refactoring_opportunities.py b/tests/unit/server/test_refactoring_opportunities.py
index 906d0247b..60a50e590 100644
--- a/tests/unit/server/test_refactoring_opportunities.py
+++ b/tests/unit/server/test_refactoring_opportunities.py
@@ -187,6 +187,104 @@ async def test_lifecycle_rolls_up_from_the_member_plans(client, app):
assert refreshed["status"] == "acknowledged"
+async def _seed_older_model(app, repo_id: str, statuses: list[str]) -> list[str]:
+ """Copies of the current rows as an older model left them, one per status."""
+ from sqlalchemy import select
+
+ from repowise.core.analysis.health.refactoring.identity import REFACTORING_MODEL_VERSION
+ from repowise.core.persistence.models import RefactoringOpportunity, _new_uuid
+
+ old = REFACTORING_MODEL_VERSION - 1
+ skip = {"id", "opportunity_id", "refactoring_model_version", "status"}
+ async with app.state.session_factory() as session:
+ current = (
+ await session.execute(
+ select(RefactoringOpportunity).where(
+ RefactoringOpportunity.repository_id == repo_id
+ )
+ )
+ ).scalars().all()
+ ids = []
+ for row, status in zip(current, statuses, strict=False):
+ values = {
+ c.name: getattr(row, c.name)
+ for c in RefactoringOpportunity.__table__.columns
+ if c.name not in skip
+ }
+ opportunity_id = f"refop{old}_{row.opportunity_id.split('_', 1)[1]}"
+ session.add(
+ RefactoringOpportunity(
+ id=_new_uuid(),
+ opportunity_id=opportunity_id,
+ refactoring_model_version=old,
+ status=status,
+ **values,
+ )
+ )
+ ids.append(opportunity_id)
+ await session.commit()
+ return ids
+
+
+async def _states(app, repo_id: str) -> dict[str, str]:
+ from sqlalchemy import select
+
+ from repowise.core.persistence.models import RefactoringOpportunity
+
+ async with app.state.session_factory() as session:
+ rows = await session.execute(
+ select(RefactoringOpportunity.opportunity_id, RefactoringOpportunity.status).where(
+ RefactoringOpportunity.repository_id == repo_id
+ )
+ )
+ return dict(rows.all())
+
+
+async def test_a_model_bump_retires_the_older_models_open_opportunities(client, app):
+ """An older model's open rows resolve on the next run and are never served.
+
+ Its plans were already resolved by the bump, so an open opportunity folded
+ from them names work nobody can act on, and it doubled every count.
+ """
+ from repowise.core.persistence.crud.analysis.fix_first import load_fix_first
+
+ repo_id = await _seed(client, app, files=3)
+ open_old, dismissed_old, picked_up_old = await _seed_older_model(
+ app, repo_id, ["open", "false_positive", "acknowledged"]
+ )
+ clear_fix_first_cache()
+
+ # Served reads skip the older model even before a run retires it.
+ listed = (await client.get(f"/api/repos/{repo_id}/refactoring/opportunities?scope=all")).json()
+ assert listed["total"] == 3
+ async with app.state.session_factory() as session:
+ rows, total = await crud.list_refactoring_opportunities(session, repo_id)
+ facets = await crud.refactoring_facet_counts(session, repo_id)
+ queue = await load_fix_first(session, repo_id, limit=0)
+ assert total == 3
+ assert not {row.opportunity_id for row in rows} & {open_old, picked_up_old}
+ assert all(sum(counts.values()) == 3 for counts in facets.values())
+ assert not set(queue.refactoring_reasons) & {open_old, picked_up_old}
+
+ async with app.state.session_factory() as session:
+ await crud.finalize_refactoring_opportunities(session, repo_id)
+ await session.commit()
+ states = await _states(app, repo_id)
+ assert states[open_old] == "resolved"
+ assert states[picked_up_old] == "resolved"
+ # A person's dismissal is a different claim from "this got done".
+ assert states[dismissed_old] == "false_positive"
+ current = {k: v for k, v in states.items() if k not in {open_old, dismissed_old, picked_up_old}}
+ assert list(current.values()) == ["open"] * 3
+
+ # A later run with no model change resolves nothing more.
+ async with app.state.session_factory() as session:
+ await crud.finalize_refactoring_opportunities(session, repo_id)
+ await session.commit()
+ assert await _states(app, repo_id) == states
+
+
# ---------------------------------------------------------------------------
# Scope: Fix first's eligible set by default, the inventory on request
# ---------------------------------------------------------------------------