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(dead-code): count real lines instead of estimating them (#2682)

Swati Ahuja8dc9dd7969ec
diff --git a/packages/api-client/src/types/dead-code.ts b/packages/api-client/src/types/dead-code.ts
index 2170d0195..b918ebb84 100644
--- a/packages/api-client/src/types/dead-code.ts
+++ b/packages/api-client/src/types/dead-code.ts
@@ -12,7 +12,7 @@ export interface DeadCodeFindingResponse {
symbol_kind: string | null;
confidence: number;
reason: string;
- lines: number;
+ lines: number | null;
start_line: number | null;
end_line: number | null;
/** Effective deletion-readiness — re-derived from confidence + risk factors. */
diff --git a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
index b5470a316..d6a285011 100644
--- a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
@@ -293,7 +293,7 @@ def dead_code_command(
name,
f"{f.confidence:.0%}",
safe,
- str(f.lines),
+ "—" if f.lines is None else str(f.lines),
f.reason[:60],
)
diff --git a/packages/core/alembic/versions/0086_dead_code_lines_nullable.py b/packages/core/alembic/versions/0086_dead_code_lines_nullable.py
new file mode 100644
index 000000000..cbc44fc70
--- /dev/null
+++ b/packages/core/alembic/versions/0086_dead_code_lines_nullable.py
@@ -0,0 +1,52 @@
+"""Allow ``dead_code_findings.lines`` to be NULL (PostgreSQL only).
+
+The analyzer used to estimate a file's lines as ``symbol_count * 10``. It now
+counts them, and a count it cannot make is stored as NULL rather than guessed,
+so the column must accept NULL.
+
+Only PostgreSQL is altered: local SQLite stores never run Alembic
+(``init_db``'s reconciler is additive-only), and new SQLite stores get the
+nullable column from the model.
+
+Revision ID: 0086
+Revises: 0085
+Create Date: 2026-09-29
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0086"
+down_revision: str | None = "0085"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ if op.get_bind().dialect.name != "postgresql":
+ return
+ op.alter_column(
+ "dead_code_findings",
+ "lines",
+ existing_type=sa.Integer(),
+ nullable=True,
+ )
+
+
+def downgrade() -> None:
+ """Restore NOT NULL. Unknown counts become 0, which is what the old
+ schema could express."""
+ if op.get_bind().dialect.name != "postgresql":
+ return
+ op.execute("UPDATE dead_code_findings SET lines = 0 WHERE lines IS NULL")
+ op.alter_column(
+ "dead_code_findings",
+ "lines",
+ existing_type=sa.Integer(),
+ nullable=False,
+ )
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index 4d62ee02a..c5aaafc13 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -737,16 +737,21 @@ def _is_declaration_only(sym: dict) -> bool:
)
+# Evidence line for a finding whose ``lines`` is ``None``: the count is
+# omitted rather than estimated.
+_LINES_UNKNOWN = "Line count unavailable: source was not read"
+
+
def _symbol_span(data: dict) -> dict[str, int | None]:
"""``lines``/``start_line``/``end_line`` for a symbol finding.
- Both-or-neither: a half-known span is worse than none.
+ Both-or-neither: a half-known span is worse than none. Spans are
+ inclusive, so a one-line symbol is 1 line; an unknown span is ``None``.
"""
- return {
- "lines": data.get("end_line", 0) - data.get("start_line", 0),
- "start_line": (data.get("start_line") or None) if data.get("end_line") else None,
- "end_line": (data.get("end_line") or None) if data.get("start_line") else None,
- }
+ start, end = data.get("start_line") or None, data.get("end_line") or None
+ if start is None or end is None or end < start:
+ return {"lines": None, "start_line": None, "end_line": None}
+ return {"lines": end - start + 1, "start_line": start, "end_line": end}
class DeadCodeAnalyzer:
@@ -904,7 +909,8 @@ class DeadCodeAnalyzer:
findings = [f for f in findings if f.confidence >= min_conf]
now = datetime.now(UTC)
- deletable = sum(f.lines for f in findings if f.safe_to_delete)
+ # Sum of the known counts: a lower bound when any count is unknown.
+ deletable = sum(f.lines or 0 for f in findings if f.safe_to_delete)
high = sum(1 for f in findings if f.confidence >= SAFE_CONFIDENCE_THRESHOLD)
medium = sum(
@@ -1124,6 +1130,9 @@ class DeadCodeAnalyzer:
risk_line = risk_evidence(risk_factors)
if risk_line:
evidence.append(risk_line)
+ lines = self._file_line_count(node)
+ if lines is None:
+ evidence.append(_LINES_UNKNOWN)
return DeadCodeFindingData(
kind=DeadCodeKind.UNREACHABLE_FILE,
@@ -1134,7 +1143,7 @@ class DeadCodeAnalyzer:
reason="File has no importers (in_degree=0)",
last_commit_at=last_commit if isinstance(last_commit, datetime) else None,
commit_count_90d=commit_90d,
- lines=node_data.get("symbol_count", 0) * 10, # rough estimate
+ lines=lines,
evidence=evidence,
safe_to_delete=safe,
primary_owner=primary_owner,
@@ -1577,6 +1586,22 @@ class DeadCodeAnalyzer:
return None
+ def _file_line_count(self, file_path: str) -> int | None:
+ """Physical line count of an indexed file, or ``None`` when unread.
+
+ Prefers ingestion's bytes; falls back to disk only under a known repo
+ root, so a missing source is reported as unknown rather than guessed.
+ """
+ data = self._source_map.get(file_path)
+ if data is None and self._repo_root is not None:
+ try:
+ data = (Path(self._repo_root) / file_path).read_bytes()
+ except OSError:
+ return None
+ if data is None:
+ return None
+ return data.count(b"\n") + (1 if data and not data.endswith(b"\n") else 0)
+
def _read_file_text(self, file_path: str) -> str | None:
"""Safely read the content of a file, using source_map if available."""
try:
@@ -1764,11 +1789,17 @@ class DeadCodeAnalyzer:
if self._has_cross_package_importer(pkg, files):
continue
- total_lines = sum(
- self.graph.nodes[f].get("symbol_count", 0) * 10
+ # A package total is only as known as its least-known file.
+ counts = [
+ self._file_line_count(f)
for f in files
- if f in self.graph
- )
+ if self.graph.nodes[f].get("node_type") != "symbol"
+ ]
+ known = [c for c in counts if c is not None]
+ total_lines = sum(known) if len(known) == len(counts) else None
+ evidence = [f"No inter-package imports into '{pkg}'"]
+ if total_lines is None:
+ evidence.append(_LINES_UNKNOWN)
activity = self._package_git_activity(files)
findings.append(
DeadCodeFindingData(
@@ -1779,7 +1810,7 @@ class DeadCodeAnalyzer:
confidence=0.5,
reason=f"Package '{pkg}' has no importers from other packages",
lines=total_lines,
- evidence=[f"No inter-package imports into '{pkg}'"],
+ evidence=evidence,
safe_to_delete=False,
risk_factors=list(path_risk_factors(pkg)),
**activity,
diff --git a/packages/core/src/repowise/core/analysis/dead_code/models.py b/packages/core/src/repowise/core/analysis/dead_code/models.py
index 39de96527..4b02bd3fd 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/models.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/models.py
@@ -24,7 +24,9 @@ class DeadCodeFindingData:
reason: str
last_commit_at: datetime | None
commit_count_90d: int
- lines: int
+ # Physical lines the finding covers; ``None`` when it could not be
+ # counted (the evidence says why) — never an estimate.
+ lines: int | None
evidence: list[str]
safe_to_delete: bool
primary_owner: str | None
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py b/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
index 75be45858..a674cbbf8 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import json
from typing import Any
-from sqlalchemy import select
+from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.dead_code.risk_factors import (
@@ -57,6 +57,34 @@ def _dead_code_row_kwargs(finding: Any, repository_id: str) -> dict:
}
+async def _lines_column_rejects_null(session: AsyncSession) -> bool:
+ """True for a SQLite store created before ``lines`` became nullable.
+
+ Local SQLite stores never run Alembic and the schema reconciler is
+ additive-only, so such a store keeps ``lines NOT NULL``. Inserting an
+ unknown (NULL) count there would fail the whole findings write.
+ """
+ bind = session.get_bind()
+ if bind.dialect.name != "sqlite":
+ return False
+ rows = await session.execute(text("PRAGMA table_info(dead_code_findings)"))
+ return any(row[1] == "lines" and row[3] for row in rows)
+
+
+def _new_rows(findings: list[Any], repository_id: str, *, null_lines_as_zero: bool) -> list:
+ rows = []
+ for finding in findings:
+ kwargs = _dead_code_row_kwargs(finding, repository_id)
+ # Deliberate shortcut: a legacy NOT NULL store can't hold "unknown",
+ # so an unreadable file's count is stored as 0 there rather than the
+ # write failing. Ceiling: that store shows 0 lines for such files
+ # until its table is rebuilt (a fresh store gets the nullable column).
+ if null_lines_as_zero and kwargs.get("lines") is None:
+ kwargs["lines"] = 0
+ rows.append(DeadCodeFinding(**kwargs))
+ return rows
+
+
async def save_dead_code_findings(
session: AsyncSession,
repository_id: str,
@@ -73,10 +101,10 @@ async def save_dead_code_findings(
for row in existing.scalars().all():
await session.delete(row)
+ null_lines_as_zero = await _lines_column_rejects_null(session)
for i in range(0, len(findings), _BATCH_SIZE):
batch = findings[i : i + _BATCH_SIZE]
- for finding in batch:
- session.add(DeadCodeFinding(**_dead_code_row_kwargs(finding, repository_id)))
+ session.add_all(_new_rows(batch, repository_id, null_lines_as_zero=null_lines_as_zero))
await session.flush()
@@ -146,13 +174,16 @@ async def replace_dead_code_findings(
acted_on.add((row.file_path, row.kind, row.symbol_name))
await session.flush()
- writable = [f for f in findings if scope is None or _finding_file_path(f) in scope]
+ writable = [
+ f
+ for f in findings
+ if (scope is None or _finding_file_path(f) in scope)
+ and _finding_identity(f) not in acted_on
+ ]
+ null_lines_as_zero = await _lines_column_rejects_null(session)
for i in range(0, len(writable), _BATCH_SIZE):
batch = writable[i : i + _BATCH_SIZE]
- for finding in batch:
- if _finding_identity(finding) in acted_on:
- continue
- session.add(DeadCodeFinding(**_dead_code_row_kwargs(finding, repository_id)))
+ session.add_all(_new_rows(batch, repository_id, null_lines_as_zero=null_lines_as_zero))
await session.flush()
@@ -227,15 +258,16 @@ async def get_dead_code_summary(session: AsyncSession, repository_id: str) -> di
summary["medium"] += 1
else:
summary["low"] += 1
- total_lines += f.lines
+ total_lines += f.lines or 0
by_kind[f.kind] = by_kind.get(f.kind, 0) + 1
# Re-derive effective safety from confidence + path risk factors rather
# than trusting the persisted boolean alone, so findings written before the
# risk-factor logic existed (or in a config/bootstrap/database/environment
# file the allowlist missed) are not counted as deletion-ready.
+ # Totals sum the known counts; an unknown (NULL) count adds nothing.
deletable_lines = sum(
- f.lines
+ f.lines or 0
for f in findings
if effective_safe_to_delete(f.confidence, f.file_path, f.safe_to_delete)
)
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index fc2db694f..baaa2dec8 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -1569,7 +1569,8 @@ class DeadCodeFinding(Base):
reason: Mapped[str] = mapped_column(Text, nullable=False, default="")
last_commit_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
commit_count_90d: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
- lines: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
+ # NULL when the analyzer could not count the lines (never an estimate).
+ lines: Mapped[int | None] = mapped_column(Integer, nullable=True)
start_line: Mapped[int | None] = mapped_column(Integer, nullable=True)
end_line: Mapped[int | None] = mapped_column(Integer, nullable=True)
# ``package`` dropped: it was ``Path(file_path).parts[0]``, equal to the
diff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
index f3165381b..17f93672e 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
@@ -130,13 +130,13 @@ async def _get_dead_code_all_repos(
# Accumulate summary stats from unfiltered findings
total_all += len(repo_findings)
- total_deletable += sum(f.lines for f in repo_findings if _effective_safe(f))
+ total_deletable += sum(f.lines or 0 for f in repo_findings if _effective_safe(f))
total_safe += sum(1 for f in repo_findings if _effective_safe(f))
for f in repo_findings:
merged_by_kind[f.kind] = merged_by_kind.get(f.kind, 0) + 1
# Sort merged findings by confidence descending
- merged_findings.sort(key=lambda d: (-d["confidence"], -d["lines"]))
+ merged_findings.sort(key=lambda d: (-d["confidence"], -(d["lines"] or 0)))
summary = {
"total_findings": total_all,
@@ -188,7 +188,7 @@ def _build_tiers_from_dicts(
return {
"description": desc,
"count": len(items),
- "lines": sum(f["lines"] for f in items),
+ "lines": sum(f["lines"] or 0 for f in items),
"safe_count": sum(1 for f in items if f["safe_to_delete"]),
"findings": items[:limit],
"truncated": len(items) > limit,
@@ -426,7 +426,7 @@ async def get_dead_code(
summary: dict[str, Any] = {
"total_findings": len(all_findings),
"filtered_findings": len(filtered),
- "deletable_lines": sum(f.lines for f in all_findings if _effective_safe(f)),
+ "deletable_lines": sum(f.lines or 0 for f in all_findings if _effective_safe(f)),
"safe_to_delete_count": sum(1 for f in all_findings if _effective_safe(f)),
"by_kind": by_kind,
}
@@ -596,15 +596,15 @@ def _build_tiers(
hi, med = _TIER_FLOORS["high"], _TIER_FLOORS["medium"]
high = sorted(
[f for f in findings if f.confidence >= hi],
- key=lambda f: (-f.confidence, -f.lines),
+ key=lambda f: (-f.confidence, -(f.lines or 0)),
)
medium = sorted(
[f for f in findings if med <= f.confidence < hi],
- key=lambda f: (-f.confidence, -f.lines),
+ key=lambda f: (-f.confidence, -(f.lines or 0)),
)
low = sorted(
[f for f in findings if f.confidence < med],
- key=lambda f: (-f.confidence, -f.lines),
+ key=lambda f: (-f.confidence, -(f.lines or 0)),
)
def _tier_block(name: str, items: list, description: str) -> dict:
@@ -623,7 +623,7 @@ def _build_tiers(
return {
"description": description,
"count": len(items),
- "lines": sum(f.lines for f in items),
+ "lines": sum(f.lines or 0 for f in items),
"safe_count": sum(1 for f in items if _effective_safe(f)),
"findings": [
_serialize_finding(f, git_meta_map, repository=repository)
@@ -652,7 +652,7 @@ def _rollup_by_directory(findings: list) -> list[dict]:
if dir_key not in dirs:
dirs[dir_key] = {"directory": dir_key, "count": 0, "lines": 0, "safe_count": 0}
dirs[dir_key]["count"] += 1
- dirs[dir_key]["lines"] += f.lines
+ dirs[dir_key]["lines"] += f.lines or 0
if _effective_safe(f):
dirs[dir_key]["safe_count"] += 1
@@ -667,7 +667,7 @@ def _rollup_by_owner(findings: list) -> list[dict]:
if name not in owners:
owners[name] = {"owner": name, "count": 0, "lines": 0, "safe_count": 0}
owners[name]["count"] += 1
- owners[name]["lines"] += f.lines
+ owners[name]["lines"] += f.lines or 0
if _effective_safe(f):
owners[name]["safe_count"] += 1
@@ -683,7 +683,7 @@ def _compute_impact(tiers: dict) -> dict:
# Approximate safe lines from findings in the tier
for f in tier_data["findings"]:
if f["safe_to_delete"]:
- safe_lines += f["lines"]
+ safe_lines += f["lines"] or 0
return {
"total_lines_reclaimable": total_lines,
diff --git a/packages/server/src/repowise/server/schemas/code_quality.py b/packages/server/src/repowise/server/schemas/code_quality.py
index 5cfb74d93..79a1f142d 100644
--- a/packages/server/src/repowise/server/schemas/code_quality.py
+++ b/packages/server/src/repowise/server/schemas/code_quality.py
@@ -21,7 +21,7 @@ class DeadCodeFindingResponse(BaseModel):
symbol_kind: str | None
confidence: float
reason: str
- lines: int
+ lines: int | None
start_line: int | None
end_line: int | None
# Effective deletion-readiness — re-derived from confidence + path risk
diff --git a/packages/server/src/repowise/server/services/attention.py b/packages/server/src/repowise/server/services/attention.py
index ae3788b59..d6fe63503 100644
--- a/packages/server/src/repowise/server/services/attention.py
+++ b/packages/server/src/repowise/server/services/attention.py
@@ -361,7 +361,8 @@ async def _dead_code_items(session: AsyncSession, repo_id: str) -> tuple[list[di
"id": f"dead-{row.id}",
"type": "dead_code",
"title": row.symbol_name or row.file_path,
- "description": f"Unreachable {row.symbol_kind or 'symbol'} ({row.lines} lines)",
+ "description": f"Unreachable {row.symbol_kind or 'symbol'}"
+ + (f" ({row.lines} lines)" if row.lines is not None else ""),
"severity": "low",
"target_id": row.file_path,
"subtype": row.kind,
diff --git a/packages/types/src/chat.ts b/packages/types/src/chat.ts
index a7343ea57..0f5b38389 100644
--- a/packages/types/src/chat.ts
+++ b/packages/types/src/chat.ts
@@ -498,7 +498,7 @@ export interface DeadCodeArtifactData {
kind: string;
confidence: number;
reason: string;
- lines: number;
+ lines: number | null;
safe_to_delete: boolean;
}>;
medium_confidence: Array<{
diff --git a/packages/types/src/dead-code.ts b/packages/types/src/dead-code.ts
index 25858376a..b0badf12f 100644
--- a/packages/types/src/dead-code.ts
+++ b/packages/types/src/dead-code.ts
@@ -77,7 +77,8 @@ export interface DeadCodeFinding {
symbol_kind: string | null;
confidence: number;
reason: string;
- lines: number;
+ /** Lines the finding covers; null when they could not be counted. */
+ lines: number | null;
/**
* Effective deletion-readiness — high confidence AND no runtime-load risk
* factors. Re-derived server-side, not the raw persisted boolean.
diff --git a/packages/types/src/files.ts b/packages/types/src/files.ts
index 10493d0f5..8de6962bf 100644
--- a/packages/types/src/files.ts
+++ b/packages/types/src/files.ts
@@ -204,7 +204,7 @@ export interface FileDeadCodeFinding {
symbol_name: string | null;
confidence: number;
reason: string;
- lines: number;
+ lines: number | null;
safe_to_delete: boolean;
}
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index de31b3bbf..ea48e0562 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -849,7 +849,7 @@ export interface DeadCodeFindingResponse {
symbol_kind: string | null;
confidence: number;
reason: string;
- lines: number;
+ lines: number | null;
start_line: number | null;
end_line: number | null;
safe_to_delete: boolean;
diff --git a/packages/types/src/symbols.ts b/packages/types/src/symbols.ts
index 5803718db..befaa169d 100644
--- a/packages/types/src/symbols.ts
+++ b/packages/types/src/symbols.ts
@@ -208,7 +208,7 @@ export interface SymbolBodyDeadFinding {
id: string;
kind: string;
reason: string;
- lines: number;
+ lines: number | null;
safe_to_delete: boolean;
}
diff --git a/packages/ui/__tests__/symbols/symbol-detail-dead-code.test.tsx b/packages/ui/__tests__/symbols/symbol-detail-dead-code.test.tsx
new file mode 100644
index 000000000..8e156f6b7
--- /dev/null
+++ b/packages/ui/__tests__/symbols/symbol-detail-dead-code.test.tsx
@@ -0,0 +1,35 @@
+import { describe, it, expect } from "vitest";
+import { render, screen } from "@testing-library/react";
+import { SymbolDetailBody } from "../../src/symbols/symbol-detail-body.js";
+import type { SymbolBodyDeadFinding } from "@repowise-dev/types/symbols";
+
+const finding = (lines: number | null): SymbolBodyDeadFinding => ({
+ id: "f1",
+ kind: "unused_export",
+ reason: "no importers",
+ lines,
+ safe_to_delete: false,
+});
+
+const renderWith = (lines: number | null) =>
+ render(
+ <SymbolDetailBody
+ data={{
+ identity: { name: "helper", kind: "function", file_path: "src/a.py", start_line: 1 },
+ dead_code: [finding(lines)],
+ }}
+ />,
+ );
+
+describe("symbol detail dead code", () => {
+ it("shows the line count when it is known", () => {
+ renderWith(12);
+ expect(screen.getByText(/no importers \(12 lines\)/)).toBeInTheDocument();
+ });
+
+ it("omits the count when it could not be measured", () => {
+ renderWith(null);
+ expect(screen.getByText(/no importers/)).toBeInTheDocument();
+ expect(screen.queryByText(/lines\)/)).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/src/chat/artifacts.tsx b/packages/ui/src/chat/artifacts.tsx
index 55c463d2f..6586b3349 100644
--- a/packages/ui/src/chat/artifacts.tsx
+++ b/packages/ui/src/chat/artifacts.tsx
@@ -936,7 +936,7 @@ function DeadCodeRow({
kind: string;
confidence: number;
reason: string;
- lines?: number;
+ lines?: number | null;
safe_to_delete?: boolean;
};
showLines?: boolean;
diff --git a/packages/ui/src/dead-code/findings-table.tsx b/packages/ui/src/dead-code/findings-table.tsx
index 577809fbd..9b041bbf0 100644
--- a/packages/ui/src/dead-code/findings-table.tsx
+++ b/packages/ui/src/dead-code/findings-table.tsx
@@ -64,7 +64,7 @@ function sortValue(f: DeadCodeFinding, key: SortKey): string | number {
case "owner":
return f.primary_owner ?? "";
case "lines":
- return f.lines;
+ return f.lines ?? 0;
case "confidence":
return f.confidence;
case "last_commit_at":
@@ -360,7 +360,7 @@ export function FindingsTable({
align: "right",
headerClassName: "w-16",
render: (f) => (
- <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">{f.lines}</span>
+ <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">{f.lines ?? "—"}</span>
),
},
{
diff --git a/packages/ui/src/dead-code/owner-leaderboard.tsx b/packages/ui/src/dead-code/owner-leaderboard.tsx
index 1ffaafa6b..8af8d0371 100644
--- a/packages/ui/src/dead-code/owner-leaderboard.tsx
+++ b/packages/ui/src/dead-code/owner-leaderboard.tsx
@@ -6,7 +6,7 @@ import { cn } from "../lib/cn";
export interface OwnerLeaderboardFinding {
primary_owner: string | null;
- lines: number;
+ lines: number | null;
safe_to_delete?: boolean;
}
@@ -38,7 +38,7 @@ export function OwnerLeaderboard({
if (safeOnly && !f.safe_to_delete) continue;
const owner = f.primary_owner?.trim() || "Unowned";
const prev = map.get(owner) ?? { lines: 0, count: 0 };
- prev.lines += Number.isFinite(f.lines) ? f.lines : 0;
+ prev.lines += f.lines ?? 0;
prev.count += 1;
map.set(owner, prev);
}
diff --git a/packages/ui/src/dead-code/safe-to-delete-pile.tsx b/packages/ui/src/dead-code/safe-to-delete-pile.tsx
index 5b9c854b3..b3c3eb2c8 100644
--- a/packages/ui/src/dead-code/safe-to-delete-pile.tsx
+++ b/packages/ui/src/dead-code/safe-to-delete-pile.tsx
@@ -10,7 +10,7 @@ export interface SafeToDeletePileFinding {
id: string;
file_path: string;
symbol_name: string | null;
- lines: number;
+ lines: number | null;
confidence: number;
}
@@ -49,7 +49,7 @@ export function SafeToDeletePile({
}: SafeToDeletePileProps) {
const lines =
reclaimableLines ??
- findings.reduce((sum, f) => sum + (Number.isFinite(f.lines) ? f.lines : 0), 0);
+ findings.reduce((sum, f) => sum + (f.lines ?? 0), 0);
const files = new Set(findings.map((f) => f.file_path)).size;
// Roll findings up by file so the preview list shows distinct files
@@ -67,7 +67,7 @@ export function SafeToDeletePile({
for (const f of findings) {
const existing = byFile.get(f.file_path);
if (existing) {
- existing.lines += Number.isFinite(f.lines) ? f.lines : 0;
+ existing.lines += f.lines ?? 0;
existing.finding_count += 1;
if ((f.lines ?? 0) > (existing.representative.lines ?? 0)) {
existing.representative = f;
@@ -75,7 +75,7 @@ export function SafeToDeletePile({
} else {
byFile.set(f.file_path, {
file_path: f.file_path,
- lines: Number.isFinite(f.lines) ? f.lines : 0,
+ lines: f.lines ?? 0,
finding_count: 1,
representative: f,
});
diff --git a/packages/ui/src/files/file-marks.tsx b/packages/ui/src/files/file-marks.tsx
index c209631e7..ff594b17c 100644
--- a/packages/ui/src/files/file-marks.tsx
+++ b/packages/ui/src/files/file-marks.tsx
@@ -44,7 +44,7 @@ export function FileMark({
* a quiet header is a healthy file rather than a header that failed to load.
*/
export function FileMarks({ data }: { data: FileDetailResponse }) {
- const deadLines = data.dead_code.reduce((s, f) => s + f.lines, 0);
+ const deadLines = data.dead_code.reduce((s, f) => s + (f.lines ?? 0), 0);
const freshness = data.wiki_page?.freshness_status;
const docStale = freshness === "stale" || freshness === "outdated";
diff --git a/packages/ui/src/files/file-overview-tab.tsx b/packages/ui/src/files/file-overview-tab.tsx
index dbabaf8eb..42fbaec84 100644
--- a/packages/ui/src/files/file-overview-tab.tsx
+++ b/packages/ui/src/files/file-overview-tab.tsx
@@ -34,7 +34,7 @@ export function FileOverviewTab({
LinkComponent = "a",
}: FileOverviewTabProps) {
const A = LinkComponent;
- const deadLines = data.dead_code.reduce((s, f) => s + f.lines, 0);
+ const deadLines = data.dead_code.reduce((s, f) => s + (f.lines ?? 0), 0);
// Keyed on the row's own symbol_id, not a rebuilt `${path}::${name}`: some
// extractors mint ids from the qualified name, and those would never match.
const rawFixCounts = data.git?.fix_symbol_counts ?? {};
diff --git a/packages/ui/src/symbols/symbol-detail-body.tsx b/packages/ui/src/symbols/symbol-detail-body.tsx
index 1b6aa4774..daffc851f 100644
--- a/packages/ui/src/symbols/symbol-detail-body.tsx
+++ b/packages/ui/src/symbols/symbol-detail-body.tsx
@@ -345,7 +345,7 @@ export function SymbolDetailBody({
<span className="text-[var(--color-text-secondary)]">
<span className="font-medium">{f.kind}</span>{" "}
<span className="text-[var(--color-text-tertiary)]">
- — {f.reason} ({f.lines} lines)
+ — {f.reason}{f.lines != null && ` (${f.lines} lines)`}
</span>
</span>
</li>
diff --git a/packages/vscode/src/features/trees/deadCode.ts b/packages/vscode/src/features/trees/deadCode.ts
index fdca5baa3..8de404959 100644
--- a/packages/vscode/src/features/trees/deadCode.ts
+++ b/packages/vscode/src/features/trees/deadCode.ts
@@ -57,7 +57,7 @@ export class DeadCodeTreeProvider extends RepowiseTreeProvider {
return {
key: `dead:${row.id}`,
label: row.symbol_name ?? baseName(row.file_path),
- description: `${row.kind} · ${row.lines} lines`,
+ description: row.lines === null ? row.kind : `${row.kind} · ${row.lines} lines`,
tooltip,
collapsibleState: vscode.TreeItemCollapsibleState.None,
command: openFileCommand(this.ctx, row.file_path, row.start_line),
diff --git a/tests/unit/dead_code/test_line_counts.py b/tests/unit/dead_code/test_line_counts.py
new file mode 100644
index 000000000..97e9c73fe
--- /dev/null
+++ b/tests/unit/dead_code/test_line_counts.py
@@ -0,0 +1,102 @@
+"""Dead-code line counts are counted, never estimated.
+
+Files used to report ``symbol_count * 10`` lines and symbols ``end - start``,
+so a one-line symbol reported 0. Spans are inclusive and file counts come from
+the source; a count that cannot be made is ``None`` with an evidence line.
+"""
+
+from __future__ import annotations
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+from tests.unit.dead_code._helpers import _build_graph, _old_date
+
+_PLAIN = {"is_entry_point": False, "is_test": False, "is_api_contract": False}
+_STALE = {"commit_count_90d": 0, "last_commit_at": _old_date(days=400), "age_days": 500}
+
+
+def _file(symbol_count: int = 0, symbols: list | None = None) -> dict:
+ return {**_PLAIN, "symbol_count": symbol_count, "symbols": symbols or []}
+
+
+def _unreachable(g, **kwargs):
+ report = DeadCodeAnalyzer(g, git_meta_map={p: _STALE for p in g.nodes}, **kwargs).analyze(
+ {"detect_unused_exports": False, "detect_zombie_packages": False, "min_confidence": 0.0}
+ )
+ return {f.file_path: f for f in report.findings}, report
+
+
+def test_one_line_symbol_counts_one_line():
+ g = _build_graph(
+ nodes={
+ "pkg/utils.py": _file(
+ 1,
+ [
+ {
+ "name": "helper",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 7,
+ "end_line": 7,
+ }
+ ],
+ ),
+ "pkg/main.py": {**_file(), "is_entry_point": True},
+ },
+ edges=[("pkg/main.py", "pkg/utils.py", {"imported_names": ["other"]})],
+ )
+ report = DeadCodeAnalyzer(g, git_meta_map={}).analyze(
+ {"detect_unreachable_files": False, "detect_zombie_packages": False}
+ )
+ finding = next(f for f in report.findings if f.symbol_name == "helper")
+ assert finding.kind == DeadCodeKind.UNUSED_EXPORT
+ assert (finding.start_line, finding.end_line, finding.lines) == (7, 7, 1)
+
+
+def test_nineteen_line_file_counts_nineteen_lines():
+ # symbol_count would have estimated 50 lines; the source says 19, with or
+ # without a trailing newline.
+ source = "\n".join(f"x{i} = {i}" for i in range(19)).encode()
+ g = _build_graph(nodes={"pkg/a.py": _file(5), "pkg/b.py": _file(5)})
+ by_path, report = _unreachable(g, source_map={"pkg/a.py": source + b"\n", "pkg/b.py": source})
+ assert by_path["pkg/a.py"].lines == 19
+ assert by_path["pkg/b.py"].lines == 19
+ assert report.deletable_lines == 38
+
+
+def test_file_counted_from_disk_without_source_map(tmp_path):
+ (tmp_path / "pkg").mkdir()
+ (tmp_path / "pkg" / "a.py").write_text("a = 1\nb = 2\nc = 3\n")
+ g = _build_graph(nodes={"pkg/a.py": _file(9)})
+ by_path, _ = _unreachable(g, repo_root=tmp_path)
+ assert by_path["pkg/a.py"].lines == 3
+
+
+def test_unreadable_file_is_unknown_not_guessed():
+ g = _build_graph(nodes={"pkg/gone.py": _file(9), "pkg/a.py": _file(1)})
+ by_path, report = _unreachable(g, source_map={"pkg/a.py": b"x = 1\n"})
+ gone = by_path["pkg/gone.py"]
+ assert gone.lines is None
+ assert "Line count unavailable: source was not read" in gone.evidence
+ # The total sums what is known rather than failing on the unknown.
+ assert report.deletable_lines == 1
+
+
+def test_zombie_package_sums_real_file_lines():
+ g = _build_graph(
+ nodes={
+ "pkgA/one.py": _file(10),
+ "pkgA/two.py": _file(10),
+ "pkgB/three.py": _file(10),
+ }
+ )
+ source_map = {"pkgA/one.py": b"a\nb\n", "pkgA/two.py": b"c\n", "pkgB/three.py": b"d\n"}
+ report = DeadCodeAnalyzer(g, git_meta_map={}, source_map=source_map).analyze(
+ {"detect_unreachable_files": False, "detect_unused_exports": False}
+ )
+ zombie = next(
+ f
+ for f in report.findings
+ if f.kind == DeadCodeKind.ZOMBIE_PACKAGE and f.file_path == "pkgA"
+ )
+ assert zombie.lines == 3
diff --git a/tests/unit/dead_code/test_whitelist_safety.py b/tests/unit/dead_code/test_whitelist_safety.py
index e2918479c..e23fad5f4 100644
--- a/tests/unit/dead_code/test_whitelist_safety.py
+++ b/tests/unit/dead_code/test_whitelist_safety.py
@@ -111,21 +111,21 @@ def test_report_deletable_lines_sum():
"is_entry_point": False,
"is_test": False,
"is_api_contract": False,
- "symbol_count": 10, # lines = 10 * 10 = 100
+ "symbol_count": 10,
"symbols": [],
},
"pkg/dead2.py": {
"is_entry_point": False,
"is_test": False,
"is_api_contract": False,
- "symbol_count": 20, # lines = 20 * 10 = 200
+ "symbol_count": 20,
"symbols": [],
},
"pkg/alive.py": {
"is_entry_point": False,
"is_test": False,
"is_api_contract": False,
- "symbol_count": 15, # lines = 15 * 10 = 150, but NOT safe
+ "symbol_count": 15, # NOT safe
"symbols": [],
},
},
@@ -150,7 +150,13 @@ def test_report_deletable_lines_sum():
},
}
- analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta)
+ # Line counts come from the source, not from symbol_count.
+ source_map = {
+ "pkg/dead1.py": b"x = 1\n" * 100,
+ "pkg/dead2.py": b"x = 1\n" * 200,
+ "pkg/alive.py": b"x = 1\n" * 150,
+ }
+ analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta, source_map=source_map)
report = analyzer.analyze(
{
"detect_unused_exports": False,
diff --git a/tests/unit/persistence/test_dead_code_crud.py b/tests/unit/persistence/test_dead_code_crud.py
index da43beca3..2524ed17f 100644
--- a/tests/unit/persistence/test_dead_code_crud.py
+++ b/tests/unit/persistence/test_dead_code_crud.py
@@ -422,3 +422,51 @@ async def test_get_dead_code_git_fields_returns_last_commit_at_aware(async_sessi
assert (datetime.now(UTC) - stored).days >= 0
assert stored > datetime(2020, 1, 1, tzinfo=UTC)
assert stored == datetime(2025, 12, 21, 0, 6, 49, tzinfo=UTC), "must not shift the instant"
+
+
+async def test_unknown_line_count_is_stored_as_null_and_summed_as_nothing(async_session):
+ """A count the analyzer could not make round-trips as NULL, not 0, and the
+ summary totals add only the counts that are known."""
+ from repowise.core.persistence.crud.analysis import dead_code as dead_code_crud
+
+ repo = await insert_repo(async_session)
+ known = _finding("known.py", "known")
+ known["lines"] = 19
+ unknown = _finding("unknown.py", "unknown")
+ unknown["lines"] = None
+ await save_dead_code_findings(async_session, repo.id, [known, unknown])
+
+ by_file = {r.file_path: r.lines for r in await _rows(async_session, repo.id)}
+ assert by_file == {"known.py": 19, "unknown.py": None}
+
+ summary = await dead_code_crud.get_dead_code_summary(async_session, repo.id)
+ assert summary["total_lines"] == 19
+ assert summary["deletable_lines"] == 19
+
+
+async def test_unknown_line_count_is_stored_as_null(async_session):
+ repo = await insert_repo(async_session)
+ finding = {**_finding("a.py", "fa"), "lines": None}
+ await save_dead_code_findings(async_session, repo.id, [finding])
+ assert [r.lines for r in await _rows(async_session, repo.id)] == [None]
+
+
+async def test_legacy_not_null_store_still_accepts_an_unknown_count(async_session):
+ """A SQLite store made before ``lines`` became nullable keeps NOT NULL
+ (no Alembic locally, additive-only reconciler). An unknown count must not
+ fail the whole write there."""
+ from sqlalchemy import text
+
+ ddl = (
+ await async_session.execute(
+ text("SELECT sql FROM sqlite_master WHERE name = 'dead_code_findings'")
+ )
+ ).scalar_one()
+ assert "lines INTEGER," in ddl
+ await async_session.execute(text("DROP TABLE dead_code_findings"))
+ await async_session.execute(text(ddl.replace("lines INTEGER,", "lines INTEGER NOT NULL,")))
+ repo = await insert_repo(async_session)
+ findings = [{**_finding("a.py", "fa"), "lines": None}, _finding("b.py", "fb")]
+ await save_dead_code_findings(async_session, repo.id, findings)
+ await replace_dead_code_findings(async_session, repo.id, findings)
+ assert sorted(r.lines for r in await _rows(async_session, repo.id)) == [0, 1]