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.

feat(health): flag Spring Data repository and MyBatis mapper calls in Java loops (#3615)

Raghav Chamadiyaeb17b9b65ab5
diff --git a/docs/layers/PERFORMANCE.md b/docs/layers/PERFORMANCE.md
index bac87665a..3d4c277fc 100644
--- a/docs/layers/PERFORMANCE.md
+++ b/docs/layers/PERFORMANCE.md
@@ -40,6 +40,11 @@ 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.
+In Java, any call on a Spring Data repository or a MyBatis mapper inside a `for`
+loop counts as a database call, whatever the method is named. The receiver's
+declared type decides: an interface that extends a Spring Data repository, carries
+`@Mapper`, or sits in a `@MapperScan` package. JPA lazy associations read in a loop
+are not reported yet.
Performance analysis covers Python, TypeScript/JavaScript (including Vue and
Svelte scripts), Java, Go, C# (including Razor), Rust, Kotlin, Scala, Ruby, C++,
diff --git a/packages/core/src/repowise/core/analysis/health/perf/lazy_load.py b/packages/core/src/repowise/core/analysis/health/perf/lazy_load.py
index 4ef9bca58..2a5819942 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/lazy_load.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/lazy_load.py
@@ -28,6 +28,7 @@ from .orm_models import (
build_model_index,
)
from .reduction_idioms import field_text, ident, walk
+from .repository_loops import collect_repository_loops
if TYPE_CHECKING:
from collections.abc import Callable, Iterable
@@ -97,7 +98,10 @@ def collect_lazy_loads(
parsed_files: Iterable[Any],
read_source: SourceReader | None = None,
) -> None:
- """Append hits to each walked file's ``perf_hits``; one file failing skips only it."""
+ """Append hits to each walked file's ``perf_hits``; one file failing skips only it.
+ The Java repository/mapper pass rides this ORM entry point."""
+ # Both passes read both inputs, so a one-shot iterable is materialized once.
+ walked, parsed_files = list(walked), list(parsed_files)
reader = read_source or _disk_read
index = build_model_index(parsed_files, reader)
for pf, fcx in walked:
@@ -105,6 +109,7 @@ def collect_lazy_loads(
fcx.perf_hits.extend(_file_hits(pf, reader, index))
except Exception as exc:
log.debug("lazy_load_failed", path=pf.file_info.abs_path, error=str(exc))
+ collect_repository_loops(walked, parsed_files, reader)
def _disk_read(abs_path: str) -> bytes | None:
diff --git a/packages/core/src/repowise/core/analysis/health/perf/repository_loops.py b/packages/core/src/repowise/core/analysis/health/perf/repository_loops.py
new file mode 100644
index 000000000..5552ae81e
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/perf/repository_loops.py
@@ -0,0 +1,345 @@
+"""A Spring Data repository or MyBatis mapper call on each iteration of a loop.
+
+The Java sink lexicon (:mod:`.dialects.java`) reads call names, so it misses
+mapper verbs (``insert``, ``selectByPrimaryKey``) and cannot tell a repository
+from a map. Here the receiver's declared type decides: a field, parameter or
+local typed to an interface the repo's own facts prove is persistence, through
+its ``extends`` chain to a Spring Data base, a MyBatis ``@Mapper``, or a
+``@MapperScan`` package. Hits are same-function ``io_in_loop`` (boundary
+``db``); a line the walker already flagged is left to it. Java only.
+"""
+
+from __future__ import annotations
+
+import re
+from functools import cache
+from pathlib import PurePosixPath
+from typing import TYPE_CHECKING, Any
+
+import structlog
+
+from ..complexity.ast_utils import _collect_function_nodes, _find_function_entry_name
+from ..complexity.models import PerfHit
+from ..complexity.perf_walk import _loop_key_feeds, _sink_call_text
+from .dialects import PERF_DIALECTS
+from .io_boundaries import collect_io_names
+from .loop_facts import LoopFacts, LoopSource
+from .reduction_idioms import walk
+
+if TYPE_CHECKING:
+ from collections.abc import Iterable
+
+ from tree_sitter import Node
+
+ from ..complexity.models import FileComplexity
+ from ..source_reader import SourceReader
+ from .dialects.base import BasePerfDialect
+
+log = structlog.get_logger(__name__)
+
+_SPRING_DATA = "org.springframework.data."
+_SPRING_DATA_BASES = frozenset(
+ {
+ "Repository", "CrudRepository", "ListCrudRepository", "PagingAndSortingRepository",
+ "ListPagingAndSortingRepository", "JpaRepository", "MongoRepository",
+ "ElasticsearchRepository", "JpaSpecificationExecutor", "QuerydslPredicateExecutor",
+ }
+)
+_MYBATIS = ("org.apache.ibatis.", "org.mybatis.")
+_MAPPER_SCAN = re.compile(r"@MapperScan\s*\(([^)]*)\)")
+_QUOTED = re.compile(r'"([\w.]+)"')
+_MAPPER = re.compile(r"@Mapper\b")
+# A plain or package-qualified type; generics (``List<FooMapper>``) and arrays are not the receiver's type.
+_PLAIN_TYPE = re.compile(r"[\w.]+")
+_SKIP_SCOPES = frozenset({"class_body", "interface_body", "enum_body"})
+# Enhanced-for only: the shape measured on the Spring corpus. Counted ``for`` and
+# ``forEach`` lambdas over the same rows are the same cost; add them once measured.
+_LOOP = "enhanced_for_statement"
+
+
+# -- which interfaces are persistence -------------------------------------------
+
+
+def _imported_from(pf: Any, name: str, prefixes: tuple[str, ...]) -> bool:
+ """*name* is bound in *pf* by an import from a package under *prefixes*."""
+ for imp in pf.imports:
+ path = imp.module_path or ""
+ if not path.startswith(prefixes):
+ continue
+ if path.endswith("." + name) or path.endswith(".*"):
+ return True
+ return False
+
+
+def _folder(path: str) -> str:
+ return "/" + str(PurePosixPath(path).parent)
+
+
+def _resolves_to(pf: Any, name: str, decl_path: str) -> bool:
+ """Whether *name* in *pf* means the repo's one declaration at *decl_path*, in
+ Java's order: a single-type import, then the same package, then an on-demand
+ import. A name imported from anywhere else is another type."""
+ single = [
+ imp.module_path for imp in pf.imports
+ if (imp.module_path or "").endswith("." + name)
+ ]
+ if single:
+ target = "/" + decl_path.rsplit(".", 1)[0]
+ return any(target.endswith("/" + fqn.replace(".", "/")) for fqn in single)
+ folder = _folder(decl_path)
+ if _folder(pf.file_info.path) == folder:
+ return True
+ return any(
+ folder.endswith("/" + imp.module_path[:-2].replace(".", "/"))
+ for imp in pf.imports
+ if (imp.module_path or "").endswith(".*")
+ )
+
+
+def _scan_packages(pf: Any) -> set[str]:
+ """Package directories (``com/acme/mapper``) a ``@MapperScan`` in *pf* names."""
+ if not _imported_from(pf, "MapperScan", _MYBATIS):
+ return set()
+ found: set[str] = set()
+ for sym in pf.symbols:
+ for deco in sym.decorators:
+ for args in _MAPPER_SCAN.findall(deco):
+ found.update(p.replace(".", "/") for p in _QUOTED.findall(args))
+ return found
+
+
+def _in_package(path: str, packages: set[str]) -> bool:
+ folder = "/" + str(PurePosixPath(path).parent) + "/"
+ return any(f"/{pkg}/" in folder for pkg in packages)
+
+
+def _seed_interface(pf: Any, sym: Any, parents: list[str], packages: set[str]) -> bool:
+ if any(p in _SPRING_DATA_BASES and _imported_from(pf, p, (_SPRING_DATA,)) for p in parents):
+ return True
+ mapper = any(_MAPPER.search(d) for d in sym.decorators)
+ if mapper and _imported_from(pf, "Mapper", _MYBATIS):
+ return True
+ return _in_package(pf.file_info.path, packages)
+
+
+def persistence_types(parsed_files: Iterable[Any]) -> frozenset[str]:
+ """Simple names of the repo's interfaces proven to be repositories or mappers.
+
+ A simple name declared by more than one type is never trusted, as a receiver
+ type or as a base others inherit from: it could mean either declaration.
+ """
+ java = [pf for pf in parsed_files if pf.file_info.language == "java"]
+ packages = {pkg for pf in java for pkg in _scan_packages(pf)}
+ # (child, its file, the parent names it extends) per interface declaration.
+ interfaces: list[tuple[str, Any, list[str]]] = []
+ declared_in: dict[str, list[str]] = {}
+ typed: set[str] = set()
+ for pf in java:
+ parents: dict[str, list[str]] = {}
+ for h in pf.heritage:
+ parents.setdefault(h.child_name, []).append(h.parent_name)
+ for sym in pf.symbols:
+ if sym.kind not in ("class", "interface", "enum"):
+ continue
+ declared_in.setdefault(sym.name, []).append(pf.file_info.path)
+ if sym.kind != "interface":
+ continue
+ own = parents.get(sym.name, [])
+ interfaces.append((sym.name, pf, own))
+ if _seed_interface(pf, sym, own, packages):
+ typed.add(sym.name)
+ unique = {name: paths[0] for name, paths in declared_in.items() if len(paths) == 1}
+ typed &= set(unique)
+ edges = [
+ (child, parent)
+ for child, pf, own in interfaces
+ if child in unique
+ for parent in own
+ if parent in unique and _resolves_to(pf, parent, unique[parent])
+ ]
+ grew = True
+ while grew:
+ grew = False
+ for child, parent in edges:
+ if child not in typed and parent in typed:
+ typed.add(child)
+ grew = True
+ return frozenset(typed)
+
+
+# -- per-file scan -----------------------------------------------------------------
+
+
+def _text(node: Node | None) -> str:
+ return node.text.decode("utf-8", "replace") if node is not None and node.text else ""
+
+
+@cache
+def _declared_types() -> Any:
+ """The Java dataflow dialect's declared-type reader, with fields added: the
+ receiver is usually an injected field."""
+ from ..dataflow.dialects.base import DeclaredTypes # deferred: dataflow imports perf
+
+ return DeclaredTypes(
+ frozenset({"formal_parameter", "local_variable_declaration", "field_declaration"}),
+ frozenset({"variable_declarator"}),
+ )
+
+
+def _declared(node: Node) -> list[tuple[str, str]]:
+ """``(name, simple type)`` for each name a field, local or parameter declares."""
+ if node.type == "formal_parameter":
+ names = [node.child_by_field_name("name")]
+ else:
+ names = [d.child_by_field_name("name") for d in node.children if d.type == "variable_declarator"]
+ out = []
+ for name in names:
+ typ = _declared_types().of(name) if name is not None else None
+ plain = typ is not None and _PLAIN_TYPE.fullmatch(typ)
+ out.append((_text(name), typ.rsplit(".", 1)[-1] if plain else ""))
+ return out
+
+
+def _class_fields(fn: Node) -> dict[str, str]:
+ body = fn.parent
+ while body is not None and body.type not in _SKIP_SCOPES:
+ body = body.parent
+ out: dict[str, str] = {}
+ for member in body.children if body is not None else ():
+ if member.type == "field_declaration":
+ out.update(_declared(member))
+ return out
+
+
+def _receivers(fn: Node, types: frozenset[str]) -> dict[str, str]:
+ """Names bound in *fn* to a persistence type. A parameter or local of another
+ type shadows a field of the same name, wherever it is declared."""
+ bound = _class_fields(fn)
+ for node in walk(fn, _SKIP_SCOPES):
+ if node.type in ("formal_parameter", "local_variable_declaration"):
+ bound.update(_declared(node))
+ return {name: t for name, t in bound.items() if t in types}
+
+
+def _receiver_name(call: Node) -> str:
+ obj = call.child_by_field_name("object")
+ if obj is None:
+ return ""
+ if obj.type == "identifier":
+ return _text(obj)
+ if obj.type == "field_access" and _text(obj.child_by_field_name("object")) == "this":
+ return _text(obj.child_by_field_name("field"))
+ return ""
+
+
+def _loop_facts(
+ call: Node, loop: Node, source: LoopSource | None, dialect: BasePerfDialect, lmap: Any
+) -> LoopFacts:
+ return LoopFacts(
+ chunked=dialect.is_chunked_loop(loop),
+ magnitude=source.magnitude if source is not None else "unknown",
+ iterates=source.iterates if source is not None else "unknown",
+ key_unused=not _loop_key_feeds(call, loop),
+ not_batchable=dialect.not_batchable(call, loop, lmap.loop_kinds),
+ )
+
+
+def _loop_hits(
+ loop: Node, fn: Node, fn_name: str | None, receivers: dict[str, str], ctx: dict[str, Any]
+) -> list[PerfHit]:
+ dialect: BasePerfDialect = ctx["dialect"]
+ body = loop.child_by_field_name("body")
+ if body is None:
+ return []
+ source = dialect.loop_source(loop, ctx["probe"])
+ if source is not None and source.iterates == "constant":
+ return []
+ hits: list[PerfHit] = []
+ for call in walk(body, _SKIP_SCOPES):
+ if call.type != "method_invocation" or _receiver_name(call) not in receivers:
+ continue
+ line = call.start_point[0] + 1
+ if line in ctx["taken"]:
+ continue
+ ctx["taken"].add(line)
+ method = dialect.callee_method_name(call) or ""
+ hits.append(
+ PerfHit(
+ "io_in_loop", line, fn_name, "db",
+ func_start=fn.start_point[0] + 1,
+ loop=_loop_facts(call, loop, source, dialect, ctx["lmap"]),
+ loop_line=loop.start_point[0] + 1,
+ sink_call=_sink_call_text(call, method, dialect),
+ )
+ )
+ return hits
+
+
+def _probe(dialect: BasePerfDialect, io_names: dict[str, str], receivers: dict[str, str]) -> Any:
+ """The walker's sink probe, plus a call on a persistence-typed receiver."""
+ has_db = any(v == "db" for v in io_names.values())
+
+ def probe(call: Node) -> str | None:
+ if call.type == "method_invocation" and _receiver_name(call) in receivers:
+ return "db"
+ return dialect.call_sink_kind(call, awaited=False, io_names=io_names, has_db_import=has_db)
+
+ return probe
+
+
+def _file_hits(
+ pf: Any, fcx: FileComplexity, source: bytes, types: frozenset[str]
+) -> list[PerfHit]:
+ from ..dataflow.parsing import parse_source # deferred: dataflow imports perf
+
+ # The walker keeps no trees, so parse again, as lazy_load does; only files
+ # whose type references name a persistence type reach here.
+ parsed = parse_source(pf.file_info.abs_path, "java", source)
+ dialect = PERF_DIALECTS.get("java")
+ if parsed is None or dialect is None:
+ return []
+ root, lmap = parsed
+ io_names = collect_io_names(root, "java")
+ taken = {h.line for h in fcx.perf_hits if h.kind == "io_in_loop"}
+ hits: list[PerfHit] = []
+ for fn in _collect_function_nodes(root, lmap):
+ receivers = _receivers(fn, types)
+ if not receivers:
+ continue
+ ctx = {
+ "dialect": dialect,
+ "lmap": lmap,
+ "probe": _probe(dialect, io_names, receivers),
+ "taken": taken,
+ }
+ name = _find_function_entry_name(fn, lmap)
+ for loop in walk(fn, _SKIP_SCOPES):
+ if loop.type == _LOOP:
+ hits.extend(_loop_hits(loop, fn, name, receivers, ctx))
+ return hits
+
+
+def collect_repository_loops(
+ walked: Iterable[tuple[Any, FileComplexity]],
+ parsed_files: Iterable[Any],
+ read_source: SourceReader,
+) -> None:
+ """Append hits to each walked Java file's ``perf_hits``; one file failing skips only it."""
+ walked = [(pf, fcx) for pf, fcx in walked if pf.file_info.language == "java"]
+ if not walked:
+ return
+ types = persistence_types(parsed_files)
+ if not types:
+ return
+ for pf, fcx in walked:
+ if pf.file_info.is_test or not any(r.type_name in types for r in pf.type_refs):
+ continue
+ try:
+ source = read_source(pf.file_info.abs_path)
+ if source is not None:
+ fcx.perf_hits.extend(_file_hits(pf, fcx, source, types))
+ except Exception as exc:
+ log.debug("repository_loops_failed", path=pf.file_info.abs_path, error=str(exc))
+
+
+__all__ = ["collect_repository_loops", "persistence_types"]
diff --git a/tests/unit/health/test_perf_repository_loops.py b/tests/unit/health/test_perf_repository_loops.py
new file mode 100644
index 000000000..28410d1d1
--- /dev/null
+++ b/tests/unit/health/test_perf_repository_loops.py
@@ -0,0 +1,361 @@
+"""Unit tests for the typed Java repository / mapper call in a loop.
+
+Each fixture is a small Java tree parsed by the real ingestion parser, so the
+heritage, imports, annotations and type references the pass reads are the ones
+an index would hold. ``walked`` lists only the file being scored.
+"""
+
+from __future__ import annotations
+
+import textwrap
+from datetime import datetime
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.health.complexity import FileComplexity, PerfHit
+from repowise.core.analysis.health.perf.lazy_load import collect_lazy_loads
+from repowise.core.analysis.health.perf.repository_loops import persistence_types
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import parse_file
+
+
+def _require_java() -> None:
+ from repowise.core.ingestion.parser import _get_language
+
+ if _get_language("java") is None:
+ pytest.skip("tree-sitter language pack missing for java")
+
+
+def _parse(tmp_path: Path, rel: str, src: str, *, is_test: bool = False):
+ p = tmp_path / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(textwrap.dedent(src), encoding="utf-8")
+ info = FileInfo(
+ path=rel, abs_path=str(p), language="java", size_bytes=p.stat().st_size, git_hash="",
+ last_modified=datetime.now(), is_test=is_test, is_config=False, is_api_contract=False,
+ is_entry_point=False,
+ )
+ return parse_file(info, p.read_bytes())
+
+
+def _hits(tmp_path: Path, files: dict[str, str], scored: str, *, is_test: bool = False,
+ seeded: list[PerfHit] | None = None) -> list[PerfHit]:
+ _require_java()
+ parsed = {rel: _parse(tmp_path, rel, src, is_test=is_test and rel == scored)
+ for rel, src in files.items()}
+ fcx = FileComplexity(functions=[], classes=[])
+ fcx.perf_hits.extend(seeded or [])
+ collect_lazy_loads([(parsed[scored], fcx)], list(parsed.values()))
+ return [h for h in fcx.perf_hits if h.kind == "io_in_loop" and h not in (seeded or [])]
+
+
+_SCAN_CONFIG = """
+ package com.shop.config;
+ import org.mybatis.spring.annotation.MapperScan;
+ @MapperScan({"com.shop.mapper"})
+ public class MyBatisConfig {}
+"""
+_BRAND_MAPPER = """
+ package com.shop.mapper;
+ public interface BrandMapper { int insert(Brand row); }
+"""
+_SERVICE = "src/com/shop/service/BrandService.java"
+
+
+def _mybatis(service_src: str) -> dict[str, str]:
+ return {
+ "src/com/shop/config/MyBatisConfig.java": _SCAN_CONFIG,
+ "src/com/shop/mapper/BrandMapper.java": _BRAND_MAPPER,
+ _SERVICE: service_src,
+ }
+
+
+def test_mapper_scan_package_insert_per_row(tmp_path: Path):
+ hits = _hits(tmp_path, _mybatis("""
+ package com.shop.service;
+ import com.shop.mapper.BrandMapper;
+ public class BrandService {
+ private BrandMapper brandMapper;
+ public int create(java.util.List<Brand> rows) {
+ for (Brand row : rows) {
+ row.setSort(0);
+ brandMapper.insert(row);
+ }
+ return rows.size();
+ }
+ }
+ """), _SERVICE)
+ assert len(hits) == 1
+ hit = hits[0]
+ assert (hit.line, hit.function, hit.detail, hit.path) == (9, "create", "db", ())
+ assert hit.sink_call == "brandMapper.insert"
+ assert hit.loop_line == 7
+
+
+def test_spring_data_repository_through_own_base(tmp_path: Path):
+ files = {
+ "src/a/BaseRepository.java": """
+ package a;
+ import org.springframework.data.jpa.repository.JpaRepository;
+ public interface BaseRepository<T> extends JpaRepository<T, Long> {}
+ """,
+ "src/a/ActivityRepository.java": """
+ package a;
+ public interface ActivityRepository extends BaseRepository<Activity> {}
+ """,
+ "src/a/Adapter.java": """
+ package a;
+ public class Adapter {
+ private final ActivityRepository activities;
+ void update(Account account) {
+ for (Activity a : account.getActivities()) {
+ this.activities.persist(a);
+ }
+ }
+ }
+ """,
+ }
+ hits = _hits(tmp_path, files, "src/a/Adapter.java")
+ assert [(h.line, h.function) for h in hits] == [(7, "update")]
+
+
+def test_mapper_annotation_and_parameter_receiver(tmp_path: Path):
+ files = {
+ "src/b/StockMapper.java": """
+ package b;
+ import org.apache.ibatis.annotations.Mapper;
+ @Mapper
+ public interface StockMapper { Stock selectByPrimaryKey(Long id); }
+ """,
+ "src/b/Locker.java": """
+ package b;
+ public class Locker {
+ void lock(StockMapper mapper, java.util.List<Item> items) {
+ for (Item item : items) {
+ Stock s = mapper.selectByPrimaryKey(item.getSkuId());
+ }
+ }
+ }
+ """,
+ }
+ assert [h.line for h in _hits(tmp_path, files, "src/b/Locker.java")] == [6]
+
+
+def test_repository_named_interface_without_spring_base_is_not_typed(tmp_path: Path):
+ files = {
+ "src/c/JpaRepository.java": "package c;\npublic interface JpaRepository<T, K> {}\n",
+ "src/c/UserRepository.java": """
+ package c;
+ public interface UserRepository extends JpaRepository<User, Long> {}
+ """,
+ "src/c/Svc.java": """
+ package c;
+ public class Svc {
+ private UserRepository userRepository;
+ void f(java.util.List<User> users) {
+ for (User u : users) { userRepository.save(u); }
+ }
+ }
+ """,
+ }
+ assert _hits(tmp_path, files, "src/c/Svc.java") == []
+
+
+ "body",
+ [
+ # Header call runs once.
+ "for (Brand b : brandMapper.selectAll()) { b.setSort(0); }",
+ # A local of another type shadows the typed field.
+ "java.util.Map<Long, Brand> brandMapper = null;\n"
+ "for (Brand b : rows) { brandMapper.get(b.getId()); }",
+ # A constant iterable is a fixed number of calls.
+ "for (Long id : List.of(1L, 2L)) { brandMapper.insert(null); }",
+ ],
+)
+def test_not_a_per_row_call(tmp_path: Path, body: str):
+ service = (
+ "package com.shop.service;\nimport com.shop.mapper.BrandMapper;\n"
+ "public class BrandService {\n private BrandMapper brandMapper;\n"
+ " void f(java.util.List<Brand> rows) {\n" + body + "\n }\n}\n"
+ )
+ assert _hits(tmp_path, _mybatis(service), _SERVICE) == []
+
+
+_LOOP_SERVICE = """
+ package com.shop.service;
+ import com.shop.mapper.BrandMapper;
+ public class BrandService {
+ private BrandMapper brandMapper;
+ void f(java.util.List<Brand> rows) {
+ for (Brand b : rows) { brandMapper.insert(b); }
+ }
+ }
+"""
+
+
+def test_test_files_are_skipped(tmp_path: Path):
+ assert _hits(tmp_path, _mybatis(_LOOP_SERVICE), _SERVICE, is_test=True) == []
+
+
+def test_line_the_walker_flagged_is_not_repeated(tmp_path: Path):
+ seeded = [PerfHit("io_in_loop", 7, "f", "db")]
+ assert _hits(tmp_path, _mybatis(_LOOP_SERVICE), _SERVICE, seeded=seeded) == []
+
+
+def test_ambiguous_simple_name_is_dropped(tmp_path: Path):
+ _require_java()
+ files = _mybatis(_LOOP_SERVICE)
+ files["src/com/other/BrandMapper.java"] = "package com.other;\npublic class BrandMapper {}\n"
+ parsed = [_parse(tmp_path, rel, src) for rel, src in files.items()]
+ assert "BrandMapper" not in persistence_types(parsed)
+
+
+def test_update_scoring_only_the_caller_matches_a_full_run(tmp_path: Path):
+ # An update walks the changed caller only; the unchanged config and mapper
+ # still come in through parsed_files, so the result equals a full run.
+ _require_java()
+ parsed = [_parse(tmp_path, rel, src) for rel, src in _mybatis(_LOOP_SERVICE).items()]
+ full = {pf.file_info.path: FileComplexity(functions=[], classes=[]) for pf in parsed}
+ collect_lazy_loads([(pf, full[pf.file_info.path]) for pf in parsed], parsed)
+ service = next(pf for pf in parsed if pf.file_info.path == _SERVICE)
+ partial = FileComplexity(functions=[], classes=[])
+ collect_lazy_loads([(service, partial)], parsed)
+ assert partial.perf_hits == full[_SERVICE].perf_hits
+ assert [h.line for h in partial.perf_hits] == [7]
+
+
+def test_qualified_field_and_local_receivers_are_typed(tmp_path: Path):
+ hits = _hits(tmp_path, _mybatis("""
+ package com.shop.service;
+ public class BrandService {
+ private com.shop.mapper.BrandMapper brandMapper;
+ void f(java.util.List<Brand> rows) {
+ for (Brand b : rows) { brandMapper.insert(b); }
+ }
+ void g(java.util.List<Brand> rows) {
+ com.shop.mapper.BrandMapper local = brandMapper;
+ for (Brand b : rows) { local.insert(b); }
+ }
+ }
+ """), _SERVICE)
+ assert sorted((h.line, h.function) for h in hits) == [(6, "f"), (10, "g")]
+
+
+def test_collection_of_mappers_is_not_a_mapper(tmp_path: Path):
+ hits = _hits(tmp_path, _mybatis("""
+ package com.shop.service;
+ import com.shop.mapper.BrandMapper;
+ public class BrandService {
+ private java.util.List<BrandMapper> brandMapper;
+ void f(java.util.List<Brand> rows) {
+ for (Brand b : rows) { brandMapper.add(null); }
+ }
+ }
+ """), _SERVICE)
+ assert hits == []
+
+
+def test_java_rows_are_held_back_and_counted_not_dropped(tmp_path: Path):
+ from repowise.core.analysis.finding_registry import split_gated
+ from repowise.core.analysis.health.biomarkers.base import FileContext
+ from repowise.core.analysis.health.biomarkers.io_in_loop import BIOMARKER
+
+ hits = _hits(tmp_path, _mybatis(_LOOP_SERVICE), _SERVICE)
+ ctx = FileContext(file_path=_SERVICE, language="java", nloc=8, has_test_file=False,
+ module=None, perf_hits=hits)
+ rows = [{"file_path": _SERVICE, "biomarker_type": r.biomarker_type}
+ for r in BIOMARKER.detect(ctx)]
+ assert len(rows) == 1
+ for layer in ("health", "performance"):
+ shown, held = split_gated(layer, rows, kind="biomarker_type", get=dict.get)
+ assert shown == [] and held["java"]["count"] == 1
+ shown, held = split_gated(layer, rows, kind="biomarker_type", get=dict.get,
+ include_unverified=True)
+ assert shown == rows and held == {}
+
+
+def test_one_shot_iterables_reach_the_java_pass(tmp_path: Path):
+ _require_java()
+ parsed = {rel: _parse(tmp_path, rel, src) for rel, src in _mybatis(_LOOP_SERVICE).items()}
+ fcx = FileComplexity(functions=[], classes=[])
+ collect_lazy_loads(
+ (pair for pair in [(parsed[_SERVICE], fcx)]), (pf for pf in parsed.values())
+ )
+ assert [h.line for h in fcx.perf_hits] == [7]
+
+
+def test_same_named_base_elsewhere_does_not_type_a_child(tmp_path: Path):
+ files = {
+ "src/data/BaseRepository.java": """
+ package data;
+ import org.springframework.data.jpa.repository.JpaRepository;
+ public interface BaseRepository<T> extends JpaRepository<T, Long> {}
+ """,
+ "src/cache/BaseRepository.java": """
+ package cache;
+ public interface BaseRepository<T> { T get(Object key); }
+ """,
+ "src/cache/SessionRepository.java": """
+ package cache;
+ public interface SessionRepository extends BaseRepository<Session> {}
+ """,
+ "src/cache/Svc.java": """
+ package cache;
+ public class Svc {
+ private SessionRepository sessions;
+ void f(java.util.List<String> ids) {
+ for (String id : ids) { sessions.get(id); }
+ }
+ }
+ """,
+ }
+ _require_java()
+ parsed = [_parse(tmp_path, rel, src) for rel, src in files.items()]
+ types = persistence_types(parsed)
+ assert "SessionRepository" not in types and "BaseRepository" not in types
+ assert _hits(tmp_path, files, "src/cache/Svc.java") == []
+
+
+_DATA_BASE = """
+ package com.data;
+ import org.springframework.data.jpa.repository.JpaRepository;
+ public interface BaseRepository<T> extends JpaRepository<T, Long> {}
+"""
+
+
+ ("child_src", "typed"),
+ [
+ # Imports a same-named base from a library the repo does not contain.
+ ("package cache;\nimport org.ehcache.BaseRepository;\n"
+ "public interface CacheRepository extends BaseRepository<Session> {}\n", False),
+ # No import and another package: the name cannot mean com.data.BaseRepository.
+ ("package cache;\npublic interface CacheRepository extends BaseRepository<Session> {}\n",
+ False),
+ ("package cache;\nimport com.data.BaseRepository;\n"
+ "public interface CacheRepository extends BaseRepository<Session> {}\n", True),
+ ("package cache;\nimport com.data.*;\n"
+ "public interface CacheRepository extends BaseRepository<Session> {}\n", True),
+ ],
+)
+def test_child_typed_only_when_its_base_name_resolves_here(
+ tmp_path: Path, child_src: str, typed: bool
+):
+ _require_java()
+ parsed = [
+ _parse(tmp_path, "src/com/data/BaseRepository.java", _DATA_BASE),
+ _parse(tmp_path, "src/cache/CacheRepository.java", child_src),
+ ]
+ assert ("CacheRepository" in persistence_types(parsed)) is typed
+
+
+def test_spring_base_through_a_wildcard_import(tmp_path: Path):
+ _require_java()
+ parsed = [_parse(tmp_path, "src/a/UserRepository.java", """
+ package a;
+ import org.springframework.data.repository.*;
+ public interface UserRepository extends CrudRepository<User, Long> {}
+ """)]
+ assert persistence_types(parsed) == frozenset({"UserRepository"})