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): eliminate three perf-detector false-positive classes across C#/Go/Python (#540)

Raghav Chamadiya5fbf82d99323
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.md
index f15c10df3..135875425 100644
--- a/docs/CODE_HEALTH.md
+++ b/docs/CODE_HEALTH.md
@@ -212,9 +212,13 @@ db/network/filesystem/subprocess lexicons and the per-language precision hazards
documented in `local-stash/performance-pillar/PHASE6_PLAN.md`. The verb sets are
gated for precision: distinctive sinks (EF `*Async`, Spring-Data `findBy*`, JDBC
`executeQuery`) fire on name alone, while ambiguous verbs require file-level
-db-import evidence (MEDIUM precision; formal per-language OSS precision gates are
-a tracked follow-up, and until they land the markers stay advisory under the
-bounded `performance` cap).
+db-import evidence. **`io_in_loop` is validated across languages** on an 11-repo
+OSS corpus: Go 96.7%, TypeScript 100%, Python 96.2% hand-labeled precision; the
+`blocking_sync_in_async` C# `.Result`/Result-pattern collision and the Go
+`*sql.Rows.Scan` cursor FP were caught and fixed by that validation. `nested_loop_quadratic`
+measured below the bar in every language (centrality gates volume, not shape) and
+stays advisory-only, as does `blocking_io_under_lock` (rare-by-good-practice: zero
+corpus instances even on concurrency-heavy Java).
**Soundness limits (honest, by design).** Performance is a *static* signal, so
it under-reports rather than over-reports (these cap recall, not precision):
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.py
index 21d9804db..9369b2826 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
@@ -257,9 +257,72 @@ class CSharpPerfDialect(BasePerfDialect):
if node.type != "member_access_expression":
return None
nm = node.child_by_field_name("name")
- if nm is not None and nm.text and nm.text.decode("utf-8", "replace") == "Result":
- return ".Result"
- return None
+ if nm is None or not nm.text or nm.text.decode("utf-8", "replace") != "Result":
+ return None
+ # ``.Result`` collides hard with the ubiquitous Result-pattern
+ # (Ardalis.Result / FluentResults / custom ``Result<T>`` DTOs), which is
+ # NOT a ``Task`` and does not block. Two precision-first guards (Phase-7c
+ # C# corpus: 10/12 FPs were ``Ardalis.Result.ResultStatus.X``, 1 a write):
+ # NOTE: py-tree-sitter returns fresh Node wrappers per call, so compare
+ # by byte span (``_same_span``), never identity.
+ parent = node.parent
+ # ``Ardalis.Result.ResultStatus`` — ``.Result`` is an INTERMEDIATE segment
+ # of a longer qualified NAMESPACE/TYPE path, not a Task block. The shape
+ # ``X.Result.Y`` is identical to a genuine ``itemGetTask.Result.CatalogItem``
+ # chained read, so we additionally require the receiver root to be
+ # type-like (PascalCase): a Task is virtually always read off a camelCase
+ # local / param / field, while ``Ardalis`` / ``FluentResults`` are
+ # PascalCase namespaces.
+ if (
+ parent is not None
+ and parent.type == "member_access_expression"
+ and self._same_span(parent.child_by_field_name("expression"), node)
+ and self._receiver_root_is_typelike(node)
+ ):
+ return None
+ # ``response.Result = ...`` — a WRITE to a DTO property, not a blocking
+ # read of ``Task.Result``.
+ if (
+ parent is not None
+ and parent.type == "assignment_expression"
+ and self._same_span(parent.child_by_field_name("left"), node)
+ ):
+ return None
+ return ".Result"
+
+ @staticmethod
+ def _same_span(a: Node | None, b: Node | None) -> bool:
+ return (
+ a is not None
+ and b is not None
+ and a.start_byte == b.start_byte
+ and a.end_byte == b.end_byte
+ )
+
+ @staticmethod
+ def _receiver_root_is_typelike(node: Node) -> bool:
+ """True if the receiver of ``.Result`` is a PascalCase qualified-name path.
+
+ Walks the ``expression`` (object) side of the ``.Result`` member access
+ down to its leftmost identifier; returns True only when that root is a
+ plain identifier starting with an uppercase letter (a namespace / type,
+ e.g. ``Ardalis`` in ``Ardalis.Result.ResultStatus``). A method-call
+ receiver (``GetAsync(id).Result``) or a camelCase local
+ (``itemGetTask.Result``) is NOT type-like, so a real ``Task.Result`` read
+ is preserved.
+ """
+ cur = node.child_by_field_name("expression")
+ for _ in range(8):
+ if cur is None:
+ return False
+ if cur.type == "identifier":
+ txt = (cur.text or b"").decode("utf-8", "replace")
+ return bool(txt) and txt[0].isupper()
+ if cur.type == "member_access_expression":
+ cur = cur.child_by_field_name("expression")
+ continue
+ return False # invocation / element access / this -> not a type path
+ return False
def loop_call_marker(
self, root: str, method: str, node: Node, list_names: frozenset[str]
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 d77bea120..ee3fe4709 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
@@ -44,6 +44,11 @@ GO_SQL_METHODS: frozenset[str] = frozenset(
# GORM finisher methods (the ones that actually hit the database, not the
# builder chain ``.Where`` / ``.Preload`` / ``.Joins``). All collide with
# ordinary method names, so gated on a GORM/db import in the file.
+# ``Scan`` is deliberately EXCLUDED: ``*sql.Rows.Scan`` (decoding an
+# already-fetched cursor row inside ``for rows.Next()``) is far more common than
+# GORM's ``db.Scan`` finisher and is NOT a round-trip — it FP'd ``io_in_loop``
+# on every cursor-read loop (Phase-7c syft corpus). Dropping it costs ~0
+# measured recall (no corpus GORM-``Scan``-in-loop) and removes the FP class.
GO_GORM_METHODS: frozenset[str] = frozenset(
{
"Find",
@@ -56,7 +61,6 @@ GO_GORM_METHODS: frozenset[str] = frozenset(
"Delete",
"Count",
"Pluck",
- "Scan",
}
)
# ``os`` / ``io/ioutil`` filesystem round-trips, keyed on the package receiver.
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 2d4cb8bb8..9dd5dc968 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
@@ -127,6 +127,15 @@ class PythonPerfDialect(BasePerfDialect):
root_kind = io_names.get(root)
db_evidence = has_db_import or root_kind == "db"
+ # ``asyncio.sleep`` / ``time.sleep`` / ``trio.sleep`` is a cooperative
+ # yield, never an I/O round-trip — but ``await asyncio.sleep(...)`` would
+ # otherwise hit the awaited-network arm below when ``asyncio`` is
+ # import-classified as network, FP-ing ``io_in_loop`` / ``serial_await``
+ # on every backoff/poll loop (Phase-7c headroom corpus). No legitimate
+ # execution sink is named ``sleep``, so excluding it costs no recall.
+ if method == "sleep":
+ return None
+
if method in PY_DB_UNAMBIGUOUS:
# A real DB sink is always a method on a session/cursor/result
# object; a bare identifier call (the builtin ``all(...)``) is not.
diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.py
index 13fc599a9..bffcc4565 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -295,7 +295,9 @@ _PERFORMANCE_WEIGHT_MULTIPLIER: dict[str, float] = {
# serial_await the lowest (cannot prove iteration independence).
"resource_construction_in_loop": 0.7,
"lock_in_loop": 0.5,
- "membership_test_against_list_in_loop": 0.5,
+ # PROMOTED 0.5 -> 0.7 (Phase-7c): 100% precision across corpora (7a 22/22 +
+ # headroom Python 12/12 = 34/34; list-vs-set gate holds). Clears the 70% bar.
+ "membership_test_against_list_in_loop": 0.7,
"serial_await_in_loop": 0.4,
# Phase 7b markers. Ship at advisory weight pending each one's Phase-0 gate
# (MARKER_BACKLOG.md / PHASE7B_LABELS.md). nested_loop_with_io rides with
diff --git a/tests/unit/health/test_perf_dialects.py b/tests/unit/health/test_perf_dialects.py
index 2e35fd134..59ffcd17c 100644
--- a/tests/unit/health/test_perf_dialects.py
+++ b/tests/unit/health/test_perf_dialects.py
@@ -77,8 +77,7 @@ _JAVA_CASES = [
"ambiguous get() WITH a db import passes the file-level gate",
),
(
- "class A{void m(java.util.List<String> ids){"
- "for(String id:ids){ helper(id); }}}",
+ "class A{void m(java.util.List<String> ids){for(String id:ids){ helper(id); }}}",
[],
"a plain helper call in a loop is not a sink",
),
@@ -119,14 +118,12 @@ _GO_CASES = [
"GORM Find with a gorm import fires",
),
(
- "package m\n"
- "func f(repo Repo, ids []int){ for _, id := range ids { repo.Find(id) } }",
+ "package m\nfunc f(repo Repo, ids []int){ for _, id := range ids { repo.Find(id) } }",
[],
"ambiguous Find with NO db import is gated out",
),
(
- 'package m\nimport "database/sql"\n'
- 'func f(db *sql.DB){ for {} ; db.Query("x") }',
+ 'package m\nimport "database/sql"\nfunc f(db *sql.DB){ for {} ; db.Query("x") }',
[],
"clause-less for{} is a real loop but the query is outside it",
),
@@ -193,3 +190,93 @@ _CSHARP_CASES = [
@pytest.mark.parametrize("src,expected,note", _CSHARP_CASES, ids=[c[2] for c in _CSHARP_CASES])
def test_csharp_cases(src, expected, note):
assert _hits("csharp", src) == sorted(expected), note
+
+
+# ---------------------------------------------------------------------------
+# Phase-7c precision fixes (multi-language corpus FP classes)
+# ---------------------------------------------------------------------------
+
+
+def test_csharp_result_pattern_collision_not_blocking():
+ """``.Result`` on a namespace/Result-DTO path is NOT a Task block.
+
+ Phase-7c C# corpus: 10/12 ``blocking_sync_in_async`` FPs were
+ ``Ardalis.Result.ResultStatus.X`` (``.Result`` as an intermediate namespace
+ segment) + a ``response.Result = ...`` DTO write. Neither blocks a thread.
+ """
+ # Intermediate segment of a qualified name (Ardalis.Result.ResultStatus).
+ assert (
+ _hits(
+ "csharp",
+ "class A{ async System.Threading.Tasks.Task M(){ var s = "
+ "Ardalis.Result.ResultStatus.Error; }}",
+ )
+ == []
+ )
+ # Write to a DTO ``.Result`` property (assignment target, not a read).
+ assert (
+ _hits(
+ "csharp",
+ "class A{ async System.Threading.Tasks.Task M(R response){ response.Result = 1; }}",
+ )
+ == []
+ )
+
+
+def test_csharp_task_result_still_blocks():
+ """A genuine terminal ``task.Result`` read in async still fires."""
+ assert ("blocking_sync_in_async", ".Result") in _hits(
+ "csharp",
+ "class A{ async System.Threading.Tasks.Task M(System.Threading.Tasks.Task<int> t){ "
+ "var x = t.Result; }}",
+ )
+
+
+def test_csharp_task_result_chained_read_still_blocks():
+ """``itemGetTask.Result.CatalogItem`` (camelCase local) still blocks.
+
+ Phase-7c eShopOnWeb: a genuine ``Task.Result`` read FOLLOWED by a member
+ access has the same ``X.Result.Y`` shape as the ``Ardalis.Result.X``
+ namespace FP; the receiver-root casing gate keeps the real one.
+ """
+ assert ("blocking_sync_in_async", ".Result") in _hits(
+ "csharp",
+ "class A{ async System.Threading.Tasks.Task M(){ "
+ "var c = itemGetTask.Result.CatalogItem; }}",
+ )
+
+
+def test_go_sql_rows_scan_not_io_in_loop():
+ """``rows.Scan`` inside ``for rows.Next()`` is a cursor decode, not a sink.
+
+ Phase-7c syft corpus: ``*sql.Rows.Scan`` FP'd ``io_in_loop`` (the query ran
+ once, outside the loop). ``Scan`` is no longer a GORM finisher verb.
+ """
+ src = (
+ 'package p\nimport "database/sql"\n'
+ "func f(rows *sql.Rows){ for rows.Next() { var x int; _ = rows.Scan(&x) } }\n"
+ )
+ assert not any(k == "io_in_loop" for k, _ in _hits("go", src))
+
+
+def test_go_gorm_create_still_io_in_loop():
+ """A real GORM finisher (``Create``) in a range loop still fires."""
+ src = (
+ 'package p\nimport "gorm.io/gorm"\n'
+ "func f(db *gorm.DB, items []int){ for _, it := range items { db.Create(&it) } }\n"
+ )
+ assert ("io_in_loop", "db") in _hits("go", src)
+
+
+def test_python_asyncio_sleep_not_a_sink():
+ """``await asyncio.sleep(...)`` in a loop is a yield, not network I/O.
+
+ Phase-7c headroom corpus: the awaited-network arm FP'd ``io_in_loop`` /
+ ``serial_await_in_loop`` on every backoff/poll loop.
+ """
+ src = (
+ "import asyncio\nasync def f(items):\n for x in items:\n await asyncio.sleep(x)\n"
+ )
+ kinds = {k for k, _ in _hits("python", src)}
+ assert "io_in_loop" not in kinds
+ assert "serial_await_in_loop" not in kinds