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): skip lock_in_loop when the lock belongs to the loop element (#4767)
Raghav Chamadiya6d06dd99686a
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py b/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.pyindex 41c32d667..c084bdffb 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py@@ -324,10 +324,82 @@ def _bound_in(part: Node) -> set[bytes]:def _loop_bound_names(loop: Node) -> set[bytes]:"""The element or index names *loop*'s header binds; empty for a ``while`` loop."""parts = [loop, *(c for c in loop.children if c.type in _LOOP_CLAUSE_KINDS)]- unfielded = [c for c in loop.children if c.type == "variable_declaration"]+ unfielded = [+ c for c in loop.children if c.type in ("variable_declaration", "multi_variable_declaration")+ ]return set().union(*(_bound_in(p) for p in parts), *(_identifiers(c) for c in unfielded))+def _block_bound_names(block: Node) -> set[bytes]:+ """The parameters a block loop's lambda binds; Kotlin's implicit ``it`` when it declares none."""+ node = block+ for _ in range(2): # Kotlin: annotated_lambda -> lambda_literal -> lambda_parameters+ params = next((c for c in node.named_children if c.type.endswith("parameters")), None)+ if params is not None:+ return _identifiers(params)+ if not node.named_children:+ break+ node = node.named_children[0]+ return {b"it"}+++def _leftmost_name(node: Node | None) -> bytes:+ """The first identifier down the leftmost path: ``x`` of ``x.mu`` / ``(x.lock)``."""+ for _ in range(8):+ if node is None or node.type.endswith("identifier"):+ break+ node = next(iter(node.named_children), None)+ return node.text or b"" if node is not None else b""+++def _lock_subject(lock: Node, receiver: str | None) -> bytes:+ """The name a lock is taken on.++ The receiver root of ``u.mu.Lock()`` / ``it.withLock {}``, else the leftmost+ name of the first operand: ``synchronized (x)``, ``lock (item)``, Kotlin's+ bare ``synchronized(x) {}``. ``None`` marks a statement-form lock.+ """+ if receiver:+ return receiver.encode()+ operand = next(iter(lock.named_children), None)+ if receiver is not None:+ # A bare call: the lock is its first argument (``call_suffix`` wraps it in Kotlin).+ operand = next(+ (+ d+ for c in lock.named_children+ for d in (c, *c.named_children)+ if d.type.endswith("arguments") or d.type == "argument_list"+ ),+ None,+ )+ operand = next(iter(operand.named_children), None) if operand is not None else None+ return _leftmost_name(operand)+++def _locks_loop_element(+ lock: Node,+ receiver: str | None,+ dialect: BasePerfDialect,+ loop_kinds: frozenset[str],+ fn_kinds: frozenset[str],+ block_loops: bool,+) -> bool:+ """The lock belongs to the element the nearest loop yields (``for u in us: u.mu.Lock()``).++ Each pass locks a different object, so there is no shared lock to hoist. A+ lock reached through a local derived from the element is not matched (recall+ ceiling).+ """+ loops = _enclosing_loops(lock, dialect, loop_kinds, fn_kinds, block_loops)+ if not loops:+ return False+ subject = _lock_subject(lock, receiver)+ block = dialect.block_loop_body(loops[0]) if block_loops else None+ bound = _block_bound_names(block) if block is not None else _loop_bound_names(loops[0])+ return bool(subject) and subject in bound++def _loop_key_feeds(call: Node, loop: Node) -> bool:"""The loop's element or index appears in *call*, which makes the call per-key.@@ -966,8 +1038,8 @@ class _PerfWalk:if self.do_loop_call_markerelse None)- if marker == "lock_in_loop" and _is_lock_acquire_spin(- call.node, nxt.func, self.dialect, self.loop_kinds, self.fn_kinds+ if marker == "lock_in_loop" and self._lock_not_hoistable(+ call.node, call.root_name if self.dialect.callee_is_attribute(call.node) else "", nxt):marker = Noneif marker is not None:@@ -1060,9 +1132,7 @@ class _PerfWalk:def _on_loop_statement(self, node: Node, nxt: _Frame) -> None:sm = self.dialect.loop_stmt_marker(node, self.list_names)- if sm == "lock_in_loop" and _is_lock_acquire_spin(- node, nxt.func, self.dialect, self.loop_kinds, self.fn_kinds- ):+ if sm == "lock_in_loop" and self._lock_not_hoistable(node, None, nxt):sm = Noneif sm is None:return@@ -1083,6 +1153,15 @@ class _PerfWalk:))+ def _lock_not_hoistable(self, node: Node, receiver: str | None, nxt: _Frame) -> bool:+ """A per-iteration lock with nothing to hoist: a lock-acquire spin, or the loop element's own lock."""+ dialect = self.dialect+ return _is_lock_acquire_spin(+ node, nxt.func, dialect, self.loop_kinds, self.fn_kinds+ ) or _locks_loop_element(+ node, receiver, dialect, self.loop_kinds, self.fn_kinds, self.do_block_loop+ )+def _is_lock_entry(self, node: Node) -> bool:"""A block-scoped lock (``lock`` / ``synchronized``) whose body runs with it held.diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/go.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/go.pyindex 8c9095ae6..32211dc93 100644--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/go.py+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/go.py@@ -118,6 +118,24 @@ def _single_identifier(node: Node | None) -> bytes | None:_GO_FN_KINDS: frozenset[str] = frozenset({"function_declaration", "method_declaration", "func_literal"})+def _in_event_loop_case(node: Node) -> bool:+ """*node* sits in a ``select`` case of a bare ``for { select { ... } }`` event loop.++ The case runs once per received event and the loop blocks between events,+ so there is no lock to hoist.+ """+ in_case = False+ cur = node.parent+ while cur is not None and cur.type not in _GO_FN_KINDS:+ if cur.type == "communication_case":+ in_case = True+ elif cur.type == "for_statement":+ # A bare ``for {`` has its body as its only named child.+ return in_case and len(cur.named_children) == 1+ cur = cur.parent+ return False++def _go_bindings(node: Node) -> list[tuple[bytes, Node]]:"""What *node* binds: ``x := v`` / ``x = v`` / ``var x = v`` (one callanswering several names counts for each), or a read filling ``&x`` (GORM@@ -282,7 +300,7 @@ class GoPerfDialect(IterableSources):# ``mu.Lock()`` / ``mu.RLock()`` — a method on a receiver (the package-# level ``sync.Lock`` does not exist, so the attribute gate is a guard).if method in GO_LOCK_METHODS and self.callee_is_attribute(node):- return "lock_in_loop"+ return None if _in_event_loop_case(node) else "lock_in_loop"return Nonedef defers_body(self, fn: Node) -> bool:diff --git a/tests/unit/health/test_perf_dialects.py b/tests/unit/health/test_perf_dialects.pyindex 43af2972f..91710d029 100644--- a/tests/unit/health/test_perf_dialects.py+++ b/tests/unit/health/test_perf_dialects.py@@ -165,6 +165,16 @@ _JAVA_CASES = [[],"a shared repository verb on a non-repository receiver is not db",),+ (+ "class A{void m(java.util.List<X> xs){for(X x:xs){ synchronized(x){ } x.lock.lock(); }}}",+ [],+ "the loop element's own lock is a different lock each pass, nothing to hoist",+ ),+ (+ "class A{void m(java.util.List<X> xs){for(X x:xs){ synchronized(this){ } }}}",+ [("lock_in_loop", "")],+ "a shared lock taken per element still fires",+ ),]@@ -217,6 +227,28 @@ _GO_CASES = [[("io_in_loop", "network")],"net/http Get in a range loop",),+ (+ "package p\nfunc f(us []*U) {\n\tfor _, u := range us {\n\t\tu.mu.RLock()\n\t\tu.mu.RUnlock()\n\t}\n}\n",+ [],+ "the range element's own mutex is a different lock each pass",+ ),+ (+ "package p\nfunc f(us []*U) {\n\tfor _, u := range us {\n\t\tmu.Lock()\n\t\tmu.Unlock()\n\t}\n}\n",+ [("lock_in_loop", "")],+ "a shared mutex locked per element still fires",+ ),+ (+ "package p\nfunc f(s *S) {\n\tfor {\n\t\tselect {\n\t\tcase <-s.t.C:\n"+ "\t\t\tmu.Lock()\n\t\t\tmu.Unlock()\n\t\t}\n\t}\n}\n",+ [],+ "a lock per event in a for-select event loop has nothing to hoist",+ ),+ (+ "package p\nfunc f(xs []int) {\n\tfor _, x := range xs {\n\t\tselect {\n"+ "\t\tcase ch <- x:\n\t\t\tmu.Lock()\n\t\t}\n\t}\n}\n",+ [("lock_in_loop", "")],+ "a select inside a range loop still locks per element",+ ),]@@ -290,6 +322,16 @@ _CSHARP_CASES = [[],"a bare SaveChangesAsync is the class's own method, not a DbContext call",),+ (+ "class A{void M(List<X> xs){foreach(var item in xs){ lock(item){ } }}}",+ [],+ "locking the foreach element is a different lock each pass",+ ),+ (+ "class A{void M(List<X> xs){foreach(var item in xs){ lock(gate){ } }}}",+ [("lock_in_loop", "")],+ "a shared gate locked per element still fires",+ ),]@@ -1410,6 +1452,26 @@ _KOTLIN_CASES = [[("lock_in_loop", "")],"an iterating lock() is not a retry loop",),+ (+ "fun f(items: List<S>) {\n items.forEach { it.withLock { } }\n}\n",+ [],+ "the forEach element's own lock via implicit it",+ ),+ (+ "fun f(ss: List<S>) {\n for (s in ss) s.withLock { }\n ss.forEach { x -> x.lock.lock() }\n}\n",+ [],+ "the for element and a named lambda parameter own their locks",+ ),+ (+ "fun f(m: Map<K, S>) {\n for ((k, s) in m) synchronized(s) { }\n}\n",+ [],+ "a destructured element passed to synchronized",+ ),+ (+ "fun f(ss: List<S>) {\n ss.forEach { lock.withLock { } }\n for (s in ss) synchronized(this) { }\n}\n",+ [("lock_in_loop", ""), ("lock_in_loop", "")],+ "a shared lock taken per element still fires",+ ),]