diff --git a/dlccore/config/project_config.py b/dlccore/config/project_config.py index 3957230..8edbc16 100644 --- a/dlccore/config/project_config.py +++ b/dlccore/config/project_config.py @@ -19,6 +19,7 @@ from dlccore.config.base_config import DLCVersionedConfig from dlccore.config.validation import ( + WINDOWS_MAX_PATH, BodypartPair, Fraction, NonNegativeInt, @@ -26,10 +27,16 @@ UniqueStrList, less_than, validate_crop_bounds, + windows_max_path_applies, ) logger = logging.getLogger(__name__) +# e.g. evaluation-results-pytorch/iteration-0/{Task}Nov17-trainset95shuffle1/ +# DLC_Resnet50_{Task}Nov17shuffle1_snapshot_200-results.csv. +_PATH_TOO_LONG_RISK_ESTIMATE = 120 +_paths_warned_for_length: set[Path] = set() + class ProjectConfig(DLCVersionedConfig): """Complete project configuration. @@ -303,3 +310,27 @@ def validate_cropping_bounds(self) -> Self: raise ValueError("When cropping is enabled, x1, x2, y1, and y2 must all be set") validate_crop_bounds(x1=self.x1, x2=self.x2, y1=self.y1, y2=self.y2) return self + + @model_validator(mode="after") + def warn_windows_path_length(self) -> Self: + """Warn, once per project, if a write might exceed the Windows path limit. + + Skipped when `project_path` is not an existing directory, typically a stale path in a moved project's + config.yaml. + Repaired by `_post_yaml_load_updates`, then validation reruns this check. + """ + if not windows_max_path_applies() or not self.project_path.is_dir(): + return self + project_path = self.project_path.absolute() + if project_path in _paths_warned_for_length: + return self + longest = len(str(project_path)) + 2 * len(self.Task) + _PATH_TOO_LONG_RISK_ESTIMATE + if longest >= WINDOWS_MAX_PATH: + _paths_warned_for_length.add(project_path) + logger.warning( + f"Paths in the project {project_path} will reach about {longest} characters, over the " + f"{WINDOWS_MAX_PATH}-character Windows limit, so writing files such as training datasets is " + "likely to fail. Enable long paths in Windows (LongPathsEnabled), move the project closer to " + "the drive root, or use a shorter Task name." + ) + return self diff --git a/dlccore/config/validation.py b/dlccore/config/validation.py index cab49ab..bcc2a27 100644 --- a/dlccore/config/validation.py +++ b/dlccore/config/validation.py @@ -8,6 +8,8 @@ # # Licensed under GNU Lesser General Public License v3.0 # +import functools +import os from collections.abc import Mapping, Sequence from typing import Annotated, Any, TypeAlias, TypeVar @@ -17,6 +19,29 @@ from pydantic_core import PydanticUseDefault +WINDOWS_MAX_PATH = 260 +"""Windows path length limit (`MAX_PATH`), terminating null included.""" + + +@functools.cache +def windows_max_path_applies() -> bool: + """Whether `WINDOWS_MAX_PATH` limits file paths on this machine. + + Returns: + True on Windows unless long paths are enabled (registry value `LongPathsEnabled`), False elsewhere. + """ + if os.name != "nt": + return False + import winreg + + try: + with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\FileSystem") as key: + enabled, _ = winreg.QueryValueEx(key, "LongPathsEnabled") + except OSError: + return True + return enabled != 1 + + def _describe(value: float, name: str | None = None) -> str: return f"{name} ({value})" if name else f"{value}" diff --git a/tests/config/test_project_config.py b/tests/config/test_project_config.py index 19ad559..6b0fbe7 100644 --- a/tests/config/test_project_config.py +++ b/tests/config/test_project_config.py @@ -11,11 +11,12 @@ """Tests for ProjectConfig — the real DLCVersionedConfig consumer.""" import logging +import os from pathlib import Path import pytest -from dlccore.config import ProjectConfig, read_config_as_dict +from dlccore.config import ProjectConfig, project_config, read_config_as_dict, validation from dlccore.config.versioning import CURRENT_CONFIG_VERSION # ----------------------------------------------------------------------------- @@ -176,6 +177,68 @@ def test_project_path_not_updated_when_already_correct(self, tmp_path): assert not cfg.is_dirty +# ----------------------------------------------------------------------------- +# Windows path length warning (warn_windows_path_length) +# ----------------------------------------------------------------------------- + +_LONG_TASK = "t" * 100 + + +class TestWindowsPathLengthWarning: + @pytest.fixture(autouse=True) + def limit_applies(self, monkeypatch): + """Apply the Windows path limit on any platform, with no project warned yet.""" + monkeypatch.setattr(project_config, "windows_max_path_applies", lambda: True) + monkeypatch.setattr(project_config, "_paths_warned_for_length", set()) + + @staticmethod + def _path_warnings(caplog) -> list[logging.LogRecord]: + return [r for r in caplog.records if "Windows limit" in r.message] + + def test_warns_for_long_paths(self, tmp_path, caplog): + with caplog.at_level(logging.WARNING, logger="dlccore.config.project_config"): + ProjectConfig(Task=_LONG_TASK, project_path=tmp_path) + assert len(self._path_warnings(caplog)) == 1 + + def test_silent_for_short_paths(self, tmp_path, caplog): + with caplog.at_level(logging.WARNING, logger="dlccore.config.project_config"): + ProjectConfig(Task="t", project_path=tmp_path) + assert not self._path_warnings(caplog) + + def test_silent_when_limit_does_not_apply(self, tmp_path, caplog, monkeypatch): + monkeypatch.setattr(project_config, "windows_max_path_applies", lambda: False) + with caplog.at_level(logging.WARNING, logger="dlccore.config.project_config"): + ProjectConfig(Task=_LONG_TASK, project_path=tmp_path) + assert not self._path_warnings(caplog) + + def test_silent_for_missing_project_path(self, tmp_path, caplog): + with caplog.at_level(logging.WARNING, logger="dlccore.config.project_config"): + ProjectConfig(Task=_LONG_TASK, project_path=tmp_path / "missing") + assert not self._path_warnings(caplog) + + def test_warns_once_per_project(self, tmp_path, caplog): + with caplog.at_level(logging.WARNING, logger="dlccore.config.project_config"): + cfg = ProjectConfig(Task=_LONG_TASK, project_path=tmp_path) + cfg.pcutoff = 0.5 + ProjectConfig(Task=_LONG_TASK, project_path=tmp_path) + assert len(self._path_warnings(caplog)) == 1 + + def test_checks_repaired_project_path(self, tmp_path, caplog): + """A stale project_path in a moved project's YAML is skipped; the repaired one is checked.""" + long_dir = tmp_path / ("d" * 150) + long_dir.mkdir() + (long_dir / "config.yaml").write_text(f"Task: {'t' * 30}\nproject_path: /stale/path\n") + with caplog.at_level(logging.WARNING, logger="dlccore.config.project_config"): + ProjectConfig.from_yaml(long_dir / "config.yaml") + [record] = self._path_warnings(caplog) + assert str(long_dir) in record.message + + @pytest.mark.skipif(os.name == "nt", reason="Off-Windows behaviour") + def test_limit_never_applies_off_windows(self): + validation.windows_max_path_applies.cache_clear() + assert validation.windows_max_path_applies() is False + + # ----------------------------------------------------------------------------- # Legacy empty / null values (normalize_legacy_empty_values) # -----------------------------------------------------------------------------