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
feat(health): add Java, Go, and C# performance dialects (#537)
Raghav Chamadiyab7078d5feb6e
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.mdindex 1e18dac1f..e95699a00 100644--- a/docs/CODE_HEALTH.md+++ b/docs/CODE_HEALTH.md@@ -143,20 +143,51 @@ category cap of 1.0, so the pillar stays advisory) are:- **`blocking_sync_in_async`**: a synchronous blocking call inside an `async`function, which stalls the whole event loop (mirrors ruff `ASYNC210/230/251`).+A few markers are language-specific, contributed by that language's dialect (see+below) rather than the shared core:++- **`regex_compile_in_loop`** (Java, Go): a `Pattern.compile` /+ `regexp.MustCompile` recompiled every iteration instead of hoisted. Skipped on+ Python / .NET, which cache compiled patterns.+- **`defer_in_loop`** (Go): a `defer` inside a loop holds the deferred handle+ until the enclosing function returns, not the iteration: the classic Go file /+ row-handle leak. A pure syntactic shape, very high precision.+- **sync-over-async** (C#, via `blocking_sync_in_async`): `.Result` / `.Wait()`+ / `.GetAwaiter().GetResult()` inside an `async` method blocks a thread-pool+ thread. C# is the one non-Python language with real `async`/`await`.+Each performance finding's `details` carry the `boundary_kind` it crosses, a`cross_function` flag, and the reachability `path` for the cross-function case.Severity is ranked by **centrality** (an N+1 in a high-traffic, churny functionoutranks one in a leaf), not by raw count.+**Languages.** The performance signal fires on **Python, TypeScript/JavaScript,+Java, Go, and C#**. Each language is a self-contained `PerfDialect` plugin+(`analysis/health/perf/dialects/`) that owns its callee-extraction grammar, its+execution-sink lexicon, the loop / string / async predicates, and its own marker+list, registered in `PERF_DIALECTS` like the rest of the per-language pipeline.+A language without a dialect emits no perf findings (never a wrong one). The+db/network/filesystem/subprocess lexicons and the per-language precision hazards+(Java `.find`/`.get`, GORM `Find`/`Save`, C# in-memory-vs-`IQueryable` LINQ) are+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).+**Soundness limits (honest, by design).** Performance is a *static* signal, soit under-reports rather than over-reports (these cap recall, not precision):dynamic dispatch / monkeypatching / callbacks-as-values produce no `calls` edgeand are invisible; ORM lazy-load N+1 fires on attribute access (no visible call)-and is explicitly out of scope; chains longer than three hops from the loop are-not followed; and an unmodelled library is untyped (`None`), so its sinks don't-fire. We call this **performance RISK**, never measured performance, and never-fold it into the defect score. The commit-agreement precision study and its-caveats live in `local-stash/performance-pillar/VALIDATION.md`.+and is explicitly out of scope --- this includes Hibernate lazy-load N+1 (fires+on a getter) and EF Core navigation-property lazy load, so we catch *explicit*+repository / query calls in loops, not attribute-triggered lazy loads; chains+longer than three hops from the loop are not followed; and an unmodelled library+is untyped (`None`), so its sinks don't fire. We call this **performance RISK**,+never measured performance, and never fold it into the defect score. The+commit-agreement precision study and its caveats live in+`local-stash/performance-pillar/VALIDATION.md`.Performance surfaces exactly where maintainability does: a `performance_average`on the overview summary and MCP `kpis`, a per-file `performance_score`, adiff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.mdindex 827f6b21e..4a1fb85bf 100644--- a/docs/LANGUAGE_SUPPORT.md+++ b/docs/LANGUAGE_SUPPORT.md@@ -429,6 +429,44 @@ without touching the shared pipeline files:class-level maps for all of those except Go (no class-grouping node).See `complexity/README.md` for the extension recipe and the LCOM4heuristic's limits.+- `analysis/health/perf/dialects/` --- the **performance** health signal+ (`io_in_loop` / `string_concat_in_loop` / language-specific markers) is+ driven by a per-language `PerfDialect` plugin, registered in+ `PERF_DIALECTS` exactly like `resolvers/` and the workspace `http/`+ dialects. A dialect owns callee extraction (the per-grammar seam: Python+ `attribute`, Go `selector_expression`, Java `method_invocation`'s+ `object`/`name`, C# `member_access_expression`), the execution-sink+ lexicon (`sink_kind`), the constant-loop / string-concat / async+ predicates, and its own **marker list** --- so Go contributes+ `defer_in_loop`, Java/Go contribute `regex_compile_in_loop`, and C#+ contributes sync-over-async `blocking_sync_in_async`, none hardcoded in+ the walker. Every method has a safe "no signal" default, so a language+ without a dialect (or one that overrides only some facets) produces no+ false perf findings. Adding a language's perf support is one module plus a+ `call_kinds` line on its `LanguageNodeMap` and its+ `external_systems/io_kind.py` ecosystem rows --- no walker edits.++#### Performance-signal coverage++The performance signal needs the `PerfDialect` above (plus `call_kinds` on+the language's `LanguageNodeMap`); it is independent of the control-flow /+class / assertion tiers. A language without a dialect simply emits no perf+findings.++| Language | io_in_loop | string_concat | Language-specific markers | sync-over-async |+|----------|:---:|:---:|---|:---:|+| Python | Y | Y | --- | `blocking_sync_in_async` |+| TypeScript / JavaScript | Y | Y | --- | --- |+| Java | Y | Y | `regex_compile_in_loop` | --- (no async syntax) |+| Go | Y | Y | `defer_in_loop`, `regex_compile_in_loop` | --- (goroutines) |+| C# | Y | Y | --- (.NET caches regexes) | `blocking_sync_in_async` (`.Result` / `.Wait()` / `.GetResult()`) |+| Kotlin / Rust / C++ | --- | --- | --- | --- |++Kotlin will be nearly free once it rides the JVM lexicon; Rust (sqlx /+reqwest) and C++ are later. What each dialect classifies as a db / network /+filesystem / subprocess sink, and the per-language precision hazards, lives+in `docs/CODE_HEALTH.md` and+`local-stash/performance-pillar/PHASE6_PLAN.md`.---diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.pyindex 93e5320c8..cb4e57fa9 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py@@ -211,6 +211,7 @@ _GO = LanguageNodeMap(# future receiver-aware grouping pass; until then Go emits no classes.# ``assert.Equal(t, ...)`` (testify) — best-effort call detection.assert_call_kinds=frozenset({"call_expression"}),+ call_kinds=frozenset({"call_expression"}),)_JAVA = LanguageNodeMap(@@ -239,6 +240,9 @@ _JAVA = LanguageNodeMap(# ``assert x`` (JUnit ``assert`` keyword) + ``assertEquals(...)`` calls.assert_kinds=frozenset({"assert_statement"}),assert_call_kinds=frozenset({"method_invocation"}),+ # The perf pass needs both forms: ``repo.find()`` (method_invocation) and+ # ``new FileInputStream()`` (object_creation_expression).+ call_kinds=frozenset({"method_invocation", "object_creation_expression"}),)_RUST = LanguageNodeMap(@@ -341,6 +345,7 @@ _CSHARP = LanguageNodeMap(# xUnit / NUnit / MSTest: ``Assert.Equal(...)`` / ``Assert.True(...)`` are# invocations whose callee chain begins with ``Assert``.assert_call_kinds=frozenset({"invocation_expression"}),+ call_kinds=frozenset({"invocation_expression"}),)diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.pyindex 83951e941..0dc4b9366 100644--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py@@ -14,6 +14,9 @@ No edits to the walker. A language absent here ⇒ the perf pass is silent for ifrom __future__ import annotations+from . import csharp as _csharp+from . import go as _go+from . import java as _javafrom . import python as _pythonfrom . import ts_js as _ts_jsfrom .base import PERF_DIALECTS, BasePerfDialect@@ -27,6 +30,9 @@ _REGISTER: tuple[tuple[str, BasePerfDialect], ...] = (("tsx", _ts_js.DIALECT),("javascript", _ts_js.DIALECT),("jsx", _ts_js.DIALECT),+ ("java", _java.DIALECT),+ ("go", _go.DIALECT),+ ("csharp", _csharp.DIALECT),)for _tag, _dialect in _REGISTER: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.pynew file mode 100644index 000000000..364f99f6a--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/csharp.py@@ -0,0 +1,238 @@+"""C# ``PerfDialect``.++Two flagship signals:++* **EF Core N+1** — an Entity Framework / Dapper / ADO.NET query inside a+ ``foreach``. The precision crux is LINQ: ``ToList`` / ``First`` / ``Where``+ are identical on an ``IQueryable`` (hits the DB) and an ``IEnumerable`` (pure+ memory). The unambiguous tell is the ``*Async`` family+ (``ToListAsync`` / ``FirstOrDefaultAsync`` / ``CountAsync`` …), which is+ EF-only and fires without a gate. Sync LINQ is gated on a file-level db+ import (MEDIUM precision in v1; receiver ``DbContext``-type binding deferred).+* **sync-over-async** — ``.Result`` / ``.Wait()`` / ``.GetAwaiter().GetResult()``+ inside an ``async`` method blocks the thread-pool thread. C# is the one new+ language with real ``async``/``await``, so ``blocking_sync_in_async`` ports+ here. ``.Wait()`` / ``.GetResult()`` are invocations (caught by+ :meth:`blocking_sync_api`); ``.Result`` is a property read — a non-call+ ``member_access_expression`` — caught by :meth:`async_blocking_member`.++C# call nodes are ``invocation_expression`` -> ``member_access_expression``+(fields ``expression`` / ``name``); the async marker is a ``modifier`` node+whose *text* is ``async`` (not a node of type ``async``), so :meth:`is_async_fn`+is overridden. .NET caches compiled regexes, so ``regex_compile_in_loop`` is+deliberately absent.++Static-blind, documented non-goal: EF navigation-property *lazy load* fires on+attribute access (no visible call) and is out of scope — we catch explicit+query calls in loops.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from .base import BasePerfDialect++if TYPE_CHECKING:+ from tree_sitter import Node++# The EF ``*Async`` LINQ family — EF-only, so UNAMBIGUOUS db (no gate).+EF_ASYNC_METHODS: frozenset[str] = frozenset(+ {+ "ToListAsync",+ "ToArrayAsync",+ "ToDictionaryAsync",+ "FirstAsync",+ "FirstOrDefaultAsync",+ "SingleAsync",+ "SingleOrDefaultAsync",+ "LastAsync",+ "LastOrDefaultAsync",+ "FindAsync",+ "AnyAsync",+ "AllAsync",+ "CountAsync",+ "LongCountAsync",+ "SumAsync",+ "MinAsync",+ "MaxAsync",+ "AverageAsync",+ "ContainsAsync",+ "ElementAtAsync",+ }+)+# EF SaveChanges + raw SQL + bulk operations — unambiguous db.+EF_EXEC_METHODS: frozenset[str] = frozenset(+ {+ "SaveChanges",+ "SaveChangesAsync",+ "ExecuteSqlRaw",+ "ExecuteSqlRawAsync",+ "ExecuteSqlInterpolated",+ "ExecuteSqlInterpolatedAsync",+ "FromSqlRaw",+ "FromSqlInterpolated",+ "ExecuteUpdate",+ "ExecuteUpdateAsync",+ "ExecuteDelete",+ "ExecuteDeleteAsync",+ }+)+# ADO.NET command execution — unambiguous db.+ADO_METHODS: frozenset[str] = frozenset(+ {+ "ExecuteReader",+ "ExecuteReaderAsync",+ "ExecuteNonQuery",+ "ExecuteNonQueryAsync",+ "ExecuteScalar",+ "ExecuteScalarAsync",+ "OpenAsync",+ }+)+# Dapper extension verbs (collide with EF / plain method names) — gated on db.+DAPPER_METHODS: frozenset[str] = frozenset(+ {+ "Query",+ "QueryAsync",+ "QueryFirst",+ "QueryFirstAsync",+ "QueryFirstOrDefault",+ "QueryFirstOrDefaultAsync",+ "QuerySingle",+ "QuerySingleAsync",+ "QueryMultiple",+ "QueryMultipleAsync",+ "Execute",+ "ExecuteAsync",+ }+)+# Sync LINQ — identical on IQueryable (db) vs IEnumerable (memory). Gated on a+# file-level db import (MEDIUM precision, v1).+SYNC_LINQ_METHODS: frozenset[str] = frozenset(+ {+ "ToList",+ "ToArray",+ "First",+ "FirstOrDefault",+ "Single",+ "SingleOrDefault",+ "Last",+ "LastOrDefault",+ "ToDictionary",+ }+)+# HttpClient async round-trips — distinctive by name, unambiguous network.+HTTP_ASYNC_METHODS: frozenset[str] = frozenset(+ {+ "GetAsync",+ "PostAsync",+ "PutAsync",+ "DeleteAsync",+ "PatchAsync",+ "SendAsync",+ "GetStringAsync",+ "GetByteArrayAsync",+ "GetStreamAsync",+ }+)+# ``System.IO.File`` static round-trips (gate on the method + ``File`` receiver,+# NOT on a fs import — ``using System.IO;`` is everywhere).+FILE_METHODS: frozenset[str] = frozenset(+ {+ "ReadAllText",+ "ReadAllLines",+ "ReadAllBytes",+ "ReadAllTextAsync",+ "ReadAllLinesAsync",+ "WriteAllText",+ "WriteAllLines",+ "WriteAllBytes",+ "WriteAllTextAsync",+ "AppendAllText",+ "Open",+ "OpenRead",+ "OpenText",+ "OpenWrite",+ "Copy",+ "Move",+ }+)+++class CSharpPerfDialect(BasePerfDialect):+ language = "csharp"+ markers = frozenset({"io_in_loop", "string_concat_in_loop", "blocking_sync_in_async"})++ # ``invocation_expression`` -> ``member_access_expression`` is the call+ # shape; add it so a member call reads as attribute-style.+ attribute_callee_kinds = BasePerfDialect.attribute_callee_kinds | frozenset(+ {"member_access_expression"}+ )+ string_literal_kinds = frozenset({"string_literal", "verbatim_string_literal"})+ aug_assign_kinds = frozenset({"assignment_expression"})++ def callee_method_name(self, call_node: Node) -> str | None:+ fn = call_node.child_by_field_name("function")+ if fn is None:+ return None+ if fn.type == "member_access_expression":+ nm = fn.child_by_field_name("name")+ if nm is not None and nm.text:+ return nm.text.decode("utf-8", "replace")+ if fn.type == "identifier" and fn.text:+ return fn.text.decode("utf-8", "replace")+ return None++ def sink_kind(+ self,+ root: str,+ method: str,+ *,+ awaited: bool,+ is_attribute: bool,+ io_names: dict[str, str],+ has_db_import: bool,+ ) -> str | None:+ root_kind = io_names.get(root)+ db_ev = has_db_import or root_kind == "db"++ if method in EF_ASYNC_METHODS or method in EF_EXEC_METHODS or method in ADO_METHODS:+ return "db"+ if method in HTTP_ASYNC_METHODS:+ return "network"+ if root == "File" and method in FILE_METHODS:+ return "filesystem"+ if root == "Process" and method == "Start":+ return "subprocess"+ if is_attribute and db_ev and (method in DAPPER_METHODS or method in SYNC_LINQ_METHODS):+ return "db"+ return None++ def is_async_fn(self, node: Node) -> bool:+ # C# async is a ``modifier`` node whose text is ``async`` (vs Python/TS+ # where it is a child of *type* ``async``).+ return any(+ c.type == "modifier" and (c.text or b"").decode("utf-8", "replace") == "async"+ for c in node.children+ )++ def blocking_sync_api(self, root: str, method: str) -> str | None:+ # The invocation forms of sync-over-async. ``.Result`` (a property read)+ # is handled by ``async_blocking_member`` instead.+ if method == "Wait":+ return ".Wait()"+ if method == "GetResult":+ return ".GetResult()"+ return None++ def async_blocking_member(self, node: Node) -> str | None:+ 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+++DIALECT = CSharpPerfDialect()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.pynew file mode 100644index 000000000..fd018db01--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/go.py@@ -0,0 +1,166 @@+"""Go ``PerfDialect``.++Flagship: ``database/sql`` / GORM queries inside a ``for … range`` (the Go N+1).+Two Go-specific markers ride along:++* ``defer_in_loop`` — a ``defer`` inside a loop holds the deferred handle until+ the *enclosing function* returns, not the loop iteration; the classic Go+ file-handle / row leak. Very high precision (it is a pure syntactic shape).+* ``regex_compile_in_loop`` — ``regexp.MustCompile`` / ``regexp.Compile``+ recompiled every iteration instead of hoisted.++Go has no ``async``/``await`` (concurrency is goroutines), so+``blocking_sync_in_async`` is intentionally not in :attr:`markers`.++Go's callee grammar (``call_expression`` -> ``selector_expression`` with+``operand`` / ``field``) is already handled by the generic base extraction, so+this dialect only supplies the lexicon + the Go-specific predicates.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from .base import BasePerfDialect+from .python import HTTP_VERBS++if TYPE_CHECKING:+ from tree_sitter import Node++# ``database/sql`` round-trip methods. Generic enough (``Query`` / ``Exec``) to+# collide with non-db receivers, so gated on db-import evidence.+GO_SQL_METHODS: frozenset[str] = frozenset(+ {+ "Query",+ "QueryRow",+ "QueryContext",+ "QueryRowContext",+ "Exec",+ "ExecContext",+ "Prepare",+ "PrepareContext",+ }+)+# 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.+GO_GORM_METHODS: frozenset[str] = frozenset(+ {+ "Find",+ "First",+ "Take",+ "Last",+ "Save",+ "Create",+ "Updates",+ "Delete",+ "Count",+ "Pluck",+ "Scan",+ }+)+# ``os`` / ``io/ioutil`` filesystem round-trips, keyed on the package receiver.+GO_OS_FS_METHODS: frozenset[str] = frozenset(+ {+ "Open",+ "Create",+ "ReadFile",+ "WriteFile",+ "OpenFile",+ "ReadDir",+ "Mkdir",+ "MkdirAll",+ "Remove",+ }+)+GO_IOUTIL_METHODS: frozenset[str] = frozenset({"ReadFile", "WriteFile", "ReadAll", "ReadDir"})+GO_REGEX_COMPILE: frozenset[str] = frozenset(+ {"MustCompile", "Compile", "MustCompilePOSIX", "CompilePOSIX"}+)+_GO_STRING_KINDS: frozenset[str] = frozenset({"interpreted_string_literal", "raw_string_literal"})+++class GoPerfDialect(BasePerfDialect):+ language = "go"+ markers = frozenset(+ {"io_in_loop", "string_concat_in_loop", "defer_in_loop", "regex_compile_in_loop"}+ )++ def sink_kind(+ self,+ root: str,+ method: str,+ *,+ awaited: bool,+ is_attribute: bool,+ io_names: dict[str, str],+ has_db_import: bool,+ ) -> str | None:+ root_kind = io_names.get(root)+ db_ev = has_db_import or root_kind == "db"+ net_ev = root_kind == "network" or "network" in io_names.values()+ sub_ev = root_kind == "subprocess" or "subprocess" in io_names.values()++ # net/http: ``http.Get`` (root binds to net/http) or ``client.Do``.+ if root_kind == "network" and method.lower() in HTTP_VERBS:+ return "network"+ if method == "Do" and net_ev:+ return "network"+ # os / ioutil filesystem.+ if root == "os" and method in GO_OS_FS_METHODS:+ return "filesystem"+ if root == "ioutil" and method in GO_IOUTIL_METHODS:+ return "filesystem"+ # os/exec subprocess: ``exec.Command`` is distinctive; ``cmd.Run`` etc.+ # are ambiguous and gated on an os/exec import.+ if root == "exec" and method == "Command":+ return "subprocess"+ if method in ("Run", "Output", "CombinedOutput", "Start") and sub_ev:+ return "subprocess"+ # database/sql + GORM, gated on a db import (the verbs are generic).+ if is_attribute and db_ev and (method in GO_SQL_METHODS or method in GO_GORM_METHODS):+ return "db"+ return None++ def is_constant_loop(self, node: Node) -> bool:+ """Only a three-clause ``for i := 0; i < <int>; i++`` is constant-bound.++ Go ``for … range`` and the clause-less infinite ``for { }`` are ALWAYS+ real loops (a range over a slice is the textbook N+1 site), so they are+ never skipped — the opposite of treating every ``for`` as constant.+ """+ if node.type != "for_statement":+ return False+ clause = next((c for c in node.children if c.type == "for_clause"), None)+ if clause is None:+ return False # range / for{} ⇒ real loop+ cond = clause.child_by_field_name("condition")+ if cond is None or cond.type != "binary_expression":+ return False+ right = cond.child_by_field_name("right")+ return right is not None and right.type in ("int_literal", "float_literal")++ def is_string_concat(self, node: Node) -> bool:+ """Go ``s += "x"`` — the RHS is wrapped in an ``expression_list``."""+ if node.type != "assignment_statement":+ return False+ if not any(c.type == "+=" for c in node.children):+ return False+ right = node.child_by_field_name("right")+ if right is None:+ return False+ targets = right.named_children if right.type == "expression_list" else [right]+ return any(c.type in _GO_STRING_KINDS for c in targets)++ def loop_call_marker(self, root: str, method: str, node: Node) -> str | None:+ if root == "regexp" and method in GO_REGEX_COMPILE:+ return "regex_compile_in_loop"+ return None++ def loop_stmt_marker(self, node: Node) -> str | None:+ if node.type == "defer_statement":+ return "defer_in_loop"+ return None+++DIALECT = GoPerfDialect()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.pynew file mode 100644index 000000000..68a789417--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/java.py@@ -0,0 +1,187 @@+"""Java ``PerfDialect``.++Flagship: the most infamous N+1 in industry — a Hibernate / Spring-Data+repository query inside a ``for`` loop (``for (id : ids) repo.findById(id)``).++The load-bearing seam is **callee extraction**: a Java call node *is* a+``method_invocation`` (fields ``object`` / ``name``) with no wrapping+member-access node, so the generic base extraction (which keys off a+``function`` field) does not work. This dialect supplies the Java arm. It also+handles ``object_creation_expression`` (``new FileInputStream(...)``) so a+constructor at a filesystem/network boundary inside a loop is caught.++New marker: ``regex_compile_in_loop`` (``Pattern.compile`` with no cached+``Pattern``). Java has no ``async``/``await`` syntax, so+``blocking_sync_in_async`` is intentionally absent (reactive-blocking would+need type information).++Static-blind, documented non-goal: Hibernate *lazy-load* N+1 fires on a getter+(no visible call), so it is invisible to a static call-shape detector — we+catch explicit repository/query calls in loops, not attribute-triggered lazy+loads. This caps recall, not precision.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING++from .base import BasePerfDialect++if TYPE_CHECKING:+ from tree_sitter import Node++# Spring-Data derived query methods: ``findByName`` / ``getAllByStatus`` /+# ``countByOwner`` … — an extremely distinctive signature, treated as db without+# an import gate.+_SPRING_DERIVED = re.compile(r"^(find|get|query|count|exists|stream|read|delete)By[A-Z]")++# JDBC — unambiguous cursor/statement round-trips.+JDBC_METHODS: frozenset[str] = frozenset(+ {"executeQuery", "executeUpdate", "executeBatch", "executeLargeUpdate", "prepareStatement"}+)+# JPA / Hibernate EntityManager + Query.+JPA_METHODS: frozenset[str] = frozenset(+ {"getResultList", "getSingleResult", "getResultStream", "createQuery", "createNativeQuery"}+)+# Spring-Data CrudRepository finishers that are distinctive enough on their own.+SPRING_REPO_METHODS: frozenset[str] = frozenset(+ {"saveAll", "findAll", "findAllById", "deleteAll", "deleteAllById"}+)+# Spring RestTemplate — distinctive HTTP round-trip method names.+REST_TEMPLATE_METHODS: frozenset[str] = frozenset(+ {"getForObject", "postForObject", "getForEntity", "postForEntity", "exchange", "patchForObject"}+)+# WebClient ``.block*`` (Reactor) — gated on a network import (``.block`` alone+# is a generic Reactor finisher).+WEBCLIENT_BLOCK: frozenset[str] = frozenset({"block", "blockFirst", "blockLast"})+# ``java.nio.file.Files`` static round-trips.+FILES_METHODS: frozenset[str] = frozenset(+ {+ "readString",+ "readAllLines",+ "readAllBytes",+ "lines",+ "newInputStream",+ "newOutputStream",+ "newBufferedReader",+ "newBufferedWriter",+ "write",+ "copy",+ "move",+ "createFile",+ "list",+ "walk",+ }+)+# Constructors that open a filesystem / network boundary.+FS_CONSTRUCTORS: frozenset[str] = frozenset(+ {"FileInputStream", "FileOutputStream", "FileReader", "FileWriter", "RandomAccessFile"}+)+NET_CONSTRUCTORS: frozenset[str] = frozenset({"Socket", "ServerSocket"})+# Ambiguous DB verbs (collide with collections/builders/streams) — the riskiest+# stratum, gated on file-level db evidence. Kept deliberately small (the plan's+# find/get/execute/save/count) so generic verbs like ``list`` / ``stream`` /+# ``delete`` do not over-fire in a db-importing file.+AMBIGUOUS_DB: frozenset[str] = frozenset({"find", "get", "execute", "save", "count"})+++class JavaPerfDialect(BasePerfDialect):+ language = "java"+ markers = frozenset({"io_in_loop", "string_concat_in_loop", "regex_compile_in_loop"})++ # ``s += "x"`` is an ``assignment_expression`` with the literal directly on+ # the ``right`` field (no list wrapper, unlike Go).+ string_literal_kinds = frozenset({"string_literal"})+ aug_assign_kinds = frozenset({"assignment_expression"})++ # -- Java callee arm ------------------------------------------------------++ def callee_method_name(self, call_node: Node) -> str | None:+ if call_node.type == "object_creation_expression":+ t = call_node.child_by_field_name("type")+ if t is not None and t.text:+ return t.text.decode("utf-8", "replace").split(".")[-1]+ return None+ name = call_node.child_by_field_name("name")+ if name is not None and name.text:+ return name.text.decode("utf-8", "replace")+ return None++ def callee_root_name(self, call_node: Node) -> str | None:+ if call_node.type == "object_creation_expression":+ t = call_node.child_by_field_name("type")+ if t is not None and t.text:+ return t.text.decode("utf-8", "replace").split(".")[-1]+ return None+ obj = call_node.child_by_field_name("object")+ if obj is not None and obj.text:+ return obj.text.decode("utf-8", "replace").split(".")[0]+ # A bare ``foo()`` (no receiver) — the name is the root.+ name = call_node.child_by_field_name("name")+ if name is not None and name.text:+ return name.text.decode("utf-8", "replace")+ return None++ def callee_is_attribute(self, call_node: Node) -> bool:+ if call_node.type == "object_creation_expression":+ return True # a constructor sink (``new FileInputStream``)+ # A ``method_invocation`` with a receiver (``repo.find()``) is+ # attribute-style; a bare ``find()`` is not.+ return call_node.child_by_field_name("object") is not None++ # -- lexicon --------------------------------------------------------------++ def sink_kind(+ self,+ root: str,+ method: str,+ *,+ awaited: bool,+ is_attribute: bool,+ io_names: dict[str, str],+ has_db_import: bool,+ ) -> str | None:+ root_kind = io_names.get(root)+ db_ev = has_db_import or root_kind == "db"+ net_ev = root_kind == "network" or "network" in io_names.values()++ if method in FS_CONSTRUCTORS:+ return "filesystem"+ if method in NET_CONSTRUCTORS:+ return "network"+ if method in JDBC_METHODS or method in JPA_METHODS or method in SPRING_REPO_METHODS:+ return "db"+ if _SPRING_DERIVED.match(method):+ return "db"+ if method in REST_TEMPLATE_METHODS:+ return "network"+ if method in WEBCLIENT_BLOCK and net_ev:+ return "network"+ if method == "send" and net_ev:+ return "network"+ if root == "Files" and method in FILES_METHODS:+ return "filesystem"+ if method == "exec": # Runtime.getRuntime().exec(...)+ return "subprocess"+ if is_attribute and db_ev and method in AMBIGUOUS_DB:+ return "db"+ return None++ def loop_call_marker(self, root: str, method: str, node: Node) -> str | None:+ # ``Pattern.compile(...)`` recompiled per iteration (no cached Pattern).+ # ``root`` is the first segment, so an FQN ``java.util.regex.Pattern``+ # lands as ``java``; match on the receiver's last segment instead.+ if method != "compile":+ return None+ obj = node.child_by_field_name("object")+ if obj is not None and obj.text:+ return (+ "regex_compile_in_loop"+ if obj.text.decode("utf-8", "replace").split(".")[-1] == "Pattern"+ else None+ )+ return "regex_compile_in_loop" if root == "Pattern" else None+++DIALECT = JavaPerfDialect()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.pyindex 35fc29b1b..4a15234e9 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@@ -123,11 +123,22 @@ def collect_io_names(tree_root: _NodeLike, language: str) -> dict[str, str]:stack: list[_NodeLike] = [tree_root]while stack:node = stack.pop()- if "import" in node.type:- kind, bound = _classify_import(node)- if kind is not None:- for name in bound:- names.setdefault(name, kind)+ # ``import`` covers Python / TS / Java / Go import nodes; C# spells its+ # import a ``using_directive`` (and Go an ``import_spec``), neither of+ # which contains the substring "import".+ if "import" in node.type or node.type == "using_directive":+ # Classify only the *leaf* import node. A Go grouped+ # ``import ( "database/sql"; "regexp" )`` is an ``import_declaration``+ # wrapping per-line ``import_spec`` leaves; classifying the wrapper+ # binds every name in the block to whichever line resolves first+ # (so ``regexp`` would inherit ``db``). Skip a node that contains a+ # nested import-spec — its children carry the scoped truth.+ has_spec_child = any("import_spec" in c.type for c in node.children)+ if not has_spec_child:+ kind, bound = _classify_import(node)+ if kind is not None:+ for name in bound:+ names.setdefault(name, kind)for child in node.children:stack.append(child)return namesdiff --git a/packages/core/src/repowise/core/ingestion/external_systems/io_kind.py b/packages/core/src/repowise/core/ingestion/external_systems/io_kind.pyindex bde394df2..86cc8ec2e 100644--- a/packages/core/src/repowise/core/ingestion/external_systems/io_kind.py+++ b/packages/core/src/repowise/core/ingestion/external_systems/io_kind.py@@ -47,6 +47,18 @@ _DB_NAMES: frozenset[str] = frozenset({"ioredis", "mongoose", "mongodb", "@prisma/client", "prisma","drizzle-orm", "knex", "pg", "mysql", "mysql2", "sequelize", "typeorm","better-sqlite3", "@elastic/elasticsearch", "@planetscale/database", "kysely",+ # JVM (dotted-prefix or bare-segment keys; the import classifier emits both+ # progressive dotted prefixes and interior path segments).+ "java.sql", "javax.sql", "org.hibernate", "jakarta.persistence",+ "javax.persistence", "org.springframework.data", "com.zaxxer.hikari",+ "org.jooq", "org.mybatis", "org.jdbi",+ # Go (module paths resolve via their interior segment, e.g.+ # github.com/go-redis/redis -> redis, already a db name above).+ "database/sql", "gorm", "sqlx", "pgx", "mongo-driver",+ # .NET (progressive dotted prefixes of the namespace).+ "microsoft.entityframeworkcore", "system.data.sqlclient",+ "microsoft.data.sqlclient", "dapper", "npgsql", "mongodb.driver",+ "stackexchange.redis",})_NETWORK_NAMES: frozenset[str] = frozenset({@@ -56,6 +68,13 @@ _NETWORK_NAMES: frozenset[str] = frozenset({# TS / Node"axios", "node-fetch", "got", "superagent", "undici", "ky", "needle","request", "@grpc/grpc-js", "ws", "socket.io-client", "graphql-request",+ # JVM+ "java.net.http", "okhttp3", "retrofit2", "feign", "org.apache.http",+ "org.apache.hc", "org.springframework.web",+ # Go (interior segments / module names)+ "net/http", "grpc", "resty", "fasthttp",+ # .NET+ "system.net.http", "grpc.net.client", "restsharp", "flurl",})_FILESYSTEM_NAMES: frozenset[str] = frozenset({@@ -63,6 +82,12 @@ _FILESYSTEM_NAMES: frozenset[str] = frozenset({"open", "aiofiles", "watchdog", "pathlib", "shutil", "fsspec",# TS / Node"node:fs", "fs", "fs-extra", "graceful-fs", "chokidar", "node:path",+ # JVM+ "java.nio.file", "java.io",+ # Go (interior segment of golang.org/x/... etc.; os/exec is subprocess)+ "io/ioutil",+ # .NET+ "system.io",})_SUBPROCESS_NAMES: frozenset[str] = frozenset({@@ -70,6 +95,8 @@ _SUBPROCESS_NAMES: frozenset[str] = frozenset({"subprocess", "sh", "pexpect", "plumbum", "invoke",# TS / Node"child_process", "node:child_process", "execa", "cross-spawn", "shelljs",+ # Go (os/exec resolves via the interior segment ``exec``)+ "os/exec",})_LOCK_NAMES: frozenset[str] = frozenset({diff --git a/tests/fixtures/lang_samples/csharp/PerfIoInLoop.cs b/tests/fixtures/lang_samples/csharp/PerfIoInLoop.csnew file mode 100644index 000000000..fa481e3fd--- /dev/null+++ b/tests/fixtures/lang_samples/csharp/PerfIoInLoop.cs@@ -0,0 +1,88 @@+// Fixture for the C# performance dialect (io_in_loop / string_concat /+// blocking_sync_in_async). Every POSITIVE is a genuine per-iteration I/O+// boundary or a sync-over-async block; every NEGATIVE is a shape the dialect+// must NOT flag. Hand-counted expectations live in test_perf_csharp.py. NOTE:+// this file imports EF Core, so file-level db evidence is present; the+// in-memory-LINQ false-positive gating is tested inline instead.+using System.Collections.Generic;+using System.IO;+using System.Net.Http;+using System.Threading.Tasks;+using Microsoft.EntityFrameworkCore;++class PerfIoInLoop+{+ // --- POSITIVES ---------------------------------------------------------++ async Task EfAsyncN1(DbContext ctx, List<int> ids)+ {+ foreach (var id in ids)+ {+ await ctx.Users.ToListAsync(); // POSITIVE: EF *Async (unambiguous db)+ }+ }++ async Task HttpInLoop(HttpClient c, List<string> urls)+ {+ foreach (var u in urls)+ {+ await c.GetAsync(u); // POSITIVE: network+ }+ }++ async Task SaveInLoop(DbContext ctx, List<int> ids)+ {+ foreach (var id in ids)+ {+ await ctx.SaveChangesAsync(); // POSITIVE: EF write+ }+ }++ void FileReadInLoop(List<string> paths)+ {+ foreach (var p in paths)+ {+ File.ReadAllText(p); // POSITIVE: filesystem+ }+ }++ void SyncLinqInLoop(DbContext ctx, List<int> ids)+ {+ foreach (var id in ids)+ {+ ctx.Users.ToList(); // POSITIVE: sync LINQ, db import present+ }+ }++ string StringConcatInLoop(List<string> rows)+ {+ string s = "";+ foreach (var r in rows)+ {+ s += "line"; // POSITIVE: quadratic string build+ }+ return s;+ }++ async Task SyncOverAsync(Task<int> task)+ {+ var r = task.Result; // POSITIVE: .Result blocks in async+ task.Wait(); // POSITIVE: .Wait() blocks in async+ }++ // --- NEGATIVES ---------------------------------------------------------++ void PureCallInLoop(List<int> items)+ {+ int total = 0;+ foreach (var x in items)+ {+ total += x; // NEGATIVE: numeric +=, no I/O+ }+ }++ async Task AwaitedAsyncResult(Task<int> task)+ {+ var r = await task; // NEGATIVE: awaited, not .Result/.Wait+ }+}diff --git a/tests/fixtures/lang_samples/go/perf_io_in_loop.go b/tests/fixtures/lang_samples/go/perf_io_in_loop.gonew file mode 100644index 000000000..bceb58a87--- /dev/null+++ b/tests/fixtures/lang_samples/go/perf_io_in_loop.go@@ -0,0 +1,75 @@+// Fixture for the Go performance dialect (io_in_loop / string_concat /+// defer_in_loop / regex_compile_in_loop). Every POSITIVE is a genuine+// per-iteration cost; every NEGATIVE is a shape the dialect must NOT flag.+// Hand-counted expectations live in test_perf_go.py. NOTE: this file imports+// database/sql, so file-level db evidence is present; ambiguous-verb gating+// (GORM Find without a db import) is tested inline instead.+package sample++import (+ "database/sql"+ "net/http"+ "os"+ "regexp"+)++// --- POSITIVES -------------------------------------------------------------++func dbQueryInRange(db *sql.DB, ids []int) {+ for _, id := range ids {+ db.Query("SELECT 1", id) // POSITIVE: database/sql round-trip per item+ }+}++func httpGetInRange(urls []string) {+ for _, u := range urls {+ http.Get(u) // POSITIVE: network per item+ }+}++func osOpenInRange(paths []string) {+ for _, p := range paths {+ os.Open(p) // POSITIVE: filesystem per item+ }+}++func deferInLoop(paths []string) {+ for _, p := range paths {+ f, _ := os.Open(p) // POSITIVE: filesystem (also the defer below)+ defer f.Close() // POSITIVE: defer in loop leaks the handle+ }+}++func regexpCompileInRange(ids []string) {+ for _, id := range ids {+ regexp.MustCompile(id) // POSITIVE: recompiled per iteration+ }+}++func stringConcatInRange(rows []string) string {+ s := ""+ for range rows {+ s += "row" // POSITIVE: quadratic string build (literal RHS)+ }+ return s+}++// --- NEGATIVES -------------------------------------------------------------++func dbQueryConstantLoop(db *sql.DB) {+ for i := 0; i < 10; i++ { // NEGATIVE: constant-bound three-clause loop+ db.Query("SELECT 1")+ }+}++func pureCallInRange(items []int) {+ total := 0+ for _, x := range items {+ total += x // NEGATIVE: numeric +=, no I/O+ }+ _ = total+}++func queryOutsideLoop(db *sql.DB) {+ db.Query("SELECT 1") // NEGATIVE: runs once, not in a loop+}diff --git a/tests/fixtures/lang_samples/java/PerfIoInLoop.java b/tests/fixtures/lang_samples/java/PerfIoInLoop.javanew file mode 100644index 000000000..e72c54bee--- /dev/null+++ b/tests/fixtures/lang_samples/java/PerfIoInLoop.java@@ -0,0 +1,73 @@+// Fixture for the Java performance dialect (io_in_loop / string_concat /+// regex_compile_in_loop). Every POSITIVE is a genuine per-iteration I/O+// boundary or wasted recompile; every NEGATIVE is a shape the dialect must NOT+// flag. Hand-counted expectations live in test_perf_java.py. NOTE: this file+// imports a db library, so file-level db evidence is present; ambiguous-verb+// gating (find/get without a db import) is tested inline instead.+import java.nio.file.Files;+import java.util.List;+import java.util.regex.Pattern;+import org.springframework.data.jpa.repository.JpaRepository;++class PerfIoInLoop {++ // --- POSITIVES ---------------------------------------------------------++ void springDataN1(List<String> ids) {+ for (String id : ids) {+ repo.findByName(id); // POSITIVE: Spring-Data derived query+ }+ }++ void jdbcInLoop(List<String> ids, java.sql.Statement st) {+ for (String id : ids) {+ st.executeQuery(id); // POSITIVE: JDBC round-trip+ }+ }++ void filesInLoop(List<String> paths) {+ for (String p : paths) {+ Files.readString(java.nio.file.Path.of(p)); // POSITIVE: filesystem+ }+ }++ void newStreamInLoop(List<String> paths) {+ for (String p : paths) {+ new java.io.FileInputStream(p); // POSITIVE: filesystem constructor+ }+ }++ void regexCompileInLoop(List<String> ids) {+ for (String id : ids) {+ Pattern.compile(id); // POSITIVE: recompiled per iteration+ }+ }++ String stringConcatInLoop(List<String> rows) {+ String out = "";+ for (String r : rows) {+ out += "line"; // POSITIVE: quadratic string build+ }+ return out;+ }++ // --- NEGATIVES ---------------------------------------------------------++ void pureCallInLoop(List<String> items) {+ int total = 0;+ for (String x : items) {+ total += x.length(); // NEGATIVE: numeric +=, pure call+ }+ }++ void sinkOutsideLoop(java.sql.Statement st) {+ st.executeQuery("SELECT 1"); // NEGATIVE: runs once, not in a loop+ }++ void regexCompileOnce(List<String> ids) {+ Pattern p = Pattern.compile("[0-9]+"); // NEGATIVE: compiled once, hoisted+ for (String id : ids) {+ p.matcher(id).matches(); // NEGATIVE: matches() is not a sink+ }+ }+}diff --git a/tests/unit/health/test_perf_dialects.py b/tests/unit/health/test_perf_dialects.pynew file mode 100644index 000000000..4f7ac1a2c--- /dev/null+++ b/tests/unit/health/test_perf_dialects.py@@ -0,0 +1,194 @@+"""Unit tests for the Phase-6 perf dialects (Java / Go / C#).++Mirrors ``test_perf_io_in_loop.py`` (Python/TS) but for the three dialects added+on top of the ``PerfDialect`` registry: each exercises the per-grammar callee+arm, the execution-sink lexicon + its evidence gates, the new markers+(``regex_compile_in_loop`` for Java/Go, ``defer_in_loop`` for Go,+sync-over-async ``blocking_sync_in_async`` for C#), and the precision hazards+the plan flags (ambiguous ``find``/``get``/``Find`` collisions, in-memory LINQ).++Grammar availability is best-effort: a missing tree-sitter grammar skips the+case (the walker degrades to "no perf hits", which the registry guarantees).+"""++from __future__ import annotations++from collections import Counter+from pathlib import Path++import pytest++from repowise.core.analysis.health.complexity import walk_file++_FIXTURE_DIR = Path(__file__).resolve().parents[2] / "fixtures" / "lang_samples"+++def _walk(rel: str, lang: str):+ path = _FIXTURE_DIR / rel+ return walk_file(str(path), lang, path.read_bytes())+++def _kinds(perf_hits) -> Counter:+ return Counter(h.kind for h in perf_hits)+++def _hits(lang: str, src: str):+ fc = walk_file(f"t.{lang}", lang, src.encode())+ return sorted((h.kind, h.detail) for h in fc.perf_hits)+++# ---------------------------------------------------------------------------+# Java+# ---------------------------------------------------------------------------+++def test_java_fixture_counts():+ fc = _walk("java/PerfIoInLoop.java", "java")+ counts = _kinds(fc.perf_hits)+ # findByName + executeQuery (db) · Files.readString + new FileInputStream (fs)+ assert counts["io_in_loop"] == 4+ assert {h.detail for h in fc.perf_hits if h.kind == "io_in_loop"} == {"db", "filesystem"}+ assert counts["regex_compile_in_loop"] == 1+ assert counts["string_concat_in_loop"] == 1+ # The hoisted ``Pattern.compile`` and the ``matches()`` / ``length()`` calls+ # do not fire; the out-of-loop ``executeQuery`` does not fire.+ assert counts["blocking_sync_in_async"] == 0+++_JAVA_CASES = [+ (+ "class A{void m(java.util.List<String> ids){"+ "for(String id:ids){ this.repo.findById(id); }}}",+ [("io_in_loop", "db")],+ "Spring-Data findById derived query (no import needed)",+ ),+ (+ "import java.util.Map;\n"+ "class A{void m(java.util.List<String> ks, Map<String,String> cache){"+ "for(String k:ks){ cache.get(k); }}}",+ [],+ "ambiguous get() with NO db import is gated out",+ ),+ (+ "import org.springframework.data.jpa.repository.JpaRepository;\n"+ "class A{void m(java.util.List<String> ks, Repo cache){"+ "for(String k:ks){ cache.get(k); }}}",+ [("io_in_loop", "db")],+ "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); }}}",+ [],+ "a plain helper call in a loop is not a sink",+ ),+]++[email protected]("src,expected,note", _JAVA_CASES, ids=[c[2] for c in _JAVA_CASES])+def test_java_cases(src, expected, note):+ assert _hits("java", src) == sorted(expected), note+++# ---------------------------------------------------------------------------+# Go+# ---------------------------------------------------------------------------+++def test_go_fixture_counts():+ fc = _walk("go/perf_io_in_loop.go", "go")+ counts = _kinds(fc.perf_hits)+ # db (db.Query) · network (http.Get) · filesystem (os.Open ×2, incl. the+ # one in deferInLoop). The constant-bound and out-of-loop queries do not.+ assert counts["io_in_loop"] == 4+ assert {h.detail for h in fc.perf_hits if h.kind == "io_in_loop"} == {+ "db",+ "network",+ "filesystem",+ }+ assert counts["defer_in_loop"] == 1+ assert counts["regex_compile_in_loop"] == 1+ assert counts["string_concat_in_loop"] == 1+++_GO_CASES = [+ (+ 'package m\nimport "gorm.io/gorm"\n'+ "func f(db *gorm.DB, ids []int){ for _, id := range ids { db.Find(id) } }",+ [("io_in_loop", "db")],+ "GORM Find with a gorm import fires",+ ),+ (+ "package m\n"+ "func 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") }',+ [],+ "clause-less for{} is a real loop but the query is outside it",+ ),+ (+ 'package m\nimport "net/http"\n'+ "func f(urls []string){ for _, u := range urls { http.Get(u) } }",+ [("io_in_loop", "network")],+ "net/http Get in a range loop",+ ),+]++[email protected]("src,expected,note", _GO_CASES, ids=[c[2] for c in _GO_CASES])+def test_go_cases(src, expected, note):+ assert _hits("go", src) == sorted(expected), note+++# ---------------------------------------------------------------------------+# C#+# ---------------------------------------------------------------------------+++def test_csharp_fixture_counts():+ fc = _walk("csharp/PerfIoInLoop.cs", "csharp")+ counts = _kinds(fc.perf_hits)+ # db (ToListAsync, SaveChangesAsync, sync ToList) · network (GetAsync) ·+ # filesystem (File.ReadAllText) = 5.+ assert counts["io_in_loop"] == 5+ assert {h.detail for h in fc.perf_hits if h.kind == "io_in_loop"} == {+ "db",+ "network",+ "filesystem",+ }+ assert counts["string_concat_in_loop"] == 1+ # .Result + .Wait() in async; the awaited ``await task`` does not fire.+ assert counts["blocking_sync_in_async"] == 2+++_CSHARP_CASES = [+ (+ "using Microsoft.EntityFrameworkCore;\n"+ "class A{ void M(DbContext ctx, System.Collections.Generic.List<int> ids){"+ "foreach(var id in ids){ ctx.Users.ToList(); }}}",+ [("io_in_loop", "db")],+ "sync ToList WITH an EF import passes the file-level gate",+ ),+ (+ "class A{ void M(System.Collections.Generic.List<int> ids){"+ "foreach(var id in ids){ ids.ToList(); }}}",+ [],+ "in-memory ToList with NO db import is gated out",+ ),+ (+ "class A{ async System.Threading.Tasks.Task M("+ "System.Collections.Generic.List<int> ids){"+ "foreach(var id in ids){ await ctx.Set().FirstOrDefaultAsync(); }}}",+ [("io_in_loop", "db")],+ "EF *Async family is unambiguous db (no import gate)",+ ),+]++[email protected]("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