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(performance): number a served cause by its place in the ranked list (#4233)
Raghav Chamadiyaf6f027a37373
diff --git a/packages/core/src/repowise/core/analysis/health/perf/serving.py b/packages/core/src/repowise/core/analysis/health/perf/serving.pyindex 15d544cc0..f43002ed7 100644--- a/packages/core/src/repowise/core/analysis/health/perf/serving.py+++ b/packages/core/src/repowise/core/analysis/health/perf/serving.py@@ -440,6 +440,16 @@ class PerformanceQuery:return None if self.role == "all" else frozenset({self.role})+def served_position(query: PerformanceQuery, index: int, stored: int) -> int:+ """Row *index*'s 0-based place in the ranked list *query* serves.++ The stored rank counts every cause in the repository, so a filtered list+ numbered by it skips. Another order keeps *stored*: a place by leverage is+ no rank, and a lookup by id has no list.+ """+ return query.offset + index if query.sort == DEFAULT_SORT else stored++def _resolve_context(context: str | None, ignored: dict[str, str]) -> PerformanceContext:if not context:return DEFAULT_CONTEXT@@ -574,6 +584,9 @@ def serialize(``decisions`` adds the fix, gain and effort to a ``summary`` row, for alist a person acts on from (the dashboard queue). The agent surface keepsits summary shape, so its responses do not grow.++ ``rank_position`` is the stored rank; a list serves+ :func:`served_position` in its place."""details = detail_map(row)payload = {@@ -824,6 +837,7 @@ __all__ = ["row_sort_key","scope_counts","serialize",+ "served_position","sort_keys","summary_payload","unresolved_detail",diff --git a/packages/server/src/repowise/server/services/performance_health.py b/packages/server/src/repowise/server/services/performance_health.pyindex 6185602a7..260982ade 100644--- a/packages/server/src/repowise/server/services/performance_health.py+++ b/packages/server/src/repowise/server/services/performance_health.py@@ -34,6 +34,7 @@ from repowise.core.analysis.health.perf.serving import (rescope_summary,scope_counts,serialize,+ served_position,summary_payload,unresolved_detail,)@@ -146,6 +147,7 @@ class PerformanceHealthService:summary=query.view == "summary",decisions=row_decisions,),+ "rank_position": served_position(query, index, row.rank_position),**(evidence_block(evidence.get(row.opportunity_id, []), row.observations_total, 0@@ -154,7 +156,7 @@ class PerformanceHealthService:else {}),}- for row in rows+ for index, row in enumerate(rows)]emitted = query.offset + len(items)facets: dict[str, list[dict[str, Any]]] = {}diff --git a/packages/types/src/health.ts b/packages/types/src/health.tsindex ff8419754..81e92f1e5 100644--- a/packages/types/src/health.ts+++ b/packages/types/src/health.ts@@ -541,6 +541,8 @@ export interface PerformanceOpportunity {actionability_reason: string;prerequisites: string[];rank_score: number;+ /** 0-based place in the ranked list that served the row; another sort or a+ * lookup by id gives its rank among every cause in the repository. */rank_position: number;rank_factors: Record<string, number>;why_ranked: PerformanceWhyRanked[];diff --git a/packages/ui/__tests__/health/performance-view.test.tsx b/packages/ui/__tests__/health/performance-view.test.tsxindex b70ca1935..6b431e9a1 100644--- a/packages/ui/__tests__/health/performance-view.test.tsx+++ b/packages/ui/__tests__/health/performance-view.test.tsx@@ -424,6 +424,16 @@ describe("PerformanceView drawer", () => {expect(within(panel).getByText(/Position/).textContent).toMatch(/^Position 1 in the queue/);});+ it("keeps the row's queue position when the detail by id carries the repository rank", async () => {+ const getDetail = vi.fn(async () => resolvedDetail({ rank_position: 7 }));+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunity: getDetail })} />);+ await openFirstRow();+ await waitFor(() => expect(getDetail).toHaveBeenCalled());+ const panel = await screen.findByRole("dialog");+ expand(panel, "Why it ranks here");+ expect(within(panel).getByText(/Position/).textContent).toMatch(/^Position 1 in the queue/);+ });+it("separates evidence confidence, actionability, and fix safety", async () => {render(<PerformanceView adapter={adapter()} />);await openFirstRow();diff --git a/packages/ui/src/health/performance/drawer/index.tsx b/packages/ui/src/health/performance/drawer/index.tsxindex b5a951704..727d24eb5 100644--- a/packages/ui/src/health/performance/drawer/index.tsx+++ b/packages/ui/src/health/performance/drawer/index.tsx@@ -94,7 +94,8 @@ export default function OpportunityDrawer({<RelatedSection adapter={adapter} filePath={current.file_path} /><TestsSection current={current} adapter={adapter} /><EvidenceSection current={current} />- <WhyRankedSection current={current} />+ {/* The row's place in the queue: a lookup by id has no list. */}+ <WhyRankedSection current={current} position={opportunity.rank_position} /><CallerPathsSection current={current} adapter={adapter} /><RawObservationsopportunityId={current.opportunity_id}diff --git a/packages/ui/src/health/performance/drawer/judgements.tsx b/packages/ui/src/health/performance/drawer/judgements.tsxindex 4d5ba25eb..b47aac17f 100644--- a/packages/ui/src/health/performance/drawer/judgements.tsx+++ b/packages/ui/src/health/performance/drawer/judgements.tsx@@ -162,11 +162,18 @@ export function EvidenceSection({ current }: { current: PerformanceOpportunity });}-export function WhyRankedSection({ current }: { current: PerformanceOpportunity }) {+export function WhyRankedSection({+ current,+ position = current.rank_position,+}: {+ current: PerformanceOpportunity;+ /** 0-based place in the queue the row was opened from. */+ position?: number;+}) {return (<CollapsibleSection title="Why it ranks here"><p className="text-sm text-[var(--color-text-secondary)]">- Position <span className="tabular-nums">{(current.rank_position + 1).toLocaleString()}</span>{" "}+ Position <span className="tabular-nums">{(position + 1).toLocaleString()}</span>{" "}in the queue.</p>{current.why_ranked.length > 0 ? (diff --git a/tests/unit/server/test_performance_opportunities.py b/tests/unit/server/test_performance_opportunities.pyindex c39799aa0..b29360532 100644--- a/tests/unit/server/test_performance_opportunities.py+++ b/tests/unit/server/test_performance_opportunities.py@@ -683,3 +683,43 @@ async def test_an_opened_area_narrows_the_rows_but_not_the_scope_sizes(opened = await _page(client, repo_id, **_EVERYTHING, area=area)assert opened["total"] == whole["areas"]["items"][0]["total"]assert opened["scopes"] == whole["scopes"]+++async def test_a_row_is_numbered_by_its_place_in_the_list_it_is_served_in(+ app, client: AsyncClient+) -> None:+ """The stored rank counts every cause in the repository, so a filtered list+ numbered by it skips; each row carries its place in the list instead."""+ # A helper four callers reach outranks the queued causes, but nothing+ # measured its loop, so the default queue leaves it out.+ unmeasured = [+ _finding(+ f"src/{name}.py",+ 50,+ [f"src/{name}.py::run", "src/slow.py::load", "src/db.py::fetch"],+ magnitude=None,+ )+ for name in ("f", "g", "h", "i")+ ]+ repo_id, _ = await _seed(app, client, [*_two_production_causes(), *unmeasured])+ queue = await _page(client, repo_id)+ async with app.state.session_factory() as session:+ stored = dict(+ (+ await session.execute(+ select(+ PerformanceOpportunity.opportunity_id, PerformanceOpportunity.rank_position+ )+ )+ ).all()+ )+ assert [stored[item["opportunity_id"]] for item in queue["items"]] == [0, 2]+ assert [item["rank_position"] for item in queue["items"]] == [0, 1]+ second = await _page(client, repo_id, limit=1, offset=1)+ assert second["items"][0]["opportunity_id"] == queue["items"][1]["opportunity_id"]+ assert second["items"][0]["rank_position"] == 1+ # Another order is not a rank: the row keeps the stored one.+ by_leverage = await _page(client, repo_id, sort="leverage")+ assert [item["rank_position"] for item in by_leverage["items"]] == [+ stored[item["opportunity_id"]] for item in by_leverage["items"]+ ]