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 flagging Rust unwraps that cannot panic and keep panics out of Fix first (#2950)

Raghav Chamadiya671239032ec9
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.py
index 623870f7f..9ec4663aa 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
@@ -33,6 +33,27 @@ _REASONS: dict[str, str] = {
"go_swallow": "error value is checked then ignored, or discarded via the blank identifier",
}
+# Rust invariant assertions (``complexity.rust_unwrap``): true, idiomatic, low
+# priority. They keep their kind (and so their id) but say what they are and
+# deduct nothing from the score.
+_IDIOM_REASONS: dict[str, str] = {
+ "lock_poison": (
+ "unwrapping a lock panics only if another thread panicked while holding it "
+ "(idiomatic poison propagation, low priority)"
+ ),
+ "thread_join": (
+ "unwrapping a thread join re-raises that thread's panic (idiomatic, low priority)"
+ ),
+ "invariant_expect": (
+ "expect panics with its stated message on failure, the usual form when "
+ "failure is a bug or makes start-up impossible (often idiomatic, low priority)"
+ ),
+ "unreachable": (
+ "unreachable! asserts this branch cannot run and panics only if it does "
+ "(often idiomatic, low priority)"
+ ),
+}
+
class ErrorHandlingDetector:
name = "error_handling"
@@ -41,6 +62,11 @@ class ErrorHandlingDetector:
def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
out: list[BiomarkerResult] = []
for hit in ctx.error_handling_hits:
+ idiom_reason = _IDIOM_REASONS.get(hit.idiom) if hit.idiom else None
+ details: dict[str, str | float] = {"kind": hit.kind}
+ if idiom_reason is not None:
+ # ``deduction`` in details is what a history refresh replays.
+ details.update(idiom=hit.idiom, deduction=0.0)
out.append(
BiomarkerResult(
biomarker_type=self.name,
@@ -48,8 +74,9 @@ class ErrorHandlingDetector:
function_name=None,
line_start=hit.line,
line_end=hit.line,
- details={"kind": hit.kind},
- reason=_REASONS.get(hit.kind, hit.kind),
+ details=details,
+ reason=idiom_reason or _REASONS.get(hit.kind, hit.kind),
+ deduction=0.0 if idiom_reason is not None else None,
)
)
return out
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.py
index f6334139f..c7c2591e9 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
@@ -14,6 +14,7 @@ from __future__ import annotations
import re
from typing import TYPE_CHECKING
+from . import rust_unwrap
from .languages import LanguageNodeMap
from .models import ErrorHandlingHit
@@ -172,17 +173,26 @@ def _eh_rust_in_test(node: Node) -> bool:
def _eh_rust_hit(node: Node) -> bool:
"""True when *node* is an unwrap/expect call or a panic-family macro."""
if node.type == "call_expression":
- fn = node.child_by_field_name("function")
- if fn is not None and fn.type == "field_expression":
- fld = fn.child_by_field_name("field")
- return fld is not None and _eh_text(fld) in _RUST_UNWRAP_METHODS
- return False
+ return rust_unwrap.method_call_parts(node)[0] in _RUST_UNWRAP_METHODS
if node.type == "macro_invocation":
mac = node.child_by_field_name("macro")
return mac is not None and _eh_text(mac) in _RUST_PANIC_MACROS
return False
+def _eh_rust_append(node: Node, hits: list[ErrorHandlingHit]) -> None:
+ """Record a Rust hit unless it provably cannot panic, labelled with its idiom."""
+ if node.type == "macro_invocation":
+ kind = "panic_macro"
+ elif rust_unwrap.cannot_panic(node):
+ return
+ else:
+ kind = "unsafe_unwrap"
+ hits.append(
+ ErrorHandlingHit(kind, rust_unwrap.anchor_line(node), rust_unwrap.idiom(node))
+ )
+
+
def _eh_go_cond_is_err_check(cond_text: str) -> bool:
t = cond_text.replace(" ", "")
return "err!=nil" in t or "err==nil" in t
@@ -268,7 +278,6 @@ def _eh_visit(
# 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))
+ _eh_rust_append(node, hits)
elif language == "go" and _eh_go_hit(node):
hits.append(ErrorHandlingHit("go_swallow", node.start_point[0] + 1))
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.py
index a58582d86..f108187b9 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py
@@ -205,7 +205,8 @@ class ErrorHandlingHit:
the BaseException-only interrupts), regardless of body.
- ``unsafe_unwrap`` — Rust ``.unwrap()`` / ``.expect()`` /
``.unwrap_unchecked()`` calls (latent panic-on-error). Suppressed inside
- ``#[test]`` / ``#[cfg(test)]`` items.
+ ``#[test]`` / ``#[cfg(test)]`` items and where the call provably cannot
+ panic (a guarded receiver, a ``write!`` into a ``String``).
- ``panic_macro`` — Rust ``panic!`` / ``unreachable!`` / ``todo!`` /
``unimplemented!`` macros (unconditional abort). Suppressed inside tests.
- ``go_swallow`` — Go empty ``if err != nil {}`` block, or a trailing
@@ -214,6 +215,10 @@ class ErrorHandlingHit:
kind: str
line: int # 1-indexed
+ # Rust only: the idiomatic invariant assertion this hit is (``lock_poison``,
+ # ``thread_join``, ``invariant_expect``, ``unreachable``), see
+ # ``complexity.rust_unwrap``. ``None`` for a plain occurrence.
+ idiom: str | None = None
@dataclass(frozen=True)
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/rust_unwrap.py b/packages/core/src/repowise/core/analysis/health/complexity/rust_unwrap.py
new file mode 100644
index 000000000..a56bc5b50
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/complexity/rust_unwrap.py
@@ -0,0 +1,286 @@
+"""Rust ``unwrap`` / ``expect`` / panic-macro verdicts for ``error_handling``.
+
+An ``.unwrap()`` is a latent crash only when the value can actually be ``None``
+or ``Err``. Two shapes provably cannot, so they are no finding:
+
+- a guarded unwrap: the receiver was checked in an enclosing ``if`` or a
+ preceding ``&&`` operand (``x.is_some() && x.unwrap()``,
+ ``!v.is_empty() && v.last().unwrap()``);
+- a ``write!`` / ``writeln!`` into a local ``String``: ``fmt::Write`` for
+ ``String`` never returns ``Err``.
+
+A few more are true but idiomatic invariant assertions. They stay findings,
+labelled with the idiom so the biomarker can say so and not score them:
+``.lock().unwrap()`` (poison propagation), ``.join().unwrap()`` (re-raise a
+thread's panic), ``expect("literal message")`` and ``unreachable!``.
+
+Purely syntactic. A guard does not count once the guarded block rebinds or
+assigns the receiver before the unwrap. Ceiling: an early-return guard
+(``if v.is_empty() { return; }``) stays a finding, and a mutation through a
+method call between the check and the unwrap (``v.clear()``) is not seen.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from collections.abc import Iterator
+
+ from tree_sitter import Node
+
+# Adapters that keep the Some/Ok-ness the guard checked.
+_GUARD_ADAPTERS = frozenset({"as_ref", "as_mut", "as_deref", "as_deref_mut", "map"})
+# Guards that prove the receiver itself is Some / Ok.
+_PRESENT_GUARDS = (".is_some()", ".is_ok()")
+# Accessors that are Some exactly when the collection is non-empty.
+_NONEMPTY_ACCESSORS = (".last()", ".first()", ".last_mut()", ".first_mut()", ".pop()")
+_NONEMPTY_GUARDS = ("!{v}.is_empty()", "{v}.len()>0", "{v}.len()!=0", "{v}.len()>=1")
+
+_STRING_WRITE_MACROS = frozenset({"write", "writeln"})
+_STRING_CTORS = ("String::new(", "String::with_capacity(", "String::from(")
+_STRING_TYPES = frozenset({"String", "&mutString"})
+
+# Zero-argument receiver call -> idiom. ``read``/``write`` take no argument
+# only on ``RwLock``; ``io::Read::read(buf)`` and ``io::Write::write(buf)`` do.
+_SYNC_RECEIVER_IDIOMS = {
+ "lock": "lock_poison",
+ "read": "lock_poison",
+ "write": "lock_poison",
+ "join": "thread_join",
+}
+_INVARIANT_MACROS = frozenset({"unreachable"})
+
+_SCOPE_KINDS = frozenset({"function_item", "closure_expression"})
+# Nodes whose ``pattern`` field binds names, and pattern nodes that bind any
+# identifier they hold directly.
+_PATTERN_FIELD_OWNERS = frozenset({"let_declaration", "parameter", "for_expression", "let_condition"})
+_PATTERN_KINDS = frozenset(
+ {
+ "closure_parameters",
+ "tuple_pattern",
+ "tuple_struct_pattern",
+ "slice_pattern",
+ "or_pattern",
+ "ref_pattern",
+ "mut_pattern",
+ "reference_pattern",
+ "captured_pattern",
+ "field_pattern",
+ }
+)
+_ROOT_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
+
+
+def _text(node: Node | None) -> str:
+ return (node.text or b"").decode("utf-8", errors="replace") if node is not None else ""
+
+
+def _norm(node: Node | None) -> str:
+ return "".join(_text(node).split())
+
+
+def _same(a: Node | None, b: Node) -> bool:
+ return a is not None and (a.start_byte, a.end_byte) == (b.start_byte, b.end_byte)
+
+
+def method_call_parts(node: Node) -> tuple[str, Node | None, Node | None]:
+ """``(method name, receiver, arguments)`` of ``recv.method(args)``, else ``("", None, None)``."""
+ fn = node.child_by_field_name("function") if node.type == "call_expression" else None
+ if fn is None or fn.type != "field_expression":
+ return "", None, None
+ method = _text(fn.child_by_field_name("field"))
+ return method, fn.child_by_field_name("value"), node.child_by_field_name("arguments")
+
+
+def _peel(node: Node) -> Node | None:
+ """The expression inside one Some/Ok-preserving layer of *node*, else ``None``."""
+ method, receiver, _ = method_call_parts(node)
+ if method:
+ return receiver if method in _GUARD_ADAPTERS else None
+ is_deref = node.type == "unary_expression" and node.children[0].type == "*"
+ if is_deref or node.type in ("parenthesized_expression", "reference_expression"):
+ return node.named_children[-1] if node.named_child_count else None
+ return None
+
+
+def _base_receiver(node: Node) -> Node:
+ """*node* with Some/Ok-preserving adapters, parentheses and ``*``/``&`` peeled."""
+ inner = _peel(node)
+ while inner is not None:
+ node, inner = inner, _peel(inner)
+ return node
+
+
+def _guard_keys(receiver: Node) -> frozenset[str]:
+ base = _norm(_base_receiver(receiver))
+ keys = {base + guard for guard in _PRESENT_GUARDS}
+ for accessor in _NONEMPTY_ACCESSORS:
+ if base.endswith(accessor):
+ coll = base[: -len(accessor)]
+ keys.update(g.format(v=coll) for g in _NONEMPTY_GUARDS)
+ return frozenset(keys)
+
+
+def _conjuncts(cond: Node) -> list[str]:
+ """The top-level ``&&`` operands of *cond*, whitespace-stripped."""
+ while cond.type == "parenthesized_expression" and cond.named_child_count == 1:
+ cond = cond.named_children[0]
+ op = cond.child_by_field_name("operator") if cond.type == "binary_expression" else None
+ if op is not None and op.type == "&&":
+ left, right = cond.child_by_field_name("left"), cond.child_by_field_name("right")
+ return _conjuncts(left) + _conjuncts(right)
+ return [_norm(cond)]
+
+
+def _guarding_condition(parent: Node, child: Node) -> Node | None:
+ """The condition that must hold for *child* (a child of *parent*) to run."""
+ if parent.type == "if_expression" and _same(parent.child_by_field_name("consequence"), child):
+ return parent.child_by_field_name("condition")
+ if parent.type == "binary_expression":
+ op = parent.child_by_field_name("operator")
+ if op is not None and op.type == "&&" and _same(parent.child_by_field_name("right"), child):
+ return parent.child_by_field_name("left")
+ return None
+
+
+def _descendants(node: Node) -> Iterator[Node]:
+ stack = [node]
+ while stack:
+ cur = stack.pop()
+ yield cur
+ stack.extend(cur.named_children)
+
+
+def _is_binder(ident: Node) -> bool:
+ """*ident* names a new binding (a ``let``/parameter/closure/``for`` pattern)."""
+ parent = ident.parent
+ if parent is None:
+ return False
+ if parent.type in _PATTERN_FIELD_OWNERS:
+ return _same(parent.child_by_field_name("pattern"), ident)
+ return parent.type in _PATTERN_KINDS
+
+
+def _binders(scope: Node, name: str, before: int | None = None) -> list[Node]:
+ """Every binding of *name* in *scope*, those starting before byte *before* if given."""
+ end = scope.end_byte if before is None else before
+ named = (n for n in _descendants(scope) if n.type == "identifier" and _text(n) == name)
+ return [n for n in named if n.start_byte < end and _is_binder(n)]
+
+
+def _rebinds(region: Node, base: str, call: Node) -> bool:
+ """*region* rebinds or assigns the guarded receiver before *call* runs."""
+ root = _ROOT_NAME.match(base)
+ if root is not None and root.group() != "self" and _binders(region, root.group(), call.start_byte):
+ return True
+ return any(
+ n.type in ("assignment_expression", "compound_assignment_expr")
+ and n.start_byte < call.start_byte
+ and _norm(n.child_by_field_name("left")) in (base, root.group() if root else base)
+ for n in _descendants(region)
+ )
+
+
+def _is_guarded(call: Node, receiver: Node) -> bool:
+ keys = _guard_keys(receiver)
+ child, parent = call, call.parent
+ while parent is not None and parent.type not in _SCOPE_KINDS:
+ cond = _guarding_condition(parent, child)
+ if cond is not None and keys.intersection(_conjuncts(cond)):
+ return not _rebinds(child, _norm(_base_receiver(receiver)), call)
+ child, parent = parent, parent.parent
+ return False
+
+
+def _write_target(macro: Node) -> str | None:
+ """The first argument of a ``write!``/``writeln!`` call, ``&mut`` dropped."""
+ name = macro.child_by_field_name("macro")
+ if _text(name) not in _STRING_WRITE_MACROS:
+ return None
+ args = next((c for c in macro.children if c.type == "token_tree"), None)
+ body = _norm(args)[1:-1]
+ first = body.split(",", 1)[0]
+ return first.removeprefix("&mut") or None
+
+
+def _declares_string(scope: Node, name: str) -> bool:
+ """*scope* binds *name* exactly once, as a ``String`` (a ``let`` or a parameter).
+
+ A second binding anywhere in the function (a shadowing ``let``, a closure
+ parameter) could be what the write reaches, so it proves nothing.
+ """
+ binders = _binders(scope, name)
+ if len(binders) != 1:
+ return False
+ decl = binders[0].parent
+ if decl.type not in ("let_declaration", "parameter"):
+ return False
+ return _norm(decl.child_by_field_name("type")) in _STRING_TYPES or _norm(
+ decl.child_by_field_name("value")
+ ).startswith(_STRING_CTORS)
+
+
+def _writes_to_string(receiver: Node) -> bool:
+ if receiver.type != "macro_invocation":
+ return False
+ target = _write_target(receiver)
+ if not target:
+ return False
+ scope = receiver.parent
+ while scope is not None and scope.type != "function_item":
+ scope = scope.parent
+ return scope is not None and _declares_string(scope, target)
+
+
+def cannot_panic(call: Node) -> bool:
+ """True when the ``unwrap``/``expect`` *call* provably cannot panic."""
+ receiver = method_call_parts(call)[1]
+ if receiver is None:
+ return False
+ return _writes_to_string(receiver) or _is_guarded(call, receiver)
+
+
+def _sync_idiom(receiver: Node | None) -> str | None:
+ if receiver is None:
+ return None
+ method, _, args = method_call_parts(receiver)
+ if args is None or args.named_child_count:
+ return None
+ return _SYNC_RECEIVER_IDIOMS.get(method)
+
+
+def _expect_message_is_literal(call: Node) -> bool:
+ args = call.child_by_field_name("arguments")
+ named = args.named_children if args is not None else []
+ if len(named) != 1:
+ return False
+ arg = named[0]
+ # A string literal, or a SCREAMING_CASE identifier (a ``const`` message).
+ return arg.type in ("string_literal", "raw_string_literal") or (
+ arg.type == "identifier" and _text(arg).isupper()
+ )
+
+
+def idiom(node: Node) -> str | None:
+ """The idiomatic-assertion label for a Rust error-handling hit, if any."""
+ if node.type == "macro_invocation":
+ mac = node.child_by_field_name("macro")
+ return "unreachable" if _text(mac) in _INVARIANT_MACROS else None
+ sync = _sync_idiom(method_call_parts(node)[1])
+ if sync is not None:
+ return sync
+ if method_call_parts(node)[0] == "expect" and _expect_message_is_literal(node):
+ return "invariant_expect"
+ return None
+
+
+def anchor_line(node: Node) -> int:
+ """1-based line of the ``.unwrap``/``.expect`` token, not the chain start."""
+ if node.type == "call_expression":
+ fn = node.child_by_field_name("function")
+ fld = fn.child_by_field_name("field") if fn is not None else None
+ if fld is not None:
+ return fld.start_point[0] + 1
+ return node.start_point[0] + 1
diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/build.py b/packages/core/src/repowise/core/analysis/health/fix_first/build.py
index 6122b6aa6..e0355b775 100644
--- a/packages/core/src/repowise/core/analysis/health/fix_first/build.py
+++ b/packages/core/src/repowise/core/analysis/health/fix_first/build.py
@@ -157,6 +157,14 @@ LOW_VALUE_KINDS: dict[str, str] = {
# whole top three; revisit when more of it is labelled.
"primitive_obsession": "dev 0/0, all 0/2",
}
+#: The same, for one detail ``kind`` of a marker whose other kinds stay. A Rust
+#: unwrap or panic is a crash path, not the hidden failure the error-handling
+#: item describes, and the raters found it not worth doing first. Both kinds
+#: were rated together on ripgrep, fd, serde and mini-redis.
+LOW_VALUE_DETAIL_KINDS: dict[tuple[str, str], str] = {
+ ("error_handling", "unsafe_unwrap"): "rust all 1/19",
+ ("error_handling", "panic_macro"): "rust all 1/19",
+}
@dataclass(frozen=True, slots=True)
@@ -1180,7 +1188,10 @@ def _refactor_exclusion(
def _finding_exclusion(finding: Any, files: _Files) -> str | None:
- if field(finding, "biomarker_type") in LOW_VALUE_KINDS:
+ marker = field(finding, "biomarker_type")
+ if marker in LOW_VALUE_KINDS or (
+ (marker, detail_map(finding).get("kind")) in LOW_VALUE_DETAIL_KINDS
+ ):
return "low_value_kind"
reason = files.unit_exclusion(
field(finding, "file_path"),
@@ -1467,6 +1478,7 @@ __all__ = [
"GROWS_ONLY_MARKERS",
"HEAD",
"HEAD_PER_KIND",
+ "LOW_VALUE_DETAIL_KINDS",
"LOW_VALUE_KINDS",
"MIN_WORTH",
"SIZE_MARKERS",
diff --git a/tests/unit/health/test_error_handling.py b/tests/unit/health/test_error_handling.py
index 891fed267..bb8f67d8e 100644
--- a/tests/unit/health/test_error_handling.py
+++ b/tests/unit/health/test_error_handling.py
@@ -205,3 +205,112 @@ def test_biomarker_no_hits_no_findings():
module=None,
)
assert ErrorHandlingDetector().detect(ctx) == []
+
+
+# Rust unwraps that provably cannot panic are no finding; the controls beside
+# each stay findings.
+_RUST_CANNOT_PANIC = [
+ (b"fn f(x: Option<u8>) { if x.is_some() { g(x.unwrap()); } }\n", 0, "is_some guard"),
+ (b"fn f(x: Option<u8>) { if x.is_some() && h() { g(x.unwrap()); } }\n", 0, "guard conjunct"),
+ (b"fn f(x: Option<u8>) { if x.is_some() || h() { g(x.unwrap()); } }\n", 1, "|| is no guard"),
+ (b"fn f(x: Option<u8>) { if !x.is_some() { g(x.unwrap()); } }\n", 1, "negated guard"),
+ (b"fn f(x: Option<u8>) { if x.is_some() { } else { g(x.unwrap()); } }\n", 1, "else branch"),
+ (b"fn f(x: Option<u8>) { if y.is_some() { g(x.unwrap()); } }\n", 1, "other receiver"),
+ (b"fn f(v: Vec<u8>) { if !v.is_empty() && v.last().unwrap() == &0 { } }\n", 0, "non-empty"),
+ (b"fn f(v: Vec<u8>) { if v.is_empty() && v.last().unwrap() == &0 { } }\n", 1, "empty check"),
+ (
+ b"fn f(s: &S) { if s.r.is_some() { let r = (*s.r).as_ref().map(|r| r).unwrap(); } }\n",
+ 0,
+ "guard through as_ref/map/deref",
+ ),
+ (
+ b'fn f() -> String { let mut s = String::new(); writeln!(s, "a").unwrap(); s }\n',
+ 0,
+ "write into a String",
+ ),
+ (
+ b'fn f(s: &mut String) { write!(&mut s, "a").unwrap(); }\n',
+ 0,
+ "write into a &mut String parameter",
+ ),
+ (
+ b'fn f() { let mut o = io::stdout(); writeln!(o, "a").unwrap(); }\n',
+ 1,
+ "write into stdout can fail",
+ ),
+ (
+ b"fn f() { let mut w = String::new(); { let mut w = io::stdout(); "
+ b'writeln!(w, "a").unwrap(); } }\n',
+ 1,
+ "a shadowing rebind of the String",
+ ),
+ (
+ b'fn f(o: &mut File) { let c = |o: String| 1; writeln!(o, "a").unwrap(); }\n',
+ 1,
+ "a closure parameter of the same name",
+ ),
+ (b"fn f(x: Option<u8>) { if x.is_some() { let x = h(); g(x.unwrap()); } }\n", 1, "rebind"),
+ (b"fn f(mut x: Option<u8>) { if x.is_some() { x = h(); g(x.unwrap()); } }\n", 1, "assign"),
+ (
+ b"fn f(s: &mut S) { if s.v.is_some() { s.v = None; g(s.v.unwrap()); } }\n",
+ 1,
+ "field assigned after the guard",
+ ),
+]
+
+
+ ("source", "expected", "note"),
+ _RUST_CANNOT_PANIC,
+ ids=[note for _, _, note in _RUST_CANNOT_PANIC],
+)
+def test_rust_unwrap_that_cannot_panic_is_no_hit(source: bytes, expected: int, note: str):
+ hits = [h for h in _hits("rust", source) if h.kind == "unsafe_unwrap"]
+ assert len(hits) == expected, note
+
+
+_RUST_IDIOMS = [
+ (b"fn f(m: &Mutex<u8>) { let g = m.lock().unwrap(); }\n", "lock_poison"),
+ (b"fn f(m: &RwLock<u8>) { let g = m.write().unwrap(); }\n", "lock_poison"),
+ (b"fn f(h: JoinHandle<()>) { h.join().unwrap(); }\n", "thread_join"),
+ (b'fn f() { g().expect("config is validated at load"); }\n', "invariant_expect"),
+ (b"fn f() { g().expect(MSG); }\n", "invariant_expect"),
+ (b'fn f(x: u8) { match x { 0 => {}, _ => unreachable!("x is 0") } }\n', "unreachable"),
+ (b"fn f() { g().unwrap(); }\n", None),
+ (b"fn f(r: &mut File) { r.read(&mut buf).unwrap(); }\n", None),
+ (b'fn f() { g().expect(&format!("bad {}", 1)); }\n', None),
+ (b'fn f() { panic!("boom"); }\n', None),
+]
+
+
[email protected](("source", "idiom"), _RUST_IDIOMS)
+def test_rust_idiomatic_assertions_are_labelled(source: bytes, idiom: str | None):
+ hits = _hits("rust", source)
+ assert len(hits) == 1
+ assert hits[0].idiom == idiom
+
+
+def test_rust_unwrap_anchors_on_the_unwrap_line_of_a_chain():
+ hits = _hits("rust", b"fn f() {\n let x = g()\n .h()\n .unwrap();\n}\n")
+ assert [h.line for h in hits] == [4]
+
+
+def test_idiomatic_hit_is_labelled_and_not_scored():
+ ctx = FileContext(
+ file_path="a.rs",
+ language="rust",
+ nloc=20,
+ has_test_file=False,
+ module=None,
+ error_handling_hits=[
+ ErrorHandlingHit("unsafe_unwrap", 3, "lock_poison"),
+ ErrorHandlingHit("unsafe_unwrap", 5),
+ ],
+ )
+ idiomatic, plain = ErrorHandlingDetector().detect(ctx)
+ assert idiomatic.details == {"kind": "unsafe_unwrap", "idiom": "lock_poison", "deduction": 0.0}
+ assert idiomatic.deduction == 0.0
+ assert "idiomatic" in idiomatic.reason
+ assert plain.details == {"kind": "unsafe_unwrap"}
+ assert plain.deduction is None
+ assert plain.reason == "unwrap/expect turns a recoverable error into a crash"
diff --git a/tests/unit/health/test_fix_first_precision.py b/tests/unit/health/test_fix_first_precision.py
index 2a12d772e..bdd8c81a9 100644
--- a/tests/unit/health/test_fix_first_precision.py
+++ b/tests/unit/health/test_fix_first_precision.py
@@ -514,3 +514,16 @@ def test_a_split_file_plan_and_a_complex_method_stay() -> None:
named = {"groups": [{"name": "io", "symbols": ["read"]}]}
assert len(_refactor_queue("split_file", named).items) == 1
assert len(_queue([_finding()]).items) == 1
+
+
+def test_a_rust_panic_path_is_no_fix_first_candidate() -> None:
+ """An unwrap or panic is a crash path, not a failure the handler hides."""
+ rows = [
+ {**_finding(f"src/{kind}.rs"), "biomarker_type": "error_handling", "line_start": 9,
+ "details": {"kind": kind}}
+ for kind in ("unsafe_unwrap", "panic_macro")
+ ]
+ queue = _queue(rows)
+ assert queue.items == () and queue.totals.excluded["low_value_kind"] == 2
+ swallowed = {**rows[0], "file_path": "src/a.py", "details": {"kind": "swallowed_catch"}}
+ assert [i.target.file_path for i in _queue([swallowed]).items] == ["src/a.py"]