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(perf): a C# task awaited earlier in the method does not block on .Result (#2823)
Raghav Chamadiya07d3d7b83afe
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 6c71a3c83..9c754de8a 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@@ -509,7 +509,7 @@ def _collect_perf_hits(lock_targets[method] = lineif do_blocking and in_async and not awaited:api = dialect.blocking_sync_api(root_name, method)- if api is not None:+ if api is not None and not dialect.task_already_complete(call_node):hits.append(PerfHit("blocking_sync_in_async", line, next_func, api, func_start=next_start@@ -519,7 +519,7 @@ def _collect_perf_hits(if do_blocking and in_async:# A non-call member read that blocks in async (C# ``task.Result``).mem = dialect.async_blocking_member(node)- if mem is not None:+ if mem is not None and not dialect.task_already_complete(node):hits.append(PerfHit("blocking_sync_in_async",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.pyindex cf36f4010..673c91bcc 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@@ -46,6 +46,10 @@ byte unchanged:``x in big_list`` membership test).``async_blocking_member(node)`` a non-call member read that blocks in async(C# ``task.Result``).+``task_already_complete(node)`` the blocking read/call targets a task already+ awaited earlier in the method (C# ``.Result``+ after ``await Task.WhenAll(t)``), so it does+ not block.``list_bound_names(root)`` names provably bound to a list literal /comprehension in this file — the gate for the``membership_test_against_list_in_loop`` marker.@@ -614,6 +618,13 @@ class BasePerfDialect:"""return None+ def task_already_complete(self, node: Node) -> bool:+ """True if the blocking ``node`` (a ``blocking_sync_api`` call or an+ ``async_blocking_member`` read) targets a task that is provably complete+ because it was awaited earlier in the same method. Default ``False``.+ """+ return False+def unbounded_read_bound_methods(self) -> frozenset[str]:"""Method names anywhere in a chain that prove a DB read is bounded.diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/csharp.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/csharp.pyindex 6d8477524..77a16ab9d 100644--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/csharp.py+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/csharp.py@@ -324,6 +324,36 @@ class CSharpPerfDialect(BasePerfDialect):return False # invocation / element access / this -> not a type pathreturn False+ def task_already_complete(self, node: Node) -> bool:+ """True if the ``.Result`` / ``.Wait()`` / ``.GetAwaiter().GetResult()``+ receiver is a local task already awaited earlier in the method.++ ``await Task.WhenAll(a, b); var x = a.Result;`` is the idiomatic way to+ read results after a fan-out: the task is complete, so nothing blocks.+ Counted as awaited: ``await t``, ``await Task.WhenAll(..t..)``, a+ ``WhenAll`` over a collection ``t`` was added to (``c.Add(t)``) or built+ from (``c = new[] { t }``), and ``var t = await Task.WhenAny(...)``.+ Only an ``await`` in an earlier plain statement of the same or an+ enclosing block counts, so one inside an ``if`` / loop / ``try`` that+ may not run does not suppress the hit.+ """+ name = _task_receiver_name(node)+ if name is None:+ return False+ blocks: list[tuple[Node, Node]] = [] # (block, child holding the read)+ cur = node+ while cur.parent is not None and cur.type not in _CS_FN_KINDS:+ if cur.parent.type == "block":+ blocks.append((cur.parent, cur))+ cur = cur.parent+ for block, holder in blocks:+ for stmt in block.named_children:+ if stmt.start_byte >= holder.start_byte:+ break+ if stmt.type in _CS_PLAIN_STMTS and _stmt_awaits(stmt, name, cur):+ return True+ return False+def loop_call_marker(self, root: str, method: str, node: Node, list_names: frozenset[str]) -> str | None:@@ -349,4 +379,153 @@ class CSharpPerfDialect(BasePerfDialect):return None+# Function-like scopes: an ``await`` outside the one holding the read says+# nothing about it, and an ``await`` inside a nested lambda may never run.+_CS_FN_KINDS: frozenset[str] = frozenset(+ {+ "method_declaration",+ "local_function_statement",+ "lambda_expression",+ "anonymous_method_expression",+ "constructor_declaration",+ "accessor_declaration",+ "operator_declaration",+ }+)+# Statements that run unconditionally once reached (no nested branch).+_CS_PLAIN_STMTS: frozenset[str] = frozenset({"expression_statement", "local_declaration_statement"})+++def _text(node: Node | None) -> str:+ return (node.text or b"").decode("utf-8", "replace") if node is not None else ""+++def _member_name(node: Node | None) -> str:+ if node is None or node.type != "member_access_expression":+ return ""+ return _text(node.child_by_field_name("name"))+++def _member_object(node: Node | None) -> Node | None:+ return node.child_by_field_name("expression") if node is not None else None+++def _strip_configure_await(node: Node | None) -> Node | None:+ # ``await x.ConfigureAwait(false)`` awaits ``x``.+ if node is not None and node.type == "invocation_expression":+ fn = node.child_by_field_name("function")+ if _member_name(fn) == "ConfigureAwait":+ return _member_object(fn)+ return node+++def _task_receiver_name(node: Node) -> str | None:+ """The local identifier the blocking read/call is made on, else ``None``."""+ if node.type == "member_access_expression": # ``t.Result``+ recv = _member_object(node)+ elif node.type == "invocation_expression": # ``t.Wait()`` / ``t.GetAwaiter().GetResult()``+ fn = node.child_by_field_name("function")+ recv = _member_object(fn)+ if (+ _member_name(fn) == "GetResult"+ and recv is not None+ and recv.type == "invocation_expression"+ and _member_name(recv.child_by_field_name("function")) == "GetAwaiter"+ ):+ recv = _member_object(recv.child_by_field_name("function"))+ else:+ return None+ return _text(recv) if recv is not None and recv.type == "identifier" else None+++def _iter_scope(node: Node):+ """DFS over *node*'s subtree, not entering nested function scopes."""+ stack = [node]+ while stack:+ cur = stack.pop()+ yield cur+ stack.extend(c for c in cur.named_children if c.type not in _CS_FN_KINDS)+++def _mentions(node: Node | None, name: str) -> bool:+ return node is not None and any(+ n.type == "identifier" and _text(n) == name for n in _iter_scope(node)+ )+++def _collection_holds(scope: Node, coll: str, name: str, before: int) -> bool:+ """True if collection ``coll`` got task ``name`` before byte *before*.++ Approximation: ``coll.Add(..name..)`` anywhere earlier in the method (even+ inside a branch), or a ``coll`` declaration / assignment whose right side+ mentions ``name``. Tighten to straight-line adds if a branch-guarded+ ``Add`` ever turns out to hide a real block.+ """+ for n in _iter_scope(scope):+ if n.start_byte >= before:+ continue+ if n.type == "invocation_expression":+ fn = n.child_by_field_name("function")+ if (+ _member_name(fn) == "Add"+ and _text(_member_object(fn)) == coll+ and _mentions(n.child_by_field_name("arguments"), name)+ ):+ return True+ elif n.type == "variable_declarator":+ if _text(n.child_by_field_name("name")) == coll and any(+ _mentions(c, name) for c in n.named_children[1:]+ ):+ return True+ elif n.type == "assignment_expression":+ if _text(n.child_by_field_name("left")) == coll and _mentions(+ n.child_by_field_name("right"), name+ ):+ return True+ return False+++def _awaited_operand(node: Node | None) -> Node | None:+ if node is None or node.type != "await_expression" or not node.named_children:+ return None+ return _strip_configure_await(node.named_children[-1])+++def _stmt_awaits(stmt: Node, name: str, scope: Node) -> bool:+ """True if plain statement *stmt* completes task ``name`` by awaiting it."""+ for n in _iter_scope(stmt):+ if n.type == "variable_declarator" and _text(n.child_by_field_name("name")) == name:+ # ``var t = await Task.WhenAny(...)``: the returned task is complete.+ op = _awaited_operand(n.named_children[-1])+ if (+ op is not None+ and op.type == "invocation_expression"+ and _member_name(op.child_by_field_name("function")) == "WhenAny"+ ):+ return True+ target = _awaited_operand(n)+ if target is None:+ continue+ if target.type == "identifier":+ if _text(target) == name:+ return True+ continue+ if target.type != "invocation_expression":+ continue+ if _member_name(target.child_by_field_name("function")) != "WhenAll":+ continue+ args = target.child_by_field_name("arguments")+ for arg in args.named_children if args is not None else ():+ expr = arg.named_children[-1] if arg.named_children else None+ if expr is None:+ continue+ if expr.type != "identifier": # inline ``WhenAll(new[] { a, b })``+ if _mentions(expr, name):+ return True+ continue+ if _text(expr) == name or _collection_holds(scope, _text(expr), name, stmt.start_byte):+ return True+ return False++DIALECT = CSharpPerfDialect()diff --git a/tests/unit/health/test_perf_dialects.py b/tests/unit/health/test_perf_dialects.pyindex 935478521..e959e9863 100644--- a/tests/unit/health/test_perf_dialects.py+++ b/tests/unit/health/test_perf_dialects.py@@ -351,6 +351,57 @@ def test_csharp_task_result_chained_read_still_blocks():)+def _csharp_async(body: str) -> list[tuple[str, str]]:+ src = (+ "class A{ async System.Threading.Tasks.Task M(bool c){ "+ "var t = F(); var u = G(); " + body + " }}"+ )+ return [h for h in _hits("csharp", src) if h[0] == "blocking_sync_in_async"]+++_AWAITED_BEFORE_READ = [+ ("await t; var r = t.Result;", "direct await"),+ ("await t.ConfigureAwait(false); var r = t.Result;", "ConfigureAwait"),+ ("await Task.WhenAll(t, u); var r = t.Result;", "WhenAll args"),+ ("await Task.WhenAll(t, u); var r = t.Result.Items;", "chained read after WhenAll"),+ (+ "var l = new List<Task>(); l.Add(t); l.Add(u); await Task.WhenAll(l); var r = t.Result;",+ "WhenAll over a list the task was added to",+ ),+ ("var a = new[] { t, u }; await Task.WhenAll(a); var r = t.Result;", "array initializer"),+ ("await Task.WhenAll(new[] { t, u }); var r = u.Result;", "inline array"),+ ("var d = await Task.WhenAny(t, u); var r = d.Result;", "task returned by WhenAny"),+ ("await Task.WhenAll(t, u); t.GetAwaiter().GetResult();", "GetAwaiter().GetResult()"),+ ("await t; if (c) { var r = t.Result; }", "read in a branch after a straight-line await"),+]+++ "body", [c[0] for c in _AWAITED_BEFORE_READ], ids=[c[1] for c in _AWAITED_BEFORE_READ]+)+def test_csharp_result_after_await_not_blocking(body):+ """A task awaited earlier in the method is complete: ``.Result`` does not block."""+ assert _csharp_async(body) == []+++_NOT_AWAITED_BEFORE_READ = [+ ("var r = t.Result;", "no await at all"),+ ("if (c) { await t; } var r = t.Result;", "await inside a branch that may not run"),+ ("await u; var r = t.Result;", "a different task was awaited"),+ ("await Task.WhenAll(u); var r = t.Result;", "WhenAll without the task"),+ ("var r = t.Result; await t;", "await after the read"),+ ("await Task.WhenAny(t, u); var r = t.Result;", "WhenAny argument may still run"),+ ("System.Action f = async () => await t; var r = t.Result;", "await inside a lambda"),+]+++ "body", [c[0] for c in _NOT_AWAITED_BEFORE_READ], ids=[c[1] for c in _NOT_AWAITED_BEFORE_READ]+)+def test_csharp_result_without_prior_await_still_blocks(body):+ assert _csharp_async(body) == [("blocking_sync_in_async", ".Result")]++def test_go_sql_rows_scan_not_io_in_loop():"""``rows.Scan`` inside ``for rows.Next()`` is a cursor decode, not a sink.