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): cut false performance flags around closures, scope, and worker pools (#735)

Swati Ahuja270ec41b7837
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 3b9830a25..6ec243f16 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
@@ -87,6 +87,23 @@ _HOT_PATH_SINK_KINDS = frozenset({"subprocess", "filesystem"})
# expression (``synchronized(repo.find(id)){…}``) runs BEFORE the lock is taken.
_LOCK_BODY_KINDS = frozenset({"block", "statement_block", "compound_statement"})
+# Non-semantic wrapper nodes tree-sitter inserts between a ``call`` and its
+# enclosing ``await`` — parenthesising an awaited call (``await (foo())``) adds a
+# ``parenthesized_expression`` hop, so the immediate-parent ``await`` check would
+# miss it and wrongly read the call as un-awaited. Walk up through these before
+# testing for ``await``.
+_AWAIT_WRAPPER_KINDS = frozenset({"parenthesized_expression"})
+
+
+def _is_awaited(node: Node) -> bool:
+ """Whether ``node`` is (transitively, through parenthesising wrappers) the
+ operand of an ``await``. Mirrors the old immediate-parent substring test but
+ first skips non-semantic wrappers so ``await (foo())`` reads as awaited."""
+ parent = node.parent
+ while parent is not None and parent.type in _AWAIT_WRAPPER_KINDS:
+ parent = parent.parent
+ return parent is not None and "await" in parent.type
+
def _perf_func_name(node: Node) -> str | None:
if node.type == "function_body":
@@ -213,6 +230,17 @@ def _collect_perf_hits(
entering_fn = t in fn_kinds or t in lambda_kinds
is_async_fn = t in async_fn_kinds or (entering_fn and dialect.is_async_fn(node))
next_async = True if is_async_fn else (False if entering_fn else in_async)
+ # A nested function/lambda opens a new execution scope: its body is not
+ # run per outer-loop-iteration nor while an outer lock is held (it is
+ # merely DEFINED here — it runs whenever/wherever it is later invoked).
+ # Reset both depths at the boundary, mirroring ``next_async``; the
+ # closure's OWN loops/locks still count from its own body.
+ # Ceiling: a closure INVOKED inline in the loop (``(lambda: io())()`` /
+ # Go's ``func(){…}()`` IIFE) does run per-iteration, but we do not detect
+ # inline invocation, so those are cleared too — accepted (favouring
+ # precision), and the Go IIFE case is the idiomatic defer-in-loop fix.
+ next_loop_depth = 0 if entering_fn else loop_depth
+ next_lock_depth = 0 if entering_fn else lock_depth
next_func = func_name
next_start = func_start
if t in fn_kinds:
@@ -248,8 +276,7 @@ def _collect_perf_hits(
if t in call_kinds:
method = dialect.callee_method_name(node) or ""
root_name = dialect.callee_root_name(node) or ""
- parent = node.parent
- awaited = parent is not None and "await" in parent.type
+ awaited = _is_awaited(node)
line = node.start_point[0] + 1
if do_bare_call_marker:
# A call that is its own iteration construct (``.reduce`` with an
@@ -406,32 +433,42 @@ def _collect_perf_hits(
# NB: tree-sitter Node wrappers are not singletons, so compare
# with ``==`` (identity by tree + byte range), never ``is``.
for c in node.children:
- cd = loop_depth + 1 if c == body else loop_depth
+ cd = next_loop_depth + 1 if c == body else next_loop_depth
stack.append(
- (c, cd, next_async, next_func, next_start, lock_depth, next_outer_iter)
+ (c, cd, next_async, next_func, next_start, next_lock_depth, next_outer_iter)
)
else:
for c in node.children:
stack.append(
(
c,
- loop_depth + 1,
+ next_loop_depth + 1,
next_async,
next_func,
next_start,
- lock_depth,
+ next_lock_depth,
next_outer_iter,
)
)
elif entering_lock:
# Raise lock_depth for the body block only (not the lock-object expr).
for c in node.children:
- cl = lock_depth + 1 if c.type in _LOCK_BODY_KINDS else lock_depth
- stack.append((c, loop_depth, next_async, next_func, next_start, cl, outer_iter))
+ cl = next_lock_depth + 1 if c.type in _LOCK_BODY_KINDS else next_lock_depth
+ stack.append(
+ (c, next_loop_depth, next_async, next_func, next_start, cl, outer_iter)
+ )
else:
for c in node.children:
stack.append(
- (c, loop_depth, next_async, next_func, next_start, lock_depth, outer_iter)
+ (
+ c,
+ next_loop_depth,
+ next_async,
+ next_func,
+ next_start,
+ next_lock_depth,
+ outer_iter,
+ )
)
# Dedup chained sinks: ``result.scalars().all()`` parses as two call nodes
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.py
index da639813e..d619615e1 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
@@ -239,9 +239,138 @@ class GoPerfDialect(BasePerfDialect):
# a RANGE loop — a bare ``for {}`` accept loop or a ``for cond`` cursor
# spawns one-per-event (idiomatic), so it is excluded.
if node.type == "go_statement" and self._nearest_for_is_range(node):
+ # A preceding send to a locally-declared buffered channel
+ # (``sem <- struct{}{}`` where ``sem := make(chan T, N)``, N>0) is the
+ # canonical worker-pool bound: the send blocks once N are in flight,
+ # so the spawn is NOT unbounded. Suppress the finding.
+ if self._bounded_by_semaphore(node):
+ return None
return "goroutine_in_unbounded_loop"
return None
+ def _bounded_by_semaphore(self, go_node: Node) -> bool:
+ """True if the spawn is guarded by a genuine buffered-channel semaphore.
+
+ The idiom is: acquire before the spawn (``sem <- struct{}{}`` in the loop
+ body, which blocks once N are in flight) and release inside the goroutine
+ (``defer func(){ <-sem }()``). A results/work channel that is only *sent*
+ to and drained elsewhere bounds nothing, so we require the SAME buffered
+ channel to also be RECEIVED FROM (``<-sem``) inside the goroutine body —
+ that receive is what distinguishes a semaphore from a plain send target.
+ """
+ block = go_node.parent
+ if block is None:
+ return False
+ chan_names: set[str] = set()
+ for sib in block.children:
+ # NB: tree-sitter Node wrappers are not singletons — compare by ==.
+ if sib == go_node:
+ break
+ if sib.type == "send_statement":
+ ch = sib.child_by_field_name("channel")
+ if ch is None:
+ ch = next((c for c in sib.children if c.is_named), None)
+ if ch is not None and ch.type == "identifier" and ch.text is not None:
+ chan_names.add(ch.text.decode("utf-8", "replace"))
+ if not chan_names:
+ return False
+ body = self._goroutine_body(go_node)
+ if body is None:
+ return False
+ return any(
+ self._is_buffered_channel(go_node, name) and self._channel_received_in(body, name)
+ for name in chan_names
+ )
+
+ @staticmethod
+ def _goroutine_body(go_node: Node) -> Node | None:
+ """The ``func_literal`` body of ``go func(){…}()`` — the first func_literal
+ under the go statement (its ``<-sem`` release lives here)."""
+ stack: list[Node] = [go_node]
+ while stack:
+ n = stack.pop()
+ if n.type == "func_literal":
+ return n
+ stack.extend(n.children)
+ return None
+
+ @staticmethod
+ def _channel_received_in(node: Node, name: str) -> bool:
+ """True if ``<-name`` (a channel receive) appears anywhere under ``node``."""
+ stack: list[Node] = [node]
+ while stack:
+ n = stack.pop()
+ if n.type == "unary_expression" and any(c.type == "<-" for c in n.children):
+ operand = n.child_by_field_name("operand")
+ if operand is None:
+ operand = next((c for c in n.children if c.is_named), None)
+ if (
+ operand is not None
+ and operand.type == "identifier"
+ and operand.text is not None
+ and operand.text.decode("utf-8", "replace") == name
+ ):
+ return True
+ stack.extend(n.children)
+ return False
+
+ def _is_buffered_channel(self, go_node: Node, name: str) -> bool:
+ """True if ``name`` is bound to a ``make(chan T, N)`` (N>0) anywhere in
+ the enclosing function. Reuses the ``func_literal`` /
+ ``function_declaration`` / ``method_declaration`` boundary walk that
+ ``_nearest_for_is_range`` uses to find the enclosing function scope."""
+ scope: Node | None = go_node.parent
+ while scope is not None and scope.type not in (
+ "function_declaration",
+ "method_declaration",
+ "func_literal",
+ ):
+ scope = scope.parent
+ if scope is None:
+ scope = go_node
+ while scope.parent is not None:
+ scope = scope.parent
+ stack: list[Node] = [scope]
+ while stack:
+ n = stack.pop()
+ if n.type in ("short_var_declaration", "assignment_statement"):
+ left = n.child_by_field_name("left")
+ right = n.child_by_field_name("right")
+ if left is not None and right is not None:
+ left_names = {
+ c.text.decode("utf-8", "replace")
+ for c in left.children
+ if c.type == "identifier" and c.text is not None
+ }
+ if name in left_names and any(
+ self._is_buffered_make(c) for c in right.children if c.is_named
+ ):
+ return True
+ stack.extend(n.children)
+ return False
+
+ @staticmethod
+ def _is_buffered_make(call: Node) -> bool:
+ """True if ``call`` is ``make(chan T, N)`` with a positive buffer size."""
+ if call.type != "call_expression":
+ return False
+ fn = call.child_by_field_name("function")
+ if fn is None or fn.text is None or fn.text.decode("utf-8", "replace") != "make":
+ return False
+ args = call.child_by_field_name("arguments")
+ if args is None:
+ return False
+ named = [c for c in args.children if c.is_named]
+ if len(named) < 2 or named[0].type != "channel_type":
+ return False
+ size = named[1]
+ if size.type != "int_literal" or size.text is None:
+ return False
+ try:
+ return int(size.text.decode("utf-8", "replace")) > 0
+ except ValueError:
+ return False
+
@staticmethod
def _nearest_for_is_range(node: Node) -> bool:
"""True if the nearest enclosing ``for`` loop ranges over a COLLECTION.
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 a7ceb0101..e2a7ac06f 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
@@ -161,7 +161,10 @@ class PythonPerfDialect(BasePerfDialect):
return "filesystem"
if method == "urlopen":
return "network"
- if root_kind == "network" and method in HTTP_VERBS:
+ if is_attribute and root_kind == "network" and method in HTTP_VERBS:
+ # ``requests.get(...)`` is a member call on an imported client; a bare
+ # ``get(...)`` (e.g. a builtin/local) never has the verb-call shape, so
+ # gate on ``is_attribute`` like the DB branches above.
return "network"
if awaited and root_kind == "network":
return "network"
@@ -314,11 +317,15 @@ class PythonPerfDialect(BasePerfDialect):
# each iteration (a fresh ``buf = [...]; buf.insert(0, x)`` is bounded,
# not O(n^2) — the same reset-per-iteration FP class as string_concat;
# Phase-7d headroom corpus).
+ # ``collections.deque.insert(0, x)`` is O(1) front-insertion by design (it
+ # is the deque's own ``appendleft`` machinery), so exclude a receiver
+ # provably constructed via ``deque()`` / ``collections.deque(...)``.
if (
method == "insert"
and self.callee_is_attribute(node)
and self._first_arg_is_zero(node)
and not self._receiver_reset_in_loop(node, root)
+ and not self._receiver_bound_to_deque(node, root)
):
return "list_insert_zero_in_loop"
# ``pd.concat([acc, chunk])`` / ``pandas.concat(...)`` in a loop copies
@@ -335,19 +342,43 @@ class PythonPerfDialect(BasePerfDialect):
``itertuples`` / ``to_dict`` when row access is unavoidable). The call
sits in the loop header, so the body ``loop_call_marker`` misses it.
Gated to the distinctive method name on a member-access receiver
- (``x.iterrows()``, never a bare ``iterrows(...)``) — high-precision by
- construction, like the ``pd``/``pandas`` ``concat`` root: ``iterrows`` is
- a pandas-only verb with no common collision.
+ (``x.iterrows()``, never a bare ``iterrows(...)``) AND to a file that
+ imports pandas (same style as the ``pd``/``pandas`` root gate in
+ ``pd_concat``). Residual limitation: this is still a name match — a
+ user-defined class with an ``iterrows`` method in a file that also
+ imports pandas would still be flagged.
"""
if node.type != "for_statement":
return None
right = node.child_by_field_name("right")
if right is None or right.type != "call":
return None
- if self.callee_method_name(right) == "iterrows" and self.callee_is_attribute(right):
+ if (
+ self.callee_method_name(right) == "iterrows"
+ and self.callee_is_attribute(right)
+ and self._file_imports_pandas(node)
+ ):
return "pandas_iterrows_in_loop"
return None
+ @staticmethod
+ def _file_imports_pandas(node: Node) -> bool:
+ """True if the enclosing file has an ``import pandas`` / ``from pandas
+ import ...`` statement (a soft gate; still a name match, see caller)."""
+ root = node
+ while root.parent is not None:
+ root = root.parent
+ stack: list[Node] = [root]
+ while stack:
+ n = stack.pop()
+ if "import" in n.type:
+ txt = (n.text or b"").decode("utf-8", "replace")
+ if "pandas" in txt:
+ return True
+ continue # imports do not nest further imports
+ stack.extend(n.children)
+ return False
+
def _receiver_reset_in_loop(self, node: Node, name: str) -> bool:
"""True if the call's receiver ``name`` is re-assigned (reset to a fresh
list) inside an enclosing loop body — so the per-front-insert is bounded
@@ -363,6 +394,46 @@ class PythonPerfDialect(BasePerfDialect):
cur = cur.parent
return False
+ def _receiver_bound_to_deque(self, node: Node, name: str) -> bool:
+ """True if the call's receiver ``name`` is bound to a ``deque()`` /
+ ``collections.deque(...)`` anywhere in the file. Mirrors the whole-tree
+ binding scan of :meth:`list_bound_names`: a scoped rewrite is out of
+ scope, so a same-named list in another scope would still be missed here —
+ acceptable, since dropping the finding only trades recall for precision.
+ """
+ if not name:
+ return False
+ root = node
+ while root.parent is not None:
+ root = root.parent
+ stack: list[Node] = [root]
+ while stack:
+ n = stack.pop()
+ if n.type == "assignment":
+ left = n.child_by_field_name("left")
+ right = n.child_by_field_name("right")
+ if (
+ left is not None
+ and left.type == "identifier"
+ and left.text is not None
+ and left.text.decode("utf-8", "replace") == name
+ and right is not None
+ and self._rhs_is_deque(right)
+ ):
+ return True
+ stack.extend(n.children)
+ return False
+
+ @staticmethod
+ def _rhs_is_deque(right: Node) -> bool:
+ if right.type != "call":
+ return False
+ fn = right.child_by_field_name("function")
+ if fn is None or fn.text is None:
+ return False
+ callee = fn.text.decode("utf-8", "replace")
+ return callee == "deque" or callee.endswith(".deque")
+
@staticmethod
def _first_arg_is_zero(node: Node) -> bool:
args = node.child_by_field_name("arguments")
@@ -424,10 +495,37 @@ class PythonPerfDialect(BasePerfDialect):
list_names.add(name)
elif self._rhs_is_nonlist_container(right):
exclude.add(name)
+ elif n.type == "parameters":
+ # A name also used as a function parameter has no proven binding
+ # inside that scope (the caller could pass a set), so it collides
+ # with an unrelated module-level list of the same name. Exclude it,
+ # mirroring the set/dict-literal exclusion above.
+ exclude.update(self._param_names(n))
for c in n.children:
stack.append(c)
return frozenset(list_names - exclude)
+ @staticmethod
+ def _param_names(params: Node) -> set[str]:
+ """The bound names declared in a ``parameters`` node (plain / typed /
+ default / splat forms), excluding any type-annotation identifiers."""
+ names: set[str] = set()
+ for p in params.children:
+ if not p.is_named:
+ continue
+ if p.type == "identifier":
+ if p.text is not None:
+ names.add(p.text.decode("utf-8", "replace"))
+ continue
+ nm = p.child_by_field_name("name")
+ if nm is None:
+ # typed_parameter has no ``name`` field: the param name is its
+ # first identifier child (the type comes after the ``:``).
+ nm = next((c for c in p.children if c.type == "identifier"), None)
+ if nm is not None and nm.text is not None:
+ names.add(nm.text.decode("utf-8", "replace"))
+ return names
+
@staticmethod
def _rhs_is_list(right: Node) -> bool:
if right.type in _PY_LIST_RHS_KINDS:
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js.py
index 3fbabb7ef..cddf66a98 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js.py
@@ -237,13 +237,54 @@ class TsJsPerfDialect(BasePerfDialect):
return first.text.decode("utf-8", "replace")
return None
+ @staticmethod
+ def _params_contain(fn: Node, name: str) -> bool:
+ """True if any parameter of ``fn`` binds ``name`` (a shadow of an outer
+ accumulator). Handles both parenthesized parameter lists and the single
+ unparenthesized ``x => …`` form."""
+ params = fn.child_by_field_name("parameters")
+ if params is not None:
+ for c in params.children:
+ ident = c if c.type == "identifier" else c.child_by_field_name("pattern")
+ if (
+ ident is not None
+ and ident.type == "identifier"
+ and ident.text is not None
+ and ident.text.decode("utf-8", "replace") == name
+ ):
+ return True
+ return False
+ first = next((c for c in fn.children if c.is_named), None)
+ return (
+ first is not None
+ and first.type == "identifier"
+ and first.text is not None
+ and first.text.decode("utf-8", "replace") == name
+ )
+
+ _FN_LITERAL_KINDS: frozenset[str] = frozenset(
+ {"arrow_function", "function", "function_expression"}
+ )
+
@staticmethod
def _spreads_name_in_collection(body: Node, name: str) -> bool:
"""True if *body* spreads ``name`` into an array / object literal
- (``[...name, x]`` / ``{...name}``) — the O(n^2) accumulator rebuild."""
+ (``[...name, x]`` / ``{...name}``) — the O(n^2) accumulator rebuild.
+
+ Stops at a nested arrow/function that re-binds ``name`` as its own
+ parameter: a spread of ``name`` inside such a scope targets THAT binding
+ (e.g. an inner ``reduce`` with its own ``acc``), not the outer
+ accumulator, so it must not be attributed to the outer reduce.
+ """
stack: list[Node] = [body]
while stack:
n = stack.pop()
+ if (
+ n != body
+ and n.type in TsJsPerfDialect._FN_LITERAL_KINDS
+ and TsJsPerfDialect._params_contain(n, name)
+ ):
+ continue
if (
n.type == "spread_element"
and n.parent is not None
diff --git a/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py b/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py
index c626129e4..9b7d85564 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py
@@ -130,6 +130,14 @@ def collect_io_names(tree_root: _NodeLike, language: str) -> dict[str, str]:
do not originate from a classified I/O library are simply absent.
"""
names: dict[str, str] = {}
+ # Names rebound by a plain local assignment (``requests = {...}``) that
+ # shadows the import. ``sink_kind`` has no call-site position, so full
+ # per-scope resolution would need a walker rewrite; instead we drop any
+ # import name that is also an assignment target *anywhere* in the file. That
+ # is coarser than true scoping (it also suppresses a genuine ``requests.get``
+ # in a file that rebinds ``requests`` elsewhere — a recall trade for
+ # precision), but closes the shadowed-receiver false flag with no new pass.
+ rebound: set[str] = set()
stack: list[_NodeLike] = [tree_root]
while stack:
node = stack.pop()
@@ -149,6 +157,15 @@ def collect_io_names(tree_root: _NodeLike, language: str) -> dict[str, str]:
if kind is not None:
for name in bound:
names.setdefault(name, kind)
+ elif node.type == "assignment":
+ # Python assignment target; ``x = ...`` shadows an imported ``x``.
+ target = (
+ node.child_by_field_name("left") if hasattr(node, "child_by_field_name") else None
+ )
+ if target is not None and target.type == "identifier" and target.text is not None:
+ rebound.add(target.text.decode("utf-8", "replace"))
for child in node.children:
stack.append(child)
+ for name in rebound:
+ names.pop(name, None)
return names
diff --git a/tests/unit/health/test_ff_track_aefg_perf.py b/tests/unit/health/test_ff_track_aefg_perf.py
new file mode 100644
index 000000000..305af6af4
--- /dev/null
+++ b/tests/unit/health/test_ff_track_aefg_perf.py
@@ -0,0 +1,289 @@
+"""False-flag regression tests for the performance perf pass + dialects.
+
+Each fixture is a counterexample the perf detectors previously mis-flagged. The
+tests drive the real collector via ``walk_file`` (which runs
+``_collect_perf_hits`` + ``get_language_map`` end to end) and the dialect marker
+methods it consumes. Every "not flagged" case is paired with a genuine-positive
+guard so the fix cannot pass by simply suppressing the whole marker.
+"""
+
+from __future__ import annotations
+
+from repowise.core.analysis.health.complexity import walk_file
+
+
+def _kinds(lang: str, ext: str, src: bytes) -> list[str]:
+ fc = walk_file(f"t.{ext}", lang, src)
+ return [h.kind for h in fc.perf_hits]
+
+
+def _hits(lang: str, ext: str, src: bytes):
+ return walk_file(f"t.{ext}", lang, src).perf_hits
+
+
+# ---------------------------------------------------------------------------
+# R1 — loop/lock depth must reset at a nested function/lambda boundary
+# ---------------------------------------------------------------------------
+
+
+def test_r1_python_closure_defined_in_loop_not_io_in_loop():
+ # ``handler`` is DEFINED in the loop but invoked elsewhere — its body does
+ # not run per outer-loop-iteration.
+ src = (
+ b"import requests\n"
+ b"def register(items, handlers):\n"
+ b" for item in items:\n"
+ b" def handler():\n"
+ b" return requests.get(item.url)\n"
+ b" handlers.append(handler)\n"
+ b" for h in handlers:\n"
+ b" h()\n"
+ )
+ assert "io_in_loop" not in _kinds("python", "py", src)
+
+
+def test_r1_python_direct_sink_in_loop_still_fires():
+ # Guard against over-suppression: a sink directly in the loop body fires.
+ src = (
+ b"import requests\ndef f(items):\n for item in items:\n requests.get(item.url)\n"
+ )
+ assert "io_in_loop" in _kinds("python", "py", src)
+
+
+def test_r1_go_iife_with_defer_not_flagged():
+ # The idiomatic ``func(){ ...; defer f.Close() }()`` loop-body wrapper — the
+ # recommended defer-in-loop fix — must not be flagged with the leak it fixes.
+ src = (
+ b"package main\n"
+ b'import "os"\n'
+ b"func processAll(items []string) {\n"
+ b" for _, item := range items {\n"
+ b" func() {\n"
+ b" f, _ := os.Open(item)\n"
+ b" defer f.Close()\n"
+ b" _ = f\n"
+ b" }()\n"
+ b" }\n"
+ b"}\n"
+ )
+ kinds = _kinds("go", "go", src)
+ assert "defer_in_loop" not in kinds
+ assert "io_in_loop" not in kinds
+
+
+def test_r1_csharp_lambda_in_lock_not_blocking_io_under_lock():
+ # ``a`` is queued inside the lock but invoked later, off the critical section.
+ src = (
+ b"using System.IO;\n"
+ b"class C {\n"
+ b" void Foo() {\n"
+ b" lock (obj) {\n"
+ b" System.Action a = () => File.ReadAllText(path);\n"
+ b" tasks.Add(a);\n"
+ b" }\n"
+ b" }\n"
+ b"}\n"
+ )
+ assert "blocking_io_under_lock" not in _kinds("csharp", "cs", src)
+
+
+def test_r1_csharp_direct_io_in_lock_still_fires():
+ # Guard: I/O executed directly inside the lock body still fires.
+ src = (
+ b"using System.IO;\n"
+ b"class C {\n"
+ b" void Foo() {\n"
+ b" lock (obj) {\n"
+ b" File.ReadAllText(path);\n"
+ b" }\n"
+ b" }\n"
+ b"}\n"
+ )
+ assert "blocking_io_under_lock" in _kinds("csharp", "cs", src)
+
+
+# ---------------------------------------------------------------------------
+# M10 — a parenthesized await must count as awaited
+# ---------------------------------------------------------------------------
+
+
+def test_m10_parenthesized_await_not_blocking():
+ src = b"import time\nasync def f():\n await (time.sleep(1))\n"
+ assert "blocking_sync_in_async" not in _kinds("python", "py", src)
+
+
+def test_m10_unawaited_sleep_still_fires():
+ src = b"import time\nasync def f():\n time.sleep(1)\n"
+ assert "blocking_sync_in_async" in _kinds("python", "py", src)
+
+
+# ---------------------------------------------------------------------------
+# R4 — deque.insert(0, x) is O(1), not O(n^2)
+# ---------------------------------------------------------------------------
+
+
+def test_r4_deque_insert_not_flagged():
+ src = (
+ b"from collections import deque\n"
+ b"def process(items):\n"
+ b" buf = deque()\n"
+ b" for x in items:\n"
+ b" buf.insert(0, x)\n"
+ b" return buf\n"
+ )
+ assert "list_insert_zero_in_loop" not in _kinds("python", "py", src)
+
+
+def test_r4_list_insert_still_flagged():
+ src = (
+ b"def process(items):\n"
+ b" buf = []\n"
+ b" for x in items:\n"
+ b" buf.insert(0, x)\n"
+ b" return buf\n"
+ )
+ assert "list_insert_zero_in_loop" in _kinds("python", "py", src)
+
+
+# ---------------------------------------------------------------------------
+# N1 — a local shadowing an I/O import is not the import
+# ---------------------------------------------------------------------------
+
+
+def test_n1_shadowed_requests_not_network():
+ src = (
+ b"import requests\n"
+ b"def build_index(pages):\n"
+ b" counts = {}\n"
+ b" for page in pages:\n"
+ b" requests = counts.setdefault(page.key, {})\n"
+ b' requests["count"] = requests.get("count", 0) + 1\n'
+ b" return counts\n"
+ )
+ assert "io_in_loop" not in _kinds("python", "py", src)
+
+
+# ---------------------------------------------------------------------------
+# N2 — a shadowing function parameter is not the module-level list
+# ---------------------------------------------------------------------------
+
+
+def test_n2_parameter_shadow_not_flagged():
+ src = (
+ b"def other_scope(big_list, items):\n"
+ b" for x in items:\n"
+ b" if x in big_list:\n"
+ b" pass\n"
+ b"\n"
+ b"big_list = [1, 2, 3]\n"
+ )
+ assert "membership_test_against_list_in_loop" not in _kinds("python", "py", src)
+
+
+def test_n2_real_module_list_membership_still_fires():
+ src = (
+ b"big_list = [1, 2, 3]\n"
+ b"def scan(items):\n"
+ b" for x in items:\n"
+ b" if x in big_list:\n"
+ b" pass\n"
+ )
+ assert "membership_test_against_list_in_loop" in _kinds("python", "py", src)
+
+
+# ---------------------------------------------------------------------------
+# N4 — iterrows needs a pandas import present
+# ---------------------------------------------------------------------------
+
+
+def test_n4_iterrows_without_pandas_not_flagged():
+ src = b"def process(qb):\n for _, row in qb.iterrows():\n handle(row)\n"
+ assert "pandas_iterrows_in_loop" not in _kinds("python", "py", src)
+
+
+def test_n4_iterrows_with_pandas_flagged():
+ src = (
+ b"import pandas\ndef process(df):\n for _, row in df.iterrows():\n handle(row)\n"
+ )
+ assert "pandas_iterrows_in_loop" in _kinds("python", "py", src)
+
+
+# ---------------------------------------------------------------------------
+# R5 — a nested reduce shadowing the accumulator must not flag the outer reduce
+# ---------------------------------------------------------------------------
+
+
+def test_r5_shadowed_nested_reduce_flags_inner_only():
+ src = (
+ b"function f(items) {\n"
+ b" return items.reduce((acc, x) => {\n"
+ b" acc.push(x);\n"
+ b" const nested = x.parts.reduce((acc, p) => [...acc, p], []);\n"
+ b" return acc;\n"
+ b" }, []);\n"
+ b"}\n"
+ )
+ hits = [h for h in _hits("typescript", "ts", src) if h.kind == "array_spread_in_reduce"]
+ # Exactly the inner reduce (line 4) fires; the outer mutate-and-return does not.
+ assert len(hits) == 1
+ assert hits[0].line == 4
+
+
+# ---------------------------------------------------------------------------
+# R6 — a semaphore-bounded goroutine spawn is not "unbounded"
+# ---------------------------------------------------------------------------
+
+
+def test_r6_semaphore_bounded_goroutine_not_flagged():
+ src = (
+ b"package main\n"
+ b'import "sync"\n'
+ b"func process(items []int) {\n"
+ b" sem := make(chan struct{}, 8)\n"
+ b" var wg sync.WaitGroup\n"
+ b" for _, item := range items {\n"
+ b" sem <- struct{}{}\n"
+ b" wg.Add(1)\n"
+ b" go func(it int) {\n"
+ b" defer wg.Done()\n"
+ b" defer func() { <-sem }()\n"
+ b" handle(it)\n"
+ b" }(item)\n"
+ b" }\n"
+ b" wg.Wait()\n"
+ b"}\n"
+ )
+ assert "goroutine_in_unbounded_loop" not in _kinds("go", "go", src)
+
+
+def test_r6_results_collector_channel_still_flagged():
+ # A buffered channel that is only SENT to (a results/work channel, drained
+ # elsewhere) bounds nothing — the spawn must still fire. The goroutine body
+ # never receives from ``results``, so it is not a semaphore.
+ src = (
+ b"package main\n"
+ b"func process(items []int) {\n"
+ b" results := make(chan int, 8)\n"
+ b" for _, item := range items {\n"
+ b" results <- item\n"
+ b" go func(it int) {\n"
+ b" handle(it)\n"
+ b" }(item)\n"
+ b" }\n"
+ b"}\n"
+ )
+ assert "goroutine_in_unbounded_loop" in _kinds("go", "go", src)
+
+
+def test_r6_unbounded_goroutine_still_flagged():
+ src = (
+ b"package main\n"
+ b"func process(items []int) {\n"
+ b" for _, item := range items {\n"
+ b" go func(it int) {\n"
+ b" handle(it)\n"
+ b" }(item)\n"
+ b" }\n"
+ b"}\n"
+ )
+ assert "goroutine_in_unbounded_loop" in _kinds("go", "go", src)
diff --git a/tests/unit/health/test_perf_dialects.py b/tests/unit/health/test_perf_dialects.py
index bde5d6710..8e2dd8add 100644
--- a/tests/unit/health/test_perf_dialects.py
+++ b/tests/unit/health/test_perf_dialects.py
@@ -490,7 +490,9 @@ def test_python_pd_concat_in_loop():
def test_python_pandas_iterrows_in_loop():
# The iterrows() call lives in the loop HEADER, so the body call-markers
# never see it — the loop_iterable_call_marker hook fires on the loop node.
- iterrows = "def f(df):\n for _, row in df.iterrows():\n use(row)\n"
+ # Soft-gated on a pandas import present in the file (a bare .iterrows() with
+ # no pandas import is now treated as a name collision, not a DataFrame).
+ iterrows = "import pandas\ndef f(df):\n for _, row in df.iterrows():\n use(row)\n"
assert ("pandas_iterrows_in_loop", "") in _hits("python", iterrows)
# itertuples is the recommended faster alternative — never flagged.
tuples = "def f(df):\n for row in df.itertuples():\n use(row)\n"