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): give error-handling findings honest rationales (#733)
Swati Ahujab5852758aae9
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/error_handling.py b/packages/core/src/repowise/core/analysis/health/biomarkers/error_handling.pyindex 9505ed5da..25c3f9bfb 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/error_handling.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/error_handling.py@@ -26,8 +26,10 @@ from .base import BiomarkerResult, FileContext_REASONS: dict[str, str] = {"swallowed_catch": "caught exception is swallowed without any handling",- "bare_except": "catch-all except hides every error, including KeyboardInterrupt",- "unsafe_unwrap": "unwrap/expect/panic turns a recoverable error into a crash",+ "bare_except": "bare/BaseException catch also swallows KeyboardInterrupt and SystemExit",+ "broad_except": "broad `except Exception` catches unrelated errors and can hide bugs",+ "unsafe_unwrap": "unwrap/expect turns a recoverable error into a crash",+ "panic_macro": "panic!/unreachable!/todo!/unimplemented! aborts the process unconditionally","go_swallow": "error value is checked then ignored, or discarded via the blank identifier",}diff --git a/packages/core/src/repowise/core/analysis/health/complexity/error_handling.py b/packages/core/src/repowise/core/analysis/health/complexity/error_handling.pyindex 62d08d6a6..823ab10b9 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/error_handling.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/error_handling.py@@ -11,6 +11,7 @@ Go err-swallow it finds, anywhere in the file (not just function bodies).from __future__ import annotations+import refrom typing import TYPE_CHECKINGfrom .languages import LanguageNodeMap@@ -19,6 +20,10 @@ from .models import ErrorHandlingHitif TYPE_CHECKING:from tree_sitter import Node+# A bare ``test`` cfg predicate token: preceded by ``(`` / ``,`` / start and+# followed by ``)`` / ``,`` / end, so ``feature = "test"`` (a string) does not match.+_RUST_TEST_CFG_TOKEN = re.compile(r"(?:^|[(,])test(?:[),]|$)")+# Block-like body node types of a catch/except clause._EH_BLOCK_KINDS = frozenset({"block", "statement_block", "compound_statement"})# Statement node types that count as "no real handling" inside a catch body.@@ -67,17 +72,91 @@ def _eh_body_is_swallowed(block: Node, language: str) -> bool:return len(real) == 0-def _eh_is_bare_except(clause: Node) -> bool:- """Python ``except:`` / ``except Exception:`` / ``except BaseException:``."""+def _eh_except_catch_all_name(clause: Node) -> tuple[bool, str | None]:+ """``(is_catch_all, leading_type_name)`` for a Python ``except`` clause.++ ``is_catch_all`` is True for bare ``except:`` and for a single leading+ ``Exception`` / ``BaseException`` identifier (with or without an ``as``+ binding). ``leading_type_name`` is that identifier's text, or ``None`` for+ truly bare ``except:``. A tuple of specific types, or any specific type,+ yields ``(False, None)`` — not a catch-all.+ """kids = [c for c in clause.children if c.type != "comment"]after = [c for c in kids if c.type not in ("except", ":") and c.type not in _EH_BLOCK_KINDS]if not after:- return True # bare ``except:``- # ``except Exception:`` / ``except BaseException:`` (single catch-all- # identifier — a tuple of specific types or an ``as`` binding on a- # specific type does not match).+ return True, None # bare ``except:``+ # ``except Exception as e:`` wraps the type in an ``as_pattern`` — unwrap to+ # the leading type identifier so the binding does not hide a catch-all.first = after[0]- return first.type == "identifier" and _eh_text(first) in ("Exception", "BaseException")+ target = first+ if first.type == "as_pattern":+ named = [c for c in first.children if c.is_named]+ target = named[0] if named else first+ if target.type == "identifier" and _eh_text(target) in ("Exception", "BaseException"):+ return True, _eh_text(target)+ return False, None+++def _eh_is_bare_except(clause: Node) -> bool:+ """Python catch-all: ``except:`` / ``except Exception:`` / ``except BaseException:``."""+ return _eh_except_catch_all_name(clause)[0]+++def _eh_catches_base(clause: Node) -> bool:+ """True only when the catch-all also catches ``BaseException`` subclasses.++ Bare ``except:`` and ``except BaseException:`` catch ``KeyboardInterrupt`` /+ ``SystemExit`` (both derive from ``BaseException``); ``except Exception:``+ provably cannot, so it is *broad* rather than truly catch-all.+ """+ is_catch_all, name = _eh_except_catch_all_name(clause)+ return is_catch_all and name != "Exception"+++def _eh_rust_attr_is_test(attr_text: str) -> bool:+ """True when a Rust attribute marks test-only code.++ Recognizes test-runner attributes (``#[test]``, ``#[tokio::test]``,+ ``#[rstest]`` …) whose name path ends in ``test``, and ``cfg`` test gates+ (``#[cfg(test)]``, ``#[cfg(all(test, feature = "x"))]``). Deliberately does+ NOT match ``#[cfg(not(test))]`` — that gates non-test builds, where an+ ``.unwrap()`` is still a real smell.+ """+ t = attr_text.replace(" ", "")+ if t.startswith("#[") and t.endswith("]"):+ t = t[2:-1]+ name = t.split("(", 1)[0]+ if name == "cfg":+ args = t[len("cfg") :]+ if "not(test)" in args:+ return False+ return bool(_RUST_TEST_CFG_TOKEN.search(args))+ # ``test`` / ``tokio::test`` / ``async_std::test`` / ``rstest`` …+ return name.endswith("test")+++def _eh_rust_in_test(node: Node) -> bool:+ """True when *node* sits inside a Rust test item.++ ``.unwrap()`` / ``.expect()`` and the panic-family macros are the intended+ failure signal inside a test, not a smell. Walks the enclosing+ ``function_item`` / ``mod_item`` chain and checks each item's preceding+ ``attribute_item`` siblings for a test-runner or ``cfg(test)`` marker.+ """+ cur: Node | None = node.parent+ while cur is not None:+ if cur.type in ("function_item", "mod_item"):+ sib = cur.prev_sibling+ while sib is not None and sib.type in (+ "attribute_item",+ "line_comment",+ "block_comment",+ ):+ if sib.type == "attribute_item" and _eh_rust_attr_is_test(_eh_text(sib)):+ return True+ sib = sib.prev_sibling+ cur = cur.parent+ return Falsedef _eh_rust_hit(node: Node) -> bool:@@ -116,13 +195,19 @@ def _eh_go_hit(node: Node) -> bool:if left is None or right is None:return Falseleft_kids = _eh_named(left)- has_blank = any(c.type == "blank_identifier" or _eh_text(c) == "_" for c in left_kids)+ # Only the LAST LHS target is Go's conventional error slot. A leading or+ # middle ``_`` discards a value, not the error (``_, err := f()`` keeps+ # the error), so it is not an error-swallow.+ last_is_blank = bool(left_kids) and (+ left_kids[-1].type == "blank_identifier" or _eh_text(left_kids[-1]) == "_"+ )right_is_call = any(c.type == "call_expression" for c in _eh_named(right)) or (right.type == "expression_list"and any(c.type == "call_expression" for c in _eh_named(right)))- # Multi-return discard: ≥2 LHS targets, a call on the RHS, a blank present.- return has_blank and len(left_kids) >= 2 and right_is_call+ # Multi-return discard: ≥2 LHS targets, a call on the RHS, blank in the+ # trailing (error) slot.+ return last_is_blank and len(left_kids) >= 2 and right_is_callreturn False@@ -150,9 +235,17 @@ def _collect_error_handling(if block is not None and _eh_body_is_swallowed(block, language):hits.append(ErrorHandlingHit("swallowed_catch", node.start_point[0] + 1))if is_python and _eh_is_bare_except(node):- hits.append(ErrorHandlingHit("bare_except", node.start_point[0] + 1))+ # ``except:`` / ``except BaseException:`` also swallow+ # KeyboardInterrupt & SystemExit; ``except Exception:`` cannot.+ kind = "bare_except" if _eh_catches_base(node) else "broad_except"+ hits.append(ErrorHandlingHit(kind, node.start_point[0] + 1))elif is_rust and _eh_rust_hit(node):- hits.append(ErrorHandlingHit("unsafe_unwrap", node.start_point[0] + 1))+ # A panic-family macro aborts unconditionally; unwrap/expect converts+ # a Result/Option into a panic. Different claims → different kinds.+ # ``.unwrap()`` inside a ``#[test]`` is the intended failure signal.+ if not _eh_rust_in_test(node):+ kind = "panic_macro" if node.type == "macro_invocation" else "unsafe_unwrap"+ hits.append(ErrorHandlingHit(kind, node.start_point[0] + 1))elif is_go and _eh_go_hit(node):hits.append(ErrorHandlingHit("go_swallow", node.start_point[0] + 1))stack.extend(node.children)diff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.pyindex 574652f41..2ea2fb79f 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py@@ -125,12 +125,17 @@ class ErrorHandlingHit:- ``swallowed_catch`` — a catch/except whose body has no real handling(empty, or only ``pass`` / ``...`` / a docstring / comments).- - ``bare_except`` — Python ``except:`` / ``except Exception:`` /- ``except BaseException:`` (catch-all) regardless of body.+ - ``bare_except`` — Python truly-catch-all ``except:`` / ``except+ BaseException:`` (also swallows KeyboardInterrupt / SystemExit),+ regardless of body.+ - ``broad_except`` — Python ``except Exception:`` (broad, but cannot catch+ the BaseException-only interrupts), regardless of body.- ``unsafe_unwrap`` — Rust ``.unwrap()`` / ``.expect()`` /- ``.unwrap_unchecked()`` calls and ``panic!`` / ``unreachable!`` /- ``todo!`` / ``unimplemented!`` macros (latent panic-on-error).- - ``go_swallow`` — Go empty ``if err != nil {}`` block, or a+ ``.unwrap_unchecked()`` calls (latent panic-on-error). Suppressed inside+ ``#[test]`` / ``#[cfg(test)]`` items.+ - ``panic_macro`` — Rust ``panic!`` / ``unreachable!`` / ``todo!`` /+ ``unimplemented!`` macros (unconditional abort). Suppressed inside tests.+ - ``go_swallow`` — Go empty ``if err != nil {}`` block, or a trailingblank-identifier discard of a multi-return call's value."""diff --git a/packages/ui/src/health/biomarker-details.tsx b/packages/ui/src/health/biomarker-details.tsxindex ac7c4a1bf..eeb8ea1b0 100644--- a/packages/ui/src/health/biomarker-details.tsx+++ b/packages/ui/src/health/biomarker-details.tsx@@ -95,7 +95,9 @@ function PartnerLink({const ERROR_HANDLING_KIND_LABEL: Record<string, string> = {swallowed_exception: "swallowed exception",bare_except: "bare except",+ broad_except: "broad except",unsafe_unwrap: "unsafe unwrap",+ panic_macro: "panic macro",discarded_error: "discarded error return",empty_catch: "empty catch block",};diff --git a/tests/unit/health/test_error_handling.py b/tests/unit/health/test_error_handling.pyindex e8117c661..891fed267 100644--- a/tests/unit/health/test_error_handling.py+++ b/tests/unit/health/test_error_handling.py@@ -21,8 +21,8 @@ _FIXTURES = [("python",b"try:\n x()\nexcept Exception:\n pass\n",- {"swallowed_catch": 1, "bare_except": 1},- "empty Exception catch -> swallowed + bare",+ {"swallowed_catch": 1, "broad_except": 1},+ "empty Exception catch -> swallowed + broad (cannot catch KeyboardInterrupt)",),("python",@@ -114,8 +114,8 @@ _FIXTURES = [("rust",b'fn f() { let x = g().expect("boom"); panic!("x"); }\n',- {"unsafe_unwrap": 2},- "expect + panic!",+ {"unsafe_unwrap": 1, "panic_macro": 1},+ "expect -> unsafe_unwrap, panic! -> panic_macro",),("rust",diff --git a/tests/unit/health/test_ff_track_d_exceptions.py b/tests/unit/health/test_ff_track_d_exceptions.pynew file mode 100644index 000000000..181a9ad05--- /dev/null+++ b/tests/unit/health/test_ff_track_d_exceptions.py@@ -0,0 +1,187 @@+"""Regression tests: honest error-handling rationale / narrowed triggers.++These cover four fixed false-flags in the ``error_handling`` biomarker:++* ``except Exception`` no longer inherits the bare-``except:`` "hides+ KeyboardInterrupt" claim — it is its own ``broad_except`` kind.+* Go's blank-identifier discard only fires when ``_`` sits in the trailing+ (conventional error) slot, so a leading ``_`` value-discard is not called an+ error swallow.+* Rust panic-family macros get their own "aborts unconditionally" rationale+ instead of the unwrap/expect "recoverable error into a crash" claim.+* ``.unwrap()`` / panic macros inside ``#[test]`` / ``#[cfg(test)]`` are the+ intended failure signal, not a smell, so they are suppressed.+"""++from __future__ import annotations++import pytest++from repowise.core.analysis.health.biomarkers.base import FileContext+from repowise.core.analysis.health.biomarkers.error_handling import (+ _REASONS,+ ErrorHandlingDetector,+)+from repowise.core.analysis.health.complexity import walk_file+++def _grammar_available(language: str) -> bool:+ try:+ from repowise.core.ingestion.parser import _get_language+ except Exception:+ return False+ try:+ return _get_language(language) is not None+ except Exception:+ return False+++def _kinds(language: str, source: bytes) -> list[str]:+ if not _grammar_available(language):+ pytest.skip(f"tree-sitter language pack missing for {language}")+ return [h.kind for h in walk_file("<fixture>", language, source).error_handling_hits]+++# --- M1: except Exception (broad) vs except: / BaseException (truly catch-all) ---+++ "source",+ [+ b"try:\n x()\nexcept Exception:\n pass\n",+ b"try:\n x()\nexcept Exception as e:\n log(e)\n",+ ],+ ids=["except-Exception", "except-Exception-as"],+)+def test_except_exception_is_broad_not_bare(source: bytes) -> None:+ kinds = _kinds("python", source)+ assert "broad_except" in kinds+ assert "bare_except" not in kinds+ # The false KeyboardInterrupt claim must be gone from the broad rationale.+ assert "KeyboardInterrupt" not in _REASONS["broad_except"]+++ "source",+ [+ b"try:\n x()\nexcept:\n pass\n",+ b"try:\n x()\nexcept BaseException:\n pass\n",+ ],+ ids=["bare-except", "except-BaseException"],+)+def test_bare_and_baseexception_stay_bare(source: bytes) -> None:+ kinds = _kinds("python", source)+ assert "bare_except" in kinds+ assert "broad_except" not in kinds+ # These genuinely swallow KeyboardInterrupt/SystemExit — the claim is true here.+ assert "KeyboardInterrupt" in _REASONS["bare_except"]+++# --- R3: Go blank-identifier discard only in the trailing (error) slot ---+++def test_go_leading_blank_value_discard_not_flagged() -> None:+ # ``_, err := f()`` keeps the error and discards the value — a leading ``_``+ # is not the error position, so it must not be called an error swallow.+ assert "go_swallow" not in _kinds("go", b"func f() { _, err := g(); _ = err }\n")+++def test_go_comma_ok_lookup_not_flagged() -> None:+ # Go's comma-ok on a (T, bool) return: ``_, ok := os.LookupEnv(...)`` keeps+ # the bool and discards the value — no error exists to swallow.+ src = b'package p\nimport "os"\nfunc f() { _, ok := os.LookupEnv("PATH"); _ = ok }\n'+ assert "go_swallow" not in _kinds("go", src)+++def test_go_trailing_blank_error_discard_still_flagged() -> None:+ # ``v, _ := f()`` discards the trailing (error) slot — a genuine swallow.+ assert "go_swallow" in _kinds("go", b"func f() { v, _ := g(); _ = v }\n")+++# --- M7: Rust panic-family macros get their own honest rationale ---+++def test_rust_panic_macro_is_its_own_kind() -> None:+ src = b'fn handle(x: i32) -> i32 { match x { 1 => 10, _ => unreachable!("inv") } }\n'+ kinds = _kinds("rust", src)+ assert "panic_macro" in kinds+ assert "unsafe_unwrap" not in kinds+ # The macro does not consume a Result/Option, so no "recoverable error" claim.+ assert "recoverable error" not in _REASONS["panic_macro"]+++def test_rust_unwrap_still_unsafe_unwrap() -> None:+ kinds = _kinds("rust", b"fn f() { let x = g().unwrap(); }\n")+ assert "unsafe_unwrap" in kinds+ assert "panic_macro" not in kinds+ assert "recoverable error" in _REASONS["unsafe_unwrap"]+++# --- M8: suppress unwrap / panic macros inside Rust tests ---+++def test_rust_unwrap_in_test_fn_not_flagged() -> None:+ src = b'#[test]\nfn parses() { let cfg = parse("v.toml").unwrap(); }\n'+ assert _kinds("rust", src) == []+++def test_rust_unwrap_in_cfg_test_mod_not_flagged() -> None:+ src = (+ b"#[cfg(test)]\nmod tests {\n"+ b' #[test]\n fn parses() { let cfg = parse("v.toml").unwrap(); }\n}\n'+ )+ assert _kinds("rust", src) == []+++def test_rust_panic_macro_in_test_not_flagged() -> None:+ src = b'#[test]\nfn t() { if bad() { panic!("boom"); } }\n'+ assert _kinds("rust", src) == []+++def test_rust_unwrap_in_tokio_test_not_flagged() -> None:+ # ``#[tokio::test]`` is a test-runner attribute even though ``#[test]`` is+ # not a literal substring of it.+ src = b'#[tokio::test]\nasync fn t() { let cfg = parse("v.toml").unwrap(); }\n'+ assert _kinds("rust", src) == []+++def test_rust_unwrap_in_cfg_all_test_mod_not_flagged() -> None:+ src = (+ b'#[cfg(all(test, feature = "x"))]\nmod tests {\n'+ b' fn parses() { let cfg = parse("v.toml").unwrap(); }\n}\n'+ )+ assert _kinds("rust", src) == []+++def test_rust_unwrap_in_production_fn_still_flagged() -> None:+ assert _kinds("rust", b"fn prod() { let x = g().unwrap(); }\n") == ["unsafe_unwrap"]+++def test_rust_unwrap_under_cfg_not_test_still_flagged() -> None:+ # ``#[cfg(not(test))]`` gates the non-test build — the unwrap is still a smell.+ src = b"#[cfg(not(test))]\nfn prod() { let x = g().unwrap(); }\n"+ assert _kinds("rust", src) == ["unsafe_unwrap"]+++# --- new kinds flow through the detector without dropping / crashing ---+++def test_detector_emits_reasons_for_new_kinds() -> None:+ from repowise.core.analysis.health.complexity import ErrorHandlingHit++ ctx = FileContext(+ file_path="a.py",+ language="python",+ nloc=20,+ has_test_file=False,+ module=None,+ error_handling_hits=[+ ErrorHandlingHit("broad_except", 3),+ ErrorHandlingHit("panic_macro", 5),+ ],+ )+ findings = ErrorHandlingDetector().detect(ctx)+ reasons = {f.details["kind"]: f.reason for f in findings}+ assert reasons["broad_except"] == _REASONS["broad_except"]+ assert reasons["panic_macro"] == _REASONS["panic_macro"]+ assert "KeyboardInterrupt" not in reasons["broad_except"]