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
fix(refactoring): refresh held plans after finalize writes their rank (#3476)
Raghav Chamadiya235d70276ab2
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.pyindex 85af31c9c..e43a5fbbe 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py@@ -20,11 +20,13 @@ from sqlalchemy import (bindparam,case,func,+ inspect,or_,select,update,)from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.orm.attributes import set_committed_valuefrom ....analysis.finding_registry import excluded_typesfrom ...models import RefactoringSuggestion, _new_uuid, _now_utc@@ -572,6 +574,27 @@ async def store_plan_ranks()for index in range(0, len(values), _BATCH_SIZE):await session.execute(statement, values[index : index + _BATCH_SIZE])+ _sync_loaded_ranks(session, repository_id, values)+++def _sync_loaded_ranks(+ session: AsyncSession, repository_id: str, values: list[dict[str, Any]]+) -> None:+ """Give every plan this session holds the rank just written: the Core writes+ bypass the identity map, and a later select returns a held instance as loaded."""+ # Not an ORM bulk update by id instead: that fires ``updated_at``'s onupdate.+ written = {item["plan_id"]: item for item in values}+ for instance in list(session.sync_session.identity_map.values()):+ if not isinstance(instance, RefactoringSuggestion):+ continue+ loaded = inspect(instance).dict+ if loaded.get("repository_id") != repository_id:+ continue+ # A plan this finalize did not rank was cleared above, so it reads None.+ item = written.get(loaded.get("id"), {})+ set_committed_value(instance, "rank_position", item.get("position"))+ set_committed_value(instance, "blast_size", item.get("surface"))+ set_committed_value(instance, "rank_json", item.get("facts"))def _base_order(view: str, predicates: list[Any]) -> tuple[Select[Any], tuple[Any, ...]]: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.pyindex dc4038728..d84de0e61 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@@ -568,7 +568,6 @@ async def _reconcile_opportunities(RefactoringOpportunity.status.not_in(tuple(_DECIDED_STATUSES)),).values(status="resolved", updated_at=now)- .execution_options(synchronize_session=False))await session.flush()diff --git a/tests/unit/server/test_refactoring_plan_rank.py b/tests/unit/server/test_refactoring_plan_rank.pyindex d7c565443..37640897d 100644--- a/tests/unit/server/test_refactoring_plan_rank.py+++ b/tests/unit/server/test_refactoring_plan_rank.py@@ -11,7 +11,7 @@ import jsonimport pytestfrom httpx import AsyncClient-from sqlalchemy import select, update+from sqlalchemy import inspect, select, updatefrom repowise.core.analysis.health.refactoring import llm, recommendationsfrom repowise.core.persistence import crud@@ -251,6 +251,48 @@ async def test_finalize_ranks_only_live_plans(client: AsyncClient, app) -> None:assert sorted(live) == list(range(len(live)))+async def test_finalize_refreshes_the_ranks_of_plans_the_session_holds(+ client: AsyncClient, app+) -> None:+ repo_id = await _seed_ranked(client, app)+ async with app.state.session_factory() as session:+ # Held across finalize, so the identity map keeps every instance.+ held = (+ (+ await session.execute(+ select(RefactoringSuggestion)+ .where(RefactoringSuggestion.repository_id == repo_id)+ .order_by(RefactoringSuggestion.rank_position)+ )+ )+ .scalars()+ .all()+ )+ before = {row.id: row.rank_position for row in held}+ # Resolving the first plan moves every other plan up one place.+ resolved_id = next(row.id for row in held if row.rank_position == 0)+ await crud.update_refactoring_suggestion_status(session, repo_id, resolved_id, "resolved")+ await crud.finalize_refactoring_opportunities(session, repo_id)+ table = RefactoringSuggestion.__table__+ stored = {+ plan_id: (position, facts)+ for plan_id, position, facts in (+ await session.execute(+ select(table.c.id, table.c.rank_position, table.c.rank_json).where(+ table.c.repository_id == repo_id+ )+ )+ ).all()+ }+ # Read from what the instances hold, never reloaded.+ assert all({"rank_position", "rank_json"} <= inspect(row).dict.keys() for row in held)+ assert {row.id: (row.rank_position, row.rank_json) for row in held} == stored+ assert stored[resolved_id] == (None, None)+ moved = [row for row in held if row.id != resolved_id and before[row.id] is not None]+ assert moved+ assert all(row.rank_position == before[row.id] - 1 for row in moved)++async def _ids(session, repo_id: str) -> list[str]:return list((