Skip to content

Commit ea13376

Browse files
authored
Merge pull request #190 from CoreTrace/fix/module-identity
fix: keep files sharing a Python module name as distinct modules
2 parents d3e9a64 + ba3b6e8 commit ea13376

11 files changed

Lines changed: 686 additions & 55 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
## Unreleased
44

5+
### Analysis
6+
7+
- Two files with the same Python module name, `a/app.py` and `z/app.py` outside any package, no longer overwrite each other: both are discovered, analysed and covered whatever the order they are found in. The engine tells them apart by their path from the root as a module name, `a.app` and `z.app`, in the module graph, the summary index, the cache keys and what project plugins see; a unique name stays what it was. An import of such a name resolves to the file in the importer's own root only, and one no root resolves is not followed. Each colliding file carries an `ambiguous-module` note and is covered as `ambiguous`, since a model or a route naming `python.app.main` applies to every definition of that symbol, and so does an importer whose import stayed unresolved; a VEX statement over such a project stays `under_investigation` (#182).
8+
59
### Precision
610

711
- A `TEMPLATES` assigned inside a function or a class no longer counts as Django settings: only a module-level assignment can activate the `request` context processor, and only a mention of the module's `TEMPLATES` elsewhere leaves that activation uncertain. A function-local `TEMPLATES`, called or not, used to enable the implicit request source, upgrading a template filter finding to exploitable (#184).

‎docs/plugins.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,11 @@ resolved through imports and aliases, so `python.os.system` covers `os.system`,
5353
symbol, so a chain such as `sqlite3.connect(p).cursor().execute` is
5454
`python.sqlite3.connect.cursor.execute`, and `app = Flask(__name__)` gives `app.route` the
5555
symbol `python.flask.Flask.route`. Builtins are `python.builtins.<name>`. Symbols are
56-
`SymbolId` values from `coretrace_python.semantic.symbols`.
56+
`SymbolId` values from `coretrace_python.semantic.symbols`. A function of the project is
57+
`python.` followed by its module's import name and its qualified name,
58+
`python.app.handlers.main`; two files with the same import name, `a/app.py` and
59+
`z/app.py` outside any package, define the same symbols, so a model naming
60+
`python.app.main` names the function of each.
5761

5862
## Kinds of plugin
5963

‎docs/usage.md‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,13 @@ coretrace-python-analyzer [--check | --emit-ir [--ssa]] [options] [path]
6565
## What is analysed
6666

