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(perf): a lock acquisition's own retry loop is not lock_in_loop (#2981)

Raghav Chamadiya246ebf8cc558
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.py
index 63b09156d..fc1f16238 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
@@ -232,6 +232,26 @@ def _enclosing_loop_iterables(
return names
+def _is_lock_acquire_spin(
+ node: Node,
+ func: str | None,
+ dialect: BasePerfDialect,
+ loop_kinds: frozenset[str],
+ fn_kinds: frozenset[str],
+) -> bool:
+ """Is *node* inside the unbounded retry loop of a lock-acquiring function?
+
+ Only the nearest enclosing loop counts: a per-item loop nested in (or
+ instead of) the spin loop still takes a lock per iteration.
+ """
+ cur = node.parent
+ while cur is not None and cur.type not in fn_kinds:
+ if cur.type in loop_kinds and cur.is_named:
+ return dialect.is_lock_acquire_spin(func, cur)
+ cur = cur.parent
+ return False
+
+
def _enclosing_loops(
node: Node, dialect: BasePerfDialect, loop_kinds: frozenset[str], fn_kinds: frozenset[str]
) -> list[Node]:
@@ -668,6 +688,10 @@ def _collect_perf_hits(
if do_loop_call_marker
else None
)
+ if marker == "lock_in_loop" and _is_lock_acquire_spin(
+ call_node, next_func, dialect, loop_kinds, fn_kinds
+ ):
+ marker = None
if marker is not None:
hits.append(
PerfHit(
@@ -729,6 +753,10 @@ def _collect_perf_hits(
)
elif do_loop_stmt_marker:
sm = dialect.loop_stmt_marker(node, list_names)
+ if sm == "lock_in_loop" and _is_lock_acquire_spin(
+ node, next_func, dialect, loop_kinds, fn_kinds
+ ):
+ sm = None
if sm is not None:
hits.append(
PerfHit(
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py
index 2779ea451..90874141a 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py
@@ -70,6 +70,7 @@ pillar depends on.
from __future__ import annotations
+import re
from typing import TYPE_CHECKING, ClassVar
if TYPE_CHECKING:
@@ -727,6 +728,20 @@ class BasePerfDialect:
"""
return frozenset()
+ # Functions that ARE a lock acquisition, and the header of an unbounded
+ # retry loop in this language. A spin loop inside such a function is how the
+ # lock gets taken (tryLock retry, CAS spin): there is nothing to hoist. Both
+ # default empty, so a language that sets neither changes nothing.
+ lock_acquire_functions: frozenset[str] = frozenset()
+ spin_loop_header: re.Pattern[str] | None = None
+
+ def is_lock_acquire_spin(self, func: str | None, loop: Node) -> bool:
+ """True when *loop* is an unbounded spin loop inside a lock-acquiring *func*."""
+ if self.spin_loop_header is None or (func or "").lower() not in self.lock_acquire_functions:
+ return False
+ head = (loop.text or b"")[:64].decode("utf-8", "replace")
+ return bool(self.spin_loop_header.match(head))
+
def is_lock_scope(self, node: Node) -> bool:
"""True if *node* opens a block-scoped held-lock region.
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/java.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/java.py
index a55809818..65d814b13 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/java.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/java.py
@@ -157,6 +157,9 @@ JAVA_RESOURCE_CTORS: frozenset[str] = frozenset({"RestTemplate", "OkHttpClient"}
JAVA_RESOURCE_METHODS: frozenset[str] = frozenset({"getConnection"})
# ``java.util.concurrent.locks.Lock`` acquisition (the contention side only).
JAVA_LOCK_METHODS: frozenset[str] = frozenset({"lock", "lockInterruptibly"})
+# A function of these names takes the lock; ``while (true)`` / ``for (;;)`` is its retry loop.
+JAVA_LOCK_ACQUIRE_FUNCTIONS: frozenset[str] = frozenset({"lock", "lockinterruptibly", "trylock"})
+JAVA_SPIN_LOOP_HEADER = re.compile(r"while\s*\(\s*true\s*\)|for\s*\(\s*;\s*;\s*\)")
# ``Lists.partition`` / ``ListUtils.partition`` / ``Iterables.partition`` and
# hand-rolled peers, matched on the call's method name (the receiver is not
# gated: a local helper counts too).
@@ -217,6 +220,8 @@ def _receiver_root(receiver: str) -> str:
class JavaPerfDialect(BasePerfDialect):
language = "java"
+ lock_acquire_functions = JAVA_LOCK_ACQUIRE_FUNCTIONS
+ spin_loop_header = JAVA_SPIN_LOOP_HEADER
markers = frozenset(
{
"io_in_loop",
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/kotlin.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/kotlin.py
index fa2019c0e..2794df692 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/kotlin.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/kotlin.py
@@ -48,9 +48,11 @@ from .java import (
AMBIGUOUS_DB,
FILES_METHODS,
FS_CONSTRUCTORS,
+ JAVA_LOCK_ACQUIRE_FUNCTIONS,
JAVA_LOCK_METHODS,
JAVA_RESOURCE_CTORS,
JAVA_RESOURCE_METHODS,
+ JAVA_SPIN_LOOP_HEADER,
NET_CONSTRUCTORS,
RECEIVER_DB_METHODS,
REST_TEMPLATE_METHODS,
@@ -200,6 +202,8 @@ def _callee(call_node: Node) -> Node | None:
class KotlinPerfDialect(BasePerfDialect):
language = "kotlin"
+ lock_acquire_functions = JAVA_LOCK_ACQUIRE_FUNCTIONS
+ spin_loop_header = JAVA_SPIN_LOOP_HEADER
markers = frozenset(
{
"io_in_loop",
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/python.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/python.py
index fde2fea9a..f1a821a40 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/python.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/python.py
@@ -195,6 +195,8 @@ _PY_MODEL_NAME_RE = re.compile(r"^[A-Z]\w*[a-z]\w*$")
class PythonPerfDialect(BasePerfDialect):
language = "python"
+ lock_acquire_functions = frozenset({"acquire", "__enter__"})
+ spin_loop_header = re.compile(r"while\s+True\s*:")
markers = frozenset(
{
"io_in_loop",
diff --git a/tests/unit/health/test_perf_dialects.py b/tests/unit/health/test_perf_dialects.py
index 8e83920bc..9b52a88b8 100644
--- a/tests/unit/health/test_perf_dialects.py
+++ b/tests/unit/health/test_perf_dialects.py
@@ -56,6 +56,26 @@ def test_java_fixture_counts():
_JAVA_CASES = [
+ (
+ "class A{void lock(){for(;;){ if(l.tryLock(1,T)) return; l.lock(); }}}",
+ [],
+ "the retry loop inside lock() is the acquisition itself",
+ ),
+ (
+ "class A{void m(java.util.List<String> ks){for(String k:ks){ l.lock(); }}}",
+ [("lock_in_loop", "")],
+ "a lock taken per item in an ordinary method still fires",
+ ),
+ (
+ "class A{void lockAll(java.util.List<Object> ks){for(Object k:ks){ locks.get(k).lock(); }}}",
+ [("lock_in_loop", "")],
+ "a lock() that iterates over items takes a lock per item",
+ ),
+ (
+ "class A{void lock(java.util.List<Object> ks){for(;;){ for(Object k:ks){ locks.get(k).lock(); } return; }}}",
+ [("lock_in_loop", "")],
+ "a per-item loop nested in the spin loop still locks per item",
+ ),
(
"class A{void m(java.util.List<String> ids){"
"for(String id:ids){ this.repo.findById(id); }}}",
@@ -1376,6 +1396,17 @@ _KOTLIN_CASES = [
[("lock_in_loop", "")],
"a lock taken every iteration is a contention site",
),
+ (
+ "class A {\n fun lock() {\n while (true) {\n"
+ " if (mutex.tryLock()) return\n mutex.lock()\n }\n }\n}\n",
+ [],
+ "the retry loop inside lock() is the acquisition, not a lock taken per item",
+ ),
+ (
+ "class A {\n fun lock(ks: List<Any>) {\n for (k in ks) {\n locks[k].lock()\n }\n }\n}\n",
+ [("lock_in_loop", "")],
+ "an iterating lock() is not a retry loop",
+ ),
]
@@ -1752,3 +1783,10 @@ def test_cpp_same_collection_nested_range_for_fact():
fc = walk_file("t.cpp", "cpp", src.encode())
assert any(f.nested_loop_line for f in fc.perf_fn_facts)
assert not any(h.kind == "nested_loop_quadratic" for h in fc.perf_hits)
+
+
+def test_python_acquire_spin_vs_per_item():
+ spin = "def acquire(self):\n while True:\n if self.flag.acquire(False):\n return\n"
+ assert _hits("python", spin) == []
+ each = "def acquire(self, items):\n for i in items:\n self.locks[i].acquire()\n"
+ assert _hits("python", each) == [("lock_in_loop", "")]