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): stop god_class judging one part of a split partial class or a stateless mixin as the whole class (#4759)

Raghav Chamadiya5acd088aa8a8
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
index ac8a19658..a220f9f08 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
@@ -90,6 +90,8 @@ class FileContext:
# Thin graph view exposing only ``has_edge``. ``None`` on test fixtures
# that never construct a graph.
graph_view: HasEdge | None = None
+ # Names of this file's ``partial`` types that have parts in other files.
+ split_partial_types: frozenset[str] = frozenset()
# Per-line blame index produced by the FULL git tier (see
# ``ingestion.git_indexer.function_blame``). ``None`` on ESSENTIAL
# tier until the FULL-tier backfill (``backfill_full_tier()``) runs;
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 b817daea6..a725db5b6 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
@@ -13,10 +13,16 @@ Requiring a brain method (not just size) keeps large-but-flat classes
(config tables, generated DTOs) from firing. Class-level metrics come from
the walker (``ClassComplexity``); the biomarker simply doesn't fire for
languages that don't expose class nodes.
+
+One part of a split class is not judged as the whole: a C# ``partial``
+class with hand-written parts in other files, or a Python ``*Mixin`` without
+``__init__``. A ``partial`` class alone in the repo (its other part is source
+generated) is the whole hand-written class and is still judged.
"""
from __future__ import annotations
+from ..complexity import ClassComplexity
from ..models import Severity
from .base import BiomarkerResult, FileContext
@@ -25,6 +31,11 @@ _BRAIN_NLOC = 70
_BRAIN_CCN = 9
+def _is_stateless_mixin(cls: ClassComplexity) -> bool:
+ """A ``*Mixin`` with no ``__init__``: a slice of its host class's behavior."""
+ return cls.name.endswith("Mixin") and all(m.name != "__init__" for m in cls.methods)
+
+
class GodClassDetector:
name = "god_class"
category = "structural_complexity"
@@ -35,6 +46,12 @@ class GodClassDetector:
def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
out: list[BiomarkerResult] = []
for cls in ctx.class_metrics:
+ # A split partial part or a stateless mixin already is the
+ # per-concern split this finding asks for.
+ if cls.name in ctx.split_partial_types or (
+ ctx.language == "python" and _is_stateless_mixin(cls)
+ ):
+ continue
if cls.total_nloc < self._NLOC_THRESHOLD:
continue
if cls.method_count < self._METHOD_THRESHOLD:
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 84767c7bf..f6bd9f4b2 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -69,7 +69,11 @@ from .refactoring import (
performance_fix_suggestions,
rank_suggestions,
)
-from .refactoring.graph_signals import build_file_scc_index, build_methods_by_file
+from .refactoring.graph_signals import (
+ build_file_scc_index,
+ build_methods_by_file,
+ build_split_partial_types,
+)
from .repo_tests import RepoTestIndex
from .repo_tests import _has_paired_test_file as _has_paired_test_file
from .repo_tests import _path_basenames as _path_basenames
@@ -706,6 +710,7 @@ class HealthAnalyzer:
active_contributors=_compute_repo_active_contributors(self.git_meta_map),
file_scc_index=build_file_scc_index(self.graph),
methods_by_file=build_methods_by_file(self.graph),
+ split_partial_types=build_split_partial_types(self.graph),
dataflow_cache=dataflow_cache,
function_tests=function_tests,
paired_test_files=paired_test_index(self.test_index.all_test_files()),
diff --git a/packages/core/src/repowise/core/analysis/health/file_evaluator.py b/packages/core/src/repowise/core/analysis/health/file_evaluator.py
index b3b353c1a..7509c2e98 100644
--- a/packages/core/src/repowise/core/analysis/health/file_evaluator.py
+++ b/packages/core/src/repowise/core/analysis/health/file_evaluator.py
@@ -224,6 +224,7 @@ class FileEvaluator:
active_contributors: int | None = None
file_scc_index: dict[str, tuple[str, ...]] | None = None
methods_by_file: dict[str, tuple[str, ...]] | None = None
+ split_partial_types: dict[str, frozenset[str]] | None = None
dataflow_cache: FileDataflowCache | None = None
function_tests: FunctionTests | None = None
#: Test files by file name (``coverage_actions.paired_test_index``).
@@ -303,6 +304,7 @@ class FileEvaluator:
duplication_pct=dup_pct,
clone_sources=clone_sources,
graph_view=self.graph_view,
+ split_partial_types=(self.split_partial_types or {}).get(file_path, frozenset()),
blame_index=blame_idx_obj if isinstance(blame_idx_obj, BlameIndex) else None,
repo_function_mod_p80=self.function_mod_p80,
repo_active_contributors_90d=self.active_contributors,
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py b/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py
index 16b38353f..15acb0546 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py
@@ -113,6 +113,23 @@ def cycle_edges(graph: Any, members: tuple[str, ...]) -> list[tuple[str, str]]:
return sorted(set(edges))
+def build_split_partial_types(graph: Any) -> dict[str, frozenset[str]]:
+ """Each file's ``partial`` type names that have parts in other files.
+
+ Read from the ``partial_class`` edges that link a partial type's files.
+ Both ends count: the linker skips a direction that already had an edge.
+ """
+ if graph is None:
+ return {}
+ out: dict[str, set[str]] = {}
+ for u, v, data in graph.edges(data=True):
+ if data.get("hint_source") == "partial_class":
+ names = data.get("imported_names") or ()
+ out.setdefault(u, set()).update(names)
+ out.setdefault(v, set()).update(names)
+ return {path: frozenset(names) for path, names in out.items()}
+
+
def build_methods_by_file(graph: Any) -> dict[str, tuple[str, ...]]:
"""Methods defined in each file, precomputed in one graph sweep.
diff --git a/tests/unit/health/test_class_biomarkers.py b/tests/unit/health/test_class_biomarkers.py
index bf8cdf591..8cac61a60 100644
--- a/tests/unit/health/test_class_biomarkers.py
+++ b/tests/unit/health/test_class_biomarkers.py
@@ -229,6 +229,53 @@ def test_god_class_requires_size_and_method_count():
assert GodClassDetector().detect(_ctx([cls])) == []
+def _god(name: str, *, init: bool = False) -> ClassComplexity:
+ methods = _brainy_methods() + ([_fn("__init__")] if init else [])
+ return _cls(name, method_count=len(methods), total_nloc=320, methods=methods)
+
+
+def test_god_class_skips_stateless_python_mixin():
+ assert GodClassDetector().detect(_ctx([_god("ResolveMixin")])) == []
+
+
[email protected](("name", "init"), [("StatefulMixin", True), ("Resolver", False)])
+def test_god_class_still_flags_stateful_mixin_and_plain_class(name: str, init: bool):
+ assert len(GodClassDetector().detect(_ctx([_god(name, init=init)]))) == 1
+
+
+def test_god_class_mixin_rule_is_python_only():
+ ctx = _ctx([_god("ResolveMixin")])
+ ctx.language = "typescript"
+ assert len(GodClassDetector().detect(ctx)) == 1
+
+
+def test_god_class_skips_partial_type_split_across_files():
+ # ``Encoder`` stands for a partial whose only other part is source
+ # generated: no co-fragment edge, so the file holds the whole class.
+ ctx = _ctx([_god("StdAdoDelegate"), _god("Encoder")])
+ ctx.split_partial_types = frozenset({"StdAdoDelegate"})
+ assert [r.function_name for r in GodClassDetector().detect(ctx)] == ["Encoder"]
+
+
+def test_split_partial_types_reads_partial_class_edges():
+ import networkx as nx
+
+ from repowise.core.analysis.health.refactoring.graph_signals import (
+ build_split_partial_types,
+ )
+
+ g = nx.DiGraph()
+ # The reverse direction already had a plain import, so the linker added one edge.
+ g.add_edge("A.Jobs.cs", "A.cs", edge_type="imports", imported_names=["X"])
+ g.add_edge("A.cs", "A.Jobs.cs", edge_type="imports", imported_names=["A"], hint_source="partial_class")
+ g.add_edge("A.cs", "B.cs", edge_type="imports", imported_names=["B"])
+ assert build_split_partial_types(g) == {
+ "A.cs": frozenset({"A"}),
+ "A.Jobs.cs": frozenset({"A"}),
+ }
+ assert build_split_partial_types(None) == {}
+
+
def test_god_class_critical_severity():
cls = _cls("Behemoth", method_count=26, total_nloc=450, methods=_brainy_methods())
out = GodClassDetector().detect(_ctx([cls]))