6767
Given a directory, every `.py` file below it is a module of one project, named after
68-
its package (`app/views.py` is `app.views`). Hidden directories, `node_modules`,
68+
its package (`app/views.py` is `app.views`). Two files that would share a name, `a/app.py`
69+
and `z/app.py` outside any package, are told apart by their path from the root, `a.app`
70+
and `z.app`, and reported: each carries an `ambiguous-module` note, since a symbol
71+
`python.app.main` may name a function of either and an import of `app` resolves only
72+
from the importer's own directory, and each is covered as `ambiguous` rather than
73+
analysed. An import of such a name that no file of the importer's own directory answers
74+
is noted where it is written and not followed. Hidden directories, `node_modules`,
6975
`__pycache__`, `build`, `dist` and any virtual environment, recognised by its
7076
`pyvenv.cfg` whatever its name, are skipped. Dependency files at the root
7177
(`requirements*.txt`, `pyproject.toml`, `poetry.lock`, `uv.lock`) are read into a
@@ -261,7 +267,9 @@ the directory of the checked file; a path outside it is printed as it is.
261267
}
262268
```
263269

264-
`root` is the directory the paths are relative to.
270+
`root` is the directory the paths are relative to. A file's `status` is `analysed`,
271+
`ambiguous` (analysed, but another file has its module name, see above), `syntax-error`
272+
or `unreadable`; only `analysed` files count in `files_analysed`.
265273

266274
A directory check also lists, in `tool.components`, what the result was produced with
267275
besides the engine and the sources: each plugin it loaded, by manifest name and version,

‎src/coretrace_python/engine.py‎

Lines changed: 93 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import concurrent.futures
1010
import hashlib
1111
import multiprocessing
12+
from collections import Counter
1213
from collections.abc import Callable, Iterable, Mapping, Sequence
1314
from dataclasses import dataclass, field, replace
1415
from pathlib import Path
@@ -88,6 +89,7 @@
8889
TemplateCallsAnalysis,
8990
build_module_graph,
9091
discover_sources,
92+
name_modules,
9193
project_symbol,
9294
)
9395
from coretrace_python.ir import PYIR_SCHEMA_VERSION
@@ -371,7 +373,11 @@ def analyze_project(
371373
strongly connected components of the module graph, imports first; with ``jobs``
372374
above one the components of a wave are analysed in that many processes (§29).
373375
``advisory_files`` add to the ``advisories.json`` at ``root``; ``policy_file``
374-
replaces the ``coretrace-policy.toml`` there."""
376+
replaces the ``coretrace-policy.toml`` there.
377+
378+
Every module is known by the name ``name_modules`` gives its file: its import name,
379+
or its path from the root when another file has that import name. Such files carry
380+
an ``ambiguous-module`` note and are covered as ``ambiguous``."""
375381

376382
if jobs < 1:
377383
raise ValueError("jobs must be at least 1")
@@ -398,18 +404,18 @@ def analyze_project(
398404
files: dict[str, SourceFile] = {}
399405
unreadable: list[tuple[Path, str]] = []
400406
coverage: list[FileCoverage] = []
401-
discovered = discover_sources(root, sources, unreadable)
407+
named = name_modules(root, discover_sources(root, sources, unreadable))
402408
for path, reason in unreadable:
403409
findings.append(_note("syntax-error", f"{path}: {reason}", sources.add_source(str(path), ""), 1))
404410
coverage.append(FileCoverage(str(path), "unreadable", 0, 0))
405-
for source in discovered:
411+
for name, source in named.items():
406412
try:
407-
modules[source.module_name] = build_hir(source)
413+
modules[name] = build_hir(source)
408414
except (ParseError, HIRBuildError) as error:
409415
findings.append(_note("syntax-error", str(error), source, 1))
410416
coverage.append(FileCoverage(str(source.source_id), "syntax-error", 0, 0))
411417
continue
412-
files[source.module_name] = source
418+
files[name] = source
413419

414420
managers = {name: _register_all(module) for name, module in modules.items()}
415421
probe = next(iter(managers.values()), None) or _register_all(build_hir(sources.add_source("<empty>", "")))
@@ -439,6 +445,8 @@ def analyze_project(
439445
graph = build_module_graph(
440446
{name: files[name] for name in analysable}, {name: modules[name] for name in analysable}, imports
441447
)
448+
shared = _shared_names(graph)
449+
findings.extend(_ambiguity_notes(graph, shared, root))
442450
routes: dict[SymbolId, EntryPoint] = {}
443451
for name in sorted(analysable):
444452
for symbol, registered in _routes_of(analysable[name]).items():
@@ -515,15 +523,16 @@ def analyze_project(
515523
if pool is not None:
516524
pool.shutdown()
517525

518-
index = _seed(results, graph, frozenset())
526+
index = _index(results, {name: name for name in results})
519527
call_graphs: dict[str, CallGraph] = {}
520528
functions: dict[str, tuple[ModuleFunction, ...]] = {}
521529
for name in sorted(analysable):
522530
entry = results[name]
523531
findings.extend(entry.findings)
524532
unsupported = sum(1 for f in entry.findings if f.rule_id == "unsupported-syntax")
533+
status = "ambiguous" if files[name].module_name in shared else "analysed"
525534
coverage.append(
526-
FileCoverage(str(files[name].source_id), "analysed", len(entry.functions), len(entry.functions) - unsupported)
535+
FileCoverage(str(files[name].source_id), status, len(entry.functions), len(entry.functions) - unsupported)
527536
)
528537
functions[name] = entry.functions
529538
sites: dict[str, list[CallSite]] = {function.name: [] for function in entry.functions}
@@ -645,24 +654,76 @@ def _advisory_paths(root: Path, advisory_files: Sequence[Path]) -> tuple[Path, .
645654
return (*([default] if default.is_file() else []), *advisory_files)
646655

647656

657+
def _shared_names(graph: ModuleGraph) -> dict[str, list[str]]:
658+
"""The import names several analysable files have, each with those files' modules."""
659+
660+
by_name: dict[str, list[str]] = {}
661+
for name in graph.modules:
662+
by_name.setdefault(graph.source(name).module_name, []).append(name)
663+
return {import_name: names for import_name, names in by_name.items() if len(names) > 1}
664+
665+
666+
def _ambiguity_notes(graph: ModuleGraph, shared: Mapping[str, list[str]], root: Path) -> list[Finding]:
667+
"""One note on each file whose import name another file shares, since a symbol of
668+
that name may denote a function of either, and one on each importer whose import of
669+
such a name no root resolved, since calls through it are not followed."""
670+
671+
def located(name: str) -> str:
672+
return _located(_path_of(graph.source(name)), root)
673+
674+
notes: list[Finding] = []
675+
for import_name, names in sorted(shared.items()):
676+
for name in names:
677+
others = ", ".join(located(other) for other in names if other != name)
678+
message = (
679+
f"{located(name)} is the module '{import_name}' like {others}: a symbol "
680+
f"python.{import_name}.* may name a function of either, and an import of "
681+
f"'{import_name}' resolves only from its own root"
682+
)
683+
notes.append(_note("ambiguous-module", message, graph.source(name), 1))
684+
for name in graph.modules:
685+
for import_name in sorted(graph.unresolved(name)):
686+
candidates = " or ".join(located(other) for other in shared[import_name])
687+
message = f"'{import_name}' imported here is {candidates}: calls into it are not followed"
688+
notes.append(_note("ambiguous-module", message, graph.source(name), 1))
689+
return notes
690+
691+
648692
def _seed(results: Mapping[str, CachedModule], graph: ModuleGraph, component: frozenset[str]) -> SummaryIndex:
649693
"""The summaries a component starts from: those of every module it imports,
650-
transitively, all final by the time its wave runs; the whole index for no component."""
651-
652-
if component:
653-
wanted: set[str] = set()
654-
pending = list(component)
655-
while pending:
656-
for imported in graph.imports(pending.pop()):
657-
if imported in results and imported not in wanted:
658-
wanted.add(imported)
659-
pending.append(imported)
660-
else:
661-
wanted = set(results)
694+
transitively, all final by the time its wave runs, each under the import name the
695+
component's code refers to it by. Of several files with one import name, only the
696+
one a member imports directly, resolved in its own root, goes under that name: the
697+
others are reached through summaries that inline them already, and a name no
698+
member's root resolved is followed into neither file."""
699+
700+
wanted: set[str] = set()
701+
pending = list(component)
702+
while pending:
703+
for imported in graph.imports(pending.pop()):
704+
if imported in results and imported not in wanted:
705+
wanted.add(imported)
706+
pending.append(imported)
707+
direct = {imported for member in component for imported in graph.imports(member)}
708+
by_import: dict[str, list[str]] = {}
709+
for name in wanted:
710+
by_import.setdefault(graph.source(name).module_name, []).append(name)
711+
names: dict[str, str] = {}
712+
for import_name, modules in by_import.items():
713+
chosen = modules if len(modules) == 1 else [name for name in modules if name in direct]
714+
if len(chosen) == 1:
715+
names[chosen[0]] = import_name
716+
return _index(results, names)
717+
718+
719+
def _index(results: Mapping[str, CachedModule], names: Mapping[str, str]) -> SummaryIndex:
720+
"""The summaries of the modules in ``names``, each function under the project symbol
721+
of the module name given for its module."""
722+
662723
return SummaryIndex(
663724
{
664-
project_symbol(name, function): summary
665-
for name in sorted(wanted)
725+
project_symbol(module, function): summary
726+
for name, module in sorted(names.items())
666727
for function, summary in results[name].summaries.items()
667728
}
668729
)
@@ -675,8 +736,12 @@ def _analyse_managers(
675736
affected: Affected,
676737
) -> dict[str, CachedModule]:
677738
"""Analyse one component: iterate its summaries to a fixpoint over ``seed`` (§21),
678-
then extract what the rest of the run needs from each module."""
739+
then extract what the rest of the run needs from each module. Each member registers
740+
its functions under its import name, what the others' code refers to it by; a name
741+
two members share, a cycle across roots, is registered by neither."""
679742

743+
counts = Counter(manager.module.name for manager in managers.values())
744+
names = {name: manager.module.name for name, manager in managers.items() if counts[manager.module.name] == 1}
680745
index = seed
681746
for manager in managers.values():
682747
manager.provide(ProjectSummaries, index)
@@ -685,9 +750,9 @@ def _analyse_managers(
685750
{
686751
**seed.summaries,
687752
**{
688-
project_symbol(name, function): summary
689-
for name, manager in managers.items()
690-
for function, summary in _summaries_of(manager).items()
753+
project_symbol(module, function): summary
754+
for name, module in names.items()
755+
for function, summary in _summaries_of(managers[name]).items()
691756
},
692757
}
693758
)
@@ -702,8 +767,9 @@ def _analyse_managers(
702767

703768
@dataclass(frozen=True)
704769
class _Batch:
705-
"""One component handed to a worker process: it rebuilds the configuration from the
706-
project root and the plugin roots, so only paths and the imported summaries travel."""
770+
"""One component handed to a worker process, its files under the engine's module
771+
names: it rebuilds the configuration from the project root and the plugin roots, so
772+
only paths and the imported summaries travel."""
707773

708774
root: Path
709775
plugin_roots: tuple[Path, ...]

‎src/coretrace_python/findings/coverage.py‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
"""Analysis coverage: which files and functions a run actually looked at.
22
33
"No findings" only means something when the reader knows what was analysed. Each file
4-
is ``analysed``, a ``syntax-error`` (the frontend rejected it) or ``unreadable`` (it could
5-
not be decoded); analysed files count their functions and how many lowered. The
6-
templates the project names but the run could not read are listed, each where the
7-
project names it: they may call any template filter.
4+
is ``analysed``, ``ambiguous`` (analysed, but another file has its Python module name,
5+
so a symbol of that name may denote a function of either and an import of it resolves
6+
only from its own root), a ``syntax-error`` (the frontend rejected it) or ``unreadable``
7+
(it could not be decoded); analysed and ambiguous files count their functions and how
8+
many lowered. The templates the project names but the run could not read are listed,
9+
each where the project names it: they may call any template filter.
810
"""
911

1012
from __future__ import annotations

‎src/coretrace_python/interprocedural/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
build_module_graph,
2020
discover_files,
2121
discover_sources,
22+
name_modules,
2223
project_symbol,
2324
)
2425
from coretrace_python.interprocedural.summaries import (
@@ -73,5 +74,6 @@
7374
"cleared_by",
7475
"discover_files",
7576
"discover_sources",
77+
"name_modules",
7678
"project_symbol",
7779
]

0 commit comments

Comments
 (0)