Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(dead-code): link Lambda handlers named in serverless, SAM and Terraform config (#2834)
Raghav Chamadiya693b853a2f45
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex 186b7aa27..140c47bd4 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -1245,10 +1245,14 @@ class DeadCodeAnalyzer:# A dynamic-use or framework edge means the runtime reaches any public# member of the file. Only these two: ``dynamic_imports`` means the# module is loaded, which a plain import edge does not rescue either.+ # A framework edge that names its exports (a Lambda handler) rescues+ # only those, through the importer check below.if any(- self.graph.get_edge_data(pred, node, {}).get("edge_type")- in ("dynamic_uses", "framework")- for pred in self.graph.predecessors(node)+ edge.get("edge_type") in ("dynamic_uses", "framework")+ and not edge.get("imported_names")+ for edge in (+ self.graph.get_edge_data(pred, node, {}) for pred in self.graph.predecessors(node)+ )):return Nonediff --git a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.pyindex 513268754..2d44b6af6 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py@@ -2,7 +2,7 @@Detects convention-based relationships (Django, FastAPI, Flask, ASP.NET, Rails,Laravel, Spring, Express/Nest, Angular, Gin/Echo/Chi, Axum/Actix/Rocket, TYPO3, Godot-``class_name`` globals, and pytest ``conftest.py``) and adds+``class_name`` globals, pytest ``conftest.py`` and AWS Lambda handlers) and adds``edge_type="framework"`` edges that no static import graph captures.Previously a single ``framework_edges.py`` module; split (PR 3.5) into one@@ -21,6 +21,7 @@ from . import (android_manifest,angular,aspnet,+ aws_lambda,django,express,fastapi,@@ -81,6 +82,7 @@ _HANDLERS: list[FrameworkHandler] = [*gtest.HANDLERS,*rust.HANDLERS,*typo3.HANDLERS,+ *aws_lambda.HANDLERS,]diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/aws_lambda.py b/packages/core/src/repowise/core/ingestion/framework_edges/aws_lambda.pynew file mode 100644index 000000000..28105f7ce--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/framework_edges/aws_lambda.py@@ -0,0 +1,204 @@+"""AWS Lambda handlers named by deployment config.++The Lambda runtime loads a handler from a string in ``serverless.yml``, a SAM+``template.yaml`` (``handler: src/users.create``, ``Handler: app.main.lambda_handler``)+or Terraform (:mod:`.aws_lambda_terraform`) and no source file imports it, so the dead-code pass reported the one export+the deployment depends on.++Each handler that resolves to a top-level symbol gets a ``framework`` edge from+the config file to the handler's file that names the export in+``imported_names``, so the file is reachable while its other exports are still+judged, and a ``framework_binds`` edge from the config's module symbol to the+handler. A handler that does not resolve adds nothing.++Ceiling: only files named ``serverless.yml`` / ``template.yaml`` (and ``.yaml``+/ ``.yml`` spellings) and ``.tf`` files are read, and only the ``file.export``+handler shape (Node.js, Python, Ruby). CDK constructs and Java or .NET handlers+are not resolved.+"""++from __future__ import annotations++import posixpath+import re+from collections.abc import Iterable, Iterator+from typing import TYPE_CHECKING, Any++import yaml++from ..resolvers import ResolverContext+from .aws_lambda_terraform import SOURCE_SUFFIXES, terraform_handlers, wanted+from .base import (+ DetectionContext,+ FrameworkHandler,+ _add_edge_if_new,+ add_symbol_edge,+ source_text,+)++if TYPE_CHECKING:+ import networkx as nx+++_SERVERLESS_FILES = frozenset({"serverless.yml", "serverless.yaml"})+_SAM_FILES = frozenset({"template.yml", "template.yaml"})+_CONFIG_FILES = _SERVERLESS_FILES | _SAM_FILES+_FUNCTION_TYPES = frozenset({"AWS::Serverless::Function", "AWS::Lambda::Function"})++# ``<module path>.<export>``: the module may be a path (``src/users``) or a+# dotted Python module (``app.main``); the export is one identifier.+_HANDLER_RE = re.compile(r"^(?P<module>[\w$./-]+)\.(?P<export>[A-Za-z_$][\w$]*)$")+++class _TagTolerantLoader(yaml.SafeLoader):+ """SafeLoader that reads CloudFormation tags (``!Ref``, ``!Sub``...) as null."""+++_TagTolerantLoader.add_multi_constructor("!", lambda _loader, _suffix, _node: None)+++def _load(text: str) -> dict[str, Any]:+ try:+ data = yaml.load(text, Loader=_TagTolerantLoader)+ except yaml.YAMLError:+ return {}+ return data if isinstance(data, dict) else {}+++def _mapping(value: Any) -> dict[str, Any]:+ return value if isinstance(value, dict) else {}+++def _string(value: Any) -> str:+ return value if isinstance(value, str) else ""+++def _serverless_handlers(data: dict[str, Any]) -> Iterator[tuple[tuple[str, ...], str]]:+ """``(code dirs, handler)`` for each function, the dirs relative to the config."""+ for spec in _mapping(data.get("functions")).values():+ yield ("",), _string(_mapping(spec).get("handler"))+++def _sam_handlers(data: dict[str, Any]) -> Iterator[tuple[tuple[str, ...], str]]:+ """``(code dirs, handler)`` for each function resource, with ``Globals`` defaults."""+ defaults = _mapping(_mapping(data.get("Globals")).get("Function"))+ for resource in _mapping(data.get("Resources")).values():+ resource = _mapping(resource)+ if resource.get("Type") not in _FUNCTION_TYPES:+ continue+ props = _mapping(resource.get("Properties"))+ code = props.get("CodeUri", props.get("Code", defaults.get("CodeUri", "")))+ # A mapping (an S3 location) or an intrinsic names no repo path.+ if isinstance(code, str):+ yield (code,), _string(props.get("Handler", defaults.get("Handler")))+++def _handler_file(+ base: str, code_dirs: tuple[str, ...], module: str, path_set: set[str]+) -> str | None:+ """The source file a handler's module names under the first code dir that has it."""+ spellings = [module]+ if "/" not in module and "." in module:+ spellings.append(module.replace(".", "/")) # Python dotted module+ for code_dir in code_dirs:+ for spelling in spellings:+ stem = posixpath.normpath(posixpath.join(base, code_dir, spelling))+ if stem.startswith(".."):+ continue+ # A Python package imports as its ``__init__.py``.+ for suffix in (*SOURCE_SUFFIXES, "/__init__.py"):+ if stem + suffix in path_set:+ return stem + suffix+ return None+++def _link(+ graph: nx.DiGraph,+ config: str,+ handlers: Iterable[tuple[tuple[str, ...], str]],+ parsed_files: dict[str, Any],+ path_set: set[str],+ source_map: dict[str, bytes],+) -> int:+ """Edges from *config* to each handler it names that resolves; the count added."""+ count = 0+ base = config.rpartition("/")[0]+ exports: dict[str, set[str]] = {}+ for code_dirs, handler in handlers:+ match = _HANDLER_RE.match(handler)+ if match is None:+ continue+ target = _handler_file(base, code_dirs, match["module"], path_set)+ if target is None:+ continue+ export = match["export"]+ parsed = parsed_files[target]+ symbol = next(+ (sym.id for sym in parsed.symbols if sym.name == export and not sym.parent_name),+ None,+ )+ if symbol is not None:+ count += add_symbol_edge(graph, f"{config}::__module__", symbol)+ # ``exports.create = ...`` declares no symbol, so the name in the+ # text is the evidence that the handler exists.+ elif not re.search(+ rf"(?<![\w$]){re.escape(export)}(?![\w$])",+ source_text(target, parsed, source_map),+ ):+ continue+ exports.setdefault(target, set()).add(export)+ for target, names in exports.items():+ count += _add_edge_if_new(graph, config, target, imported_names=sorted(names))+ return count+++def _add_lambda_edges(+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ ctx: ResolverContext,+ path_set: set[str],+) -> int:+ count = 0+ source_map = getattr(ctx, "source_map", None) or {}+ tf_texts: dict[str, dict[str, str]] = {}+ for config in sorted(path_set):+ tf_dir, _, name = config.rpartition("/")+ if name.endswith(".tf"):+ text = source_text(config, parsed_files[config], source_map)+ if wanted(text):+ tf_texts.setdefault(tf_dir, {})[config] = text+ continue+ if name in _SERVERLESS_FILES:+ read_handlers = _serverless_handlers+ elif name in _SAM_FILES:+ read_handlers = _sam_handlers+ else:+ continue+ data = _load(source_text(config, parsed_files[config], source_map))+ count += _link(graph, config, read_handlers(data), parsed_files, path_set, source_map)+ for tf_dir, texts in tf_texts.items():+ by_file: dict[str, list[tuple[tuple[str, ...], str]]] = {}+ for tf_file, code_dirs, handler in terraform_handlers(tf_dir, texts):+ by_file.setdefault(tf_file, []).append((code_dirs, handler))+ for tf_file, handlers in by_file.items():+ count += _link(graph, tf_file, handlers, parsed_files, path_set, source_map)+ return count+++class _AwsLambdaHandler:+ def detect(self, dctx: DetectionContext) -> bool:+ return any(+ p.endswith(".tf") or p.rpartition("/")[2] in _CONFIG_FILES for p in dctx.path_set+ )++ def add_edges(+ self,+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ ctx: ResolverContext,+ path_set: set[str],+ ) -> int:+ return _add_lambda_edges(graph, parsed_files, ctx, path_set)+++HANDLERS: list[FrameworkHandler] = [_AwsLambdaHandler()]diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/aws_lambda_terraform.py b/packages/core/src/repowise/core/ingestion/framework_edges/aws_lambda_terraform.pynew file mode 100644index 000000000..b8dd2342d--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/framework_edges/aws_lambda_terraform.py@@ -0,0 +1,147 @@+"""Lambda handlers declared in Terraform, read for :mod:`.aws_lambda`.++Three shapes name a handler and where its code lives:++* ``resource "aws_lambda_function"`` with ``handler`` and ``filename`` / ``s3_key``,+ the zip usually being ``data.archive_file.X.output_path``, whose+ ``source_dir`` or ``source_file`` is the code;+* any ``module`` block carrying both ``handler`` and ``source_path``, the+ ``terraform-aws-modules/lambda/aws`` interface (also used through a local+ ``source``).++No HCL parser is installed, so this is a bounded read of those attributes, not a+parse. Ceiling: a value must be a string literal (``${path.module}`` is the one+interpolation understood) or an ``archive_file`` reference; variables, locals,+heredocs and ``for`` expressions are not evaluated, and an attribute is taken+from the first line that assigns it anywhere in the block. A relative path+Terraform resolves from the working directory is tried from the ``.tf`` file's+directory up to the repository root.+"""++from __future__ import annotations++import posixpath+import re+from collections.abc import Callable, Iterator++from ..framework_routes import match_paren++# The prefilter: a ``.tf`` file mentioning none of these is not read further.+_KEYWORDS = ("aws_lambda_function", "archive_file", "source_path")++_BLOCK_RE = re.compile(+ r'^[ \t]*(?P<kind>resource|data|module)[ \t]+"(?P<type>[^"]+)"(?:[ \t]+"(?P<name>[^"]+)")?[ \t]*\{',+ re.MULTILINE,+)+_STRING_RE = re.compile(r'"((?:[^"\\]|\\.)*)"')+_ARCHIVE_REF_RE = re.compile(r'^"?\$?\{?data\.archive_file\.(?P<name>[\w-]+)\.output_path\}?"?$')+_PATH_MODULE = "${path.module}"+# The runtimes whose handler is ``<file>.<export>``: Node.js, Python, Ruby.+SOURCE_SUFFIXES = (".js", ".mjs", ".cjs", ".ts", ".mts", ".cts", ".py", ".rb")+++def _blocks(text: str) -> Iterator[tuple[str, str, str, str]]:+ """``(kind, type, name, body)`` for each top-level block opening a line."""+ for m in _BLOCK_RE.finditer(text):+ open_idx = m.end() - 1+ close = match_paren(text, open_idx, quotes='"', hash_comments=True)+ if close != -1:+ yield m["kind"], m["type"], m["name"] or "", text[open_idx + 1 : close]+++def _attr(body: str, name: str) -> str:+ """The raw expression assigned to *name*, or ``""``. A ``[`` value runs to its ``]``."""+ m = re.search(rf"^[ \t]*{name}[ \t]*=[ \t]*(\S.*)$", body, re.MULTILINE)+ if m is None:+ return ""+ if m[1].startswith("["):+ close = match_paren(body, m.start(1), quotes='"', hash_comments=True)+ return body[m.start(1) : close + 1] if close != -1 else ""+ return m[1].strip()+++def _literal(expr: str) -> str | None:+ """The string an expression spells (a trailing comment allowed), or None."""+ m = _STRING_RE.match(expr)+ if m is None or expr[m.end() :].strip()[:1] not in ("", "#", "/"):+ return None+ return m[1]+++def _dir_candidates(path: str, depth: int) -> tuple[str, ...]:+ """Code dirs relative to the ``.tf`` dir that *path* (a dir or a source file) may mean."""+ if path.endswith(SOURCE_SUFFIXES):+ path = posixpath.dirname(path)+ if path.startswith(_PATH_MODULE):+ rest = path[len(_PATH_MODULE) :].lstrip("/")+ return () if "${" in rest else (rest,)+ if "${" in path or path.startswith("/"):+ return ()+ return tuple("../" * up + path for up in range(depth + 1))+++def _code_dirs(+ body: str, archives: dict[str, tuple[str, ...]], dirs: Callable[[str], tuple[str, ...]]+) -> tuple[str, ...]:+ """Where an ``aws_lambda_function``'s code lives, best guess first."""+ for attr in ("filename", "s3_key"):+ expr = _attr(body, attr)+ ref = _ARCHIVE_REF_RE.match(expr)+ if ref is not None:+ return archives.get(ref["name"], ())+ zip_path = _literal(expr)+ if zip_path:+ # A prebuilt zip: try the directory named like it, then its own.+ stem = posixpath.splitext(zip_path)[0]+ return dirs(stem) + dirs(posixpath.dirname(zip_path))+ return dirs("")+++def _module_dirs(body: str, dirs: Callable[[str], tuple[str, ...]]) -> tuple[str, ...]:+ expr = _attr(body, "source_path")+ if expr.startswith("["):+ # A list of paths or of ``{ path = "..." }`` objects.+ paths = re.findall(r'\bpath[ \t]*=[ \t]*"([^"]*)"', expr) or _STRING_RE.findall(expr)+ else:+ paths = [p for p in (_literal(expr),) if p]+ return tuple(d for p in paths for d in dirs(p))+++def terraform_handlers(+ tf_dir: str, texts: dict[str, str]+) -> Iterator[tuple[str, tuple[str, ...], str]]:+ """``(tf file, code dirs, handler)`` for each Lambda in one Terraform module dir.++ *texts* maps each ``.tf`` path in *tf_dir* to its source; an ``archive_file``+ in one file serves a function declared in another, as in Terraform.+ """+ depth = tf_dir.count("/") + 1 if tf_dir else 0++ def dirs(path: str) -> tuple[str, ...]:+ return _dir_candidates(path, depth)++ archives: dict[str, tuple[str, ...]] = {}+ declared: list[tuple[str, str, str]] = []+ for path, text in texts.items():+ for kind, block_type, name, body in _blocks(text):+ if kind == "data" and block_type == "archive_file":+ source = _literal(_attr(body, "source_dir")) or _literal(_attr(body, "source_file"))+ if source:+ archives[name] = dirs(source)+ elif (kind, block_type) == ("resource", "aws_lambda_function") or kind == "module":+ declared.append((path, kind, body))+ for path, kind, body in declared:+ handler = _literal(_attr(body, "handler"))+ if not handler or "${" in handler:+ continue+ if kind == "module":+ if not _attr(body, "source_path"):+ continue+ yield path, _module_dirs(body, dirs), handler+ else:+ yield path, _code_dirs(body, archives, dirs), handler+++def wanted(text: str) -> bool:+ """Whether a ``.tf`` file can declare a Lambda or the archive one uses."""+ return any(keyword in text for keyword in _KEYWORDS)diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/base.py b/packages/core/src/repowise/core/ingestion/framework_edges/base.pyindex 35a12e552..c431316a8 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/base.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/base.py@@ -58,13 +58,19 @@ class FrameworkHandler(Protocol):...-def _add_edge_if_new(graph: nx.DiGraph, source: str, target: str) -> bool:- """Add a framework edge if no edge already exists. Returns True if added."""+def _add_edge_if_new(+ graph: nx.DiGraph, source: str, target: str, imported_names: list[str] | None = None+) -> bool:+ """Add a framework edge if no edge already exists. Returns True if added.++ An edge without *imported_names* tells dead code the runtime may reach any+ public member of *target*; one with names vouches for those names only.+ """if source == target:return Falseif graph.has_edge(source, target):return False- graph.add_edge(source, target, edge_type="framework", imported_names=[])+ graph.add_edge(source, target, edge_type="framework", imported_names=imported_names or [])return Truediff --git a/tests/unit/ingestion/test_aws_lambda_framework_edges.py b/tests/unit/ingestion/test_aws_lambda_framework_edges.pynew file mode 100644index 000000000..f83a184b4--- /dev/null+++ b/tests/unit/ingestion/test_aws_lambda_framework_edges.py@@ -0,0 +1,370 @@+"""AWS Lambda handlers named in serverless.yml, SAM templates and Terraform as graph edges.++The cases go through traverse -> parse -> graph -> framework edges -> dead code,+the path a real index takes.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.analysis.dead_code import DeadCodeAnalyzer+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder++_SERVERLESS_NODE = """\+service: users+provider:+ name: aws+ runtime: nodejs20.x+functions:+ create:+ handler: src/handlers/users.create+ legacy:+ handler: src/handlers/legacy.run+ missing:+ handler: src/handlers/users.doesNotExist+ variable:+ handler: ${self:custom.handler}+ nowhere:+ handler: src/handlers/absent.main+"""++_SERVERLESS_PYTHON = """\+service: reports+provider:+ name: aws+ runtime: python3.12+functions:+ main:+ handler: app.handlers.lambda_handler+ package:+ handler: tasks.worker.process+"""++_SAM_TEMPLATE = """\+AWSTemplateFormatVersion: '2010-09-09'+Transform: AWS::Serverless-2016-10-31+Globals:+ Function:+ Runtime: nodejs20.x+ CodeUri: functions/+Resources:+ IndexFn:+ Type: AWS::Serverless::Function+ Properties:+ CodeUri: src/+ Handler: index.handler+ Role: !GetAtt Role.Arn+ Environment:+ Variables:+ TABLE: !Ref Table+ URL: !Sub "https://${Api}.example.com"+ AppFn:+ Type: AWS::Serverless::Function+ Properties:+ Handler: app.lambdaHandler+ Policies:+ - !Ref Policy+ Table:+ Type: AWS::DynamoDB::Table+"""++_TF_ARCHIVE_DIR = """\+data "archive_file" "broker" {+ type = "zip"+ source_dir = "${path.module}/../lambda"+ output_path = "${path.module}/broker.zip"+}++resource "aws_lambda_function" "broker" {+ function_name = "broker"+ filename = data.archive_file.broker.output_path+ handler = "broker.handler" # the export AWS invokes+ runtime = "nodejs20.x"+ environment {+ variables = { MODE = "${var.mode}" }+ }+}+"""++# The archive is declared in one file and used in another, as Terraform allows.+_TF_ARCHIVE_FILE_DATA = """\+data "archive_file" "fn" {+ type = "zip"+ source_file = "${path.module}/example_lambda.js"+ output_path = "${path.module}/example_lambda.js.zip"+}+"""+_TF_ARCHIVE_FILE_FN = """\+resource "aws_lambda_function" "fn" {+ filename = "${data.archive_file.fn.output_path}"+ handler = "example_lambda.handler"+ assume_role_policy = <<EOF+{ "Version": "2012-10-17" }+EOF+}+"""++# A path Terraform resolves from the working directory, not the module.+_TF_WORKDIR_RELATIVE = """\+data "archive_file" "zip" {+ source_file = "lambda/function_src/index.js"+ output_path = "lambda/function_src/index.zip"+}+resource "aws_lambda_function" "fn" {+ filename = data.archive_file.zip.output_path+ handler = "index.main"+}+"""++_TF_PREBUILT_ZIPS = """\+resource "aws_lambda_function" "worker" {+ filename = "artifacts/worker.zip"+ handler = "worker.run"+}+resource "aws_lambda_function" "report" {+ s3_bucket = "artifacts"+ s3_key = "report.zip"+ handler = "app.report"+}+"""++_TF_MODULES = """\+module "one" {+ source = "terraform-aws-modules/lambda/aws"+ handler = "index.lambda_handler"+ source_path = "../src/fn1"+}+module "two" {+ source = "terraform-aws-modules/lambda/aws"+ handler = "app.handle"+ source_path = [+ {+ path = "${path.module}/../src/fn2"+ pip_requirements = true+ }+ ]+}+"""++_TF_UNRESOLVABLE = """\+resource "aws_lambda_function" "from_var" {+ filename = data.archive_file.missing.output_path+ handler = var.handler+}+resource "aws_lambda_function" "missing_archive" {+ filename = data.archive_file.missing.output_path+ handler = "broker.handler"+}+resource "aws_lambda_function" "no_such_export" {+ filename = "../lambda.zip"+ handler = "broker.doesNotExist"+}+module "not_a_lambda" {+ source = "./whatever"+ handler = "broker.handler"+}+# resource "aws_lambda_function" "commented" {+# handler = "broker.handler"+# }+"""++_APP = {+ "node-svc/serverless.yml": _SERVERLESS_NODE,+ "node-svc/src/handlers/users.mjs": (+ "import { save } from '../lib/db.mjs';\n"+ "export const create = async (event) => save(format(event));\n"+ "export function format(x) { return x; }\n"+ "export function orphanExport() { return 1; }\n"+ ),+ "node-svc/src/handlers/legacy.js": "module.exports.run = async (event) => event;\n",+ "node-svc/src/lib/db.mjs": "export function save(x) { return x; }\n",+ "node-svc/src/lib/report.mjs": (+ "import { format } from '../handlers/users.mjs';\nexport const render = (x) => format(x);\n"+ ),+ "py-svc/serverless.yml": _SERVERLESS_PYTHON,+ "py-svc/app/__init__.py": "",+ "py-svc/app/handlers.py": (+ "def lambda_handler(event, context):\n return shared(event)\n\n\n"+ "def shared(x):\n return x\n\n\n"+ "def unused_py():\n return 2\n"+ ),+ "py-svc/app/jobs.py": "from app.handlers import shared\n\n\ndef run():\n return shared(1)\n",+ "py-svc/tasks/__init__.py": "",+ "py-svc/tasks/worker/__init__.py": "def process(event, context):\n return event\n",+ "sam-app/template.yaml": _SAM_TEMPLATE,+ "sam-app/src/index.mjs": "export const handler = async (e) => e;\n",+ "sam-app/functions/app.mjs": (+ "export const lambdaHandler = async (e) => e;\nexport const helper = (x) => x;\n"+ ),+ "sam-app/functions/use.mjs": "import { helper } from './app.mjs';\nexport const u = helper(1);\n",+ "tf-a/infra/lambda.tf": _TF_ARCHIVE_DIR,+ "tf-a/lambda/broker.mjs": (+ "export const handler = async () => 1;\nexport const stale = () => 2;\n"+ ),+ "tf-b/data.tf": _TF_ARCHIVE_FILE_DATA,+ "tf-b/lambda.tf": _TF_ARCHIVE_FILE_FN,+ "tf-b/example_lambda.js": "exports.handler = async (event) => event;\n",+ "tf-c/iac/lambda/lambda.tf": _TF_WORKDIR_RELATIVE,+ "tf-c/iac/lambda/function_src/index.js": "exports.main = async () => 1;\n",+ "tf-d/main.tf": _TF_PREBUILT_ZIPS,+ "tf-d/artifacts/worker/worker.py": "def run(event, context):\n return event\n",+ "tf-d/report/app.py": "def report(event, context):\n return event\n",+ "tf-e/infra/main.tf": _TF_MODULES,+ "tf-e/src/fn1/index.py": (+ "def lambda_handler(event, context):\n return 1\n\n\ndef orphan_py():\n return 2\n"+ ),+ "tf-e/src/fn2/app.py": "def handle(event, context):\n return 1\n",+ "tf-f/infra/bad.tf": _TF_UNRESOLVABLE,+ "tf-f/lambda/broker.mjs": "export const handler = async () => 1;\n",+ # Not a mapping and not valid YAML: both must be skipped quietly.+ "broken/serverless.yml": "functions: [unclosed\n",+ "list/template.yml": "- just\n- a list\n",+}+++def _write(repo: Path, files: dict[str, str]) -> Path:+ for rel, text in files.items():+ path = repo / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ return repo+++def _graph(repo: Path) -> tuple[object, set[tuple[str, str, str]]]:+ builder = GraphBuilder(repo)+ parser = ASTParser()+ source_map: dict[str, bytes] = {}+ for fi in FileTraverser(repo).traverse():+ src = Path(fi.abs_path).read_bytes()+ builder.add_file(parser.parse_file(fi, src))+ source_map[fi.path] = src+ builder.set_source_map(source_map)+ builder.build()+ builder.add_framework_edges([])+ report = DeadCodeAnalyzer(+ builder.graph(), {}, parsed_files=builder._parsed_files, source_map=source_map, repo_root=repo+ ).analyze({})+ dead = {(f.kind.value, f.file_path, f.symbol_name or "") for f in report.findings}+ return builder.graph(), dead+++def _framework_names(graph, source: str, target: str) -> list[str]:+ data = graph.get_edge_data(source, target) or {}+ assert data.get("edge_type") == "framework", data+ return data["imported_names"]+++def test_node_handler_by_file_path_and_export(tmp_path: Path) -> None:+ graph, dead = _graph(_write(tmp_path, _APP))+ names = _framework_names(graph, "node-svc/serverless.yml", "node-svc/src/handlers/users.mjs")+ assert names == ["create"]+ assert ("unused_export", "node-svc/src/handlers/users.mjs", "create") not in dead+ # The rest of the handler file is still judged on its own uses.+ assert ("unused_export", "node-svc/src/handlers/users.mjs", "orphanExport") in dead+++def test_commonjs_handler_keeps_its_file_reachable(tmp_path: Path) -> None:+ graph, dead = _graph(_write(tmp_path, _APP))+ assert _framework_names(graph, "node-svc/serverless.yml", "node-svc/src/handlers/legacy.js") == [+ "run"+ ]+ assert ("unreachable_file", "node-svc/src/handlers/legacy.js", "") not in dead+++def test_python_handler_by_dotted_module(tmp_path: Path) -> None:+ graph, dead = _graph(_write(tmp_path, _APP))+ assert _framework_names(graph, "py-svc/serverless.yml", "py-svc/app/handlers.py") == [+ "lambda_handler"+ ]+ binds = graph.get_edge_data(+ "py-svc/serverless.yml::__module__", "py-svc/app/handlers.py::lambda_handler"+ )+ assert binds["edge_type"] == "framework_binds"+ assert ("unused_export", "py-svc/app/handlers.py", "lambda_handler") not in dead+ assert ("unused_export", "py-svc/app/handlers.py", "unused_py") in dead+++def test_python_handler_in_a_package_init(tmp_path: Path) -> None:+ graph, _dead = _graph(_write(tmp_path, _APP))+ target = "py-svc/tasks/worker/__init__.py"+ assert _framework_names(graph, "py-svc/serverless.yml", target) == ["process"]+ binds = graph.get_edge_data("py-svc/serverless.yml::__module__", f"{target}::process")+ assert binds["edge_type"] == "framework_binds"+++def test_sam_code_uri_and_globals(tmp_path: Path) -> None:+ graph, dead = _graph(_write(tmp_path, _APP))+ assert _framework_names(graph, "sam-app/template.yaml", "sam-app/src/index.mjs") == ["handler"]+ assert _framework_names(graph, "sam-app/template.yaml", "sam-app/functions/app.mjs") == [+ "lambdaHandler"+ ]+ assert ("unused_export", "sam-app/src/index.mjs", "handler") not in dead+ assert ("unused_export", "sam-app/functions/app.mjs", "lambdaHandler") not in dead+++def _lambda_targets(graph, config: str) -> set[str]:+ return {+ target+ for source in (config, f"{config}::__module__")+ for _, target, data in graph.out_edges(source, data=True)+ if data.get("edge_type") in ("framework", "framework_binds")+ }+++def test_unresolvable_handlers_add_nothing(tmp_path: Path) -> None:+ graph, _dead = _graph(_write(tmp_path, _APP))+ # A function the file does not define, a variable and a missing file.+ names = _framework_names(graph, "node-svc/serverless.yml", "node-svc/src/handlers/users.mjs")+ assert "doesNotExist" not in names+ assert _lambda_targets(graph, "node-svc/serverless.yml") == {+ "node-svc/src/handlers/users.mjs",+ "node-svc/src/handlers/users.mjs::create",+ "node-svc/src/handlers/legacy.js",+ }+ # Invalid YAML and a top-level list are skipped without raising.+ assert _lambda_targets(graph, "broken/serverless.yml") == set()+ assert _lambda_targets(graph, "list/template.yml") == set()+++def test_terraform_archive_source_dir(tmp_path: Path) -> None:+ graph, dead = _graph(_write(tmp_path, _APP))+ assert _framework_names(graph, "tf-a/infra/lambda.tf", "tf-a/lambda/broker.mjs") == ["handler"]+ binds = graph.get_edge_data("tf-a/infra/lambda.tf::__module__", "tf-a/lambda/broker.mjs::handler")+ assert binds["edge_type"] == "framework_binds"+ assert ("unused_export", "tf-a/lambda/broker.mjs", "handler") not in dead+ assert ("unused_export", "tf-a/lambda/broker.mjs", "stale") in dead+++def test_terraform_archive_source_file_across_files(tmp_path: Path) -> None:+ graph, dead = _graph(_write(tmp_path, _APP))+ assert _framework_names(graph, "tf-b/lambda.tf", "tf-b/example_lambda.js") == ["handler"]+ assert ("unreachable_file", "tf-b/example_lambda.js", "") not in dead+++def test_terraform_path_relative_to_working_directory(tmp_path: Path) -> None:+ graph, _dead = _graph(_write(tmp_path, _APP))+ target = "tf-c/iac/lambda/function_src/index.js"+ assert _framework_names(graph, "tf-c/iac/lambda/lambda.tf", target) == ["main"]+++def test_terraform_prebuilt_zip_and_s3_key(tmp_path: Path) -> None:+ graph, _dead = _graph(_write(tmp_path, _APP))+ assert _framework_names(graph, "tf-d/main.tf", "tf-d/artifacts/worker/worker.py") == ["run"]+ assert _framework_names(graph, "tf-d/main.tf", "tf-d/report/app.py") == ["report"]+++def test_terraform_lambda_module_source_path(tmp_path: Path) -> None:+ graph, dead = _graph(_write(tmp_path, _APP))+ assert _framework_names(graph, "tf-e/infra/main.tf", "tf-e/src/fn1/index.py") == [+ "lambda_handler"+ ]+ assert _framework_names(graph, "tf-e/infra/main.tf", "tf-e/src/fn2/app.py") == ["handle"]+ assert ("unused_export", "tf-e/src/fn1/index.py", "orphan_py") in dead+++def test_terraform_unresolvable_handlers_add_nothing(tmp_path: Path) -> None:+ graph, _dead = _graph(_write(tmp_path, _APP))+ # A variable, a missing archive, an export the file lacks, a module that is+ # not a Lambda and a commented-out block.+ assert _lambda_targets(graph, "tf-f/infra/bad.tf") == set()