diff --git a/dlccore/project/discovery/__init__.py b/dlccore/project/discovery/__init__.py new file mode 100644 index 0000000..d329f1d --- /dev/null +++ b/dlccore/project/discovery/__init__.py @@ -0,0 +1,10 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# diff --git a/dlccore/project/discovery/observer.py b/dlccore/project/discovery/observer.py new file mode 100644 index 0000000..7c2fa8a --- /dev/null +++ b/dlccore/project/discovery/observer.py @@ -0,0 +1,519 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +from __future__ import annotations + +from enum import Enum +from pathlib import Path + +from dlccore.project.discovery.probe import FileIdentity, file_identity, probe_path +from dlccore.project.schemas.base.filesystem import ( + DirectorySchema, + FileSchema, + NodeSchema, +) +from dlccore.project.schemas.base.observations import ( + NodeStatus, + ObservedNode, +) +from dlccore.project.schemas.base.probes import ( + FilesystemEntryKind, + PathProbe, + PathProbeStatus, +) +from dlccore.project.schemas.base.resources import ( + DirectoryResourceKind, + FileResourceKind, + ProjectResource, + ResourceKind, + ResourceManagement, + UnknownResourceKind, +) +from dlccore.project.schemas.base.symlinks import ( + SymlinkObservation, + SymlinkTargetKind, +) +from dlccore.project.schemas.project_layout.project import PROJECT + +_UNREADABLE_SYMLINK_TARGET_KINDS = frozenset( + { + SymlinkTargetKind.MISSING, + SymlinkTargetKind.INACCESSIBLE, + } +) + + +class ExpectedEntryKind(str, Enum): + """Filesystem type required by a schema node.""" + + FILE = "file" + DIRECTORY = "directory" + + +def status_for_expected_entry( + probe: PathProbe, + *, + expected_kind: ExpectedEntryKind, +) -> NodeStatus: + """Derive the ``NodeStatus`` of a schema-expected entry from its probe. + + Consumes only ``PathProbe`` facts, does not touch the filesystem. + """ + + if probe.status == PathProbeStatus.MISSING: + return NodeStatus.MISSING + + if probe.entry_kind is None: + # Entry-level access failure (PathProbeStatus.INACCESSIBLE). + return NodeStatus.UNREADABLE + + if probe.entry_kind == FilesystemEntryKind.SYMLINK: + symlink = probe.symlink + assert symlink is not None # guaranteed by PathProbe invariants + + if symlink.target_kind in _UNREADABLE_SYMLINK_TARGET_KINDS: + return NodeStatus.UNREADABLE + + expected_target = ( + SymlinkTargetKind.DIRECTORY if expected_kind == ExpectedEntryKind.DIRECTORY else SymlinkTargetKind.FILE + ) + + return NodeStatus.PRESENT if symlink.target_kind == expected_target else NodeStatus.WRONG_TYPE + + matches_expected_kind = ( + expected_kind == ExpectedEntryKind.FILE and probe.entry_kind == FilesystemEntryKind.FILE + ) or (expected_kind == ExpectedEntryKind.DIRECTORY and probe.entry_kind == FilesystemEntryKind.DIRECTORY) + + return NodeStatus.PRESENT if matches_expected_kind else NodeStatus.WRONG_TYPE + + +def classify_unclaimed_entry( + probe: PathProbe, +) -> tuple[ + ResourceKind, + SymlinkObservation | None, +]: + """Return which resource kind an unclaimed entry corresponds to, from its probe. + + Consumes only ``PathProbe``, does not touch the filesystem. + + A symlink to a directory is retained as one, rather than refused: the target + kind already says what it is, and an unknown directory is recorded without + its contents being interpreted, so nothing follows the link. + + An entry whose kind cannot be determined is classified as + ``UnknownResourceKind.UNKNOWN`` rather than refused. + """ + + if probe.entry_kind is None: + return UnknownResourceKind.UNKNOWN, None + + if probe.entry_kind == FilesystemEntryKind.SYMLINK: + symlink = probe.symlink + assert symlink is not None # guaranteed by PathProbe invariants + + if symlink.target_kind == SymlinkTargetKind.FILE: + return FileResourceKind.UNKNOWN_FILE, symlink + + if symlink.target_kind == SymlinkTargetKind.DIRECTORY: + return DirectoryResourceKind.UNKNOWN_DIRECTORY, symlink + + return UnknownResourceKind.UNKNOWN, symlink # broken / unreachable + + if probe.entry_kind == FilesystemEntryKind.FILE: + return FileResourceKind.UNKNOWN_FILE, None + + if probe.entry_kind == FilesystemEntryKind.DIRECTORY: + return DirectoryResourceKind.UNKNOWN_DIRECTORY, None + + return UnknownResourceKind.UNKNOWN, None + + +def expected_kind_for( + schema: NodeSchema, +) -> ExpectedEntryKind: + """Return the filesystem kind a schema node declares. + + Raises: + TypeError: If the schema is neither a file nor a directory node. + """ + + if isinstance( + schema, + FileSchema, + ): + return ExpectedEntryKind.FILE + + if isinstance( + schema, + DirectorySchema, + ): + return ExpectedEntryKind.DIRECTORY + + raise TypeError(f"Unsupported schema node type: {type(schema).__name__}") + + +def entry_matches_expected_kind( + probe: PathProbe, + *, + expected_kind: ExpectedEntryKind, +) -> bool: + """Whether a plain entry is of the kind a schema declares. + + Only regular files and directories are judged here. Symlinks, access + failures and unsupported entry types are left to + ``status_for_expected_entry``, which reports them rather than dropping + them. + """ + + if probe.entry_kind == FilesystemEntryKind.FILE: + return expected_kind == ExpectedEntryKind.FILE + + if probe.entry_kind == FilesystemEntryKind.DIRECTORY: + return expected_kind == ExpectedEntryKind.DIRECTORY + + return True + + +def discover_node( + *, + physical_path: Path, + project_relative_path: Path, + schema: NodeSchema, +) -> ObservedNode: + """Observe one path against one layout-schema node.""" + + expected_kind = expected_kind_for(schema) + + probe = probe_path(physical_path) + status = status_for_expected_entry( + probe, + expected_kind=expected_kind, + ) + + return ObservedNode( + schema_id=schema.schema_id, + project_relative_path=(project_relative_path), + probe=probe, + status=status, + kind=schema.kind, + management=schema.management, + ) + + +def discover_schema_node( + *, + physical_path: Path, + project_relative_path: Path, + project_root: Path, + schema: NodeSchema, + ancestors: frozenset[FileIdentity] = frozenset(), +) -> ObservedNode: + """Observe a schema node, recursively when the schema is a directory.""" + + if isinstance(schema, DirectorySchema): + return discover_directory_node( + physical_path=physical_path, + project_relative_path=project_relative_path, + project_root=project_root, + schema=schema, + ancestors=ancestors, + ) + + return discover_node( + physical_path=physical_path, + project_relative_path=project_relative_path, + schema=schema, + ) + + +def discover_fixed_children( + *, + physical_directory: Path, + project_relative_directory: Path, + project_root: Path, + schema: DirectorySchema, + ancestors: frozenset[FileIdentity] = frozenset(), +) -> tuple[ObservedNode, ...]: + """Observe children with exact names declared by a directory schema. + + Fixed children occupy predetermined locations in the project layout, + such as ``config.yaml``, ``videos/``, and ``labeled-data/``. + + This function does not discover dynamically named children, such as + source videos or labeled-dataset directories. Those are described by + ``DirectorySchema.repeated_children`` and observed separately. + + Example: + project_root/ + ├── config.yaml # fixed file + ├── videos/ # fixed directory + │ └── session-01.mp4 # repeated child + └── labeled-data/ # fixed directory + └── session-01/ # repeated child + """ + + observations: list[ObservedNode] = [] + + for child_schema in schema.children: + exact_name = child_schema.name.exact + + if exact_name is None: + raise ValueError(f"Fixed child schema {child_schema.schema_id!r} must define an exact name.") + + observations.append( + discover_schema_node( + physical_path=physical_directory / exact_name, + project_relative_path=(project_relative_directory / exact_name), + project_root=project_root, + schema=child_schema, + ancestors=ancestors, + ) + ) + + return tuple(observations) + + +def discover_repeated_children( + *, + entries: tuple[Path, ...], + project_relative_directory: Path, + project_root: Path, + schema: DirectorySchema, + ancestors: frozenset[FileIdentity] = frozenset(), +) -> tuple[ObservedNode, ...]: + """Observe dynamically named children declared by a schema. + + A schema claims an entry only when the name matches *and* the entry is of + the kind the schema declares. An entry of the wrong kind is left unclaimed + so it is retained as an unidentified resource, rather than reported against + a schema it never belonged to. + """ + + fixed_names = {child.name.exact for child in schema.children if child.name.exact is not None} + + observations: list[ObservedNode] = [] + + for entry in entries: + if entry.name in fixed_names: + continue + + probe = probe_path(entry) + + matching_schemas = tuple( + repeated.child + for repeated in schema.repeated_children + if repeated.child.name.matches(entry) + and entry_matches_expected_kind(probe, expected_kind=expected_kind_for(repeated.child)) + ) + + if not matching_schemas: + continue + + if len(matching_schemas) > 1: + matching_ids = [matching_schema.schema_id for matching_schema in matching_schemas] + + raise ValueError(f"Filesystem entry {entry!s} matches multiple repeated-child schemas: {matching_ids}") + + observations.append( + discover_schema_node( + physical_path=entry, + project_relative_path=(project_relative_directory / entry.name), + project_root=project_root, + schema=matching_schemas[0], + ancestors=ancestors, + ) + ) + + return tuple(observations) + + +def claimed_child_names( + *, + fixed_children: tuple[ObservedNode, ...], + repeated_children: tuple[ObservedNode, ...], +) -> frozenset: + """Return immediate filesystem names claimed by schema observations. + + Missing fixed children are excluded because no corresponding filesystem + entry exists. Present, unreadable, and wrong-type entries remain claimed + to prevent them from also being reported as unknown. + """ + + return frozenset( + child.project_relative_path.name + for child in fixed_children + repeated_children + if child.status != NodeStatus.MISSING + ) + + +def _observe_unknown_resource( + *, + physical_path: Path, + project_root: Path, +) -> ProjectResource | None: + """Observe one unclaimed immediate filesystem entry. + + Returns ``None`` for an entry that vanished between listing and probing, so + ``resources`` holds only entries with a filesystem entry, as claimed nodes do. + An inaccessible entry does exist, and is retained. + """ + + probe = probe_path(physical_path) + + if probe.status == PathProbeStatus.MISSING: + return None + + kind, symlink = classify_unclaimed_entry(probe) + + return ProjectResource( + project_relative_path=(physical_path.relative_to(project_root)), + kind=kind, + management=(ResourceManagement.UNDETERMINED), + symlink=symlink, + ) + + +def discover_unknown_children( + *, + entries: tuple[Path, ...], + claimed_names: frozenset[str], + project_root: Path, +) -> tuple[ProjectResource, ...]: + """Retain immediate entries not claimed by a schema.""" + + observed = ( + _observe_unknown_resource( + physical_path=entry, + project_root=project_root, + ) + for entry in entries + if entry.name not in claimed_names + ) + + return tuple(resource for resource in observed if resource is not None) + + +def discover_directory_node( + *, + physical_path: Path, + project_relative_path: Path, + project_root: Path, + schema: DirectorySchema, + ancestors: frozenset[FileIdentity] = frozenset(), +) -> ObservedNode: + """Observe a directory and classify its immediate contents. + + Fixed and repeated children are observed according to the layout schema. + Entries that remain unclaimed are retained as unknown resources. + + Directory schemas are observed recursively, through symlinks, while unknown + directories are recorded without interpreting their contents. A directory that + is one of its own ancestors, reached through a link, is unreadable and not entered. + """ + + observed = discover_node( + physical_path=physical_path, + project_relative_path=project_relative_path, + schema=schema, + ) + + if observed.status != NodeStatus.PRESENT: + return observed + + try: + identity = file_identity(physical_path) + except OSError as error: + return _unreadable(observed, type(error).__name__, str(error)) + + if identity in ancestors: + return _unreadable(observed, "SymlinkLoop", f"{physical_path} is the same directory as one of its ancestors") + + ancestors = ancestors | {identity} + + try: + entries = tuple( + sorted( + physical_path.iterdir(), + key=lambda entry: entry.name.casefold(), + ) + ) + except OSError as error: + return _unreadable(observed, type(error).__name__, str(error)) + + fixed_children = discover_fixed_children( + physical_directory=physical_path, + project_relative_directory=project_relative_path, + project_root=project_root, + schema=schema, + ancestors=ancestors, + ) + + repeated_children = discover_repeated_children( + entries=entries, + project_relative_directory=project_relative_path, + project_root=project_root, + schema=schema, + ancestors=ancestors, + ) + + claimed_names = claimed_child_names( + fixed_children=fixed_children, + repeated_children=repeated_children, + ) + + unclaimed_resources = discover_unknown_children( + entries=entries, + claimed_names=claimed_names, + project_root=project_root, + ) + + # NOTE: @C-Achard 2026-09-03 - this kind of update is not ideal. Consider alternatives. + return observed.model_copy( + update={ + "schema_children": fixed_children + repeated_children, + "unclaimed_resources": unclaimed_resources, + } + ) + + +def _unreadable(observed: ObservedNode, error_type: str, error_message: str) -> ObservedNode: + """Mark a present directory unreadable and say why; its probe, the entry's own observation, is unchanged.""" + + return observed.model_copy( + update={ + "status": NodeStatus.UNREADABLE, + "traversal_error_type": error_type, + "traversal_error_message": error_message, + } + ) + + +def discover_project(project_root: Path) -> ObservedNode: + """Observe a project against the canonical DLC layout.""" + + return _discover_project_with_schema( + project_root, + schema=PROJECT, + ) + + +def _discover_project_with_schema( + project_root: Path, + *, + schema: DirectorySchema, +) -> ObservedNode: + return discover_directory_node( + physical_path=project_root, + project_relative_path=Path(), + project_root=project_root, + schema=schema, + ) diff --git a/dlccore/project/discovery/probe.py b/dlccore/project/discovery/probe.py new file mode 100644 index 0000000..facc695 --- /dev/null +++ b/dlccore/project/discovery/probe.py @@ -0,0 +1,135 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +"""Low-level, typed filesystem probing. + +``probe_path()`` inspects one path on disk and classifies it; +``file_identity()`` tells whether two paths name the same file. Both record +raw filesystem facts only; they never decide schema validity, finding codes, +or remediation. +""" + +from __future__ import annotations + +import os +import stat +from pathlib import Path + +from dlccore.project.schemas.base.probes import ( + FilesystemEntryKind, + PathProbe, + PathProbeStatus, +) +from dlccore.project.schemas.base.symlinks import SymlinkObservation, SymlinkTargetKind + +FileIdentity = tuple[int, int] | Path + + +def probe_path(path: Path) -> PathProbe: + """Observe one filesystem path without following symlinks unconditionally.""" + + try: + entry_mode = path.lstat().st_mode + except FileNotFoundError: + return PathProbe(status=PathProbeStatus.MISSING) + except (OSError, ValueError) as error: # ValueError: a path the OS cannot take, such as one holding NUL + return PathProbe( + status=PathProbeStatus.INACCESSIBLE, + error_type=type(error).__name__, + error_message=str(error), + ) + + if stat.S_ISLNK(entry_mode): + return _probe_symlink(path) + + if stat.S_ISREG(entry_mode): + return PathProbe(status=PathProbeStatus.OBSERVED, entry_kind=FilesystemEntryKind.FILE) + + if stat.S_ISDIR(entry_mode): + return PathProbe(status=PathProbeStatus.OBSERVED, entry_kind=FilesystemEntryKind.DIRECTORY) + + return PathProbe(status=PathProbeStatus.OBSERVED, entry_kind=FilesystemEntryKind.OTHER) + + +def file_identity(path: Path, *, follow_symlinks: bool = True) -> FileIdentity: + """Return what two paths are compared by to tell whether they name the same file. + + The device and file ID, or the resolved path where the filesystem reports no file ID. With + ``follow_symlinks=False`` a symlink is identified itself, not its target. For comparison only: never output it. + + Raises: + OSError: If the path cannot be stat'd. + ValueError: If the OS cannot take the path, such as one holding NUL. + """ + + status = os.stat(path, follow_symlinks=follow_symlinks) + + # st_ino is unique only when non-zero (os.stat_result); a shared 0 would merge every file + if status.st_ino == 0: + return path.resolve() if follow_symlinks else path.parent.resolve() / path.name + + return status.st_dev, status.st_ino + + +def _probe_symlink(path: Path) -> PathProbe: + """Observe a confirmed symlink entry and its lexical/resolved target.""" + + try: + raw_target = path.readlink() + absolute_target = (raw_target if raw_target.is_absolute() else path.parent / raw_target).absolute() + except OSError as error: + return PathProbe( + status=PathProbeStatus.INACCESSIBLE, + error_type=type(error).__name__, + error_message=str(error), + ) + + try: + target_mode = absolute_target.stat().st_mode + except FileNotFoundError: + return PathProbe( + status=PathProbeStatus.OBSERVED, + entry_kind=FilesystemEntryKind.SYMLINK, + symlink=SymlinkObservation( + raw_target=raw_target, + absolute_target=absolute_target, + target_kind=SymlinkTargetKind.MISSING, + ), + ) + except OSError as error: + return PathProbe( + status=PathProbeStatus.OBSERVED, + entry_kind=FilesystemEntryKind.SYMLINK, + symlink=SymlinkObservation( + raw_target=raw_target, + absolute_target=absolute_target, + target_kind=SymlinkTargetKind.INACCESSIBLE, + ), + error_type=type(error).__name__, + error_message=str(error), + ) + + if stat.S_ISREG(target_mode): + target_kind = SymlinkTargetKind.FILE + elif stat.S_ISDIR(target_mode): + target_kind = SymlinkTargetKind.DIRECTORY + else: + target_kind = SymlinkTargetKind.OTHER + + return PathProbe( + status=PathProbeStatus.OBSERVED, + entry_kind=FilesystemEntryKind.SYMLINK, + symlink=SymlinkObservation( + raw_target=raw_target, + absolute_target=absolute_target, + target_kind=target_kind, + ), + ) diff --git a/tests/io/conftest.py b/tests/conftest.py similarity index 67% rename from tests/io/conftest.py rename to tests/conftest.py index fec6164..d52b0a8 100644 --- a/tests/io/conftest.py +++ b/tests/conftest.py @@ -9,6 +9,7 @@ # Licensed under GNU Lesser General Public License v3.0 # +import os from collections.abc import Callable from pathlib import Path @@ -40,3 +41,16 @@ def create_symlink_or_skip() -> Callable[..., None]: """Return a helper that creates a symlink or skips the test cleanly.""" return _create_symlink_or_skip + + +@pytest.fixture +def without_file_ids(monkeypatch: pytest.MonkeyPatch) -> None: + """Make ``os.stat`` report file ID 0, as a filesystem without file IDs does.""" + + real_stat = os.stat + + def stat_without_file_id(path: object, *args: object, **kwargs: object) -> os.stat_result: + result = real_stat(path, *args, **kwargs) + return os.stat_result((result[0], 0, *result[2:])) + + monkeypatch.setattr(os, "stat", stat_without_file_id) diff --git a/tests/project/discovery/test_node_construction.py b/tests/project/discovery/test_node_construction.py new file mode 100644 index 0000000..f37add2 --- /dev/null +++ b/tests/project/discovery/test_node_construction.py @@ -0,0 +1,71 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +from collections.abc import Callable +from pathlib import Path + +import pytest + +from dlccore.project.discovery.observer import discover_project +from dlccore.project.schemas.base.observations import NodeStatus, ObservedNode + + +@pytest.fixture +def model_copy_updates(monkeypatch: pytest.MonkeyPatch) -> list[dict]: + """Record the ``update`` of every ``ObservedNode.model_copy`` call.""" + + updates: list[dict] = [] + original = ObservedNode.model_copy + + def spy(self: ObservedNode, *, update: dict | None = None, deep: bool = False) -> ObservedNode: + updates.append(update or {}) + return original(self, update=update, deep=deep) + + monkeypatch.setattr(ObservedNode, "model_copy", spy) + return updates + + +@pytest.mark.xfail( + reason="discover_directory_node attaches children with model_copy, which skips validation", + raises=AssertionError, + strict=True, +) +def test_discovery_builds_directory_nodes_through_validation(tmp_path: Path, model_copy_updates: list[dict]) -> None: + (tmp_path / "config.yaml").write_text("Task: demo", encoding="utf-8") + (tmp_path / "videos").mkdir() + (tmp_path / "labeled-data" / "session-01").mkdir(parents=True) + + discover_project(tmp_path) + + assert model_copy_updates == [] + + +@pytest.mark.xfail( + reason="_unreadable marks a node unreadable with model_copy, which skips validation", + raises=AssertionError, + strict=True, +) +def test_discovery_builds_unreadable_nodes_through_validation( + tmp_path: Path, + model_copy_updates: list[dict], + create_symlink_or_skip: Callable[..., None], +) -> None: + (tmp_path / "config.yaml").write_text("Task: demo", encoding="utf-8") + (tmp_path / "labeled-data").mkdir() + create_symlink_or_skip(tmp_path / "videos", tmp_path, target_is_directory=True) + + project = discover_project(tmp_path) + + videos = next(child for child in project.schema_children if child.project_relative_path.name == "videos") + if (videos.status, videos.traversal_error_type) != (NodeStatus.UNREADABLE, "SymlinkLoop"): + pytest.fail(f"the symlink loop was not reached: {videos.status}, {videos.traversal_error_type}") + + assert [update for update in model_copy_updates if "status" in update] == [] diff --git a/tests/project/discovery/test_observer.py b/tests/project/discovery/test_observer.py new file mode 100644 index 0000000..e5ad48b --- /dev/null +++ b/tests/project/discovery/test_observer.py @@ -0,0 +1,376 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +from collections.abc import Iterator +from pathlib import Path + +import pytest + +from dlccore.project.discovery.observer import discover_directory_node, discover_project +from dlccore.project.schemas.base.filesystem import ( + DirectorySchema, + FileSchema, + NamePattern, + NodeSchema, +) +from dlccore.project.schemas.base.observations import ( + NodeStatus, +) +from dlccore.project.schemas.base.probes import FilesystemEntryKind, PathProbeStatus +from dlccore.project.schemas.base.resources import ( + DirectoryResourceKind, + FileResourceKind, + ResourceManagement, +) +from dlccore.project.schemas.project_layout.project import PROJECT + + +def test_discovered_directory_populates_renamed_fields( + tmp_path: Path, +) -> None: + (tmp_path / "config.yaml").touch() + (tmp_path / "videos").mkdir() + + project = discover_project(tmp_path) + + assert project.schema_children + assert {child.project_relative_path for child in project.schema_children} >= { + Path("config.yaml"), + Path("videos"), + } + + model_fields = type(project).model_fields + + assert "children" not in model_fields + assert "unknown_children" not in model_fields + + +def test_discover_project_fixed_children(tmp_path: Path) -> None: + (tmp_path / "config.yaml").write_text("", encoding="utf-8") + (tmp_path / "videos").mkdir() + + observed = discover_project( + tmp_path, + ) + + statuses = {child.project_relative_path: child.status for child in observed.schema_children} + + assert statuses[Path("config.yaml")] == NodeStatus.PRESENT + assert statuses[Path("videos")] == NodeStatus.PRESENT + assert statuses[Path("labeled-data")] == NodeStatus.MISSING + + +def test_observe_fixed_child_with_wrong_type(tmp_path: Path) -> None: + (tmp_path / "config.yaml").write_text("", encoding="utf-8") + (tmp_path / "videos").write_text( + "not a directory", + encoding="utf-8", + ) + + observed = discover_directory_node( + physical_path=tmp_path, + project_relative_path=Path(), + project_root=tmp_path, + schema=PROJECT, + ) + + videos = next(child for child in observed.schema_children if child.project_relative_path == Path("videos")) + + assert videos.status == NodeStatus.WRONG_TYPE + assert videos.should_be_directory + + +def test_observe_repeated_video_files(tmp_path: Path) -> None: + (tmp_path / "config.yaml").write_text( + "Task: demo", + encoding="utf-8", + ) + + videos = tmp_path / "videos" + videos.mkdir() + + (videos / "session-01.mp4").touch() + (videos / "session-02.avi").touch() + (videos / "notes.txt").write_text( + "user notes", + encoding="utf-8", + ) + + observed = discover_project( + tmp_path, + ) + + videos_node = next( + child for child in observed.schema_children if child.kind == DirectoryResourceKind.VIDEOS_DIRECTORY + ) + + source_videos = [child for child in videos_node.schema_children if child.kind == FileResourceKind.SOURCE_VIDEO] + + assert {node.project_relative_path for node in source_videos} == { + Path("videos/session-01.mp4"), + Path("videos/session-02.avi"), + } + + +def test_observe_labeled_dataset(tmp_path: Path) -> None: + labeled_data = tmp_path / "labeled-data" + dataset = labeled_data / "session-01" + + dataset.mkdir(parents=True) + + (dataset / "img001.png").touch() + (dataset / "CollectedData_Sc.h5").touch() + + observed = discover_project( + tmp_path, + ) + + labeled_data_node = next( + child for child in observed.schema_children if child.kind == DirectoryResourceKind.LABELED_DATA_DIRECTORY + ) + + dataset_node = next( + child for child in labeled_data_node.schema_children if child.kind == DirectoryResourceKind.LABELED_DATASET + ) + + assert dataset_node.project_relative_path == Path("labeled-data/session-01") + + assert {child.kind for child in dataset_node.schema_children} == { + FileResourceKind.LABELED_FRAME, + FileResourceKind.HUMAN_LABELS, + FileResourceKind.NAPARI_DLC_METADATA, + } + + +def test_loose_file_in_labeled_data_is_retained_unclaimed(tmp_path: Path) -> None: + """A file beside the datasets is unidentified, never a wrong-type dataset. + + The dataset schema's name pattern matches every entry, so without entry-kind + matching any file here is claimed as a labeled dataset and reported + ``WRONG_TYPE``. Whatever a user leaves in this directory is theirs: it is + retained and left alone, not judged against a schema it never belonged to. + """ + + labeled_data = tmp_path / "labeled-data" + dataset = labeled_data / "session-01" + + dataset.mkdir(parents=True) + + (dataset / "img001.png").touch() + (labeled_data / "notes.txt").write_text("user notes", encoding="utf-8") + (labeled_data / "export.csv").write_text("", encoding="utf-8") + + observed = discover_project( + tmp_path, + ) + + labeled_data_node = next( + child for child in observed.schema_children if child.kind == DirectoryResourceKind.LABELED_DATA_DIRECTORY + ) + + assert {child.project_relative_path for child in labeled_data_node.schema_children} == { + Path("labeled-data/session-01"), + } + + assert all(child.status != NodeStatus.WRONG_TYPE for child in labeled_data_node.schema_children) + + unclaimed = {resource.project_relative_path: resource for resource in labeled_data_node.unclaimed_resources} + + assert set(unclaimed) == { + Path("labeled-data/notes.txt"), + Path("labeled-data/export.csv"), + } + + assert {resource.kind for resource in unclaimed.values()} == {FileResourceKind.UNKNOWN_FILE} + assert {resource.management for resource in unclaimed.values()} == {ResourceManagement.UNDETERMINED} + + +def _repeated_child_schemas() -> list[tuple[DirectorySchema, NodeSchema]]: + """Every (parent, repeated child) pair reachable from the project schema.""" + + pairs: list[tuple[DirectorySchema, NodeSchema]] = [] + pending: list[NodeSchema] = [PROJECT] + + while pending: + schema = pending.pop() + + if not isinstance(schema, DirectorySchema): + continue + + pairs.extend((schema, repeated.child) for repeated in schema.repeated_children) + pending.extend(schema.children) + pending.extend(repeated.child for repeated in schema.repeated_children) + + return pairs + + +def _name_matching(pattern: NamePattern) -> str: + """Build a filesystem name the pattern accepts.""" + + if pattern.exact is not None: + return pattern.exact + + suffix = sorted(pattern.suffixes)[0] if pattern.suffixes else "" + + return f"{pattern.prefix or ''}entry{suffix}" + + +@pytest.mark.parametrize( + ("parent", "child"), + _repeated_child_schemas(), + ids=lambda schema: getattr(schema, "schema_id", ""), +) +def test_every_repeated_child_leaves_a_wrong_kind_entry_unclaimed( + parent: DirectorySchema, + child: NodeSchema, + tmp_path: Path, +) -> None: + """No schema claims an entry of the kind it does not declare. + + Parametrised over the whole layout rather than over the cases that prompted + the rule, so a schema added later is covered without anyone remembering to + come back. A new repeated child that mis-claims fails here on the day it + lands. + """ + + name = _name_matching(child.name) + entry = tmp_path / name + + if isinstance(child, FileSchema): + entry.mkdir() + else: + entry.write_text("", encoding="utf-8") + + observed = discover_directory_node( + physical_path=tmp_path, + project_relative_path=Path(), + project_root=tmp_path, + schema=parent, + ) + + assert name not in {node.project_relative_path.name for node in observed.schema_children} + assert name in {resource.project_relative_path.name for resource in observed.unclaimed_resources} + + +@pytest.mark.xfail( + reason="check_labels plot output is claimed as a labeled dataset and its plots as labeled frames", + strict=True, + raises=AssertionError, +) +def test_check_labels_plot_output_is_not_a_labeled_dataset(tmp_path: Path) -> None: + labeled_data = tmp_path / "labeled-data" + dataset = labeled_data / "session-01" + plot_output = labeled_data / "session-01_labeled" + + dataset.mkdir(parents=True) + plot_output.mkdir() + + (dataset / "img001.png").touch() + (plot_output / "img001_bodypart.png").touch() + + observed = discover_project( + tmp_path, + ) + + labeled_data_node = next( + child for child in observed.schema_children if child.kind == DirectoryResourceKind.LABELED_DATA_DIRECTORY + ) + + datasets = { + child.project_relative_path + for child in labeled_data_node.schema_children + if child.kind == DirectoryResourceKind.LABELED_DATASET + } + + assert datasets == {Path("labeled-data/session-01")} + + +def test_retain_unknown_video_entries(tmp_path: Path) -> None: + videos = tmp_path / "videos" + backups = videos / "old-backups" + + videos.mkdir() + backups.mkdir() + + (videos / "session-01.mp4").touch() + (videos / "notes.txt").write_text( + "user notes", + encoding="utf-8", + ) + + observed = discover_project( + tmp_path, + ) + + videos_node = next( + child for child in observed.schema_children if child.kind == DirectoryResourceKind.VIDEOS_DIRECTORY + ) + + assert {child.project_relative_path for child in videos_node.schema_children} == { + Path("videos/session-01.mp4"), + } + + assert {resource.project_relative_path for resource in videos_node.unclaimed_resources} == { + Path("videos/notes.txt"), + Path("videos/old-backups"), + } + + unknown = {resource.project_relative_path: resource.kind for resource in videos_node.unclaimed_resources} + + assert unknown[Path("videos/notes.txt")] == FileResourceKind.UNKNOWN_FILE + + assert unknown[Path("videos/old-backups")] == DirectoryResourceKind.UNKNOWN_DIRECTORY + + +def test_directory_traversal_failure_is_independent_of_entry_probe( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A failed ``iterdir()`` marks the node UNREADABLE and keeps why, without touching its probe.""" + + videos = tmp_path / "videos" + videos.mkdir() + + real_iterdir = Path.iterdir + + def fake_iterdir(self: Path, *args: object, **kwargs: object) -> Iterator[Path]: + if self == videos: + raise OSError("Directory listing failed") + + return real_iterdir(self, *args, **kwargs) + + monkeypatch.setattr(Path, "iterdir", fake_iterdir) + + observed = discover_project(tmp_path) + + videos_node = next(child for child in observed.schema_children if child.project_relative_path == Path("videos")) + + assert videos_node.status == NodeStatus.UNREADABLE + assert videos_node.traversal_error_type == "OSError" + assert videos_node.traversal_error_message == "Directory listing failed" + assert videos_node.probe.status == PathProbeStatus.OBSERVED + assert videos_node.probe.entry_kind == FilesystemEntryKind.DIRECTORY + assert videos_node.probe.error_type is None + + +@pytest.mark.usefixtures("without_file_ids") +def test_without_file_ids_a_subdirectory_is_not_a_symlink_loop(tmp_path: Path) -> None: + (tmp_path / "config.yaml").touch() + (tmp_path / "videos").mkdir() + (tmp_path / "labeled-data" / "session-01").mkdir(parents=True) + + observed = discover_project(tmp_path) + + by_path = {child.project_relative_path: child for child in observed.schema_children} + + assert by_path[Path("videos")].status == NodeStatus.PRESENT + assert by_path[Path("labeled-data")].status == NodeStatus.PRESENT + assert by_path[Path("labeled-data")].traversal_error_type is None diff --git a/tests/project/discovery/test_probe.py b/tests/project/discovery/test_probe.py new file mode 100644 index 0000000..6112527 --- /dev/null +++ b/tests/project/discovery/test_probe.py @@ -0,0 +1,359 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +from __future__ import annotations + +import os +import stat +import sys +from collections.abc import Callable +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from dlccore.project.discovery.observer import ExpectedEntryKind, status_for_expected_entry +from dlccore.project.discovery.probe import file_identity, probe_path +from dlccore.project.schemas.base.observations import NodeStatus +from dlccore.project.schemas.base.probes import FilesystemEntryKind, PathProbe, PathProbeStatus +from dlccore.project.schemas.base.symlinks import SymlinkObservation, SymlinkTargetKind + + +def _same_file(path: Path, other: Path) -> bool: + """Whether two paths name the same file; ``False`` when either cannot be stat'd.""" + + try: + return file_identity(path) == file_identity(other) + except (OSError, ValueError): + return False + + +def test_probe_missing_path(tmp_path: Path) -> None: + probe = probe_path(tmp_path / "missing.mp4") + + assert probe.status == PathProbeStatus.MISSING + assert probe.entry_kind is None + assert probe.symlink is None + + +def test_probe_a_path_the_os_cannot_take(tmp_path: Path) -> None: + probe = probe_path(tmp_path / "a\x00b") + + assert probe.status == PathProbeStatus.INACCESSIBLE + assert probe.error_type == "ValueError" + + +def test_probe_regular_file(tmp_path: Path) -> None: + path = tmp_path / "video.mp4" + path.touch() + + probe = probe_path(path) + + assert probe.status == PathProbeStatus.OBSERVED + assert probe.entry_kind == FilesystemEntryKind.FILE + assert probe.symlink is None + + +def test_probe_regular_directory(tmp_path: Path) -> None: + path = tmp_path / "videos" + path.mkdir() + + probe = probe_path(path) + + assert probe.status == PathProbeStatus.OBSERVED + assert probe.entry_kind == FilesystemEntryKind.DIRECTORY + assert probe.symlink is None + + +def test_probe_absolute_file_symlink( + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + target = tmp_path / "source.mp4" + target.touch() + + link = tmp_path / "linked.mp4" + create_symlink_or_skip(link, target) + + probe = probe_path(link) + + assert probe.status == PathProbeStatus.OBSERVED + assert probe.entry_kind == FilesystemEntryKind.SYMLINK + assert probe.symlink is not None + assert probe.symlink.raw_target == link.readlink() + assert file_identity(probe.symlink.raw_target) == file_identity(target) + assert file_identity(probe.symlink.absolute_target) == file_identity(target) + assert probe.symlink.target_kind == SymlinkTargetKind.FILE + + +def test_probe_relative_file_symlink( + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + target = tmp_path / "source.mp4" + target.touch() + + link = tmp_path / "linked.mp4" + relative_target = Path("source.mp4") + create_symlink_or_skip(link, relative_target) + + probe = probe_path(link) + + assert probe.entry_kind == FilesystemEntryKind.SYMLINK + assert probe.symlink is not None + assert probe.symlink.raw_target == relative_target + assert probe.symlink.absolute_target == target.absolute() + assert probe.symlink.target_kind == SymlinkTargetKind.FILE + + +def test_probe_directory_symlink( + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + target = tmp_path / "target-directory" + target.mkdir() + + link = tmp_path / "linked-directory" + create_symlink_or_skip(link, target, target_is_directory=True) + + probe = probe_path(link) + + assert probe.status == PathProbeStatus.OBSERVED + assert probe.entry_kind == FilesystemEntryKind.SYMLINK + assert probe.symlink is not None + assert probe.symlink.target_kind == SymlinkTargetKind.DIRECTORY + + +def test_probe_broken_symlink( + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + target = tmp_path / "missing.mp4" + link = tmp_path / "linked.mp4" + create_symlink_or_skip(link, target) + + probe = probe_path(link) + + assert probe.status == PathProbeStatus.OBSERVED + assert probe.entry_kind == FilesystemEntryKind.SYMLINK + assert probe.symlink is not None + assert probe.symlink.raw_target == link.readlink() + assert probe.symlink.absolute_target.name == target.name + assert file_identity(probe.symlink.absolute_target.parent) == file_identity(tmp_path) + assert probe.symlink.target_kind == SymlinkTargetKind.MISSING + + +def test_probe_symlink_to_unsupported_target_type( + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A symlink whose target is neither a regular file nor a directory.""" + + target = tmp_path / "device" + target.touch() + + link = tmp_path / "linked-device" + create_symlink_or_skip(link, target) + + real_stat = Path.stat + + def fake_stat(self: Path, *args: object, follow_symlinks: bool = True, **kwargs: object) -> os.stat_result: + result = real_stat(self, *args, follow_symlinks=follow_symlinks, **kwargs) + + if follow_symlinks and _same_file(self, target): + fake_mode = (result.st_mode & ~stat.S_IFMT(result.st_mode)) | stat.S_IFCHR + return os.stat_result((fake_mode, *result[1:])) + + return result + + monkeypatch.setattr(Path, "stat", fake_stat) + + probe = probe_path(link) + + assert probe.entry_kind == FilesystemEntryKind.SYMLINK + assert probe.symlink is not None + assert probe.symlink.target_kind == SymlinkTargetKind.OTHER + + +def test_probe_unsupported_entry_type( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A non-symlink entry that is neither a regular file nor a directory.""" + + path = tmp_path / "device" + path.touch() + + real_lstat = Path.lstat + + def fake_lstat(self: Path, *args: object, **kwargs: object) -> os.stat_result: + result = real_lstat(self, *args, **kwargs) + + if self == path: + fake_mode = (result.st_mode & ~stat.S_IFMT(result.st_mode)) | stat.S_IFCHR + return os.stat_result((fake_mode, *result[1:])) + + return result + + monkeypatch.setattr(Path, "lstat", fake_lstat) + + probe = probe_path(path) + + assert probe.status == PathProbeStatus.OBSERVED + assert probe.entry_kind == FilesystemEntryKind.OTHER + assert probe.symlink is None + + +def test_probe_entry_access_failure( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + path = tmp_path / "locked.mp4" + path.touch() + + def fake_lstat(self: Path, *args: object, **kwargs: object) -> os.stat_result: + if self == path: + raise PermissionError("Access is denied") + + return Path.lstat(self, *args, **kwargs) + + monkeypatch.setattr(Path, "lstat", fake_lstat) + + probe = probe_path(path) + + assert probe.status == PathProbeStatus.INACCESSIBLE + assert probe.entry_kind is None + assert probe.symlink is None + assert probe.error_type == "PermissionError" + assert probe.error_message + + +def test_probe_symlink_target_access_failure( + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], + monkeypatch: pytest.MonkeyPatch, +) -> None: + target = tmp_path / "source.mp4" + target.touch() + + link = tmp_path / "linked.mp4" + create_symlink_or_skip(link, target) + + real_stat = Path.stat + + def fake_stat(self: Path, *args: object, follow_symlinks: bool = True, **kwargs: object) -> os.stat_result: + if follow_symlinks and _same_file(self, target): + raise PermissionError("Access is denied") + + return real_stat(self, *args, follow_symlinks=follow_symlinks, **kwargs) + + monkeypatch.setattr(Path, "stat", fake_stat) + + probe = probe_path(link) + + assert probe.status == PathProbeStatus.OBSERVED + assert probe.entry_kind == FilesystemEntryKind.SYMLINK + assert probe.symlink is not None + assert probe.symlink.target_kind == SymlinkTargetKind.INACCESSIBLE + assert probe.error_type == "PermissionError" + assert probe.error_message + + +def test_inaccessible_probe_rejects_an_entry_kind() -> None: + """``INACCESSIBLE`` is reserved for entries that were never observed.""" + + with pytest.raises( + ValidationError, + match="must not carry an entry kind", + ): + PathProbe( + status=PathProbeStatus.INACCESSIBLE, + entry_kind=FilesystemEntryKind.FILE, + error_type="PermissionError", + ) + + +def test_inaccessible_symlink_target_still_reads_as_unreadable() -> None: + """An observed entry with an unreadable target stays ``UNREADABLE``. + + Pins the mapping that lets ``INACCESSIBLE`` describe the entry alone, + without needing a symlink the platform may refuse to create. + """ + + probe = PathProbe( + status=PathProbeStatus.OBSERVED, + entry_kind=FilesystemEntryKind.SYMLINK, + symlink=SymlinkObservation( + raw_target=Path("target.mp4"), + absolute_target=Path("/videos/target.mp4"), + target_kind=SymlinkTargetKind.INACCESSIBLE, + ), + error_type="PermissionError", + error_message="Access is denied", + ) + + assert status_for_expected_entry(probe, expected_kind=ExpectedEntryKind.FILE) == NodeStatus.UNREADABLE + + +def test_file_identity_tells_files_apart(tmp_path: Path) -> None: + (tmp_path / "a.mp4").touch() + (tmp_path / "b.mp4").touch() + + assert file_identity(tmp_path / "a.mp4") == file_identity(tmp_path / "a.mp4") + assert file_identity(tmp_path / "a.mp4") != file_identity(tmp_path / "b.mp4") + + +@pytest.mark.skipif(sys.platform != "win32", reason="the extended-length prefix is Windows syntax") +def test_file_identity_matches_extended_length_and_plain_spellings(tmp_path: Path) -> None: + path = (tmp_path / "a.mp4").resolve() + path.touch() + + assert file_identity(Path("\\\\?\\" + str(path))) == file_identity(path) + + +def test_file_identity_matches_hard_links(tmp_path: Path) -> None: + (tmp_path / "a.mp4").touch() + os.link(tmp_path / "a.mp4", tmp_path / "b.mp4") + + assert file_identity(tmp_path / "a.mp4") == file_identity(tmp_path / "b.mp4") + + +def test_file_identity_follows_a_symlink_unless_asked_not_to( + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + target = tmp_path / "a.mp4" + target.touch() + link = tmp_path / "linked.mp4" + create_symlink_or_skip(link, target) + + assert file_identity(link) == file_identity(target) + assert file_identity(link, follow_symlinks=False) != file_identity(target, follow_symlinks=False) + + +@pytest.mark.usefixtures("without_file_ids") +def test_file_identity_without_file_ids_falls_back_to_the_resolved_path(tmp_path: Path) -> None: + (tmp_path / "a.mp4").touch() + (tmp_path / "b.mp4").touch() + + assert file_identity(tmp_path / "a.mp4") == (tmp_path / "a.mp4").resolve() + assert file_identity(tmp_path / "a.mp4") != file_identity(tmp_path / "b.mp4") + + +def test_file_identity_of_a_missing_path_raises(tmp_path: Path) -> None: + with pytest.raises(FileNotFoundError): + file_identity(tmp_path / "missing.mp4") + + +def test_file_identity_of_a_path_the_os_cannot_take_raises(tmp_path: Path) -> None: + with pytest.raises(ValueError, match="null"): + file_identity(tmp_path / "a\x00b") diff --git a/tests/project/discovery/test_symlinks.py b/tests/project/discovery/test_symlinks.py new file mode 100644 index 0000000..600356a --- /dev/null +++ b/tests/project/discovery/test_symlinks.py @@ -0,0 +1,281 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +from __future__ import annotations + +from collections.abc import Callable +from pathlib import Path + +import pytest + +from dlccore.project.discovery.observer import ( + ExpectedEntryKind, + classify_unclaimed_entry, + status_for_expected_entry, +) +from dlccore.project.discovery.probe import probe_path +from dlccore.project.schemas.base.observations import NodeStatus +from dlccore.project.schemas.base.probes import ( + FilesystemEntryKind, + PathProbe, + PathProbeStatus, +) +from dlccore.project.schemas.base.resources import ( + DirectoryResourceKind, + FileResourceKind, + UnknownResourceKind, +) +from dlccore.project.schemas.base.symlinks import ( + SymlinkObservation, + SymlinkTargetKind, +) + + +def test_expected_file_accepts_file_symlink( + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + target = tmp_path / "source.mp4" + target.touch() + + link = tmp_path / "linked.mp4" + create_symlink_or_skip( + link, + target, + ) + + probe = probe_path(link) + status = status_for_expected_entry(probe, expected_kind=ExpectedEntryKind.FILE) + + assert status == NodeStatus.PRESENT + assert probe.symlink is not None + assert probe.symlink.target_kind == SymlinkTargetKind.FILE + + +def test_expected_file_preserves_broken_symlink( + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + link = tmp_path / "linked.mp4" + + create_symlink_or_skip( + link, + tmp_path / "missing.mp4", + ) + + probe = probe_path(link) + status = status_for_expected_entry(probe, expected_kind=ExpectedEntryKind.FILE) + + assert status == NodeStatus.UNREADABLE + assert probe.symlink is not None + assert probe.symlink.target_kind == SymlinkTargetKind.MISSING + + +def test_expected_file_reports_directory_target_as_wrong_type( + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + target = tmp_path / "target-directory" + target.mkdir() + + link = tmp_path / "linked.mp4" + create_symlink_or_skip( + link, + target, + target_is_directory=True, + ) + + probe = probe_path(link) + status = status_for_expected_entry(probe, expected_kind=ExpectedEntryKind.FILE) + + assert status == NodeStatus.WRONG_TYPE + assert probe.symlink is not None + assert probe.symlink.target_kind == SymlinkTargetKind.DIRECTORY + + +def test_expected_directory_symlink_is_present( + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + target = tmp_path / "target-directory" + target.mkdir() + + link = tmp_path / "linked-directory" + create_symlink_or_skip( + link, + target, + target_is_directory=True, + ) + + probe = probe_path(link) + + assert status_for_expected_entry(probe, expected_kind=ExpectedEntryKind.DIRECTORY) == NodeStatus.PRESENT + assert status_for_expected_entry(probe, expected_kind=ExpectedEntryKind.FILE) == NodeStatus.WRONG_TYPE + + +def test_expected_directory_broken_symlink_is_unreadable( + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + """A broken directory-expected symlink is UNREADABLE, not a raise.""" + + link = tmp_path / "linked-directory" + create_symlink_or_skip( + link, + tmp_path / "missing-directory", + target_is_directory=True, + ) + + probe = probe_path(link) + status = status_for_expected_entry(probe, expected_kind=ExpectedEntryKind.DIRECTORY) + + assert status == NodeStatus.UNREADABLE + + +def test_unknown_file_symlink_is_classified_as_file( + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + target = tmp_path / "target.bin" + target.touch() + + link = tmp_path / "unknown-link" + create_symlink_or_skip( + link, + target, + ) + + kind, symlink = classify_unclaimed_entry(probe_path(link)) + + assert kind is FileResourceKind.UNKNOWN_FILE + assert symlink is not None + assert symlink.target_kind == SymlinkTargetKind.FILE + + +def test_unknown_broken_symlink_is_classified_unknown_and_retained( + tmp_path: Path, + create_symlink_or_skip: Callable[..., None], +) -> None: + """A dangling link is described rather than refused, and keeps what was seen. + + The kind cannot be determined because the target is gone, but the + observation still records that it was a link and where it pointed. That + retention is what separates a diagnosable entry from a merely unclassified + one, and it is why the undeterminable cases are not all interchangeable. + + Built on a real symlink rather than a constructed probe: this is the one + place the whole path, ``probe_path`` through classification, runs on bytes. + """ + + link = tmp_path / "unknown-link" + + create_symlink_or_skip( + link, + tmp_path / "missing-target", + ) + + kind, symlink = classify_unclaimed_entry(probe_path(link)) + + assert kind is UnknownResourceKind.UNKNOWN + assert symlink is not None + assert symlink.target_kind == SymlinkTargetKind.MISSING + + +def test_unknown_directory_symlink_is_classified_as_a_directory() -> None: + """A symlinked directory the layout does not claim is retained, not refused. + + Relocating a large directory to bulk storage and linking it back is an + ordinary project layout, and refusing it costs the whole snapshot rather + than the one entry. The probe is constructed rather than made on disk so + this runs where creating a symlink needs privileges. + """ + + probe = PathProbe( + status=PathProbeStatus.OBSERVED, + entry_kind=FilesystemEntryKind.SYMLINK, + symlink=SymlinkObservation( + raw_target=Path("bulk/training-datasets"), + absolute_target=Path("/bulk/training-datasets"), + target_kind=SymlinkTargetKind.DIRECTORY, + ), + ) + + kind, symlink = classify_unclaimed_entry(probe) + + assert kind is DirectoryResourceKind.UNKNOWN_DIRECTORY + assert symlink is not None + assert symlink.target_kind == SymlinkTargetKind.DIRECTORY + + +def _unclaimed_probe(target_kind: SymlinkTargetKind) -> PathProbe: + return PathProbe( + status=PathProbeStatus.OBSERVED, + entry_kind=FilesystemEntryKind.SYMLINK, + symlink=SymlinkObservation( + raw_target=Path("gone"), + absolute_target=Path("/gone"), + target_kind=target_kind, + ), + ) + + +@pytest.mark.parametrize( + "probe", + [ + pytest.param(PathProbe(status=PathProbeStatus.MISSING), id="entry-vanished"), + pytest.param( + PathProbe( + status=PathProbeStatus.INACCESSIBLE, + error_type="PermissionError", + error_message="denied", + ), + id="entry-unreadable", + ), + pytest.param( + PathProbe(status=PathProbeStatus.OBSERVED, entry_kind=FilesystemEntryKind.OTHER), + id="fifo-socket-device", + ), + pytest.param(_unclaimed_probe(SymlinkTargetKind.MISSING), id="symlink-target-missing"), + pytest.param(_unclaimed_probe(SymlinkTargetKind.INACCESSIBLE), id="symlink-target-unreadable"), + pytest.param(_unclaimed_probe(SymlinkTargetKind.OTHER), id="symlink-target-other"), + ], +) +def test_undeterminable_unclaimed_entry_is_classified_rather_than_refused( + probe: PathProbe, +) -> None: + """An unclaimed entry is retained whatever it turns out to be. + + Discovery surfaces facts and validation decides, so an entry that cannot be + identified is a fact to report, not grounds for abandoning the snapshot: a + file removed mid-scan, an unreadable entry, a device node or a dangling link + must not cost the parts of the project that are fine. + """ + + kind, _ = classify_unclaimed_entry(probe) + + assert kind is UnknownResourceKind.UNKNOWN + + +def test_mapping_functions_do_not_touch_the_filesystem(tmp_path: Path) -> None: + """status_for_expected_entry/classify_unclaimed_entry consume only the probe.""" + + path = tmp_path / "video.mp4" + path.touch() + + probe = probe_path(path) + path.unlink() + + status = status_for_expected_entry(probe, expected_kind=ExpectedEntryKind.FILE) + kind, symlink = classify_unclaimed_entry(probe) + + assert status == NodeStatus.PRESENT + assert kind is FileResourceKind.UNKNOWN_FILE + assert symlink is None diff --git a/tests/project/discovery/test_utils.py b/tests/project/discovery/test_utils.py new file mode 100644 index 0000000..9d2bf08 --- /dev/null +++ b/tests/project/discovery/test_utils.py @@ -0,0 +1,142 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +from collections.abc import Iterator +from pathlib import Path + +import pytest + +from dlccore.project.discovery.observer import discover_project +from dlccore.project.schemas.base.resources import DirectoryResourceKind, FileResourceKind +from dlccore.project.schemas.utils import flatten_observed_project + + +def test_flatten_observed_project(tmp_path: Path) -> None: + videos = tmp_path / "videos" + labeled_data = tmp_path / "labeled-data" + dataset = labeled_data / "session-01" + + videos.mkdir() + dataset.mkdir(parents=True) + + (tmp_path / "config.yaml").write_text( + "Task: demo", + encoding="utf-8", + ) + (videos / "session-01.mp4").touch() + (videos / "notes.txt").write_text( + "user notes", + encoding="utf-8", + ) + (dataset / "img001.png").touch() + (dataset / "CollectedData_Sc.h5").touch() + + observed = discover_project( + tmp_path, + ) + + resources = flatten_observed_project(observed) + + resources_by_path = {resource.project_relative_path: resource.kind for resource in resources} + + assert resources_by_path[Path("config.yaml")] == (FileResourceKind.PROJECT_CONFIG) + assert resources_by_path[Path("videos")] == (DirectoryResourceKind.VIDEOS_DIRECTORY) + assert resources_by_path[Path("videos/session-01.mp4")] == (FileResourceKind.SOURCE_VIDEO) + assert resources_by_path[Path("videos/notes.txt")] == (FileResourceKind.UNKNOWN_FILE) + assert resources_by_path[Path("labeled-data/session-01")] == (DirectoryResourceKind.LABELED_DATASET) + assert resources_by_path[Path("labeled-data/session-01/img001.png")] == FileResourceKind.LABELED_FRAME + + +def test_flat_projection_excludes_missing_nodes( + tmp_path: Path, +) -> None: + (tmp_path / "config.yaml").write_text( + "Task: demo", + encoding="utf-8", + ) + + observed = discover_project( + tmp_path, + ) + + resources = flatten_observed_project(observed) + + paths = {resource.project_relative_path for resource in resources} + + assert Path("config.yaml") in paths + assert Path("videos") not in paths + assert Path("labeled-data") not in paths + + +def test_flat_projection_excludes_project_root_by_default( + tmp_path: Path, +) -> None: + observed = discover_project( + tmp_path, + ) + + resources = flatten_observed_project(observed) + + assert all(resource.project_relative_path != Path() for resource in resources) + + +def test_flat_projection_includes_wrong_type_nodes( + tmp_path: Path, +) -> None: + (tmp_path / "config.yaml").write_text( + "Task: demo", + encoding="utf-8", + ) + (tmp_path / "videos").write_text( + "not a directory", + encoding="utf-8", + ) + + observed = discover_project( + tmp_path, + ) + + resources = flatten_observed_project(observed) + resources_by_path = {resource.project_relative_path: resource.kind for resource in resources} + + assert resources_by_path[Path("videos")] == DirectoryResourceKind.VIDEOS_DIRECTORY + + +def test_flat_projection_includes_unreadable_nodes( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + videos = tmp_path / "videos" + videos.mkdir() + + (tmp_path / "config.yaml").write_text( + "Task: demo", + encoding="utf-8", + ) + + real_iterdir = Path.iterdir + + def fake_iterdir(self: Path, *args: object, **kwargs: object) -> Iterator[Path]: + if self == videos: + raise OSError("Directory listing failed") + + return real_iterdir(self, *args, **kwargs) + + monkeypatch.setattr(Path, "iterdir", fake_iterdir) + + observed = discover_project( + tmp_path, + ) + + resources = flatten_observed_project(observed) + resources_by_path = {resource.project_relative_path: resource.kind for resource in resources} + + assert resources_by_path[Path("videos")] == DirectoryResourceKind.VIDEOS_DIRECTORY