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(health): keep finding triage across re-index (#2819)
Raghav Chamadiya5418d62e20d1
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.mdindex 9c705b926..9a7304728 100644--- a/docs/architecture/code-health.md+++ b/docs/architecture/code-health.md@@ -656,8 +656,9 @@ Four tables, all in the repo's `.repowise/wiki.db`. Foreign-keyed to### `health_findings`One row per marker hit. Lifecycle: `open → acknowledged | resolved |-false_positive` (matches Dead Code). Bulk-deleted-and-rewritten on full-init; selectively upserted on `repowise update`.+false_positive` (matches Dead Code). Open rows are deleted and rewritten on+full init and per changed file on `repowise update`; a triaged row is kept and+refreshed when its `public_id` is detected again, and `resolved` reopens.| Column | Notes ||---|---|diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex 0e24b2d54..4be4fb16d 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -686,6 +686,22 @@ the category caps are the calibrated constants the published accuracy numbersrest on, and they are deliberately not overridable — so a team's local policy cannever silently change what those numbers mean.+## Finding identity and triage++Every finding carries a stable public id (`finding_<digest>`). Inside a known+function or class it is anchored on that symbol's name plus the finding's line+offset into it, so an edit above the symbol does not change the id; a+file-level finding keeps its absolute lines. Metric values (a CCN, a churn+figure, a coverage percentage) are not part of the id, so a finding keeps its+id while its numbers move; only the few detail keys a marker needs to tell two+of its findings apart (a coupling partner, an error kind) are.++Triage survives re-indexing. Each index replaces the open findings, and a+re-detected finding whose id matches a triaged row updates that row's evidence+(lines, severity, reason, details, impact) in place: `acknowledged` and+`false_positive` stay as they are, and `resolved` reopens, because the finding+marked fixed was detected again.+## Incremental updates`repowise update` re-scores only changed files. Findings and metrics fordiff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex b69360d30..a1ff895f2 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -50,6 +50,7 @@ from .coverage import is_test_file as _coverage_is_test_filefrom .dataflow import FileDataflowCachefrom .duplication import ClonePair, DuplicationReportfrom .duplication.isolation import detect_clones_with_isolation as detect_clones+from .finding_identity import SYMBOL_INDEX_KEY, SYMBOL_KEY, SYMBOL_LINE_KEYfrom .history_refresh import BLAME_MARKERS, as_biomarker_resultfrom .models import HealthFileMetricData, HealthFindingData, HealthReport, Severityfrom .perf import (@@ -124,6 +125,10 @@ log = structlog.get_logger(__name__)# ``code_origin``. Complexity findings copy ``dispatch_share`` into their# details and findings on a deprecated function gain ``deprecated: true``. No# CCN, threshold, weight or score moves.+# v37 (also): a finding inside a function or class records that symbol's first+# line (``details["symbol_line"]``) and its public id is anchored on the symbol+# plus the offset into it, hashing no metric values, so every stored finding id+# moves once.## v36 (also): which files are tests changed (``repowise.core.test_paths``).# Compound directories headed by a test word (``e2e-tests/``, ``pkg_tests/``,@@ -397,6 +402,43 @@ def walked_functions(return tuple(sorted(fc_list, key=lambda fc: (fc.start_line, fc.end_line)))++def _stamp_symbol_lines(findings: list[HealthFindingData], fcx: FileComplexity) -> None:+ """Record the symbol each finding sits in, so its id can be anchored there.++ The finding id is the symbol plus the offset into it, so an edit above the+ symbol leaves the id alone. The anchor is the innermost function or class+ holding the finding's line and sharing its name; a finding the detector+ left unnamed takes the innermost one of any name, recorded under+ ``symbol``. ``symbol_index`` tells same-named symbols in one file apart (two+ ``run`` methods, sibling ``it`` callbacks). A finding outside every symbol+ keeps absolute lines, and a replayed stored finding keeps its anchor.+ """+ spans = sorted(+ [(fc.start_line, fc.end_line, fc.name) for fc in fcx.functions]+ + [(c.start_line, c.end_line, c.name) for c in fcx.classes]+ )+ for f in findings:+ if f.line_start is None or SYMBOL_LINE_KEY in f.details:+ continue+ holding = [+ span+ for span in spans+ if span[0] <= f.line_start <= span[1]+ and (not f.function_name or span[2] == f.function_name)+ ]+ if not holding:+ continue+ start, _, name = max(holding, key=lambda span: (span[0], -span[1]))+ stamp: dict = {SYMBOL_LINE_KEY: start}+ if not f.function_name:+ stamp[SYMBOL_KEY] = name+ index = sum(1 for span in spans if span[2] == name and span[0] < start)+ if index:+ stamp[SYMBOL_INDEX_KEY] = index+ f.details = {**f.details, **stamp}++# Method-level smells that make the dataflow / Extract Method pass worthwhile.# Only files carrying one of these get a CFG + def/use + reaching pass built._EXTRACT_METHOD_SOURCES = frozenset({"large_method", "brain_method", "complex_method"})@@ -1485,6 +1527,7 @@ class HealthAnalyzer:for f in findings:f.file_path = file_path_mark_deprecated(findings, fc_list)+ _stamp_symbol_lines(findings, fcx)# The overall surfaced score stays == the defect dimension (no blend# yet); the per-dimension scores ride alongside it, additively.diff --git a/packages/core/src/repowise/core/analysis/health/finding_identity.py b/packages/core/src/repowise/core/analysis/health/finding_identity.pyindex a70f91faa..eb24e660f 100644--- a/packages/core/src/repowise/core/analysis/health/finding_identity.py+++ b/packages/core/src/repowise/core/analysis/health/finding_identity.py@@ -5,12 +5,19 @@ UUID every time and cannot be quoted back. This kernel names the finding bywhat it *is* instead, which makes the id stable across runs, storable as acolumn, and safe to hand to an agent.-The kernel holds structural coordinates and detector evidence. It deliberately-excludes prose and derived values: ``reason`` is generated text that a wording-change would churn, and a few ``details`` keys are outputs of later passes or-annotations of the enclosing function, not evidence for the finding, so-leaving them in would make the id of a finding move whenever an unrelated-model changed its mind.+The kernel holds structural coordinates only: dimension, path, marker, the+symbol the finding sits in and where inside it. Detector ``details`` are+evidence (a CCN, a correlation, a coverage percentage) that moves with every+edit, so only the few keys a marker needs to tell two of its own findings on+one symbol apart are hashed (:data:`IDENTITY_DETAIL_KEYS`). Prose is excluded+for the same reason.++A finding inside a known symbol is located by the symbol's name, its ordinal+among same-named symbols in the file, and its line offset within that symbol+(the engine stamps ``symbol_line`` and, when needed, ``symbol`` and+``symbol_index`` into ``details``), so an edit above the symbol does not move+the id. A finding with no symbol, or one stored before that anchor existed,+keeps absolute lines."""from __future__ import annotations@@ -23,7 +30,7 @@ from repowise.core.references import path_identityfrom .rows import detail_map, field-FINDING_ID_VERSION = 1+FINDING_ID_VERSION = 2"""Version of the identity kernel below.It is hashed rather than spelled into the id, because the public reference@@ -34,40 +41,111 @@ value, and an id minted by an older kernel stops matching._PREFIX = "finding"+SYMBOL_LINE_KEY = "symbol_line"+"""Detail key holding the first line of the symbol a finding sits in."""++SYMBOL_KEY = "symbol"+"""Detail key naming the enclosing symbol of a finding the detector left unnamed."""++SYMBOL_INDEX_KEY = "symbol_index"+"""Detail key holding the ordinal among same-named symbols in the file, when not 0."""++_STAMP_KEYS = frozenset({SYMBOL_LINE_KEY, SYMBOL_KEY, SYMBOL_INDEX_KEY})++IDENTITY_DETAIL_KEYS: dict[str, tuple[str, ...]] = {+ # A loop can reach two helpers from one call line; the first hop names each.+ "io_in_loop": ("cross_function", "path"),+ "blocking_io_under_lock": ("cross_function", "path"),+ "lazy_load_in_loop": ("relationship",),+ "error_handling": ("kind",),+ "complex_conditional": ("enclosing_construct",),+ "duplicated_assertion_block": ("assertion_lines",),+ "sql_cartesian_join": ("table",),+ "hidden_coupling": ("partner",),+ "contradictory_decision": ("src_decision_id", "dst_decision_id"),+}+"""Per marker, the detail keys that separate two findings of it on one symbol.++Every other marker emits at most one finding per symbol and line, so it hashes+no details at all. ``path`` is reduced to its first hop and line-valued keys+are made relative to the symbol, so neither moves with an unrelated edit.+"""+_DERIVED_DETAIL_KEYS = frozenset({"opportunity_id", "reliable_entry_reachability", "dispatch_share", "deprecated"})-"""Detail keys written by later passes, not by the detector that found the row.--``opportunity_id`` is stamped by causal grouping, so leaving it in would make-every finding id churn whenever the performance model version moved.-``reliable_entry_reachability`` is a repository-wide graph answer that flips-when unrelated code changes. ``dispatch_share`` and ``deprecated`` describe the-function a finding sits in, not the finding, and joined after ids were already-stored: counting them would have renamed every complexity finding at once.-"""+"""Keys version 1 left out of its hash; only :func:`legacy_finding_public_id` reads it."""+++def _digest(kernel: dict[str, Any]) -> str:+ payload = json.dumps(kernel, sort_keys=True, separators=(",", ":"), default=str)+ return f"{_PREFIX}_{hashlib.sha256(payload.encode('utf-8')).hexdigest()[:20]}"+++def _identity_details(kind: str, details: dict[str, Any], anchor: int | None) -> dict[str, Any]:+ out: dict[str, Any] = {}+ for key in IDENTITY_DETAIL_KEYS.get(kind, ()):+ value = details.get(key)+ if key == "path" and isinstance(value, list):+ value = value[1] if len(value) > 1 else None+ elif key == "assertion_lines" and anchor is not None and isinstance(value, list):+ value = [line - anchor for line in value if isinstance(line, int)]+ out[key] = value+ return outdef finding_public_id(row: Any) -> str:"""The stable public id for one finding row."""+ details = detail_map(row)+ kind = field(row, "biomarker_type", "") or ""+ symbol = field(row, "function_name", None) or details.get(SYMBOL_KEY) or ""+ line_start = field(row, "line_start", None)+ anchor = details.get(SYMBOL_LINE_KEY)+ if not (symbol and isinstance(anchor, int) and isinstance(line_start, int)):+ anchor = None+ if anchor is not None:+ location: dict[str, Any] = {+ "symbol_index": details.get(SYMBOL_INDEX_KEY, 0),+ "line_offset": line_start - anchor,+ }+ else:+ location = {"line_start": line_start, "line_end": field(row, "line_end", None)}+ return _digest(+ {+ "kernel_version": FINDING_ID_VERSION,+ "dimension": field(row, "dimension", None) or "defect",+ "path": path_identity(field(row, "file_path", "") or ""),+ "kind": kind,+ "symbol": symbol,+ **location,+ "details": _identity_details(kind, details, anchor),+ }+ )+++def legacy_finding_public_id(row: Any) -> str:+ """The id kernel version 1 minted for *row* (absolute lines, all details).++ Only the triage carry-over reads it, to match a row triaged under version 1+ to its re-detection. Removable once stores written before version 2 are gone.+ """details = {key: valuefor key, value in detail_map(row).items()- if key not in _DERIVED_DETAIL_KEYS+ if key not in _DERIVED_DETAIL_KEYS and key not in _STAMP_KEYS}- kernel = {- "kernel_version": FINDING_ID_VERSION,- "dimension": field(row, "dimension", None) or "defect",- "path": path_identity(field(row, "file_path", "") or ""),- "kind": field(row, "biomarker_type", "") or "",- "symbol": field(row, "function_name", None) or "",- "line_start": field(row, "line_start", None),- "line_end": field(row, "line_end", None),- "details": details,- }- payload = json.dumps(kernel, sort_keys=True, separators=(",", ":"), default=str)- digest = hashlib.sha256(payload.encode("utf-8")).hexdigest()[:20]- return f"{_PREFIX}_{digest}"+ return _digest(+ {+ "kernel_version": 1,+ "dimension": field(row, "dimension", None) or "defect",+ "path": path_identity(field(row, "file_path", "") or ""),+ "kind": field(row, "biomarker_type", "") or "",+ "symbol": field(row, "function_name", None) or "",+ "line_start": field(row, "line_start", None),+ "line_end": field(row, "line_end", None),+ "details": details,+ }+ )def is_finding_public_id(value: str) -> bool:@@ -76,4 +154,13 @@ def is_finding_public_id(value: str) -> bool:return bool(separator) and prefix == _PREFIX and len(digest) == 20-__all__ = ["FINDING_ID_VERSION", "finding_public_id", "is_finding_public_id"]+__all__ = [+ "FINDING_ID_VERSION",+ "IDENTITY_DETAIL_KEYS",+ "SYMBOL_INDEX_KEY",+ "SYMBOL_KEY",+ "SYMBOL_LINE_KEY",+ "finding_public_id",+ "is_finding_public_id",+ "legacy_finding_public_id",+]diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.pyindex 40be087c9..0f34c43f1 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py@@ -15,7 +15,10 @@ if TYPE_CHECKING:from ....analysis.health.perf.coverage import PerfCoveragefrom ....analysis.finding_registry import excluded_types-from ....analysis.health.finding_identity import finding_public_id+from ....analysis.health.finding_identity import (+ finding_public_id,+ legacy_finding_public_id,+)from ....analysis.health.governance import GOVERNANCE_BIOMARKERS# The comparator is pure and lives with the health read models; only the SQL@@ -84,6 +87,59 @@ def _health_finding_row_kwargs(finding: Any, repository_id: str) -> dict:}+_NOT_REFRESHED = frozenset({"id", "repository_id", "status", "created_at"})+++async def _insert_keeping_triage(+ session: AsyncSession,+ repository_id: str,+ findings: list[Any],+ scope: list[Any],+) -> None:+ """Insert *findings*, keeping the triage a person recorded on any of them.++ Callers delete the open rows in *scope* first. A finding whose public id+ matches a triaged row in *scope* is folded into that row: its detection+ fields are refreshed and ``acknowledged`` / ``false_positive`` stand, while+ ``resolved`` reopens because the finding said to be fixed is still there.+ Extra triaged rows sharing that id are deleted. Every other finding, a+ second one on an already claimed id included, is inserted open.+ """+ triaged: dict[str, list[HealthFinding]] = {}+ rows = await session.execute(+ select(HealthFinding)+ .where(*scope, HealthFinding.status != "open", HealthFinding.public_id.is_not(None))+ .order_by(HealthFinding.updated_at.desc())+ )+ for row in rows.scalars().all():+ triaged.setdefault(row.public_id, []).append(row)++ now = _now_utc()+ claimed: set[str] = set()+ for i in range(0, len(findings), _BATCH_SIZE):+ for f in findings[i : i + _BATCH_SIZE]:+ values = _health_finding_row_kwargs(f, repository_id)+ matches = triaged and (+ triaged.get(values["public_id"]) or triaged.get(legacy_finding_public_id(f))+ )+ kept, *extra = matches or [None]+ if kept is None or kept.id in claimed:+ # A second finding on a claimed id is inserted open: two+ # findings colliding on one id must not lose either.+ session.add(HealthFinding(**values))+ continue+ claimed.add(kept.id)+ for row in extra:+ await session.delete(row)+ for name, value in values.items():+ if name not in _NOT_REFRESHED:+ setattr(kept, name, value)+ if kept.status == "resolved":+ kept.status = "open"+ kept.updated_at = now+ await session.flush()++async def save_health_findings(session: AsyncSession,repository_id: str,@@ -91,23 +147,19 @@ async def save_health_findings() -> None:"""Replace open health findings for *repository_id* with *findings*.- Mirrors ``save_dead_code_findings`` — delete-then-insert. Accepts- either ``HealthFindingData`` dataclasses or plain dicts.+ Delete-then-insert over the open rows; triaged rows carry over by public id+ (``_insert_keeping_triage``). Accepts either ``HealthFindingData``+ dataclasses or plain dicts."""+ scope = [HealthFinding.repository_id == repository_id]existing = await session.execute(- select(HealthFinding).where(- HealthFinding.repository_id == repository_id,- HealthFinding.status == "open",- )+ select(HealthFinding).where(*scope, HealthFinding.status == "open"))for row in existing.scalars().all():await session.delete(row)+ await session.flush()- for i in range(0, len(findings), _BATCH_SIZE):- batch = findings[i : i + _BATCH_SIZE]- for f in batch:- session.add(HealthFinding(**_health_finding_row_kwargs(f, repository_id)))- await session.flush()+ await _insert_keeping_triage(session, repository_id, findings, scope)async def replace_governance_findings(@@ -117,10 +169,10 @@ async def replace_governance_findings() -> None:"""Idempotent additive write of governance-layer health findings.- Deletes any existing ``health_findings`` rows whose ``biomarker_type``+ Deletes the open ``health_findings`` rows whose ``biomarker_type``is one of ``ungoverned_hotspot``, ``stale_governance``, or``contradictory_decision`` for *repository_id*, then inserts the new- *findings* in batches.+ *findings* in batches, keeping triage by public id like the other writers.This function deliberately does **not** recompute ``HealthFileMetric.score``— that pass has already completed in the upstream health-analysis phase.@@ -137,25 +189,19 @@ async def replace_governance_findings(Accepts ``HealthFindingData`` dataclasses or plain dicts (same protocolas ``save_health_findings``)."""- # Delete existing governance findings for this repo only.+ # Delete existing open governance findings for this repo only.+ scope = [+ HealthFinding.repository_id == repository_id,+ HealthFinding.biomarker_type.in_(list(GOVERNANCE_BIOMARKERS)),+ ]existing = await session.execute(- select(HealthFinding).where(- HealthFinding.repository_id == repository_id,- HealthFinding.biomarker_type.in_(list(GOVERNANCE_BIOMARKERS)),- )+ select(HealthFinding).where(*scope, HealthFinding.status == "open"))for row in existing.scalars().all():await session.delete(row)await session.flush()- if not findings:- return-- for i in range(0, len(findings), _BATCH_SIZE):- batch = findings[i : i + _BATCH_SIZE]- for f in batch:- session.add(HealthFinding(**_health_finding_row_kwargs(f, repository_id)))- await session.flush()+ await _insert_keeping_triage(session, repository_id, findings, scope)def _health_metric_row_data(metric: Any) -> dict:@@ -1041,12 +1087,13 @@ async def upsert_health_findings(returnpredicates = [HealthFinding.repository_id == repository_id,- HealthFinding.status == "open",HealthFinding.file_path.in_(file_paths),]if dimension is not None:predicates.append(HealthFinding.dimension == dimension)- existing = await session.execute(select(HealthFinding).where(*predicates))+ existing = await session.execute(+ select(HealthFinding).where(*predicates, HealthFinding.status == "open")+ )for row in existing.scalars().all():await session.delete(row)await session.flush()@@ -1067,11 +1114,7 @@ async def upsert_health_findings(== dimension)]- for i in range(0, len(scoped), _BATCH_SIZE):- batch = scoped[i : i + _BATCH_SIZE]- for f in batch:- session.add(HealthFinding(**_health_finding_row_kwargs(f, repository_id)))- await session.flush()+ await _insert_keeping_triage(session, repository_id, scoped, predicates)async def upsert_health_metrics(diff --git a/tests/fixtures/perf_corpus/golden_opportunities.json b/tests/fixtures/perf_corpus/golden_opportunities.jsonindex b24d53608..958b0e656 100644--- a/tests/fixtures/perf_corpus/golden_opportunities.json+++ b/tests/fixtures/perf_corpus/golden_opportunities.json@@ -15,7 +15,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/owners.py",- "finding_id": "finding_fda81ef13ef4cf19ba17",+ "finding_id": "finding_c7e0cff49d2e4944af6c","function_name": "load_owners","line_end": 22,"line_start": 20,@@ -94,7 +94,7 @@{"biomarker_type": "serial_await_in_loop","file_path": "src/app/fetch.py",- "finding_id": "finding_763ec1cb433e3ef63614",+ "finding_id": "finding_f8f8bae754849200b18a","function_name": "fetch_each","line_end": 42,"line_start": 40,@@ -173,7 +173,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/entry.py",- "finding_id": "finding_a201efe1e1c9df9c6097",+ "finding_id": "finding_d1b7702a840faaee6230","function_name": "a","line_end": 252,"line_start": 250,@@ -188,7 +188,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/entry.py",- "finding_id": "finding_c7cbdc90f0dffc630671",+ "finding_id": "finding_66292afa8823b8db693a","function_name": "b","line_end": 257,"line_start": 255,@@ -276,7 +276,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/api.py",- "finding_id": "finding_7a93e35224cdbe6464f5",+ "finding_id": "finding_165492e638f0ce198bad","function_name": "list_users","line_end": 32,"line_start": 30,@@ -291,7 +291,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/api.py",- "finding_id": "finding_b502c8ca8878ade8c752",+ "finding_id": "finding_7a74222fa7b3681d4b81","function_name": "list_orders","line_end": 33,"line_start": 31,@@ -380,7 +380,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/reindex.py",- "finding_id": "finding_edae08cde216b8678b58",+ "finding_id": "finding_dd1107d677ac5244c707","function_name": "one","line_end": 212,"line_start": 210,@@ -395,7 +395,7 @@{"biomarker_type": "nested_loop_with_io","file_path": "src/app/reindex.py",- "finding_id": "finding_37906110543334a495f1",+ "finding_id": "finding_e7a60ff74d2f2b7ca67b","function_name": "many","line_end": 217,"line_start": 215,@@ -483,7 +483,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/sync.py",- "finding_id": "finding_030499578345115bf627",+ "finding_id": "finding_3181306320c607f836ff","function_name": "sync_one","line_end": 72,"line_start": 70,@@ -498,7 +498,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/sync.py",- "finding_id": "finding_ff3e61eed3f93515485b",+ "finding_id": "finding_77b2373b82e9257f6ee4","function_name": "sync_all","line_end": 73,"line_start": 71,@@ -586,7 +586,7 @@{"biomarker_type": "blocking_io_under_lock","file_path": "src/app/cache.py",- "finding_id": "finding_1e5678e8e33fd6960a6b",+ "finding_id": "finding_8ea43b76f67150954aef","function_name": "refresh","line_end": 112,"line_start": 110,@@ -672,7 +672,7 @@{"biomarker_type": "serial_await_in_loop","file_path": "src/app/fanout.py",- "finding_id": "finding_28eb6a8735fdf18585c6",+ "finding_id": "finding_2fd4157a8e2822d774f3","function_name": "gather_all","line_end": 92,"line_start": 90,@@ -752,7 +752,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/billing.py",- "finding_id": "finding_6379ce5a318505017239",+ "finding_id": "finding_afbcfc0c666017b74c22","function_name": "handle","line_end": 13,"line_start": 11,@@ -839,7 +839,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/orders.py",- "finding_id": "finding_cad43bf01be5d5f78ee3",+ "finding_id": "finding_8277702ee7a1de73ddf9","function_name": "handle","line_end": 12,"line_start": 10,@@ -926,7 +926,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/reports.py",- "finding_id": "finding_aac082c5466872ab8b9b",+ "finding_id": "finding_8e1d9d853534ecd57392","function_name": "handle","line_end": 14,"line_start": 12,@@ -1013,7 +1013,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/job.py",- "finding_id": "finding_4bc7b73af1f456af57b6",+ "finding_id": "finding_a4ca438d1238f8956526","function_name": "run","line_end": 202,"line_start": 200,@@ -1100,7 +1100,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/commits.py",- "finding_id": "finding_cdc3430a0de872c130b3",+ "finding_id": "finding_67809361ebc8f5a864d8","function_name": "first_commit_each","line_end": 32,"line_start": 30,@@ -1181,7 +1181,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/lone.py",- "finding_id": "finding_85307ceeab392a03daf6",+ "finding_id": "finding_9cfd6311dc82a0049c6a","function_name": "run","line_end": 11,"line_start": 9,@@ -1266,7 +1266,7 @@{"biomarker_type": "io_in_loop","file_path": "scripts/backfill.py",- "finding_id": "finding_9317f3939e8ba7a1dd00",+ "finding_id": "finding_d8a564a824ecf8f12ecb","function_name": "run","line_end": 202,"line_start": 200,@@ -1353,7 +1353,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/edge.py",- "finding_id": "finding_14ea9dfdb77b0df39e75",+ "finding_id": "finding_323137fff890d9e629dc","function_name": "run","line_end": 232,"line_start": 230,@@ -1440,7 +1440,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/retry.py",- "finding_id": "finding_1bdd58a5f59d1771055a",+ "finding_id": "finding_0e8c0794491c7384f4c4","function_name": "post_with_retry","line_end": 52,"line_start": 50,@@ -1521,7 +1521,7 @@{"biomarker_type": "io_in_loop","file_path": "tests/test_job.py",- "finding_id": "finding_059a3a02cba6c95befa3",+ "finding_id": "finding_e34ca4ba22d5f482348d","function_name": "run","line_end": 202,"line_start": 200,@@ -1608,7 +1608,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/guess.py",- "finding_id": "finding_2c964005af179686b46e",+ "finding_id": "finding_e287cbc148e5a8ea8ca8","function_name": "run","line_end": 242,"line_start": 240,@@ -1696,7 +1696,7 @@{"biomarker_type": "membership_test_against_list_in_loop","file_path": "src/app/filters.py",- "finding_id": "finding_ffe2b0bc5340930cea74",+ "finding_id": "finding_9fa77c322fa3d741a8c4","function_name": "select","line_end": 152,"line_start": 150,@@ -1777,7 +1777,7 @@{"biomarker_type": "string_concat_in_loop","file_path": "src/app/render.py",- "finding_id": "finding_05e1666dc8637c4749e3",+ "finding_id": "finding_ffee3cf5c3bbf22b87ba","function_name": "to_csv","line_end": 162,"line_start": 160,@@ -1857,7 +1857,7 @@{"biomarker_type": "blocking_io_under_lock","file_path": "src/app/pool.py",- "finding_id": "finding_0f4d6ed4b8e62ab7acec",+ "finding_id": "finding_2cca2a2e17c82f868f98","function_name": "reaper","line_end": 132,"line_start": 130,@@ -1872,7 +1872,7 @@{"biomarker_type": "blocking_io_under_lock","file_path": "src/app/pool.py",- "finding_id": "finding_0a1cbec352aadd5800a1",+ "finding_id": "finding_401246625d2b912b7c5c","function_name": "writer","line_end": 132,"line_start": 130,@@ -1955,7 +1955,7 @@{"biomarker_type": "resource_construction_in_loop","file_path": "src/app/clients.py",- "finding_id": "finding_36449d699224e623c1f6",+ "finding_id": "finding_b3099686f4d36c75f964","function_name": "each_varying","line_end": 182,"line_start": 180,@@ -2031,7 +2031,7 @@{"biomarker_type": "resource_construction_in_loop","file_path": "src/app/clients.py",- "finding_id": "finding_17256c41ed2a1893e6ce",+ "finding_id": "finding_840a26ef5269b670f5a2","function_name": "each","line_end": 172,"line_start": 170,@@ -2107,7 +2107,7 @@{"biomarker_type": "serial_await_in_loop","file_path": "src/app/fanout.py",- "finding_id": "finding_c1f4482918ae3823bedb",+ "finding_id": "finding_6f5702e6e6af64656121","function_name": "gather_seq","line_end": 97,"line_start": 95,@@ -2183,7 +2183,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/formatter.py",- "finding_id": "finding_b853807b08e242e784f5",+ "finding_id": "finding_74b3cc4ea0afc2828ead","function_name": "run","line_end": 24,"line_start": 22,@@ -2198,7 +2198,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/lexer.py",- "finding_id": "finding_7e425174e879fb9f9d23",+ "finding_id": "finding_f1d7e9138afa40a0f1b7","function_name": "run","line_end": 22,"line_start": 20,@@ -2213,7 +2213,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/linter.py",- "finding_id": "finding_34d631c0ff0bed50aafd",+ "finding_id": "finding_04801d753f6bc1eb8675","function_name": "run","line_end": 23,"line_start": 21,@@ -2228,7 +2228,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/resolver.py",- "finding_id": "finding_ef6b980a3a371a707424",+ "finding_id": "finding_1bb5c282969f6d4c8f99","function_name": "run","line_end": 25,"line_start": 23,@@ -2309,7 +2309,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/walker.py",- "finding_id": "finding_2bf692d084c65fdb5995",+ "finding_id": "finding_a609e571a99e409b1aab","function_name": "scan","line_end": 52,"line_start": 50,@@ -2389,7 +2389,7 @@{"biomarker_type": "io_in_loop","file_path": "src/app/walker.py",- "finding_id": "finding_aa5de561c0b650b976ac",+ "finding_id": "finding_57d0612e4678a6b34b8d","function_name": "index","line_end": 53,"line_start": 51,@@ -2469,7 +2469,7 @@{"biomarker_type": "io_in_loop","file_path": "docs/snippets/walk.py",- "finding_id": "finding_8e360766909208ee01a2",+ "finding_id": "finding_d0b10a5d5eeb35e40893","function_name": "demo","line_end": 10,"line_start": 8,@@ -2543,7 +2543,7 @@{"biomarker_type": "io_in_loop","file_path": "bootstrap.py",- "finding_id": "finding_23610573a960e1c72ac3",+ "finding_id": "finding_a88c49a6ad4cfd7bc111","function_name": "main","line_end": 16,"line_start": 14,diff --git a/tests/unit/health/test_finding_identity.py b/tests/unit/health/test_finding_identity.pynew file mode 100644index 000000000..df2d5d94d--- /dev/null+++ b/tests/unit/health/test_finding_identity.py@@ -0,0 +1,217 @@+"""A finding id survives edits that do not change what the finding is.++It holds still when lines are inserted above the symbol and when a metric in+the evidence moves, and it still tells apart two findings that differ in+substance: other symbols, same-named symbols, and every marker that can emit+several findings on one symbol.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from repowise.core.analysis.health.complexity import walk_file+from repowise.core.analysis.health.duplication import DuplicationReport+from repowise.core.analysis.health.engine import HealthAnalyzer+from repowise.core.analysis.health.finding_identity import (+ IDENTITY_DETAIL_KEYS,+ SYMBOL_INDEX_KEY,+ SYMBOL_KEY,+ SYMBOL_LINE_KEY,+ finding_public_id,+ legacy_finding_public_id,+)++_SOURCE = (+ "def load_users(cur, ids):\n"+ " for i in ids:\n"+ " cur.execute('SELECT * FROM users WHERE id = %s', (i,))\n"+ "\n"+ "\n"+ "def load_orders(cur, ids):\n"+ " for i in ids:\n"+ " cur.execute('SELECT * FROM orders WHERE id = %s', (i,))\n"+ " try:\n"+ " pass\n"+ " except:\n"+ " pass\n"+ "\n"+ "\n"+ "class A:\n"+ " def run(self, cur, ids):\n"+ " for i in ids:\n"+ " cur.execute('SELECT * FROM a WHERE id = %s', (i,))\n"+ "\n"+ "\n"+ "class B:\n"+ " def run(self, cur, ids):\n"+ " for i in ids:\n"+ " cur.execute('SELECT * FROM b WHERE id = %s', (i,))\n"+)+++def _findings(source: str):+ data = source.encode("utf-8")+ fcx = walk_file("/tmp/repo.py", "python", data)+ if not fcx.functions:+ pytest.skip("python tree-sitter pack missing")+ pf = SimpleNamespace(+ file_info=SimpleNamespace(+ path="src/repo.py", language="python", abs_path="/tmp/repo.py", is_test=False+ ),+ symbols=[],+ )+ _, findings, _ = HealthAnalyzer(graph=None)._evaluate_file(+ pf, fcx, paired_tests=set(), package_roots=set(), disabled=[], dup_report=DuplicationReport()+ )+ return findings+++def _ids(source: str) -> dict[tuple[str, str, int], str]:+ ids = {}+ for f in _findings(source):+ if f.biomarker_type in ("io_in_loop", "error_handling"):+ symbol = f.function_name or f.details.get(SYMBOL_KEY)+ key = (f.biomarker_type, symbol, f.details.get(SYMBOL_INDEX_KEY, 0))+ ids[key] = finding_public_id(f)+ return ids+++def test_engine_findings_are_anchored_on_their_symbol() -> None:+ assert set(_ids(_SOURCE)) == {+ ("io_in_loop", "load_users", 0),+ ("io_in_loop", "load_orders", 0),+ ("io_in_loop", "run", 0),+ ("io_in_loop", "run", 1),+ ("error_handling", "load_orders", 0),+ }+++def test_lines_inserted_above_keep_every_finding_id() -> None:+ before = _ids(_SOURCE)+ after = _ids("import os\n\n\nCONFIG = os.environ\n\n" + _SOURCE)+ assert after == before+++def test_the_same_marker_in_another_symbol_has_another_id() -> None:+ io = [v for k, v in _ids(_SOURCE).items() if k[0] == "io_in_loop"]+ assert len(set(io)) == len(io) == 4+++def _row(**overrides):+ base = {+ "file_path": "src/a.py",+ "biomarker_type": "complex_method",+ "function_name": "f",+ "line_start": 10,+ "line_end": 30,+ "details": {"ccn": 12, SYMBOL_LINE_KEY: 10},+ "dimension": "defect",+ }+ base.update(overrides)+ return base+++def test_a_metric_change_keeps_the_id() -> None:+ changed = _row(line_end=31, details={"ccn": 13, "cognitive": 20, SYMBOL_LINE_KEY: 10})+ assert finding_public_id(changed) == finding_public_id(_row())+ file_level = _row(+ biomarker_type="churn_risk", function_name=None, line_start=None, line_end=None+ )+ assert finding_public_id(file_level) == finding_public_id(+ {**file_level, "details": {"relative_churn": 9.9}}+ )+++def test_an_offset_into_the_symbol_is_what_the_id_holds() -> None:+ shifted = _row(line_start=40, line_end=60, details={"ccn": 12, SYMBOL_LINE_KEY: 40})+ assert finding_public_id(shifted) == finding_public_id(_row())+ moved_inside = _row(line_start=41, details={"ccn": 12, SYMBOL_LINE_KEY: 40})+ assert finding_public_id(moved_inside) != finding_public_id(_row())+++def test_same_named_symbols_are_told_apart() -> None:+ second = _row(details={"ccn": 12, SYMBOL_LINE_KEY: 10, SYMBOL_INDEX_KEY: 1})+ assert finding_public_id(second) != finding_public_id(_row())+++def test_without_an_anchor_the_id_keeps_absolute_lines() -> None:+ bare = _row(details={})+ assert finding_public_id(bare) != finding_public_id(_row(details={}, line_start=11))+++# One pair per allowlisted marker: same symbol and line, different substance.+_DISTINCT = {+ "io_in_loop": (+ {"cross_function": True, "path": ["a.py::f", "a.py::g", "db.py::q"]},+ {"cross_function": True, "path": ["a.py::f", "a.py::h", "db.py::q"]},+ ),+ "blocking_io_under_lock": (+ {"cross_function": False},+ {"cross_function": True, "path": ["a.py::f", "a.py::g", "db.py::q"]},+ ),+ "lazy_load_in_loop": ({"relationship": "author"}, {"relationship": "tags"}),+ "error_handling": ({"kind": "bare_except"}, {"kind": "swallowed_catch"}),+ "complex_conditional": (+ {"enclosing_construct": "if"},+ {"enclosing_construct": "ternary"},+ ),+ "duplicated_assertion_block": (+ {"assertion_lines": [10, 14]},+ {"assertion_lines": [10, 18]},+ ),+ "sql_cartesian_join": ({"table": "a"}, {"table": "b"}),+ "hidden_coupling": ({"partner": "b.py"}, {"partner": "c.py"}),+ "contradictory_decision": (+ {"src_decision_id": "d1", "dst_decision_id": "d2"},+ {"src_decision_id": "d1", "dst_decision_id": "d3"},+ ),+}+++def test_every_allowlisted_marker_has_a_distinctness_case() -> None:+ assert set(_DISTINCT) == set(IDENTITY_DETAIL_KEYS)++[email protected]("kind", sorted(_DISTINCT))+def test_two_findings_of_one_marker_on_one_symbol_stay_distinct(kind: str) -> None:+ a, b = _DISTINCT[kind]+ anchor = {SYMBOL_LINE_KEY: 10}+ first = _row(biomarker_type=kind, details={**a, **anchor})+ second = _row(biomarker_type=kind, details={**b, **anchor})+ assert finding_public_id(first) != finding_public_id(second)+++ "kind", ["large_assertion_block", "complex_conditional", "string_concat_in_loop"]+)+def test_findings_at_different_lines_of_one_symbol_stay_distinct(kind: str) -> None:+ first = _row(biomarker_type=kind, line_start=12)+ second = _row(biomarker_type=kind, line_start=15)+ assert finding_public_id(first) != finding_public_id(second)+++def test_assertion_lines_are_relative_to_the_symbol() -> None:+ def block(shift: int):+ return _row(+ biomarker_type="duplicated_assertion_block",+ function_name=None,+ line_start=12 + shift,+ line_end=14 + shift,+ details={+ "assertion_lines": [12 + shift, 14 + shift],+ "partner_file": "tests/test_b.py",+ SYMBOL_LINE_KEY: 10 + shift,+ SYMBOL_KEY: "test_a",+ },+ )++ assert finding_public_id(block(0)) == finding_public_id(block(7))+++def test_the_legacy_id_ignores_the_stamps() -> None:+ bare = _row(details={"ccn": 12})+ assert legacy_finding_public_id(bare) == legacy_finding_public_id(_row())+ assert legacy_finding_public_id(bare) != finding_public_id(_row())diff --git a/tests/unit/persistence/test_health_finding_triage.py b/tests/unit/persistence/test_health_finding_triage.pynew file mode 100644index 000000000..55b3b602a--- /dev/null+++ b/tests/unit/persistence/test_health_finding_triage.py@@ -0,0 +1,218 @@+"""Triage on a health finding survives the next index, on every writer.++A re-detected finding folds into the triaged row that holds its public id:+``acknowledged`` and ``false_positive`` stand, ``resolved`` reopens, and an+open row is simply replaced. No public id ever names two rows.+"""++from __future__ import annotations++from collections import Counter++import pytest+from sqlalchemy import select++from repowise.core.analysis.health.finding_identity import legacy_finding_public_id+from repowise.core.analysis.health.models import HealthFindingData, Severity+from repowise.core.persistence.crud.analysis import (+ replace_governance_findings,+ save_health_findings,+ update_health_finding_status,+ upsert_health_findings,+)+from repowise.core.persistence.models import HealthFinding+from tests.unit.persistence.helpers import insert_repo+++def _finding(function: str, *, reason: str = "first", severity=Severity.MEDIUM, **kw):+ base = dict(+ biomarker_type="complex_method",+ severity=severity,+ file_path="a.py",+ function_name=function,+ line_start=10,+ line_end=20,+ details={"ccn": 12, "symbol_line": 10},+ health_impact=0.5,+ reason=reason,+ dimension="defect",+ )+ base.update(kw)+ return HealthFindingData(**base)+++async def _rows(session, repo_id) -> list[HealthFinding]:+ result = await session.execute(+ select(HealthFinding).where(HealthFinding.repository_id == repo_id)+ )+ return list(result.scalars().all())+++async def _write(session, repo_id, writer, findings):+ if writer == "save":+ await save_health_findings(session, repo_id, findings)+ else:+ await upsert_health_findings(session, repo_id, findings, file_paths=["a.py"])+ await session.commit()+++async def _triage(session, repo_id, status_by_function: dict[str, str]):+ for row in await _rows(session, repo_id):+ if row.function_name in status_by_function:+ await update_health_finding_status(session, row.id, status_by_function[row.function_name])+ await session.commit()++[email protected]("writer", ["save", "upsert"])+async def test_triage_carries_over_by_public_id(async_session, writer):+ repo = await insert_repo(async_session)+ names = ["acked", "wrong", "fixed", "plain"]+ await _write(async_session, repo.id, writer, [_finding(n) for n in names])+ await _triage(+ async_session,+ repo.id,+ {"acked": "acknowledged", "wrong": "false_positive", "fixed": "resolved"},+ )+ created = {r.function_name: r.created_at for r in await _rows(async_session, repo.id)}++ await _write(+ async_session,+ repo.id,+ writer,+ [+ # The same findings two lines lower (an edit above the function),+ # and one point more complex.+ _finding(+ n,+ reason="second",+ severity=Severity.HIGH,+ line_start=12,+ line_end=22,+ details={"ccn": 13, "symbol_line": 12},+ )+ for n in names+ ],+ )++ rows = await _rows(async_session, repo.id)+ assert Counter(r.public_id for r in rows).most_common(1)[0][1] == 1+ by_name = {r.function_name: r for r in rows}+ assert len(rows) == len(names)+ assert by_name["acked"].status == "acknowledged"+ assert by_name["wrong"].status == "false_positive"+ assert by_name["fixed"].status == "open"+ assert by_name["plain"].status == "open"+ for name in ("acked", "wrong", "fixed"):+ row = by_name[name]+ assert row.created_at == created[name]+ assert (row.reason, row.severity, row.line_start) == ("second", "high", 12)+++async def test_a_triaged_row_outside_the_upsert_scope_is_untouched(async_session):+ repo = await insert_repo(async_session)+ await save_health_findings(+ async_session, repo.id, [_finding("f"), _finding("f", file_path="b.py")]+ )+ await async_session.commit()+ for row in await _rows(async_session, repo.id):+ await update_health_finding_status(async_session, row.id, "acknowledged")+ await async_session.commit()++ await upsert_health_findings(async_session, repo.id, [_finding("f")], file_paths=["a.py"])+ await async_session.commit()++ rows = await _rows(async_session, repo.id)+ assert sorted((r.file_path, r.status) for r in rows) == [+ ("a.py", "acknowledged"),+ ("b.py", "acknowledged"),+ ]+++async def test_duplicate_triaged_rows_collapse_to_one(async_session):+ """A store the old writers left with an acked row and its acked twin."""+ repo = await insert_repo(async_session)+ await save_health_findings(async_session, repo.id, [_finding("f")])+ await async_session.commit()+ (row,) = await _rows(async_session, repo.id)+ async_session.add(+ HealthFinding(+ repository_id=repo.id,+ file_path=row.file_path,+ biomarker_type=row.biomarker_type,+ severity=row.severity,+ function_name=row.function_name,+ line_start=row.line_start,+ line_end=row.line_end,+ details_json=row.details_json,+ public_id=row.public_id,+ dimension=row.dimension,+ status="acknowledged",+ )+ )+ await update_health_finding_status(async_session, row.id, "acknowledged")+ await async_session.commit()++ await save_health_findings(async_session, repo.id, [_finding("f")])+ await async_session.commit()++ rows = await _rows(async_session, repo.id)+ assert [r.status for r in rows] == ["acknowledged"]+++async def test_a_row_triaged_under_the_old_kernel_still_matches(async_session):+ repo = await insert_repo(async_session)+ finding = _finding("f")+ await save_health_findings(async_session, repo.id, [finding])+ await async_session.commit()+ (row,) = await _rows(async_session, repo.id)+ current = row.public_id+ row.public_id = legacy_finding_public_id(finding)+ row.status = "false_positive"+ await async_session.commit()++ await save_health_findings(async_session, repo.id, [finding])+ await async_session.commit()++ rows = await _rows(async_session, repo.id)+ assert [(r.status, r.public_id) for r in rows] == [("false_positive", current)]+++async def test_governance_triage_survives_its_rewrite(async_session):+ repo = await insert_repo(async_session)+ finding = _finding(+ None,+ biomarker_type="ungoverned_hotspot",+ line_start=None,+ line_end=None,+ details={},+ health_impact=0.0,+ )+ await replace_governance_findings(async_session, repo.id, [finding])+ await async_session.commit()+ (row,) = await _rows(async_session, repo.id)+ await update_health_finding_status(async_session, row.id, "acknowledged")+ await async_session.commit()++ await replace_governance_findings(async_session, repo.id, [finding])+ await async_session.commit()++ rows = await _rows(async_session, repo.id)+ assert [(r.id, r.status) for r in rows] == [(row.id, "acknowledged")]++[email protected]("writer", ["save", "upsert"])+async def test_two_findings_colliding_on_a_triaged_id_are_both_kept(async_session, writer):+ repo = await insert_repo(async_session)+ await _write(async_session, repo.id, writer, [_finding("f")])+ await _triage(async_session, repo.id, {"f": "acknowledged"})++ await _write(async_session, repo.id, writer, [_finding("f"), _finding("f", reason="twin")])++ rows = await _rows(async_session, repo.id)+ assert sorted(r.status for r in rows) == ["acknowledged", "open"]