From 1b43f60bdfaec57ed7028b309f695966a3209036 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Thu, 26 Nov 2026 15:17:43 +0100 Subject: [PATCH 1/3] Copy project video validation and the validation registry --- dlccore/project/schemas/base/finding_codes.py | 61 +++ dlccore/project/validation/__init__.py | 13 +- .../project/validation/deeplabcut/videos.py | 361 ++++++++++++++++++ dlccore/project/validation/project.py | 57 +++ dlccore/project/validation/registry.py | 109 ++++++ tests/project/validation/test_registry.py | 88 +++++ 6 files changed, 678 insertions(+), 11 deletions(-) create mode 100644 dlccore/project/validation/deeplabcut/videos.py create mode 100644 dlccore/project/validation/project.py create mode 100644 dlccore/project/validation/registry.py create mode 100644 tests/project/validation/test_registry.py diff --git a/dlccore/project/schemas/base/finding_codes.py b/dlccore/project/schemas/base/finding_codes.py index 38f2cdf..638f163 100644 --- a/dlccore/project/schemas/base/finding_codes.py +++ b/dlccore/project/schemas/base/finding_codes.py @@ -89,6 +89,12 @@ class StructureFindingCode(FindingCode): Severity.ERROR, ("resource_kind", "error_type", "error_message"), ) + PROJECT_RESOURCE_PATH_COLLISION = ( + "PROJECT_RESOURCE_PATH_COLLISION", + "This project resource resolves to the same filesystem path as another; each one is reported.", + Severity.ERROR, + ("resource_kind", "collision_path", "collision_group"), + ) class ConfigFindingCode(FindingCode): @@ -159,6 +165,61 @@ class ConfigFindingCode(FindingCode): ) +class ConfiguredVideoFindingCode(FindingCode): + """Findings about video paths declared in ``config.yaml``.""" + + CONFIGURED_VIDEO_PATH_MISSING = ( + "CONFIGURED_VIDEO_PATH_MISSING", + "The configured video path does not exist.", + Severity.ERROR, + (), + ) + CONFIGURED_VIDEO_PATH_SYMLINK_TARGET_MISSING = ( + "CONFIGURED_VIDEO_PATH_SYMLINK_TARGET_MISSING", + "The configured video path is a symlink whose target does not exist.", + Severity.ERROR, + ("raw_target", "absolute_target"), + ) + CONFIGURED_VIDEO_PATH_UNREADABLE = ( + "CONFIGURED_VIDEO_PATH_UNREADABLE", + "The configured video path could not be read.", + Severity.ERROR, + ("error_type", "error_message"), + ) + CONFIGURED_VIDEO_PATH_NOT_FILE = ( + "CONFIGURED_VIDEO_PATH_NOT_FILE", + "The configured video path exists but is not a file.", + Severity.ERROR, + (), + ) + CONFIGURED_VIDEOS_UNDER_MISSING_ROOT = ( + "CONFIGURED_VIDEOS_UNDER_MISSING_ROOT", + "Configured video paths end in videos/, the video exists in this project, but the paths " + "themselves do not exist. Was the project moved or copied?", + Severity.WARNING, + ("declared_paths", "matched_paths"), + ) + CONFIGURED_VIDEO_IN_OTHER_COPY = ( + "CONFIGURED_VIDEO_IN_OTHER_COPY", + "The configured video path ends in videos/ and exists, but is a different file from this " + "project's video with the same name. DeepLabCut will read the configured one.", + Severity.WARNING, + ("matched_path",), + ) + CONFIGURED_VIDEO_OUTSIDE_PROJECT = ( + "CONFIGURED_VIDEO_OUTSIDE_PROJECT", + "The configured video path exists but is not in the project's videos directory.", + Severity.ERROR, + (), + ) + VIDEO_NOT_IN_VIDEO_SETS = ( + "VIDEO_NOT_IN_VIDEO_SETS", + "A video in the project's videos directory has no corresponding path in the configuration.", + Severity.NOTE, + ("resource_kind",), + ) + + def iter_finding_codes() -> tuple[FindingCode, ...]: """Return every declared finding code, namespace by namespace.""" diff --git a/dlccore/project/validation/__init__.py b/dlccore/project/validation/__init__.py index 43646a1..ac51098 100644 --- a/dlccore/project/validation/__init__.py +++ b/dlccore/project/validation/__init__.py @@ -1,15 +1,5 @@ -# -# 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 .context import ValidationContext, build_validation_context +from .project import validate_project from .requests import ( ProjectValidationRequest, ResourceValidationRequest, @@ -21,5 +11,6 @@ "ResourceValidationRequest", "ValidationContext", "build_validation_context", + "validate_project", "validate_project_structure", ] diff --git a/dlccore/project/validation/deeplabcut/videos.py b/dlccore/project/validation/deeplabcut/videos.py new file mode 100644 index 0000000..41ff471 --- /dev/null +++ b/dlccore/project/validation/deeplabcut/videos.py @@ -0,0 +1,361 @@ +from __future__ import annotations + +import re +from collections.abc import Iterator +from dataclasses import dataclass +from pathlib import Path + +from pydantic import JsonValue + +from dlc_octopus.discovery.observer import ExpectedEntryKind, status_for_expected_entry +from dlc_octopus.discovery.probe import probe_path +from dlc_octopus.schemas.base.core import instance_from_path +from dlc_octopus.schemas.base.finding_codes import ( + ConfiguredVideoFindingCode, + StructureFindingCode, +) +from dlc_octopus.schemas.base.findings import ( + Finding, +) +from dlc_octopus.schemas.base.observations import ( + NodeStatus, + ObservedNode, +) +from dlc_octopus.schemas.base.probes import ( + PathProbe, +) +from dlc_octopus.schemas.base.resources import ( + DirectoryResourceKind, + FileResourceKind, +) +from dlc_octopus.schemas.base.symlinks import ( + SymlinkTargetKind, +) +from dlc_octopus.schemas.base.validation import ( + ValidationCheck, + ValidationCheckStatus, + ValidationDepth, +) +from dlc_octopus.schemas.locations import one_of, one_per_project +from dlc_octopus.schemas.project_layout.project import PROJECT_CONFIG +from dlc_octopus.schemas.project_layout.videos import SOURCE_VIDEO +from dlc_octopus.schemas.snapshots import ProjectSnapshot +from dlc_octopus.validation.context import ValidationContext +from dlc_octopus.validation.results import ValidationResult + + +@dataclass(frozen=True) +class _ObservedVideos: + """The source videos in ``videos/``, indexed for reconciliation with config keys. + + Attributes: + present: Present videos, in layout order. + by_identity: Present videos by the file they resolve to. + by_name: Present videos directly under ``videos/``, by file name. + physical_paths: The lexical path of every source-video node, of any status. + collision_findings: One finding per video resolving to the same file as another. + """ + + present: tuple[ObservedNode, ...] + by_identity: dict[Path, tuple[ObservedNode, ...]] + by_name: dict[str, ObservedNode] + physical_paths: frozenset[Path] + collision_findings: tuple[Finding, ...] + + +def validate_videos( + snapshot: ProjectSnapshot, + context: ValidationContext | None, + depth: ValidationDepth, +) -> ValidationResult: + """Run the requested video-validation suite.""" + + if context is None: + return ValidationResult( + checks=( + ValidationCheck( + code="VIDEO_FILENAME_VALIDATION", + kind=(DirectoryResourceKind.VIDEOS_DIRECTORY), + depth=depth, + status=(ValidationCheckStatus.UNAVAILABLE), + message=( + "Configured video paths could not be " + "checked because a canonical project " + "config was unavailable." + ), + ), + ), + ) + + findings = check_configured_video_paths( + snapshot, + context, + ) + + return ValidationResult( + findings=findings, + checks=( + ValidationCheck( + code="VIDEO_FILENAME_VALIDATION", + kind=(DirectoryResourceKind.VIDEOS_DIRECTORY), + depth=depth, + status=(ValidationCheckStatus.COMPLETED), + message=("Reconciled config-declared video paths with the videos directory."), + ), + ), + ) + + +def check_configured_video_paths( + snapshot: ProjectSnapshot, + context: ValidationContext, +) -> tuple[Finding, ...]: + """Reconcile config-declared video paths with the videos in ``videos/``. + + Each key is classified by the first rule that applies: it resolves to a + video in ``videos/``; it ends in ``videos/`` for a video here and does + not exist, or exists as a different file; it exists elsewhere; it is + missing, broken, unreadable or not a file. Keys are reported as written. + """ + + observed = _index_observed_videos(snapshot) + findings: list[Finding] = list(observed.collision_findings) + matched: set[Path] = set() + under_missing_root: list[tuple[str, ObservedNode]] = [] + + for declared_value in sorted(context.config.video_sets): + checked_path = _absolute_configured_path( + declared_value, + project_root=snapshot.project_root, + ) + + identity = _identity(checked_path) + if identity in observed.by_identity: + matched.update(node.project_relative_path for node in observed.by_identity[identity]) + continue + + probe = probe_path(checked_path) + node_status = status_for_expected_entry(probe, expected_kind=ExpectedEntryKind.FILE) + # Either separator, so a key written on another platform still points to the video + segments = [segment for segment in re.split(r"[\\/]", declared_value) if segment] + named = observed.by_name.get(segments[-1]) if segments[-2:-1] == ["videos"] else None + + if named is not None and node_status in (NodeStatus.MISSING, NodeStatus.PRESENT): + matched.add(named.project_relative_path) + + if node_status == NodeStatus.MISSING: + under_missing_root.append((declared_value, named)) + continue + + findings.append( + Finding( + code=ConfiguredVideoFindingCode.CONFIGURED_VIDEO_IN_OTHER_COPY, + **one_per_project(PROJECT_CONFIG), + path=checked_path, + field_location=("video_sets", declared_value), + evidence={"matched_path": named.project_relative_path.as_posix()}, + ) + ) + continue + + if node_status == NodeStatus.PRESENT: + findings.append( + Finding( + code=ConfiguredVideoFindingCode.CONFIGURED_VIDEO_OUTSIDE_PROJECT, + **one_per_project(PROJECT_CONFIG), + path=checked_path, + field_location=("video_sets", declared_value), + ) + ) + continue + + code = _configured_video_path_code( + node_status, + probe, + ) + + if ( + code == ConfiguredVideoFindingCode.CONFIGURED_VIDEO_PATH_SYMLINK_TARGET_MISSING + and checked_path in observed.physical_paths + ): + continue + + evidence: dict[str, JsonValue] = {} + + if "error_type" in code.evidence_keys: + evidence["error_type"] = probe.error_type + evidence["error_message"] = probe.error_message + + if probe.symlink is not None: + evidence["raw_target"] = str(probe.symlink.raw_target) + evidence["absolute_target"] = str(probe.symlink.absolute_target) + + findings.append( + Finding( + code=code, + **one_per_project(PROJECT_CONFIG), + path=checked_path, + field_location=( + "video_sets", + declared_value, + ), + evidence=evidence, + ) + ) + + if under_missing_root: + findings.append( + Finding( + code=ConfiguredVideoFindingCode.CONFIGURED_VIDEOS_UNDER_MISSING_ROOT, + **one_per_project(PROJECT_CONFIG), + field_location=("video_sets",), + evidence={ + "declared_paths": [declared_value for declared_value, _node in under_missing_root], + "matched_paths": [node.project_relative_path.as_posix() for _value, node in under_missing_root], + }, + ) + ) + + findings.extend( + Finding( + code=ConfiguredVideoFindingCode.VIDEO_NOT_IN_VIDEO_SETS, + **one_of(SOURCE_VIDEO, instance_from_path(node.project_relative_path)), + path=snapshot.project_root / node.project_relative_path, + evidence={"resource_kind": FileResourceKind.SOURCE_VIDEO.value}, + ) + for node in observed.present + if node.project_relative_path not in matched + ) + + return tuple(findings) + + +def _configured_video_path_code( + node_status: NodeStatus, + probe: PathProbe, +) -> ConfiguredVideoFindingCode: + """Return the finding code for a rejected video path. + + A broken symlink is reported ahead of the unreadable case because it + reaches here as ``UNREADABLE`` yet has a distinct cause and remedy. + """ + + if node_status == NodeStatus.MISSING: + return ConfiguredVideoFindingCode.CONFIGURED_VIDEO_PATH_MISSING + + if probe.symlink is not None and probe.symlink.target_kind == SymlinkTargetKind.MISSING: + return ConfiguredVideoFindingCode.CONFIGURED_VIDEO_PATH_SYMLINK_TARGET_MISSING + + if node_status == NodeStatus.UNREADABLE: + return ConfiguredVideoFindingCode.CONFIGURED_VIDEO_PATH_UNREADABLE + + return ConfiguredVideoFindingCode.CONFIGURED_VIDEO_PATH_NOT_FILE + + +def _absolute_configured_path( + declared_value: str, + *, + project_root: Path, +) -> Path: + """Return the lexical absolute path for one config declaration.""" + + declared_path = Path(declared_value) + + return (declared_path if declared_path.is_absolute() else project_root / declared_path).absolute() + + +def _index_observed_videos( + snapshot: ProjectSnapshot, +) -> _ObservedVideos: + r"""Index the source videos in ``videos/`` for reconciliation with config keys. + + Built from ``snapshot.project`` rather than ``snapshot.resources`` so that + a wrong-type or unreadable video node - which now also appears as a + physical resource - is not mistaken for a valid, present one. + + Two videos may legitimately resolve to one file, so a collision is reported + rather than raised: once per colliding video, at that video, the findings of + one collision sharing ``collision_group``, the first member's instance. + + Collisions compare fully resolved files, so a chain of links still collides. + A resolved path is for comparison only and never reaches a finding. + """ + + by_name: dict[str, ObservedNode] = {} + collisions: dict[ + Path, + list[tuple[ObservedNode, Path, Path]], + ] = {} + findings: list[Finding] = [] + present: list[ObservedNode] = [] + physical_paths: set[Path] = set() + + for node in _iter_source_videos(snapshot.project): + physical_path = (snapshot.project_root / node.project_relative_path).absolute() + physical_paths.add(physical_path) + + if node.status != NodeStatus.PRESENT: + continue + + present.append(node) + observed_target = physical_path + + if node.symlink is not None and node.symlink.target_kind == SymlinkTargetKind.FILE: + observed_target = node.symlink.absolute_target + + collisions.setdefault(_identity(observed_target), []).append((node, physical_path, observed_target)) + + if len(node.project_relative_path.parts) == 2: + by_name.setdefault(node.project_relative_path.name, node) + + for members in collisions.values(): + if len(members) < 2: + continue + + first, _path, _target = members[0] + group: list[JsonValue] = list(instance_from_path(first.project_relative_path)) + + findings.extend( + Finding( + code=StructureFindingCode.PROJECT_RESOURCE_PATH_COLLISION, + **one_of(SOURCE_VIDEO, instance_from_path(member.project_relative_path)), + path=physical_path, + evidence={ + "resource_kind": FileResourceKind.SOURCE_VIDEO.value, + "collision_path": str(observed_target), + "collision_group": group, + }, + ) + for member, physical_path, observed_target in members + ) + + return _ObservedVideos( + present=tuple(present), + by_identity={ + identity: tuple(node for node, _path, _target in members) for identity, members in collisions.items() + }, + by_name=by_name, + physical_paths=frozenset(physical_paths), + collision_findings=tuple(findings), + ) + + +def _identity(path: Path) -> Path: + """Return the file a path resolves to, for comparison only.""" + + try: + return path.resolve() + except OSError: + return path + + +def _iter_source_videos( + node: ObservedNode, +) -> Iterator[ObservedNode]: + """Yield source-video nodes, of any status, from a schema-observed subtree.""" + + if node.kind == FileResourceKind.SOURCE_VIDEO: + yield node + + for child in node.schema_children: + yield from _iter_source_videos(child) diff --git a/dlccore/project/validation/project.py b/dlccore/project/validation/project.py new file mode 100644 index 0000000..42f3e1a --- /dev/null +++ b/dlccore/project/validation/project.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +from dlc_octopus.schemas.snapshots import ProjectSnapshot +from dlc_octopus.validation.baseline import run_baseline_checks +from dlc_octopus.validation.context import ( + build_validation_context, +) +from dlc_octopus.validation.registry import ( + get_validator_registration, +) +from dlc_octopus.validation.requests import ( + ProjectValidationRequest, +) +from dlc_octopus.validation.results import ValidationResult + + +def validate_project( + snapshot: ProjectSnapshot, + *, + request: ProjectValidationRequest | None = None, +) -> ValidationResult: + """Run baseline checks and explicitly requested resource validators.""" + + context = build_validation_context(snapshot) + result = ValidationResult( + findings=run_baseline_checks( + snapshot, + context, + ) + ) + + if request is None: + return result + + for resource_request in request.resources: + registration = get_validator_registration(resource_request.kind) + + if registration is None: + raise ValueError(f"No validator is available for resource kind {resource_request.kind.value!r}.") + + if resource_request.depth not in registration.supported_depths: + supported = ", ".join(depth.value for depth in registration.supported_depths) + + raise ValueError( + "Validation depth " + f"{resource_request.depth.value!r} is not supported for resource kind " + f"{resource_request.kind.value!r}. Supported depths are: {supported or ''}." + ) + result = result.merge( + registration.validator( + snapshot, + context=context, + depth=resource_request.depth, + ) + ) + + return result diff --git a/dlccore/project/validation/registry.py b/dlccore/project/validation/registry.py new file mode 100644 index 0000000..59b53a2 --- /dev/null +++ b/dlccore/project/validation/registry.py @@ -0,0 +1,109 @@ +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass + +from dlc_octopus.schemas.base.resources import ( + DirectoryResourceKind, + ResourceKind, +) +from dlc_octopus.schemas.base.validation import ( + ValidationDepth, +) +from dlc_octopus.schemas.snapshots import ProjectSnapshot +from dlc_octopus.validation.context import ( + ValidationContext, +) +from dlc_octopus.validation.deeplabcut.videos import ( + validate_videos, +) +from dlc_octopus.validation.results import ( + ValidationResult, +) + +ResourceValidator = Callable[ + [ + ProjectSnapshot, + ValidationContext | None, + ValidationDepth, + ], + ValidationResult, +] + + +@dataclass(frozen=True) +class ValidatorRegistration: + """Registration for one resource-validation suite.""" + + code: str + validator: ResourceValidator + supported_depths: tuple[ValidationDepth, ...] + + +_VALIDATOR_REGISTRATIONS = ( + ( + DirectoryResourceKind.VIDEOS_DIRECTORY, + ValidatorRegistration( + code="VIDEOS", + validator=validate_videos, + supported_depths=(ValidationDepth.FILENAME_ONLY,), + ), + ), +) + + +def index_registrations( + registrations: tuple[ + tuple[ + ResourceKind, + ValidatorRegistration, + ], + ..., + ], +) -> dict[ + ResourceKind, + ValidatorRegistration, +]: + """Index registrations by resource kind. + + Raises: + ValueError: If one resource kind is registered more than once. + """ + + index: dict[ + ResourceKind, + ValidatorRegistration, + ] = {} + + for kind, registration in registrations: + if kind in index: + raise ValueError( + f"Resource kind {kind.value!r} is registered twice: {index[kind].code!r} and {registration.code!r}." + ) + + index[kind] = registration + + return index + + +_REGISTRATIONS_BY_KIND = index_registrations(_VALIDATOR_REGISTRATIONS) + + +def get_validator_registration( + kind: ResourceKind, +) -> ValidatorRegistration | None: + """Return the validator registered for one resource kind.""" + + return _REGISTRATIONS_BY_KIND.get(kind) + + +def iter_validator_registrations() -> tuple[ + tuple[ + ResourceKind, + ValidatorRegistration, + ], + ..., +]: + """Return validator registrations in deterministic order.""" + + return _VALIDATOR_REGISTRATIONS diff --git a/tests/project/validation/test_registry.py b/tests/project/validation/test_registry.py new file mode 100644 index 0000000..49bbff8 --- /dev/null +++ b/tests/project/validation/test_registry.py @@ -0,0 +1,88 @@ +from __future__ import annotations + +import pytest + +from dlc_octopus.schemas.base.resources import DirectoryResourceKind +from dlc_octopus.schemas.base.validation import ValidationDepth +from dlc_octopus.validation.registry import ( + ValidatorRegistration, + get_validator_registration, + index_registrations, + iter_validator_registrations, +) +from dlc_octopus.validation.results import ValidationResult + + +def _never_dispatched( + *_args: object, + **_kwargs: object, +) -> ValidationResult: + """Stand-in validator; these tests index registrations without running them.""" + + return ValidationResult() + + +def _registration( + code: str, +) -> ValidatorRegistration: + """Return a registration whose validator reports nothing.""" + + return ValidatorRegistration( + code=code, + validator=_never_dispatched, + supported_depths=(ValidationDepth.FILENAME_ONLY,), + ) + + +def test_each_resource_kind_is_registered_once() -> None: + kinds = tuple(kind for kind, _ in iter_validator_registrations()) + + assert kinds + assert len(kinds) == len(set(kinds)) + + +def test_indexing_rejects_a_resource_kind_registered_twice() -> None: + """The positive control for the test above, which cannot fail on a manifest of one.""" + + duplicated = ( + ( + DirectoryResourceKind.VIDEOS_DIRECTORY, + _registration("FIRST"), + ), + ( + DirectoryResourceKind.VIDEOS_DIRECTORY, + _registration("SECOND"), + ), + ) + + with pytest.raises(ValueError, match="registered twice") as raised: + index_registrations(duplicated) + + message = str(raised.value) + + assert "FIRST" in message + assert "SECOND" in message + + +def test_indexing_keeps_distinct_kinds() -> None: + distinct = ( + ( + DirectoryResourceKind.VIDEOS_DIRECTORY, + _registration("VIDEOS"), + ), + ( + DirectoryResourceKind.LABELED_DATA_DIRECTORY, + _registration("LABELED_DATA"), + ), + ) + + index = index_registrations(distinct) + + assert set(index) == { + DirectoryResourceKind.VIDEOS_DIRECTORY, + DirectoryResourceKind.LABELED_DATA_DIRECTORY, + } + + +def test_lookup_returns_none_for_an_unregistered_kind() -> None: + assert get_validator_registration(DirectoryResourceKind.LABELED_DATA_DIRECTORY) is None From d3da6b57907de1d321d3bc64c421e6873abfeb20 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Thu, 26 Nov 2026 15:19:04 +0100 Subject: [PATCH 2/3] Adapt project video validation and the validation registry to dlccore - Rename the packages to dlccore.project and add the dlccore license header - validation's __init__ now matches the prototype - Add test_a_moved_anchor_is_detected to tests/project/validation/test_finding_schema_ids.py - The closed-catalogue test now expects ConfiguredVideoFindingCode too - tests/validation/deeplabcut/test_videos.py and test_validation_coverage.py need inspect_project and land with inspection --- dlccore/project/validation/__init__.py | 11 +++++ .../project/validation/deeplabcut/videos.py | 43 ++++++++++++------- dlccore/project/validation/project.py | 23 +++++++--- dlccore/project/validation/registry.py | 23 +++++++--- tests/project/schemas/test_finding_codes.py | 3 +- .../validation/test_finding_schema_ids.py | 27 ++++++++++++ tests/project/validation/test_registry.py | 19 ++++++-- 7 files changed, 116 insertions(+), 33 deletions(-) diff --git a/dlccore/project/validation/__init__.py b/dlccore/project/validation/__init__.py index ac51098..ddcac89 100644 --- a/dlccore/project/validation/__init__.py +++ b/dlccore/project/validation/__init__.py @@ -1,3 +1,14 @@ +# +# 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 .context import ValidationContext, build_validation_context from .project import validate_project from .requests import ( diff --git a/dlccore/project/validation/deeplabcut/videos.py b/dlccore/project/validation/deeplabcut/videos.py index 41ff471..d680b4a 100644 --- a/dlccore/project/validation/deeplabcut/videos.py +++ b/dlccore/project/validation/deeplabcut/videos.py @@ -1,3 +1,14 @@ +# +# 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 re @@ -7,41 +18,41 @@ from pydantic import JsonValue -from dlc_octopus.discovery.observer import ExpectedEntryKind, status_for_expected_entry -from dlc_octopus.discovery.probe import probe_path -from dlc_octopus.schemas.base.core import instance_from_path -from dlc_octopus.schemas.base.finding_codes import ( +from dlccore.project.discovery.observer import ExpectedEntryKind, status_for_expected_entry +from dlccore.project.discovery.probe import probe_path +from dlccore.project.schemas.base.core import instance_from_path +from dlccore.project.schemas.base.finding_codes import ( ConfiguredVideoFindingCode, StructureFindingCode, ) -from dlc_octopus.schemas.base.findings import ( +from dlccore.project.schemas.base.findings import ( Finding, ) -from dlc_octopus.schemas.base.observations import ( +from dlccore.project.schemas.base.observations import ( NodeStatus, ObservedNode, ) -from dlc_octopus.schemas.base.probes import ( +from dlccore.project.schemas.base.probes import ( PathProbe, ) -from dlc_octopus.schemas.base.resources import ( +from dlccore.project.schemas.base.resources import ( DirectoryResourceKind, FileResourceKind, ) -from dlc_octopus.schemas.base.symlinks import ( +from dlccore.project.schemas.base.symlinks import ( SymlinkTargetKind, ) -from dlc_octopus.schemas.base.validation import ( +from dlccore.project.schemas.base.validation import ( ValidationCheck, ValidationCheckStatus, ValidationDepth, ) -from dlc_octopus.schemas.locations import one_of, one_per_project -from dlc_octopus.schemas.project_layout.project import PROJECT_CONFIG -from dlc_octopus.schemas.project_layout.videos import SOURCE_VIDEO -from dlc_octopus.schemas.snapshots import ProjectSnapshot -from dlc_octopus.validation.context import ValidationContext -from dlc_octopus.validation.results import ValidationResult +from dlccore.project.schemas.locations import one_of, one_per_project +from dlccore.project.schemas.project_layout.project import PROJECT_CONFIG +from dlccore.project.schemas.project_layout.videos import SOURCE_VIDEO +from dlccore.project.schemas.snapshots import ProjectSnapshot +from dlccore.project.validation.context import ValidationContext +from dlccore.project.validation.results import ValidationResult @dataclass(frozen=True) diff --git a/dlccore/project/validation/project.py b/dlccore/project/validation/project.py index 42f3e1a..9154351 100644 --- a/dlccore/project/validation/project.py +++ b/dlccore/project/validation/project.py @@ -1,17 +1,28 @@ +# +# 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 dlc_octopus.schemas.snapshots import ProjectSnapshot -from dlc_octopus.validation.baseline import run_baseline_checks -from dlc_octopus.validation.context import ( +from dlccore.project.schemas.snapshots import ProjectSnapshot +from dlccore.project.validation.baseline import run_baseline_checks +from dlccore.project.validation.context import ( build_validation_context, ) -from dlc_octopus.validation.registry import ( +from dlccore.project.validation.registry import ( get_validator_registration, ) -from dlc_octopus.validation.requests import ( +from dlccore.project.validation.requests import ( ProjectValidationRequest, ) -from dlc_octopus.validation.results import ValidationResult +from dlccore.project.validation.results import ValidationResult def validate_project( diff --git a/dlccore/project/validation/registry.py b/dlccore/project/validation/registry.py index 59b53a2..eeed701 100644 --- a/dlccore/project/validation/registry.py +++ b/dlccore/project/validation/registry.py @@ -1,23 +1,34 @@ +# +# 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 dataclasses import dataclass -from dlc_octopus.schemas.base.resources import ( +from dlccore.project.schemas.base.resources import ( DirectoryResourceKind, ResourceKind, ) -from dlc_octopus.schemas.base.validation import ( +from dlccore.project.schemas.base.validation import ( ValidationDepth, ) -from dlc_octopus.schemas.snapshots import ProjectSnapshot -from dlc_octopus.validation.context import ( +from dlccore.project.schemas.snapshots import ProjectSnapshot +from dlccore.project.validation.context import ( ValidationContext, ) -from dlc_octopus.validation.deeplabcut.videos import ( +from dlccore.project.validation.deeplabcut.videos import ( validate_videos, ) -from dlc_octopus.validation.results import ( +from dlccore.project.validation.results import ( ValidationResult, ) diff --git a/tests/project/schemas/test_finding_codes.py b/tests/project/schemas/test_finding_codes.py index 8e40ab8..dd9683f 100644 --- a/tests/project/schemas/test_finding_codes.py +++ b/tests/project/schemas/test_finding_codes.py @@ -19,6 +19,7 @@ from dlccore.project.schemas.base.finding_codes import ( ConfigFindingCode, + ConfiguredVideoFindingCode, FindingCode, Severity, StructureFindingCode, @@ -202,7 +203,7 @@ def test_an_example_namespace_leaves_the_catalogue_after_its_test() -> None: def test_the_finding_code_catalogue_is_closed() -> None: """The catalogue is closed: adding a namespace is deliberate, so it fails here first.""" - assert set(FindingCode.__subclasses__()) == {StructureFindingCode, ConfigFindingCode} + assert set(FindingCode.__subclasses__()) == {StructureFindingCode, ConfigFindingCode, ConfiguredVideoFindingCode} def test_severity_has_three_rungs() -> None: diff --git a/tests/project/validation/test_finding_schema_ids.py b/tests/project/validation/test_finding_schema_ids.py index 90173dd..d337e7a 100644 --- a/tests/project/validation/test_finding_schema_ids.py +++ b/tests/project/validation/test_finding_schema_ids.py @@ -13,6 +13,8 @@ from dlccore.project.schemas.base.filesystem import walk_schema from dlccore.project.schemas.base.finding_codes import ( + ConfigFindingCode, + ConfiguredVideoFindingCode, StructureFindingCode, ) from dlccore.project.schemas.base.findings import Finding, Reach @@ -25,6 +27,19 @@ # Moving a code to another node changes every consumer's scope, so each non-structural code's # anchor is pinned here. Structure codes anchor at the node they are about. +_PINNED_ANCHORS = { + **dict.fromkeys(ConfigFindingCode, "dlc.project.config"), + **dict.fromkeys(ConfiguredVideoFindingCode, "dlc.project.config"), + StructureFindingCode.PROJECT_RESOURCE_PATH_COLLISION: "dlc.videos.source_video", +} + + +def _moved_anchors(findings: tuple[Finding, ...]) -> set[tuple[str, str]]: + return { + (finding.code.value, finding.schema_id) + for finding in findings + if finding.code in _PINNED_ANCHORS and finding.schema_id != _PINNED_ANCHORS[finding.code] + } def _undeclared_schema_ids(findings: tuple[Finding, ...]) -> set[str]: @@ -67,6 +82,18 @@ def test_an_undeclared_schema_id_is_detected() -> None: assert _undeclared_schema_ids((planted,)) == {"dlc.not_declared_anywhere"} +def test_a_moved_anchor_is_detected() -> None: + code = ConfigFindingCode.CONFIG_PROJECT_PATH_MISMATCH + moved = Finding( + code=code, + schema_id="dlc.project", + reach=Reach.ONE_PER_PROJECT, + evidence=dict.fromkeys(code.evidence_keys, "placeholder"), + ) + + assert _moved_anchors((moved,)) == {("CONFIG_PROJECT_PATH_MISMATCH", "dlc.project")} + + def test_a_reach_that_does_not_fit_the_layout_is_detected() -> None: code = StructureFindingCode.PROJECT_NODE_UNREADABLE # The model accepts this, since it does not know the layout: only the helpers would refuse it. diff --git a/tests/project/validation/test_registry.py b/tests/project/validation/test_registry.py index 49bbff8..ca10cbb 100644 --- a/tests/project/validation/test_registry.py +++ b/tests/project/validation/test_registry.py @@ -1,16 +1,27 @@ +# +# 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 pytest -from dlc_octopus.schemas.base.resources import DirectoryResourceKind -from dlc_octopus.schemas.base.validation import ValidationDepth -from dlc_octopus.validation.registry import ( +from dlccore.project.schemas.base.resources import DirectoryResourceKind +from dlccore.project.schemas.base.validation import ValidationDepth +from dlccore.project.validation.registry import ( ValidatorRegistration, get_validator_registration, index_registrations, iter_validator_registrations, ) -from dlc_octopus.validation.results import ValidationResult +from dlccore.project.validation.results import ValidationResult def _never_dispatched( From 3e4587a2e255f5ef6790a96c808de0deb5fa7e68 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Mon, 30 Nov 2026 10:27:38 +0100 Subject: [PATCH 3/3] Use file identities for video validation Detect collisions across hard links and compare symlink entries without following them when suppressing duplicate findings. --- .../project/validation/deeplabcut/videos.py | 37 ++++++++++--------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/dlccore/project/validation/deeplabcut/videos.py b/dlccore/project/validation/deeplabcut/videos.py index d680b4a..26a14a8 100644 --- a/dlccore/project/validation/deeplabcut/videos.py +++ b/dlccore/project/validation/deeplabcut/videos.py @@ -19,7 +19,7 @@ from pydantic import JsonValue from dlccore.project.discovery.observer import ExpectedEntryKind, status_for_expected_entry -from dlccore.project.discovery.probe import probe_path +from dlccore.project.discovery.probe import FileIdentity, file_identity, probe_path from dlccore.project.schemas.base.core import instance_from_path from dlccore.project.schemas.base.finding_codes import ( ConfiguredVideoFindingCode, @@ -61,16 +61,16 @@ class _ObservedVideos: Attributes: present: Present videos, in layout order. - by_identity: Present videos by the file they resolve to. + by_identity: Present videos by the file they name. by_name: Present videos directly under ``videos/``, by file name. - physical_paths: The lexical path of every source-video node, of any status. - collision_findings: One finding per video resolving to the same file as another. + entry_identities: The identity of every source-video entry itself, links not followed, of any status. + collision_findings: One finding per video naming the same file as another. """ present: tuple[ObservedNode, ...] - by_identity: dict[Path, tuple[ObservedNode, ...]] + by_identity: dict[FileIdentity, tuple[ObservedNode, ...]] by_name: dict[str, ObservedNode] - physical_paths: frozenset[Path] + entry_identities: frozenset[FileIdentity] collision_findings: tuple[Finding, ...] @@ -187,7 +187,7 @@ def check_configured_video_paths( if ( code == ConfiguredVideoFindingCode.CONFIGURED_VIDEO_PATH_SYMLINK_TARGET_MISSING - and checked_path in observed.physical_paths + and _identity(checked_path, follow_symlinks=False) in observed.entry_identities ): continue @@ -284,26 +284,27 @@ def _index_observed_videos( a wrong-type or unreadable video node - which now also appears as a physical resource - is not mistaken for a valid, present one. - Two videos may legitimately resolve to one file, so a collision is reported + Two videos may legitimately name one file, so a collision is reported rather than raised: once per colliding video, at that video, the findings of one collision sharing ``collision_group``, the first member's instance. - Collisions compare fully resolved files, so a chain of links still collides. - A resolved path is for comparison only and never reaches a finding. + Collisions compare ``file_identity``, so a chain of links still collides. + An identity, which may be a resolved path, is for comparison only and never + reaches a finding. """ by_name: dict[str, ObservedNode] = {} collisions: dict[ - Path, + FileIdentity, list[tuple[ObservedNode, Path, Path]], ] = {} findings: list[Finding] = [] present: list[ObservedNode] = [] - physical_paths: set[Path] = set() + entry_identities: set[FileIdentity] = set() for node in _iter_source_videos(snapshot.project): physical_path = (snapshot.project_root / node.project_relative_path).absolute() - physical_paths.add(physical_path) + entry_identities.add(_identity(physical_path, follow_symlinks=False)) if node.status != NodeStatus.PRESENT: continue @@ -346,17 +347,17 @@ def _index_observed_videos( identity: tuple(node for node, _path, _target in members) for identity, members in collisions.items() }, by_name=by_name, - physical_paths=frozenset(physical_paths), + entry_identities=frozenset(entry_identities), collision_findings=tuple(findings), ) -def _identity(path: Path) -> Path: - """Return the file a path resolves to, for comparison only.""" +def _identity(path: Path, *, follow_symlinks: bool = True) -> FileIdentity: + """Return ``file_identity``, or the path itself when it cannot be stat'd.""" try: - return path.resolve() - except OSError: + return file_identity(path, follow_symlinks=follow_symlinks) + except (OSError, ValueError): return path