Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(perf): read a TS/JS import's library from its module string only (#3447)

Raghav Chamadiyab8459cd7e8be
diff --git a/docs/layers/PERFORMANCE.md b/docs/layers/PERFORMANCE.md
index 55dd69ec0..0430f43fb 100644
--- a/docs/layers/PERFORMANCE.md
+++ b/docs/layers/PERFORMANCE.md
@@ -25,6 +25,10 @@ performance signal, never the defect score.
The loop and the I/O call do not have to be in the same function. Repowise
follows the resolved call graph up to three hops and attaches the
caller-to-sink path. Per-function linters cannot see that case.
+An I/O call is recognised by the library its receiver was imported from. In
+TypeScript and JavaScript only the module name counts, so a local variable named
+like a package (`ws`) or a module path that contains a library name
+(`plugin-sdk/provider-http`) is not read as that library.
Performance analysis covers Python, TypeScript/JavaScript (including Vue and
Svelte scripts), Java, Go, C# (including Razor), Rust, Kotlin, Scala, Ruby, C++,
@@ -47,8 +51,9 @@ Each opportunity gets one state:
| `expected` | The repetition is real and nothing should change, such as deleting N files, or the function is switched off by a constant flag (reason `gated_off`) or runs once per deploy, boot or incident (reason `cold_path`), or its loop runs a fixed number of times (reason `bounded_loop`) |
A plan lists its edits, one step per call site and loop, each naming the call it
-repeats. When every site reaches one sink, the step that adds a bulk form of that
-sink comes first. The plan also lists tests to run, found from coverage, the call
+repeats and the kind of I/O that call does (database, network, file system or
+subprocess). When every site reaches one sink, the step that adds a bulk form of
+that sink comes first. The plan also lists tests to run, found from coverage, the call
graph and the import graph. An opportunity with a supported shared fix links to a
`performance_fix` plan in [REFACTORING.md](REFACTORING.md).
diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/text.py b/packages/core/src/repowise/core/analysis/health/fix_first/text.py
index 6cb155e50..e1676d97c 100644
--- a/packages/core/src/repowise/core/analysis/health/fix_first/text.py
+++ b/packages/core/src/repowise/core/analysis/health/fix_first/text.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import posixpath
+from ..perf.actionability import BOUNDARY_NOUN
from ..refactoring.render import brief
TITLE_MAX = 90
@@ -69,13 +70,6 @@ REFACTOR_TITLE: dict[str, str] = {
#: Appended to a why when a duplicate sits in the function being split.
CLONED = "and part of it is duplicated, so splitting it also removes a copy"
-BOUNDARY_NOUN = {
- "db": "database",
- "filesystem": "file system",
- "network": "network",
- "subprocess": "subprocess",
-}
-
#: Performance causes whose cost is not a boundary call: (title, problem, gain).
PERF_SHAPE: dict[str, tuple[str, str, str]] = {
"string_concat_in_loop": (
diff --git a/packages/core/src/repowise/core/analysis/health/perf/actionability.py b/packages/core/src/repowise/core/analysis/health/perf/actionability.py
index 45c4889dd..b2d506c9d 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/actionability.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/actionability.py
@@ -59,6 +59,14 @@ CONCURRENCY_SENSITIVE_BOUNDARIES = frozenset({"db", "network"})
# I/O out of the lock reintroduces the race the lock prevents.
LOCK_SERIALIZED_BOUNDARIES = frozenset({"filesystem", "subprocess"})
+#: What a boundary's call is named in prose ("a database call").
+BOUNDARY_NOUN = {
+ "db": "database",
+ "filesystem": "file system",
+ "network": "network",
+ "subprocess": "subprocess",
+}
+
@dataclass(frozen=True, slots=True)
class PerformanceFix:
@@ -359,6 +367,7 @@ def actionability(
__all__ = [
"BATCHABLE_BOUNDARIES",
"BATCHABLE_MARKERS",
+ "BOUNDARY_NOUN",
"LOCK_SERIALIZED_BOUNDARIES",
"Actionability",
"ActionabilityState",
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 d50f90712..d60fec89a 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
@@ -51,6 +51,19 @@ _IMPORT_KW: frozenset[str] = frozenset(
}
)
_RUST_LOCAL_ROOTS: frozenset[str] = frozenset({"crate", "self", "super"})
+_QUOTED_RE = re.compile(r"""["']([^"']+)["']""")
+# Parts of a TS / JS import statement. The statement names the module, so a part
+# classified alone would read an imported local name (``{ request }``) as a library.
+_ES_IMPORT_PARTS: frozenset[str] = frozenset(
+ {
+ "import_clause",
+ "named_imports",
+ "import_specifier",
+ "namespace_import",
+ "import_require_clause",
+ "import_attribute",
+ }
+)
class _NodeLike(Protocol):
@@ -119,9 +132,9 @@ def _classify_import(node: _NodeLike) -> tuple[str | None, list[str]]:
``"@prisma/client"``, or a Python/Java dotted module's full path + interior
segments + progressive prefixes) is tried until one resolves. When it does,
every importable identifier in the statement is bound to that kind.
- Over-binding is deliberate and harmless: an imported name only becomes a
- finding when it is later *called as an execution sink*, which a non-I/O
- symbol never is.
+ Over-binding is deliberate: an imported name only becomes a finding when it
+ is later *called as an execution sink*. A TS / JS module string is the one
+ exception, since a local named like the package (``ws``) is not the import.
Within one token, the most specific (longest) variant wins; candidates are
tried in a fixed order so the result never depends on set iteration, which
@@ -131,9 +144,19 @@ def _classify_import(node: _NodeLike) -> tuple[str | None, list[str]]:
one member's kind onto another (#2894).
"""
text = _decode(node)
- # TS / JS module sources are quoted string literals, tried first; then
- # Python / Java / ... dotted modules and bare identifiers.
- tokens = re.findall(r"""["']([^"']+)["']""", text) + re.findall(r"[A-Za-z0-9_.:@/]+", text)
+ source = _es_module_source(node)
+ if source is not None:
+ # A TS / JS import names its module once; an import attribute
+ # (``with { type: "json" }``) is not a module. Only the clause before
+ # the module binds: ``import { WebSocket } from "ws"`` leaves ``ws`` unbound.
+ module = _decode(source)
+ tokens = [module.strip("\"'`")]
+ text = text[: text.find(module)]
+ else:
+ # A quoted module (Go / Ruby / Dart) is classified whole: split on its
+ # hyphens it would name libraries it is not (``provider-http`` -> ``http``).
+ # Python / Java / ... dotted modules and bare identifiers otherwise.
+ tokens = _QUOTED_RE.findall(text) or re.findall(r"[A-Za-z0-9_.:@/]+", text)
kind: str | None = None
for tok in tokens:
@@ -152,6 +175,16 @@ def _classify_import(node: _NodeLike) -> tuple[str | None, list[str]]:
return kind, bound
+def _es_module_source(node: _NodeLike) -> _NodeLike | None:
+ """The module string of a TS / JS import (``from "ws"`` / ``require("ws")``)."""
+ for holder in (node, *(c for c in node.children if c.type == "import_require_clause")):
+ get = getattr(holder, "child_by_field_name", None)
+ source = get("source") if get is not None else None
+ if source is not None:
+ return source
+ return None
+
+
def _rust_use_argument(node: _NodeLike) -> _NodeLike | None:
"""The use tree of a ``use_declaration`` (the part after ``use``)."""
arg = node.child_by_field_name("argument") if hasattr(node, "child_by_field_name") else None
@@ -331,7 +364,9 @@ def _io_visit(
names.setdefault(name, kind)
elif node_type == "use_declaration" and language == "rust":
_bind_rust_use_names(node, names)
- elif "import" in node_type or node_type in ("using_directive", "use_declaration"):
+ elif (
+ "import" in node_type or node_type in ("using_directive", "use_declaration")
+ ) and node_type not in _ES_IMPORT_PARTS:
# 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
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/performance_fix.py b/packages/core/src/repowise/core/analysis/health/refactoring/performance_fix.py
index f4a2e755d..25355d2d5 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/performance_fix.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/performance_fix.py
@@ -8,7 +8,7 @@ from typing import Any
from repowise.core.analysis.execution_graph import file_of_symbol
-from ..perf.actionability import PerformanceFix
+from ..perf.actionability import BOUNDARY_NOUN, PerformanceFix
from ..perf.opportunities import PerformanceOpportunity
from ..perf.opportunity_rank import band
from .models import RefactoringSuggestion
@@ -74,14 +74,16 @@ def fix_steps(
sink: str | None,
locations: list[dict[str, object]],
api: str | None = None,
+ boundary: str | None = None,
) -> list[dict[str, object]]:
"""Ordered edits for one plan; mechanical only when the strategy is proven.
*sink* is the sink every site shares, or ``None``: a bulk form added to one
- member's sink would leave the other sites' calls per-key.
+ member's sink would leave the other sites' calls per-key. *boundary* is the
+ I/O kind every site's call reaches, which the step names.
"""
steps = _intro_steps(strategy, intervention, sink, api)
- steps += _site_steps(strategy, safety, locations, api)
+ steps += _site_steps(strategy, safety, locations, api, boundary)
return [{"order": index, **step} for index, step in enumerate(steps, 1)]
@@ -108,7 +110,11 @@ def _intro_steps(
def _site_steps(
- strategy: str, safety: str, locations: list[dict[str, object]], api: str | None
+ strategy: str,
+ safety: str,
+ locations: list[dict[str, object]],
+ api: str | None,
+ boundary: str | None = None,
) -> list[dict[str, object]]:
"""One step per place that changes: a call site, or a loop and variable."""
_, per_site = (_API_STEPS if api else _STEPS).get(strategy, (None, ""))
@@ -130,7 +136,9 @@ def _site_steps(
]
return [
{
- "action": per_site.format(api=api, call=_call_phrase(location.get("call"))),
+ "action": per_site.format(
+ api=api, call=_call_phrase(location.get("call"), boundary)
+ ),
"symbol": location.get("function_name"),
"file_path": location.get("file_path"),
"line": location.get("line_start"),
@@ -161,8 +169,10 @@ def _loop_edits(locations: list[dict[str, object]]) -> list[dict[str, object]]:
return list(edits.values())
-def _call_phrase(call: object) -> str:
- return f"{call} call" if call else "call"
+def _call_phrase(call: object, boundary: str | None) -> str:
+ """``session.get database call``: the call and the kind of I/O it does."""
+ noun = BOUNDARY_NOUN.get(boundary or "")
+ return " ".join(str(part) for part in (call, noun, "call") if part)
_EFFORT_BANDS = ((1, "S"), (3, "M"), (8, "L"))
@@ -274,7 +284,9 @@ def _suggestion(
_shared_sink(opportunity),
fix.api,
)
- edits = _site_steps(fix.strategy, fix.safety, locations, fix.api)
+ edits = _site_steps(
+ fix.strategy, fix.safety, locations, fix.api, opportunity.boundary_kind
+ )
steps = [{"order": index, **step} for index, step in enumerate(intro + edits, 1)]
# One edit per site, as before, less the sites a loop's one step covers.
# Sites past the evidence cap stay one each: nothing says which share a loop.
diff --git a/packages/core/src/repowise/core/ingestion/external_systems/io_kind.py b/packages/core/src/repowise/core/ingestion/external_systems/io_kind.py
index 1f396ee28..6b1b6934c 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
@@ -44,7 +44,7 @@ _DB_NAMES: frozenset[str] = frozenset({
"elasticsearch", "neo4j", "sqlmodel", "peewee", "tortoise-orm", "databases",
"duckdb", "clickhouse-driver", "pyodbc",
# TS / Node (cassandra-driver above is published in both ecosystems)
- "ioredis", "mongoose", "mongodb", "@prisma/client", "prisma",
+ "ioredis", "mongoose", "mongodb", "@prisma/client", "prisma", "pg-promise", "redis-om",
"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
@@ -84,7 +84,8 @@ _NETWORK_NAMES: frozenset[str] = frozenset({
"httpx", "requests", "aiohttp", "urllib3", "websockets", "websocket-client",
"grpcio", "httpcore", "tornado", "treq", "niquests", "socket",
# TS / Node
- "axios", "node-fetch", "got", "superagent", "undici", "ky", "needle",
+ "axios", "node-fetch", "got", "superagent", "undici", "ky", "needle", "cross-fetch",
+ "isomorphic-ws",
"request", "@grpc/grpc-js", "ws", "socket.io-client", "graphql-request",
# JVM
"java.net.http", "okhttp3", "retrofit2", "feign", "org.apache.http",
@@ -186,4 +187,6 @@ def classify_io_kind(name: str) -> str | None:
"""
if not name:
return None
- return _BY_NAME.get(name.strip().lower())
+ key = name.strip().lower()
+ # ``node:http`` is Node's spelling of the ``http`` builtin.
+ return _BY_NAME.get(key) or _BY_NAME.get(key.removeprefix("node:"))
diff --git a/tests/fixtures/perf_corpus/golden_plans.json b/tests/fixtures/perf_corpus/golden_plans.json
index 1629e0b2f..7c76bb057 100644
--- a/tests/fixtures/perf_corpus/golden_plans.json
+++ b/tests/fixtures/perf_corpus/golden_plans.json
@@ -76,7 +76,7 @@
"safety": "advisory",
"steps": [
{
- "action": "Collect the keys before the loop and replace the per-key call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/jobs.py",
"line": 40,
@@ -84,7 +84,7 @@
"symbol": "drain"
},
{
- "action": "Collect the keys before the loop and replace the per-key call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/jobs.py",
"line": 42,
@@ -92,7 +92,7 @@
"symbol": "drain"
},
{
- "action": "Collect the keys before the loop and replace the per-key save call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key save database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/jobs.py",
"line": 44,
@@ -191,7 +191,7 @@
"symbol": "src/app/reindex.py::_write"
},
{
- "action": "Collect the keys before the loop and replace the per-key _write call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key _write database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/reindex.py",
"line": 210,
@@ -199,7 +199,7 @@
"symbol": "one"
},
{
- "action": "Collect the keys before the loop and replace the per-key _write call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key _write database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/reindex.py",
"line": 215,
@@ -270,7 +270,7 @@
"safety": "proven",
"steps": [
{
- "action": "Collect the keys before the loop and make one call with .in_(\"repo_id\", keys) in place of the per-key call",
+ "action": "Collect the keys before the loop and make one call with .in_(\"repo_id\", keys) in place of the per-key database call",
"applicability": "mechanical",
"file_path": "src/app/owners.py",
"line": 20,
@@ -369,7 +369,7 @@
"safety": "advisory",
"steps": [
{
- "action": "Collect the keys before the loop and replace the per-key _move call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key _move database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/ledger.py",
"line": 587,
@@ -377,7 +377,7 @@
"symbol": "apply"
},
{
- "action": "Collect the keys before the loop and replace the per-key _fold_one call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key _fold_one database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/ledger.py",
"line": 590,
@@ -385,7 +385,7 @@
"symbol": "apply"
},
{
- "action": "Collect the keys before the loop and replace the per-key _write_alias call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key _write_alias database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/ledger.py",
"line": 591,
@@ -483,7 +483,7 @@
"symbol": "src/app/entry.py::_hit"
},
{
- "action": "Collect the keys before the loop and replace the per-key _hit call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key _hit database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/entry.py",
"line": 250,
@@ -491,7 +491,7 @@
"symbol": "a"
},
{
- "action": "Collect the keys before the loop and replace the per-key _hit call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key _hit database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/entry.py",
"line": 255,
@@ -589,7 +589,7 @@
"symbol": "src/app/repo.py::fetch_page"
},
{
- "action": "Collect the keys before the loop and replace the per-key fetch_page call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key fetch_page database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/api.py",
"line": 30,
@@ -597,7 +597,7 @@
"symbol": "list_users"
},
{
- "action": "Collect the keys before the loop and replace the per-key fetch_page call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key fetch_page database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/api.py",
"line": 31,
@@ -695,7 +695,7 @@
"symbol": "src/app/sync.py::_load"
},
{
- "action": "Collect the keys before the loop and replace the per-key _load call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key _load database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/sync.py",
"line": 70,
@@ -703,7 +703,7 @@
"symbol": "sync_one"
},
{
- "action": "Collect the keys before the loop and replace the per-key _load call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key _load database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/sync.py",
"line": 71,
@@ -851,7 +851,7 @@
"safety": "proven",
"steps": [
{
- "action": "Run the independent calls concurrently, each still inside self._sem",
+ "action": "Run the independent network calls concurrently, each still inside self._sem",
"applicability": "mechanical",
"file_path": "src/app/fetch.py",
"line": 40,
@@ -922,7 +922,7 @@
"safety": "advisory",
"steps": [
{
- "action": "Collect the keys before the loop and make one call with .in_(\"repo_id\", keys) in place of the per-key call",
+ "action": "Collect the keys before the loop and make one call with .in_(\"repo_id\", keys) in place of the per-key database call",
"applicability": "judgment",
"file_path": "src/app/commits.py",
"line": 30,
@@ -993,7 +993,7 @@
"safety": "advisory",
"steps": [
{
- "action": "Run the independent calls concurrently, with a bound on how many at once",
+ "action": "Run the independent network calls concurrently, with a bound on how many at once",
"applicability": "judgment",
"file_path": "src/app/fanout.py",
"line": 90,
@@ -1078,7 +1078,7 @@
"symbol": "src/app/db.py::get_session"
},
{
- "action": "Collect the keys before the loop and replace the per-key get_session call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key get_session database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/job.py",
"line": 200,
@@ -1161,7 +1161,7 @@
"symbol": "src/app/db.py::only_sink"
},
{
- "action": "Collect the keys before the loop and replace the per-key call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/lone.py",
"line": 9,
@@ -1370,7 +1370,7 @@
"symbol": "src/app/db.py::get_session"
},
{
- "action": "Collect the keys before the loop and replace the per-key get_session call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key get_session database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/orders.py",
"line": 10,
@@ -1455,7 +1455,7 @@
"symbol": "src/app/db.py::get_session"
},
{
- "action": "Collect the keys before the loop and replace the per-key get_session call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key get_session database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/reports.py",
"line": 12,
@@ -1540,7 +1540,7 @@
"symbol": "src/app/db.py::get_session"
},
{
- "action": "Collect the keys before the loop and replace the per-key get_session call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key get_session database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/billing.py",
"line": 11,
@@ -1625,7 +1625,7 @@
"symbol": "src/app/db.py::get_session"
},
{
- "action": "Collect the keys before the loop and replace the per-key get_session call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key get_session database call with one batched call",
"applicability": "judgment",
"file_path": "scripts/backfill.py",
"line": 200,
@@ -1710,7 +1710,7 @@
"symbol": "src/app/db.py::reliable_sink"
},
{
- "action": "Collect the keys before the loop and replace the per-key reliable_sink call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key reliable_sink database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/edge.py",
"line": 230,
@@ -1795,7 +1795,7 @@
"symbol": "src/app/db.py::guessed_sink"
},
{
- "action": "Collect the keys before the loop and replace the per-key guessed_sink call with one batched call",
+ "action": "Collect the keys before the loop and replace the per-key guessed_sink database call with one batched call",
"applicability": "judgment",
"file_path": "src/app/guess.py",
"line": 240,
diff --git a/tests/unit/health/test_perf_io_in_loop.py b/tests/unit/health/test_perf_io_in_loop.py
index 96e461369..cf77fd8b6 100644
--- a/tests/unit/health/test_perf_io_in_loop.py
+++ b/tests/unit/health/test_perf_io_in_loop.py
@@ -399,6 +399,65 @@ def test_io_in_loop_fires_regardless_of_grouped_use_order():
assert ("io_in_loop", "db") in {(h.kind, h.detail) for h in fc.perf_hits}
+def test_a_ts_module_string_binds_no_name_of_its_own():
+ # A local named like the package (``ws``) is a loop variable, not the import.
+ src = (
+ b'import { type WebSocket, WebSocketServer } from "ws";\n'
+ b"function broadcast(sockets: Set<WebSocket>) {\n"
+ b' for (const ws of sockets) { ws.send("reload"); }\n'
+ b"}\n"
+ )
+ fc = walk_file("t.ts", "typescript", src)
+ assert fc.io_boundary_names == {"WebSocket": "network", "WebSocketServer": "network"}
+ assert not fc.perf_hits
+
+
+def test_a_hyphenated_ts_module_path_names_no_library():
+ # ``provider-http`` is a local helper module, not the ``http`` package.
+ fc = walk_file(
+ "t.ts",
+ "typescript",
+ b'import { readBody } from "openclaw/plugin-sdk/provider-http";\n'
+ b'import { request } from "./client.js";\n',
+ )
+ assert fc.io_boundary_names == {}
+
+
+ ("source", "expected"),
+ [
+ (b'import http from "node:http";\n', {"http": "network"}),
+ (b'import x = require("axios");\n', {"x": "network"}),
+ (b'import * as fs from "node:fs/promises";\n', {"fs": "filesystem"}),
+ (b'import { PrismaClient } from "@prisma/client";\n', {"PrismaClient": "db"}),
+ (b'import type { Pool } from "pg";\n', {"Pool": "db"}),
+ (b'import ws from "ws";\n', {"ws": "network"}),
+ (b'import "ws";\n', {}),
+ (b'import cfg from "./c.json" with { type: "http" };\n', {}),
+ (b'import cfg from "./c.json" assert { type: "pg" };\n', {}),
+ (b'import { Pool } from "pg" with { type: "json" };\n', {"Pool": "db"}),
+ ],
+)
+def test_a_ts_import_binds_only_its_clause_names(source: bytes, expected: dict[str, str]):
+ assert walk_file("t.ts", "typescript", source).io_boundary_names == expected
+
+
+ ("path", "language", "source", "expected"),
+ [
+ (
+ "t.go",
+ "go",
+ b'package p\nimport h "net/http"\n',
+ {"h": "network", "net": "network", "http": "network"},
+ ),
+ ("t.rb", "ruby", b'require "net/http"\n', {"net": "network", "http": "network"}),
+ ],
+)
+def test_go_and_ruby_still_bind_through_the_quoted_path(path, language, source, expected):
+ assert walk_file(path, language, source).io_boundary_names == expected
+
+
class _FakeImportNode:
def __init__(self, node_type: str, text: bytes, children: list[_FakeImportNode] | None = None):
self.type = node_type
diff --git a/tests/unit/health/test_perf_plan_steps.py b/tests/unit/health/test_perf_plan_steps.py
index 61eb093a5..a39616cc2 100644
--- a/tests/unit/health/test_perf_plan_steps.py
+++ b/tests/unit/health/test_perf_plan_steps.py
@@ -10,6 +10,7 @@ from __future__ import annotations
from repowise.core.analysis.health.complexity import walk_file
from repowise.core.analysis.health.perf.opportunities import build_performance_opportunities
from repowise.core.analysis.health.refactoring.performance_fix import (
+ fix_steps,
performance_fix_suggestions,
)
from tests.unit.health.test_perf_opportunities import _finding
@@ -82,7 +83,16 @@ def test_sites_that_reach_one_sink_keep_the_bulk_form_step_and_every_site() -> N
("b.py", 20),
("b.py", 25),
]
- assert all("load call" in s["action"] for s in steps[1:])
+ assert all("load database call" in s["action"] for s in steps[1:])
+
+
+def test_each_site_step_names_the_kind_of_io_it_repeats() -> None:
+ network = _steps([_finding("a.py", 10, loop_line=8, sink_call="client.get", boundary="network")])
+ site = [{"file_path": "a.py", "function_name": "run", "line_start": 10, "call": "client.get"}]
+ unknown = fix_steps("batch_or_prefetch_io", "proven", None, None, site)
+
+ assert "per-key client.get network call" in network[-1]["action"]
+ assert "per-key client.get call" in unknown[-1]["action"]
def test_direct_calls_with_no_sink_get_no_unnamed_bulk_form_step() -> None:
diff --git a/tests/unit/ingestion/test_io_kind.py b/tests/unit/ingestion/test_io_kind.py
index 2964c5ea5..edb588edf 100644
--- a/tests/unit/ingestion/test_io_kind.py
+++ b/tests/unit/ingestion/test_io_kind.py
@@ -90,3 +90,18 @@ def test_pascal_bare_system_prefix_is_not_seeded() -> None:
seeding the short prefixes by accident."""
assert classify_io_kind("system") is None
assert classify_io_kind("system.net") is None
+
+
+ ("name", "kind"),
+ [
+ ("isomorphic-ws", "network"),
+ ("cross-fetch", "network"),
+ ("pg-promise", "db"),
+ ("redis-om", "db"),
+ ("node:http", "network"),
+ ("node:child_process", "subprocess"),
+ ],
+)
+def test_compound_and_node_scheme_names_classify_whole(name: str, kind: str) -> None:
+ assert classify_io_kind(name) == kind