Skip to content

Commit 7437f99

Browse files
committed
Detect import path mismatches
1 parent bc11240 commit 7437f99

6 files changed

Lines changed: 108 additions & 7 deletions

File tree

‎src/_pytask/exceptions.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,7 @@ class ResolvingDependenciesError(PytaskError):
3333

3434
class ExecutionError(PytaskError):
3535
"""Exception during execution."""
36+
37+
38+
class ImportPathMismatchError(ImportError):
39+
"""Exception for a cached module imported from a different path."""

‎src/_pytask/path.py‎

Lines changed: 40 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,15 @@
1717

1818
from _pytask._hashlib import file_digest
1919
from _pytask.cache import Cache
20+
from _pytask.exceptions import ImportPathMismatchError
2021

2122
if TYPE_CHECKING:
2223
from collections.abc import Sequence
2324

2425
from _pytask.typing import NodePath
2526

2627
__all__ = [
28+
"ImportPathMismatchError",
2729
"find_case_sensitive_path",
2830
"find_closest_ancestor",
2931
"find_common_ancestor",
@@ -182,21 +184,22 @@ def import_path(path: Path, root: Path) -> ModuleType:
182184
except CouldNotResolvePathError:
183185
pass
184186
else:
185-
# If the given module name is already in sys.modules, do not import it again.
186-
with contextlib.suppress(KeyError):
187-
return sys.modules[module_name]
187+
cached_module = _get_cached_module(module_name, path)
188+
if cached_module is not None:
189+
return cached_module
188190

189191
mod = _import_module_using_spec(module_name, path, pkg_root)
190192
if mod is not None:
191193
return mod
192194

193195
module_name = _module_name_from_path(path, root)
194-
with contextlib.suppress(KeyError):
195-
return sys.modules[module_name]
196+
cached_module = _get_cached_module(module_name, path)
197+
if cached_module is not None:
198+
return cached_module
196199

197200
spec = importlib.util.spec_from_file_location(module_name, str(path))
198201

199-
if spec is None:
202+
if spec is None or spec.loader is None:
200203
msg = f"Can't find module {module_name!r} at location {path}."
201204
raise ImportError(msg)
202205

@@ -207,6 +210,37 @@ def import_path(path: Path, root: Path) -> ModuleType:
207210
return mod
208211

209212

213+
def _get_cached_module(module_name: str, path: Path) -> ModuleType | None:
214+
"""Return a cached module only when it originates from the requested path."""
215+
module = sys.modules.get(module_name)
216+
if module is None:
217+
return None
218+
219+
module_file = getattr(module, "__file__", None)
220+
if module_file is not None and _normalize_import_path(module_file) == (
221+
_normalize_import_path(path)
222+
):
223+
return module
224+
225+
imported_path = "<unknown>" if module_file is None else str(module_file)
226+
msg = (
227+
f"Module {module_name!r} was already imported from:\n{imported_path}\n\n"
228+
f"Pytask is trying to collect:\n{path}\n\n"
229+
"Pytask will not reuse a module from a different path.\n\n"
230+
"Use a unique package or module name, or start the build in a fresh process "
231+
"or notebook kernel."
232+
)
233+
raise ImportPathMismatchError(msg)
234+
235+
236+
def _normalize_import_path(path: str | os.PathLike[str]) -> str:
237+
"""Normalize a module path for cache comparisons."""
238+
raw_path = os.fspath(path)
239+
if raw_path.endswith((".pyc", ".pyo")):
240+
raw_path = raw_path[:-1]
241+
return os.path.normcase(str(Path(raw_path).resolve()))
242+
243+
210244
def _resolve_package_path(path: Path) -> Path | None:
211245
"""Resolve package path.
212246

‎src/pytask/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
from _pytask.exceptions import CollectionError
2828
from _pytask.exceptions import ConfigurationError
2929
from _pytask.exceptions import ExecutionError
30+
from _pytask.exceptions import ImportPathMismatchError
3031
from _pytask.exceptions import NodeNotCollectedError
3132
from _pytask.exceptions import NodeLoadError
3233
from _pytask.exceptions import NodeNotFoundError
@@ -103,6 +104,7 @@
103104
"ExecutionReport",
104105
"Exit",
105106
"ExitCode",
107+
"ImportPathMismatchError",
106108
"Mark",
107109
"MarkDecorator",
108110
"MarkGenerator",

‎src/pytask/path.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22

33
from __future__ import annotations
44

5+
from _pytask.exceptions import ImportPathMismatchError
56
from _pytask.path import hash_path
67
from _pytask.path import import_path
78

8-
__all__ = ["hash_path", "import_path"]
9+
__all__ = ["ImportPathMismatchError", "hash_path", "import_path"]

‎tests/test_collect.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from _pytask.node_protocols import PPathNode
1515
from pytask import CollectionOutcome
1616
from pytask import ExitCode
17+
from pytask import ImportPathMismatchError
1718
from pytask import NodeInfo
1819
from pytask import PickleNode
1920
from pytask import Session
@@ -376,6 +377,42 @@ def test_collect_tasks_from_modules_with_the_same_name(tmp_path):
376377
assert modules == {"a.task_module", "b.task_module"}
377378

378379

380+
def test_repeated_builds_report_import_path_mismatch(tmp_path):
381+
first_root = tmp_path / "first"
382+
second_root = tmp_path / "second"
383+
first_root.mkdir()
384+
second_root.mkdir()
385+
module_name = "task_repeated_build_import_path"
386+
first_path = first_root / f"{module_name}.py"
387+
second_path = second_root / f"{module_name}.py"
388+
first_path.write_text(
389+
"from pathlib import Path\n"
390+
"def task_example():\n"
391+
" Path(__file__).with_name('result.txt').write_text('first')\n"
392+
)
393+
second_path.write_text(
394+
"from pathlib import Path\n"
395+
"def task_example():\n"
396+
" Path(__file__).with_name('result.txt').write_text('second')\n"
397+
)
398+
399+
first_session = build(paths=first_root)
400+
second_session = build(paths=second_root)
401+
402+
assert first_session.exit_code == ExitCode.OK
403+
assert first_root.joinpath("result.txt").read_text() == "first"
404+
assert second_session.exit_code == ExitCode.COLLECTION_FAILED
405+
assert not second_root.joinpath("result.txt").exists()
406+
failed_reports = [
407+
report
408+
for report in second_session.collection_reports
409+
if report.outcome == CollectionOutcome.FAIL
410+
]
411+
assert len(failed_reports) == 1
412+
assert failed_reports[0].exc_info is not None
413+
assert isinstance(failed_reports[0].exc_info[1], ImportPathMismatchError)
414+
415+
379416
def test_collect_module_name(tmp_path):
380417
"""We need to add a task module to the sys.modules. See #373 and #374."""
381418
source = """

‎tests/test_path.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
from _pytask.path import normalize_local_upath
2525
from _pytask.path import relative_to
2626
from _pytask.path import shorten_path
27+
from pytask.path import ImportPathMismatchError
2728
from pytask.path import import_path
2829

2930
if TYPE_CHECKING:
@@ -193,6 +194,28 @@ def test_remembers_previous_imports(simple_module: Path, tmp_path: Path) -> None
193194
assert module1 is module2
194195

195196

197+
def test_rejects_cached_module_from_different_path(tmp_path: Path) -> None:
198+
module_name = "task_import_path_mismatch"
199+
first_path = tmp_path / "first" / f"{module_name}.py"
200+
second_path = tmp_path / "second" / f"{module_name}.py"
201+
first_path.parent.mkdir()
202+
second_path.parent.mkdir()
203+
first_path.write_text("VALUE = 'first'")
204+
second_path.write_text("VALUE = 'second'")
205+
206+
first_module = import_path(first_path, root=first_path.parent)
207+
208+
assert first_module.VALUE == "first"
209+
with pytest.raises(ImportPathMismatchError) as exc_info:
210+
import_path(second_path, root=second_path.parent)
211+
212+
message = str(exc_info.value)
213+
assert module_name in message
214+
assert str(first_path) in message
215+
assert str(second_path) in message
216+
assert "fresh process or notebook kernel" in message
217+
218+
196219
def test_no_meta_path_found(
197220
simple_module: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
198221
) -> None:

0 commit comments

Comments
 (0)