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(health): correct god-class, SQL LIMIT, large-method, and coupling findings (#736)

Swati Ahujaa81a53c155c6
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/god_class.py b/packages/core/src/repowise/core/analysis/health/biomarkers/god_class.py
index ce140bb93..b817daea6 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/god_class.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/god_class.py
@@ -39,7 +39,19 @@ class GodClassDetector:
continue
if cls.method_count < self._METHOD_THRESHOLD:
continue
- if not any(m.nloc >= _BRAIN_NLOC and m.ccn >= _BRAIN_CCN for m in cls.methods):
+ # Find the actual brain method (the one that satisfies the gate)
+ # and quote *its* CCN — not the class-wide ``max_method_ccn``, which
+ # can belong to a short, high-CCN method that never passed the gate
+ # (that would point a reviewer at the wrong function).
+ brain_ccn, brain_name = max(
+ (
+ (m.ccn, m.name)
+ for m in cls.methods
+ if m.nloc >= _BRAIN_NLOC and m.ccn >= _BRAIN_CCN
+ ),
+ default=(0, None),
+ )
+ if brain_name is None:
continue
if cls.total_nloc >= 400 and cls.method_count >= 25:
@@ -61,11 +73,13 @@ class GodClassDetector:
"total_nloc": cls.total_nloc,
"method_count": cls.method_count,
"max_method_ccn": cls.max_method_ccn,
+ "brain_method_ccn": brain_ccn,
+ "brain_method_name": brain_name,
},
reason=(
f"{cls.name} is a god class: {cls.total_nloc} lines across "
f"{cls.method_count} methods, including a brain method "
- f"(max method CCN {cls.max_method_ccn})"
+ f"({brain_name}, CCN {brain_ccn})"
),
)
)
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py b/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py
index eb86fd420..63f4ec755 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py
@@ -34,6 +34,13 @@ _MIN_CORRELATION = 0.5
_HIGH_THRESHOLD = 0.65
_CRITICAL_THRESHOLD = 0.8
_MAX_FINDINGS_PER_FILE = 3
+# Absolute number of shared commits required before HIGH/CRITICAL severity is
+# allowed. A high correlation ratio over a handful of commits (e.g. 4 shared of
+# 5 = 80%) is very likely coincidental — small-sample correlations oversell
+# confidence, and a repo-wide scan compares thousands of pairs, so some clear
+# any ratio by chance. Until the raw co-change count clears this floor (well
+# above ``_MIN_COMMITS``), severity is capped at MEDIUM: a hint, not a verdict.
+_MIN_CO_CHANGE_FOR_HIGH = 8
# Same conventions used by engine._has_paired_test_file. Keeping them
# inline (rather than importing) avoids a circular dependency between
@@ -101,7 +108,11 @@ def _as_int(value: object, default: int = 0) -> int:
return default
-def _severity_for(correlation: float) -> Severity:
+def _severity_for(correlation: float, co_count: int) -> Severity:
+ # Confidence-weight by absolute sample size: below the co-change floor the
+ # ratio isn't trustworthy enough to assert HIGH/CRITICAL, so cap at MEDIUM.
+ if co_count < _MIN_CO_CHANGE_FOR_HIGH:
+ return Severity.MEDIUM
if correlation >= _CRITICAL_THRESHOLD:
return Severity.CRITICAL
if correlation >= _HIGH_THRESHOLD:
@@ -164,7 +175,7 @@ class HiddenCouplingDetector:
findings.append(
BiomarkerResult(
biomarker_type=self.name,
- severity=_severity_for(correlation),
+ severity=_severity_for(correlation, co_count),
function_name=None,
line_start=None,
line_end=None,
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/large_method.py b/packages/core/src/repowise/core/analysis/health/biomarkers/large_method.py
index 26dc60633..6f3e6d1ca 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/large_method.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/large_method.py
@@ -21,11 +21,17 @@ class LargeMethodDetector:
category = "size_and_complexity"
_NLOC_THRESHOLD = 60
- # Minimal branching required so a long-but-flat body (CCN 1, e.g. a big
- # config dict) doesn't read as a complexity smell. Anything with even a
- # single branch clears this floor. Keeps the trigger about substance,
- # not raw line count — directly targeting the size-confound critique.
- _CCN_FLOOR = 2
+ # Minimal branching required so a long-but-flat body doesn't read as a
+ # complexity smell. Set to 3 (not 2) so a flat ``match``/``case`` dispatch
+ # table — every arm a single-expression return, functionally a data literal
+ # — is excluded too: the walker gives it CCN 2 (base 1 + the lone ``match``
+ # keyword point, no per-arm counting), the exact "layout artefact" shape
+ # this floor exists to filter. Tradeoff: a long body whose *only* branch is
+ # a single ``if``/``for`` also lands at CCN 2 and is now skipped. That is an
+ # acceptable loss — a 60-line function with one branch is weak evidence of a
+ # maintainability problem, and distinguishing it from a flat match would need
+ # a per-function flat-match flag threaded from the walker (a larger change).
+ _CCN_FLOOR = 3
def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
out: list[BiomarkerResult] = []
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/gating.py b/packages/core/src/repowise/core/analysis/health/dataflow/gating.py
index 65c7a7cfb..705b0a422 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/gating.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/gating.py
@@ -33,9 +33,9 @@ log = structlog.get_logger(__name__)
# Pulled from the biomarker detectors so the gate stays in lockstep with the
# flags it mirrors. ``complex_method`` (ccn >= 9) already subsumes the
# ``brain_method`` ccn condition, so the predicate needs only these two shapes.
-_COMPLEX_CCN = ComplexMethodDetector._CCN_THRESHOLD # 9
-_LARGE_NLOC = LargeMethodDetector._NLOC_THRESHOLD # 60
-_LARGE_CCN_FLOOR = LargeMethodDetector._CCN_FLOOR # 2
+_COMPLEX_CCN = ComplexMethodDetector._CCN_THRESHOLD
+_LARGE_NLOC = LargeMethodDetector._NLOC_THRESHOLD
+_LARGE_CCN_FLOOR = LargeMethodDetector._CCN_FLOOR
def is_flagged(*, ccn: int, nloc: int) -> bool:
@@ -44,7 +44,7 @@ def is_flagged(*, ccn: int, nloc: int) -> bool:
The union of the size/complexity biomarker triggers:
- ``complex_method`` -- ``ccn >= 9`` (also covers ``brain_method``'s ccn).
- - ``large_method`` -- ``nloc >= 60`` with at least one branch (``ccn >= 2``).
+ - ``large_method`` -- ``nloc >= 60`` with real branching (``ccn >= 3``).
"""
if ccn >= _COMPLEX_CCN:
return True
diff --git a/packages/core/src/repowise/core/analysis/health/sql_complexity.py b/packages/core/src/repowise/core/analysis/health/sql_complexity.py
index c069ac4c0..3a17bafed 100644
--- a/packages/core/src/repowise/core/analysis/health/sql_complexity.py
+++ b/packages/core/src/repowise/core/analysis/health/sql_complexity.py
@@ -215,7 +215,14 @@ def _statement_smells(text: str, dialect: str | None) -> list[PerfHit]:
break # one finding per relation, not per nested select
# -- sql_update_delete_without_where: whole-table DML.
- elif isinstance(stmt, (exp.Update, exp.Delete)) and not stmt.args.get("where"):
+ # A LIMIT (``UPDATE ... LIMIT n`` / ``DELETE ... LIMIT n`` in MySQL and
+ # friends) bounds the affected row count, so the statement provably does
+ # NOT touch every row — treat it like a WHERE and stay silent.
+ elif (
+ isinstance(stmt, (exp.Update, exp.Delete))
+ and not stmt.args.get("where")
+ and not stmt.args.get("limit")
+ ):
table = _clean_ident(getattr(stmt.this, "name", "") or "")
if table:
hits.append(
diff --git a/tests/unit/health/test_dataflow_cfg.py b/tests/unit/health/test_dataflow_cfg.py
index 73f7d96ea..8623bc27d 100644
--- a/tests/unit/health/test_dataflow_cfg.py
+++ b/tests/unit/health/test_dataflow_cfg.py
@@ -334,8 +334,11 @@ def test_is_flagged_thresholds():
# complex_method: ccn >= 9 alone flags.
assert is_flagged(ccn=9, nloc=10)
assert not is_flagged(ccn=8, nloc=10)
- # large_method: nloc >= 60 with at least one branch (ccn >= 2).
- assert is_flagged(ccn=2, nloc=60)
+ # large_method: nloc >= 60 with real branching (ccn >= 3). CCN 2 no longer
+ # qualifies — that's the score a flat match/case dispatch table gets from its
+ # lone keyword point, a layout artefact rather than a complexity smell.
+ assert is_flagged(ccn=3, nloc=60)
+ assert not is_flagged(ccn=2, nloc=60) # flat-match dispatch, not substance
assert not is_flagged(ccn=1, nloc=200) # flat body, no branching
assert not is_flagged(ccn=8, nloc=59)
diff --git a/tests/unit/health/test_ff_track_iljk_structural.py b/tests/unit/health/test_ff_track_iljk_structural.py
new file mode 100644
index 000000000..7791fa19d
--- /dev/null
+++ b/tests/unit/health/test_ff_track_iljk_structural.py
@@ -0,0 +1,213 @@
+"""Regression tests for structural / SQL false-flag fixes.
+
+Each test drives the REAL project functions against a hand-built counterexample
+(no reimplementations): ``walk_file`` for the AST metrics that feed the class /
+method biomarkers, ``_statement_smells`` for the SQL DML smell, and
+``_severity_for`` for the coupling confidence cap.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from repowise.core.analysis.health.biomarkers import FileContext
+from repowise.core.analysis.health.biomarkers.god_class import GodClassDetector
+from repowise.core.analysis.health.biomarkers.hidden_coupling import (
+ HiddenCouplingDetector,
+ _severity_for,
+)
+from repowise.core.analysis.health.biomarkers.large_method import LargeMethodDetector
+from repowise.core.analysis.health.complexity.walker import walk_file
+from repowise.core.analysis.health.models import Severity
+from repowise.core.analysis.health.sql_complexity import _statement_smells
+
+# --------------------------------------------------------------------------
+# Fixture builders
+# --------------------------------------------------------------------------
+
+
+def _god_class_src() -> str:
+ """A class that fires god_class, with a genuine brain method (``brainy``,
+ high NLOC + moderate CCN) plus a short but very-high-CCN method
+ (``shorty``) that has the highest CCN in the class but is NOT the brain."""
+ lines = ["class Big:", " def brainy(self, x):", " y = 0"]
+ for i in range(9): # 9 branches -> ccn ~10
+ lines.append(f" if x == {i}:")
+ lines.append(f" y += {i}")
+ for i in range(140): # padding to push brainy (and the class) over the gates
+ lines.append(f" y = y + {i}")
+ lines.append(" return y")
+ lines.append("")
+ lines.append(" def shorty(self, z):") # nloc < 70, ccn ~31 (highest in class)
+ lines.append(" if z == 0: return 0")
+ for i in range(1, 30):
+ lines.append(f" elif z == {i}: return {i}")
+ lines.append(" else: return -1")
+ lines.append("")
+ for i in range(14): # filler methods -> method_count 16
+ lines.append(f" def m{i}(self): return {i}")
+ return "\n".join(lines) + "\n"
+
+
+def _flat_match_src() -> str:
+ """A flat ``match``/``case`` dispatch table: every arm a single-expression
+ return. Long enough to trip the NLOC threshold; CCN is 2 (base 1 + the lone
+ match keyword point) — a layout artefact, not a complexity smell."""
+ lines = ["def dispatch(status):", " match status:"]
+ for i in range(31):
+ lines.append(f" case {i}:")
+ lines.append(f' return "s{i}"')
+ lines.append(" case _:")
+ lines.append(' return "unknown"')
+ return "\n".join(lines) + "\n"
+
+
+def _branchy_src() -> str:
+ """A long method with real branching (several ``if`` statements) — a genuine
+ large_method that must still fire after the CCN floor bump."""
+ lines = ["def branchy(n):", " total = 0"]
+ for i in range(5):
+ lines.append(f" if n == {i}:")
+ lines.append(f" total += {i}")
+ for i in range(60):
+ lines.append(f" total = total + {i}")
+ lines.append(" return total")
+ return "\n".join(lines) + "\n"
+
+
+def _class_ctx(classes) -> FileContext:
+ return FileContext(
+ file_path="src/example.py",
+ language="python",
+ nloc=400,
+ has_test_file=False,
+ module=None,
+ class_metrics=classes,
+ )
+
+
+def _fn_ctx(functions) -> FileContext:
+ return FileContext(
+ file_path="src/example.py",
+ language="python",
+ nloc=200,
+ has_test_file=False,
+ module=None,
+ function_metrics={f.name: f for f in functions},
+ )
+
+
+# --------------------------------------------------------------------------
+# god_class: quote the brain method's own CCN, not the class-wide max
+# --------------------------------------------------------------------------
+
+
+def test_god_class_reason_quotes_the_brain_methods_own_ccn():
+ fc = walk_file("big.py", "python", _god_class_src().encode())
+ assert fc.classes, "expected a class to be parsed (tree-sitter python present)"
+ cls = fc.classes[0]
+
+ # Sanity-check the fixture reproduces the false-flag setup.
+ by_name = {m.name: m for m in cls.methods}
+ assert by_name["brainy"].nloc >= 70 and by_name["brainy"].ccn >= 9 # the brain
+ assert by_name["shorty"].nloc < 70 # NOT a brain method...
+ assert cls.max_method_ccn == by_name["shorty"].ccn # ...yet has the highest CCN
+ assert cls.max_method_ccn > by_name["brainy"].ccn
+
+ out = GodClassDetector().detect(_class_ctx([cls]))
+ assert len(out) == 1
+ result = out[0]
+
+ brain_ccn = by_name["brainy"].ccn
+ # The reason quotes the brain method's OWN CCN (~10), never shorty's (31).
+ assert result.details["brain_method_name"] == "brainy"
+ assert result.details["brain_method_ccn"] == brain_ccn
+ assert f"CCN {brain_ccn}" in result.reason
+ assert str(cls.max_method_ccn) not in result.reason.split("CCN ")[1]
+
+
+# --------------------------------------------------------------------------
+# sql_update_delete_without_where: a LIMIT bounds the row count
+# --------------------------------------------------------------------------
+
+
+def _smell_kinds(sql: str, dialect: str | None) -> list[str]:
+ return [h.kind for h in _statement_smells(sql, dialect)]
+
+
[email protected]("dialect", [None, "mysql"])
+def test_limit_bounded_update_is_not_flagged(dialect):
+ sql = "UPDATE logs SET archived = 1 ORDER BY created_at LIMIT 1000;\n"
+ assert "sql_update_delete_without_where" not in _smell_kinds(sql, dialect)
+
+
[email protected]("dialect", [None, "mysql"])
+def test_unbounded_update_still_flagged(dialect):
+ sql = "UPDATE logs SET archived = 1;\n"
+ assert _smell_kinds(sql, dialect) == ["sql_update_delete_without_where"]
+
+
+# --------------------------------------------------------------------------
+# large_method: a flat match dispatch is layout, not a size smell
+# --------------------------------------------------------------------------
+
+
+def test_large_method_skips_flat_match_dispatch():
+ fm = walk_file("m.py", "python", _flat_match_src().encode())
+ assert fm.functions, "expected a function to be parsed"
+ fn = fm.functions[0]
+ # The flat dispatch trips the NLOC threshold but sits at CCN 2 (layout).
+ assert fn.nloc >= LargeMethodDetector._NLOC_THRESHOLD
+ assert fn.ccn == 2
+ assert LargeMethodDetector().detect(_fn_ctx([fn])) == []
+
+
+def test_large_method_still_fires_on_real_branching():
+ fb = walk_file("b.py", "python", _branchy_src().encode())
+ fn = fb.functions[0]
+ assert fn.nloc >= LargeMethodDetector._NLOC_THRESHOLD
+ assert fn.ccn >= LargeMethodDetector._CCN_FLOOR
+ out = LargeMethodDetector().detect(_fn_ctx([fn]))
+ assert len(out) == 1
+ assert out[0].function_name == "branchy"
+
+
+# --------------------------------------------------------------------------
+# hidden_coupling: small-sample correlations are capped at MEDIUM
+# --------------------------------------------------------------------------
+
+
+def test_severity_capped_at_medium_for_few_shared_commits():
+ # 4 shared of 5 = 80% correlation would be CRITICAL on ratio alone, but the
+ # absolute count is far too small to trust that confidence.
+ assert _severity_for(0.8, co_count=4) == Severity.MEDIUM
+ assert _severity_for(0.7, co_count=3) == Severity.MEDIUM
+
+
+def test_severity_reaches_high_and_critical_with_enough_shared_commits():
+ assert _severity_for(0.8, co_count=16) == Severity.CRITICAL
+ assert _severity_for(0.65, co_count=12) == Severity.HIGH
+
+
+def test_detector_caps_small_sample_pair_at_medium():
+ ctx = FileContext(
+ file_path="src/payments.py",
+ language="python",
+ nloc=120,
+ has_test_file=False,
+ module=None,
+ function_metrics={},
+ git_meta={
+ "commit_count_total": 5,
+ "co_change_partners_json": json.dumps(
+ [{"file_path": "src/billing.py", "co_change_count": 4}]
+ ),
+ },
+ repo_commit_counts={"src/payments.py": 5, "src/billing.py": 5},
+ )
+ out = HiddenCouplingDetector().detect(ctx)
+ assert len(out) == 1
+ # 4 / min(5, 5) = 0.8 — CRITICAL on ratio alone, capped to MEDIUM here.
+ assert out[0].severity == Severity.MEDIUM
diff --git a/tests/unit/health/test_test_quality_biomarkers.py b/tests/unit/health/test_test_quality_biomarkers.py
index e7ff3b086..ef85c21d4 100644
--- a/tests/unit/health/test_test_quality_biomarkers.py
+++ b/tests/unit/health/test_test_quality_biomarkers.py
@@ -148,8 +148,11 @@ def test_large_method_skips_long_flat_body():
assert LargeMethodDetector().detect(_ctx(file_path="src/x.py", functions=[flat])) == []
-def test_large_method_fires_with_any_branching():
- branchy = _fn("process", nloc=150, ccn=2)
+def test_large_method_fires_with_real_branching():
+ # CCN 3 = genuine branching (two decision points). CCN 2 no longer fires:
+ # it's the score a flat ``match`` dispatch table gets from its lone keyword
+ # point, and that layout artefact should not read as a large-method smell.
+ branchy = _fn("process", nloc=150, ccn=3)
out = LargeMethodDetector().detect(_ctx(file_path="src/x.py", functions=[branchy]))
assert len(out) == 1
assert out[0].details["nloc"] == 150