From d0cd801343e394d6ec919ec6fbc849471e47f5c0 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Thu, 26 Nov 2026 15:24:45 +0100 Subject: [PATCH 1/2] Copy project content reads and file fingerprints --- dlccore/project/content/__init__.py | 29 ++ dlccore/project/content/fingerprints.py | 195 ++++++++++ dlccore/project/content/reads.py | 58 +++ dlccore/project/schemas/base/finding_codes.py | 17 + tests/project/content/test_fingerprints.py | 361 ++++++++++++++++++ 5 files changed, 660 insertions(+) create mode 100644 dlccore/project/content/__init__.py create mode 100644 dlccore/project/content/fingerprints.py create mode 100644 dlccore/project/content/reads.py create mode 100644 tests/project/content/test_fingerprints.py diff --git a/dlccore/project/content/__init__.py b/dlccore/project/content/__init__.py new file mode 100644 index 0000000..28d9452 --- /dev/null +++ b/dlccore/project/content/__init__.py @@ -0,0 +1,29 @@ +"""Octopus requests over DLC Project Management's read-only I/O; the only package that imports ``dlc_octopus.io``.""" + +from dlc_octopus.content.fingerprints import ( + FileFingerprint, + ResourcesFileFingerprint, + compare_file_fingerprints, + resources_file_fingerprint, +) +from dlc_octopus.content.labeled_data import ( + InspectedLabeledDataFile, + LabeledDataEntry, + ProjectLabeledData, + inspect_labeled_data_file, + read_project_labeled_data, +) +from dlc_octopus.content.reads import FailedRead + +__all__ = [ + "FailedRead", + "FileFingerprint", + "InspectedLabeledDataFile", + "LabeledDataEntry", + "ProjectLabeledData", + "ResourcesFileFingerprint", + "compare_file_fingerprints", + "inspect_labeled_data_file", + "read_project_labeled_data", + "resources_file_fingerprint", +] diff --git a/dlccore/project/content/fingerprints.py b/dlccore/project/content/fingerprints.py new file mode 100644 index 0000000..07c1121 --- /dev/null +++ b/dlccore/project/content/fingerprints.py @@ -0,0 +1,195 @@ +"""File fingerprints of a snapshot's file resources, requested from ``dlc_octopus.io`` and reported as findings.""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Iterable +from pathlib import Path +from typing import Annotated + +from pydantic import Field + +from dlc_octopus.content.reads import FailedRead, covered, present_files_in_scope +from dlc_octopus.io import UnreadableFileError, fingerprint_file +from dlc_octopus.schemas.base.core import FrozenModel, ProjectRelativePath, SchemaId, Sha256Hex +from dlc_octopus.schemas.base.filesystem import FileSchema, LayoutIndex +from dlc_octopus.schemas.base.finding_codes import FingerprintFindingCode +from dlc_octopus.schemas.base.findings import Finding +from dlc_octopus.schemas.base.observations import NodeStatus, walk_observed_nodes +from dlc_octopus.schemas.locations import node_location +from dlc_octopus.schemas.project_layout.project import PROJECT_INDEX +from dlc_octopus.schemas.scope import Scope +from dlc_octopus.schemas.snapshots import ProjectSnapshot +from dlc_octopus.validation.results import ValidationResult + + +class FileFingerprint(FrozenModel): + """The file fingerprint of one file resource: the SHA-256 of its full bytes. + + Attributes: + schema_id: The layout node fingerprinted; ``node_location`` gives its finding anchor. + project_relative_path: The path as the snapshot observed it. + sha256: Hex SHA-256 of the bytes read. + size_bytes: Bytes read. + """ + + schema_id: SchemaId + project_relative_path: ProjectRelativePath + sha256: Sha256Hex + size_bytes: Annotated[int, Field(strict=True, ge=0)] + + @property + def posix_path(self) -> str: + """The project-relative path with ``/`` separators, the same on every platform.""" + + return self.project_relative_path.as_posix() + + +class ResourcesFileFingerprint(FrozenModel): + """The requested file fingerprints, and the snapshot with one finding per resource that could not be read. + + Attributes: + snapshot: The input snapshot with ``FILE_FINGERPRINT_FAILED`` findings merged in. + fingerprints: One file fingerprint per present file node in scope that could be read. + failed: One entry per present file node in scope that could not be read. + """ + + snapshot: ProjectSnapshot + fingerprints: tuple[FileFingerprint, ...] = () + failed: tuple[FailedRead, ...] = () + + +def resources_file_fingerprint( + snapshot: ProjectSnapshot, + scope: Scope, + *, + index: LayoutIndex = PROJECT_INDEX, +) -> ResourcesFileFingerprint: + """File-fingerprint every present file node ``scope`` covers in ``snapshot``, without rediscovering the project. + + Nodes not ``PRESENT`` are skipped: structure validation already reports them. Symlinks are hashed through; + paths are never resolved. Each such file is in ``fingerprints`` or in ``failed``, never both. A file that cannot + be read yields a ``FILE_FINGERPRINT_FAILED`` finding, carried by its ``FailedRead`` and merged into the returned + snapshot. The input snapshot is not modified. + + Args: + snapshot: A snapshot from ``inspect_project``. + scope: The nodes whose files to fingerprint, each within its instance prefix; see ``Scope.covers``. + index: The layout the snapshot was observed against. + + Raises: + ValueError: If ``scope`` names a node the layout does not declare. + """ + + fingerprints: list[FileFingerprint] = [] + failed: list[FailedRead] = [] + + for node in present_files_in_scope(snapshot, scope, scope.file_schema_ids(index=index), index=index): + path = snapshot.project_root / node.project_relative_path + + try: + read = fingerprint_file(path) + except UnreadableFileError as error: + finding = Finding( + code=FingerprintFindingCode.FILE_FINGERPRINT_FAILED, + **node_location(node.schema_id, node.project_relative_path, index=index), + path=path, + evidence={ + "resource_kind": node.kind.value, + "error_type": type(error.__cause__ or error).__name__, + "error_message": str(error), + }, + ) + failed.append(FailedRead(node.schema_id, node.project_relative_path, (finding,))) + continue + + fingerprints.append( + FileFingerprint( + schema_id=node.schema_id, + project_relative_path=node.project_relative_path, + sha256=read.sha256, + size_bytes=read.size_bytes, + ) + ) + + findings = tuple(finding for failure in failed for finding in failure.findings) + return ResourcesFileFingerprint( + snapshot=snapshot.with_validation_result(ValidationResult(findings=findings)), + fingerprints=tuple(fingerprints), + failed=tuple(failed), + ) + + +def compare_file_fingerprints( + snapshot: ProjectSnapshot, + scope: Scope, + recorded: Iterable[FileFingerprint], + *, + index: LayoutIndex = PROJECT_INDEX, +) -> ResourcesFileFingerprint: + """File-fingerprint ``scope`` as ``resources_file_fingerprint`` does, and compare recorded file fingerprints. + + Matched by schema ID and path. A recorded file whose bytes differ, or that is not fingerprinted because it is + gone, yields a ``FILE_FINGERPRINT_CHANGED`` finding merged into the returned snapshot. A recorded file that + could not be read carries ``FILE_FINGERPRINT_FAILED`` only. One inspection found ``UNREADABLE``, or that sits + in an ``UNREADABLE`` directory, carries nothing here: structure validation reports it. A file fingerprinted but + not recorded is not reported. + + A change is a ``WARNING``: a consumer that relies on the recorded bytes refuses it by passing the code to + ``get_blocking_findings(..., block=...)``. + + Raises: + ValueError: If a record's node is not a file the layout declares or its path does not match the layout, if a + file is recorded more than once, if ``scope`` does not cover a recorded file, or if ``scope`` names a node + the layout does not declare. + """ + + recorded = tuple(recorded) + malformed = [r.posix_path for r in recorded if not _matches_layout(r, index)] + if malformed: + raise ValueError(f"{malformed} are recorded under a node that is not a declared file, or not matching it.") + + counts = Counter((r.schema_id, r.project_relative_path) for r in recorded) + repeated = sorted({r.posix_path for r in recorded if counts[r.schema_id, r.project_relative_path] > 1}) + if repeated: + raise ValueError(f"{repeated} are recorded more than once.") + + outside = [r.posix_path for r in recorded if not covered(scope, r.schema_id, r.project_relative_path, index)] + if outside: + raise ValueError(f"{outside} are recorded but outside the scope compared.") + + fingerprinted = resources_file_fingerprint(snapshot, scope, index=index) + observed = {(f.schema_id, f.project_relative_path): f.sha256 for f in fingerprinted.fingerprints} + failed = {(failure.schema_id, failure.project_relative_path) for failure in fingerprinted.failed} + unreadable = [ + node.project_relative_path + for node in walk_observed_nodes(snapshot.project) + if node.status is NodeStatus.UNREADABLE + ] + findings = tuple( + Finding( + code=FingerprintFindingCode.FILE_FINGERPRINT_CHANGED, + **node_location(record.schema_id, record.project_relative_path, index=index), + path=snapshot.project_root / record.project_relative_path, + evidence={"recorded_sha256": record.sha256, "observed_sha256": observed.get(key)}, + ) + for record in recorded + if (key := (record.schema_id, record.project_relative_path)) not in failed + and observed.get(key) != record.sha256 + and not any(record.project_relative_path.is_relative_to(path) for path in unreadable) + ) + return fingerprinted.model_copy( + update={"snapshot": fingerprinted.snapshot.with_validation_result(ValidationResult(findings=findings))} + ) + + +def _matches_layout(record: FileFingerprint, index: LayoutIndex) -> bool: + """Return whether the record's node is a declared file and each part of its path matches the node at that depth.""" + + if record.schema_id not in index.schema_ids_of(FileSchema): + return False + nodes = [index.schemas[schema_id] for schema_id in index.ancestry(record.schema_id)[:-1]] + parts = record.project_relative_path.parts[::-1] + return len(parts) == len(nodes) and all( + node.name.matches(Path(part)) for node, part in zip(nodes, parts, strict=True) + ) diff --git a/dlccore/project/content/reads.py b/dlccore/project/content/reads.py new file mode 100644 index 0000000..30577d7 --- /dev/null +++ b/dlccore/project/content/reads.py @@ -0,0 +1,58 @@ +"""What every data entry point shares: which observed files it reads, and how it reports one it could not.""" + +from __future__ import annotations + +from collections.abc import Collection +from dataclasses import dataclass + +from dlc_octopus.schemas.base.core import ProjectRelativePath, SchemaId +from dlc_octopus.schemas.base.filesystem import LayoutIndex +from dlc_octopus.schemas.base.findings import Finding +from dlc_octopus.schemas.base.observations import NodeStatus, ObservedNode, walk_observed_nodes +from dlc_octopus.schemas.locations import node_location +from dlc_octopus.schemas.scope import Scope +from dlc_octopus.schemas.snapshots import ProjectSnapshot + + +@dataclass(frozen=True) +class FailedRead: + """One requested file that could not be read, with the findings saying why. + + Attributes: + schema_id: The layout node of the file. + project_relative_path: The path as the snapshot observed it. + findings: Why it could not be read; also merged into the snapshot the entry point returns. + """ + + schema_id: SchemaId + project_relative_path: ProjectRelativePath + findings: tuple[Finding, ...] + + +def present_files_in_scope( + snapshot: ProjectSnapshot, + scope: Scope, + schema_ids: Collection[SchemaId], + *, + index: LayoutIndex, +) -> tuple[ObservedNode, ...]: + """Return every ``PRESENT`` node of ``schema_ids`` that ``scope`` covers, in walk order, without rediscovering. + + Nodes not ``PRESENT`` are left out: structure validation already reports them. + """ + + return tuple( + node + for node in walk_observed_nodes(snapshot.project) + if node.schema_id in schema_ids + and node.status is NodeStatus.PRESENT + and covered(scope, node.schema_id, node.project_relative_path, index) + ) + + +def covered(scope: Scope, schema_id: SchemaId, project_relative_path: ProjectRelativePath, index: LayoutIndex) -> bool: + """Return whether ``scope`` covers the node with this schema ID at this path.""" + + instance = node_location(schema_id, project_relative_path, index=index)["instance"] + + return scope.covers(schema_id, instance, index=index) diff --git a/dlccore/project/schemas/base/finding_codes.py b/dlccore/project/schemas/base/finding_codes.py index 638f163..7db20f0 100644 --- a/dlccore/project/schemas/base/finding_codes.py +++ b/dlccore/project/schemas/base/finding_codes.py @@ -220,6 +220,23 @@ class ConfiguredVideoFindingCode(FindingCode): ) +class FingerprintFindingCode(FindingCode): + """Findings about file and frame fingerprints of requested project resources.""" + + FILE_FINGERPRINT_FAILED = ( + "FILE_FINGERPRINT_FAILED", + "A requested resource could not be file-fingerprinted.", + Severity.ERROR, + ("resource_kind", "error_type", "error_message"), + ) + FILE_FINGERPRINT_CHANGED = ( + "FILE_FINGERPRINT_CHANGED", + "A resource's file fingerprint differs from the one recorded for it, or it was not fingerprinted.", + Severity.WARNING, + ("recorded_sha256", "observed_sha256"), + ) + + def iter_finding_codes() -> tuple[FindingCode, ...]: """Return every declared finding code, namespace by namespace.""" diff --git a/tests/project/content/test_fingerprints.py b/tests/project/content/test_fingerprints.py new file mode 100644 index 0000000..4fe233f --- /dev/null +++ b/tests/project/content/test_fingerprints.py @@ -0,0 +1,361 @@ +import hashlib +from collections.abc import Callable +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from dlc_octopus.api import findings_in_scope, inspect_project +from dlc_octopus.api.helpers import get_blocking_findings +from dlc_octopus.content import FailedRead, FileFingerprint, compare_file_fingerprints, resources_file_fingerprint +from dlc_octopus.schemas.base.finding_codes import FingerprintFindingCode, Severity, StructureFindingCode +from dlc_octopus.schemas.base.findings import Reach +from dlc_octopus.schemas.base.observations import NodeStatus +from dlc_octopus.schemas.base.resources import FileResourceKind +from dlc_octopus.schemas.project_layout.project import PROJECT_CONFIG +from dlc_octopus.schemas.project_layout.videos import SOURCE_VIDEO, VIDEOS +from dlc_octopus.schemas.scope import Scope + +FAILED = FingerprintFindingCode.FILE_FINGERPRINT_FAILED +CHANGED = FingerprintFindingCode.FILE_FINGERPRINT_CHANGED +ALL_VIDEOS = Scope(SOURCE_VIDEO) + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _codes(findings: tuple) -> list: + return [finding.code for finding in findings] + + +def test_inspection_never_file_fingerprints(valid_project: Path) -> None: + snapshot = inspect_project(valid_project) + + assert FAILED not in _codes(snapshot.findings) + assert not [name for name in type(snapshot).model_fields if "fingerprint" in name] + + +def test_a_node_the_layout_does_not_declare_is_refused_even_when_nothing_is_present(tmp_path: Path) -> None: + impostor = SOURCE_VIDEO.model_copy(update={"description": "not the layout's own"}) + + with pytest.raises(ValueError, match="does not declare"): + resources_file_fingerprint(inspect_project(tmp_path), Scope(impostor)) + + +def test_only_the_files_in_scope_are_file_fingerprinted(valid_project: Path) -> None: + (valid_project / "videos" / "session-01.mp4").write_bytes(b"frames") + snapshot = inspect_project(valid_project) + + result = resources_file_fingerprint(snapshot, Scope(PROJECT_CONFIG)) + + assert result.fingerprints == ( + FileFingerprint( + schema_id="dlc.project.config", + project_relative_path=Path("config.yaml"), + sha256=_sha256(valid_project / "config.yaml"), + size_bytes=(valid_project / "config.yaml").stat().st_size, + ), + ) + assert result.snapshot == snapshot + + +def test_the_snapshot_is_not_rediscovered(valid_project: Path) -> None: + snapshot = inspect_project(valid_project) + (valid_project / "videos" / "added-later.mp4").write_bytes(b"frames") + + result = resources_file_fingerprint(snapshot, Scope(SOURCE_VIDEO)) + + assert (result.fingerprints, result.snapshot) == ((), snapshot) + + +def test_a_node_that_is_not_present_is_neither_file_fingerprinted_nor_reported(valid_project: Path) -> None: + (valid_project / "config.yaml").unlink() + snapshot = inspect_project(valid_project) + statuses = [(node.kind, node.status) for node in snapshot.project.schema_children] + assert (FileResourceKind.PROJECT_CONFIG, NodeStatus.MISSING) in statuses # control: the node was observed + + result = resources_file_fingerprint(snapshot, Scope(PROJECT_CONFIG)) + + assert (result.fingerprints, result.snapshot) == ((), snapshot) + + +def test_a_file_that_vanished_is_one_merged_error_finding_and_the_rest_are_file_fingerprinted( + valid_project: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + (valid_project / "videos" / "session-01.mp4").write_bytes(b"frames 1") + (valid_project / "videos" / "session-02.mp4").write_bytes(b"frames 2") + monkeypatch.chdir(valid_project.parent) + snapshot = inspect_project(Path(valid_project.name)) + (valid_project / "videos" / "session-01.mp4").unlink() + + result = resources_file_fingerprint(snapshot, Scope(SOURCE_VIDEO)) + + assert [f.project_relative_path for f in result.fingerprints] == [Path("videos/session-02.mp4")] + (finding,) = result.snapshot.findings[len(snapshot.findings) :] + assert result.snapshot.findings[: len(snapshot.findings)] == snapshot.findings + assert (finding.code, finding.severity, finding.reach, finding.instance) == ( + FAILED, + Severity.ERROR, + Reach.ONE_OF, + ("videos", "session-01.mp4"), + ) + assert finding.path == valid_project / "videos" / "session-01.mp4" # absolute, never resolved + assert finding.evidence["resource_kind"] == "source_video" + assert finding.evidence["error_type"] == "FileNotFoundError" + assert "session-01.mp4" in finding.evidence["error_message"] + assert result.failed == (FailedRead("dlc.videos.source_video", Path("videos/session-01.mp4"), (finding,)),) + + +def test_every_requested_file_is_either_file_fingerprinted_or_failed(valid_project: Path) -> None: + for name in ("session-01.mp4", "session-02.mp4", "session-03.mp4"): + (valid_project / "videos" / name).write_bytes(b"frames") + snapshot = inspect_project(valid_project) + (valid_project / "videos" / "session-02.mp4").unlink() + + result = resources_file_fingerprint(snapshot, Scope(SOURCE_VIDEO)) + + fingerprinted = [f.project_relative_path.name for f in result.fingerprints] + failed = [failure.project_relative_path.name for failure in result.failed] + assert (fingerprinted, failed) == (["session-01.mp4", "session-03.mp4"], ["session-02.mp4"]) + + +def test_a_merged_finding_is_seen_by_the_scope_query(valid_project: Path) -> None: + (valid_project / "videos" / "session-01.mp4").write_bytes(b"frames") + snapshot = inspect_project(valid_project) + (valid_project / "videos" / "session-01.mp4").unlink() + + result = resources_file_fingerprint(snapshot, Scope(SOURCE_VIDEO)) + + assert FAILED in _codes( + findings_in_scope(result.snapshot, Scope(SOURCE_VIDEO, within=("videos", "session-01.mp4"))) + ) + + +def test_a_scope_within_one_instance_file_fingerprints_that_instance_only(valid_project: Path) -> None: + (valid_project / "videos" / "session-01.mp4").write_bytes(b"frames 1") + (valid_project / "videos" / "session-02.mp4").write_bytes(b"frames 2") + snapshot = inspect_project(valid_project) + assert len(resources_file_fingerprint(snapshot, Scope(SOURCE_VIDEO)).fingerprints) == 2 # control + + result = resources_file_fingerprint(snapshot, Scope(SOURCE_VIDEO, within=("videos", "session-02.mp4"))) + + assert [f.project_relative_path for f in result.fingerprints] == [Path("videos/session-02.mp4")] + + +def test_a_directory_scope_file_fingerprints_the_files_beneath_it(valid_project: Path) -> None: + (valid_project / "videos" / "session-01.mp4").write_bytes(b"frames") + + result = resources_file_fingerprint(inspect_project(valid_project), Scope(VIDEOS)) + + assert [f.schema_id for f in result.fingerprints] == ["dlc.videos.source_video"] + + +def test_a_symlinked_resource_is_file_fingerprinted_through_the_link( + valid_project: Path, tmp_path_factory: pytest.TempPathFactory, create_symlink_or_skip: Callable[..., None] +) -> None: + target = tmp_path_factory.mktemp("elsewhere") / "session-01.mp4" + target.write_bytes(b"frames") + create_symlink_or_skip(valid_project / "videos" / "session-01.mp4", target) + + result = resources_file_fingerprint(inspect_project(valid_project), Scope(SOURCE_VIDEO)) + + assert [(f.project_relative_path, f.sha256) for f in result.fingerprints] == [ + (Path("videos/session-01.mp4"), _sha256(target)) + ] + + +def test_a_file_fingerprint_spells_its_path_the_same_on_every_platform(valid_project: Path) -> None: + (valid_project / "videos" / "session-01.mp4").write_bytes(b"frames") + + (fingerprint,) = resources_file_fingerprint(inspect_project(valid_project), Scope(SOURCE_VIDEO)).fingerprints + + assert fingerprint.project_relative_path == Path("videos", "session-01.mp4") # the host's Path + assert fingerprint.posix_path == "videos/session-01.mp4" + assert "posix_path" not in fingerprint.model_dump() # not part of the serialized form + + +@pytest.mark.parametrize("sha256", ["A" * 64, "a" * 63, ""]) +def test_a_malformed_sha256_is_refused_when_loaded(sha256: str) -> None: + with pytest.raises(ValidationError): + FileFingerprint.model_validate( + { + "schema_id": "dlc.project.config", + "project_relative_path": "config.yaml", + "sha256": sha256, + "size_bytes": 1, + } + ) + + +def _fingerprint_record(size_bytes: object) -> dict[str, object]: + return { + "schema_id": "dlc.project.config", + "project_relative_path": "config.yaml", + "sha256": "a" * 64, + "size_bytes": size_bytes, + } + + +@pytest.mark.parametrize("size_bytes", [-1, True, 3.0, "7"], ids=repr) +def test_a_size_that_is_not_a_byte_count_is_refused_when_loaded(size_bytes: object) -> None: + with pytest.raises(ValidationError): + FileFingerprint.model_validate(_fingerprint_record(size_bytes)) + + +def test_a_byte_count_survives_a_json_round_trip() -> None: + # Control: strict integers must still load from JSON, where a consumer stores them. + fingerprint = FileFingerprint.model_validate(_fingerprint_record(0)) + + assert FileFingerprint.model_validate_json(fingerprint.model_dump_json()) == fingerprint + + +def test_the_public_api_reexports_file_fingerprinting() -> None: + import dlc_octopus.api as api + import dlc_octopus.content as content + + assert ( + api.resources_file_fingerprint, + api.compare_file_fingerprints, + api.FileFingerprint, + api.ResourcesFileFingerprint, + ) == ( + content.resources_file_fingerprint, + content.compare_file_fingerprints, + content.FileFingerprint, + content.ResourcesFileFingerprint, + ) + assert api.FileResourceKind is FileResourceKind + assert api.helpers.Scope is Scope + + +def _videos(project: Path, *names: str) -> tuple[FileFingerprint, ...]: + for name in names: + (project / "videos" / name).write_bytes(name.encode()) + return resources_file_fingerprint(inspect_project(project), Scope(SOURCE_VIDEO)).fingerprints + + +def _compared(project: Path, recorded: tuple[FileFingerprint, ...], scope: Scope = ALL_VIDEOS) -> tuple: + snapshot = inspect_project(project) + return compare_file_fingerprints(snapshot, scope, recorded).snapshot.findings[len(snapshot.findings) :] + + +def test_unchanged_files_compare_without_findings(valid_project: Path) -> None: + recorded = _videos(valid_project, "session-01.mp4", "session-02.mp4") + + assert _compared(valid_project, recorded) == () + + +def test_a_changed_file_is_one_finding_with_both_fingerprints_blocking_only_on_request(valid_project: Path) -> None: + recorded = _videos(valid_project, "session-01.mp4", "session-02.mp4") + (valid_project / "videos" / "session-02.mp4").write_bytes(b"relabeled") + + (finding,) = _compared(valid_project, recorded) + + assert (finding.code, finding.severity, finding.instance) == ( + CHANGED, + Severity.WARNING, + ("videos", "session-02.mp4"), + ) + assert finding.evidence == { + "recorded_sha256": recorded[1].sha256, + "observed_sha256": _sha256(valid_project / "videos" / "session-02.mp4"), + } + assert (get_blocking_findings([finding]), get_blocking_findings([finding], block={CHANGED})) == ((), (finding,)) + + +def test_a_recorded_file_that_is_gone_is_reported_with_no_observed_fingerprint(valid_project: Path) -> None: + recorded = _videos(valid_project, "session-01.mp4") + (valid_project / "videos" / "session-01.mp4").unlink() + + (finding,) = _compared(valid_project, recorded) + + assert (finding.code, finding.evidence["observed_sha256"]) == (CHANGED, None) + + +def test_a_recorded_file_that_cannot_be_read_is_reported_once_as_failed(valid_project: Path) -> None: + recorded = _videos(valid_project, "session-01.mp4") + snapshot = inspect_project(valid_project) + (valid_project / "videos" / "session-01.mp4").unlink() + + result = compare_file_fingerprints(snapshot, Scope(SOURCE_VIDEO), recorded) + + assert _codes(result.snapshot.findings) == [FAILED] + + +def test_a_file_fingerprinted_but_never_recorded_is_not_reported(valid_project: Path) -> None: + recorded = _videos(valid_project, "session-01.mp4") + _videos(valid_project, "session-02.mp4") + + assert _compared(valid_project, recorded) == () + + +def test_a_scope_within_one_instance_compares_that_instance_only(valid_project: Path) -> None: + recorded = _videos(valid_project, "session-01.mp4", "session-02.mp4") + (valid_project / "videos" / "session-01.mp4").unlink() + assert _codes(_compared(valid_project, recorded)) == [CHANGED] # control: the whole scope sees it gone + + within = Scope(SOURCE_VIDEO, within=("videos", "session-02.mp4")) + + assert _compared(valid_project, recorded[1:], within) == () + + +def test_a_recorded_file_outside_the_scope_is_refused(valid_project: Path) -> None: + recorded = _videos(valid_project, "session-01.mp4", "session-02.mp4") + + with pytest.raises(ValueError, match=r"session-01\.mp4"): + _compared(valid_project, recorded, Scope(SOURCE_VIDEO, within=("videos", "session-02.mp4"))) + + +@pytest.mark.parametrize( + ("schema_id", "path"), + [ + (SOURCE_VIDEO.schema_id, "videos/notes.txt"), + (SOURCE_VIDEO.schema_id, "labeled-data/mouse1/clip.mp4"), + (VIDEOS.schema_id, "videos"), + ], + ids=["name the node does not match", "a directory the node does not sit in", "a directory node"], +) +def test_a_record_that_does_not_fit_its_node_is_refused(valid_project: Path, schema_id: str, path: str) -> None: + record = FileFingerprint(schema_id=schema_id, project_relative_path=Path(path), sha256="0" * 64, size_bytes=0) + + with pytest.raises(ValueError, match="not a declared file"): + _compared(valid_project, (record,)) + + +@pytest.mark.parametrize("sha256", ["same", "conflicting"]) +def test_a_file_recorded_twice_is_refused(valid_project: Path, sha256: str) -> None: + (record,) = _videos(valid_project, "session-01.mp4") + twice = record if sha256 == "same" else record.model_copy(update={"sha256": "0" * 64}) + + with pytest.raises(ValueError, match=r"session-01\.mp4.*more than once"): + _compared(valid_project, (record, twice)) + + +def _deny(monkeypatch: pytest.MonkeyPatch, method: str, denied: Path) -> None: + real = getattr(Path, method) + + def refuse(self: Path, *args: object, **kwargs: object) -> object: + if self == denied: + raise PermissionError("Access is denied") + return real(self, *args, **kwargs) + + monkeypatch.setattr(Path, method, refuse) + + +@pytest.mark.parametrize( + ("method", "denied"), + [("lstat", "videos/session-02.mp4"), ("iterdir", "videos")], + ids=["the file", "its directory"], +) +def test_a_recorded_file_unreadable_at_inspection_is_left_to_structure_validation( + valid_project: Path, monkeypatch: pytest.MonkeyPatch, method: str, denied: str +) -> None: + recorded = _videos(valid_project, "session-01.mp4", "session-02.mp4") + _deny(monkeypatch, method, valid_project / denied) + snapshot = inspect_project(valid_project) + assert StructureFindingCode.PROJECT_NODE_UNREADABLE in _codes(snapshot.findings) # control: inspection saw it + + result = compare_file_fingerprints(snapshot, ALL_VIDEOS, recorded) + + assert result.snapshot.findings[len(snapshot.findings) :] == () From 2d4c81971fc8f1995e3e4de51fb7c7b1fba9454c Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Thu, 26 Nov 2026 15:27:00 +0100 Subject: [PATCH 2/2] Adapt project content reads and file fingerprints to dlccore - Rename the packages to dlccore.project and dlccore.io, and add the dlccore license header - content's __init__ exports reads and fingerprints only; labeled data follows with its PR - Re-export the fingerprint entry points from the API package - Add the control that content does import io to tests/io/test_boundaries.py - The closed-catalogue test now expects FingerprintFindingCode too --- dlccore/project/api/__init__.py | 12 +++++++ dlccore/project/content/__init__.py | 29 ++++++++-------- dlccore/project/content/fingerprints.py | 37 +++++++++++++-------- dlccore/project/content/reads.py | 25 ++++++++++---- tests/io/test_boundaries.py | 5 +++ tests/project/content/test_fingerprints.py | 35 ++++++++++++------- tests/project/schemas/test_finding_codes.py | 8 ++++- 7 files changed, 103 insertions(+), 48 deletions(-) diff --git a/dlccore/project/api/__init__.py b/dlccore/project/api/__init__.py index 8e8d3c1..0282b27 100644 --- a/dlccore/project/api/__init__.py +++ b/dlccore/project/api/__init__.py @@ -12,14 +12,26 @@ """Public entry points of ``dlccore.project``; consumer helpers are in ``api.helpers``. Re-exports only.""" from dlccore.project.api import helpers +from dlccore.project.content import ( + FailedRead, + FileFingerprint, + ResourcesFileFingerprint, + compare_file_fingerprints, + resources_file_fingerprint, +) from dlccore.project.inspection import inspect_project, project_name from dlccore.project.schemas.base.resources import FileResourceKind from dlccore.project.schemas.scope import findings_in_scope __all__ = [ + "FailedRead", + "FileFingerprint", "FileResourceKind", + "ResourcesFileFingerprint", + "compare_file_fingerprints", "findings_in_scope", "helpers", "inspect_project", "project_name", + "resources_file_fingerprint", ] diff --git a/dlccore/project/content/__init__.py b/dlccore/project/content/__init__.py index 28d9452..5deb6b8 100644 --- a/dlccore/project/content/__init__.py +++ b/dlccore/project/content/__init__.py @@ -1,29 +1,28 @@ -"""Octopus requests over DLC Project Management's read-only I/O; the only package that imports ``dlc_octopus.io``.""" +# +# 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 dlc_octopus.content.fingerprints import ( +"""The project layer's requests over the per-file I/O; the only package that imports ``dlccore.io``.""" + +from dlccore.project.content.fingerprints import ( FileFingerprint, ResourcesFileFingerprint, compare_file_fingerprints, resources_file_fingerprint, ) -from dlc_octopus.content.labeled_data import ( - InspectedLabeledDataFile, - LabeledDataEntry, - ProjectLabeledData, - inspect_labeled_data_file, - read_project_labeled_data, -) -from dlc_octopus.content.reads import FailedRead +from dlccore.project.content.reads import FailedRead __all__ = [ "FailedRead", "FileFingerprint", - "InspectedLabeledDataFile", - "LabeledDataEntry", - "ProjectLabeledData", "ResourcesFileFingerprint", "compare_file_fingerprints", - "inspect_labeled_data_file", - "read_project_labeled_data", "resources_file_fingerprint", ] diff --git a/dlccore/project/content/fingerprints.py b/dlccore/project/content/fingerprints.py index 07c1121..87e5b30 100644 --- a/dlccore/project/content/fingerprints.py +++ b/dlccore/project/content/fingerprints.py @@ -1,4 +1,15 @@ -"""File fingerprints of a snapshot's file resources, requested from ``dlc_octopus.io`` and reported as findings.""" +# +# 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 +# + +"""File fingerprints of a snapshot's file resources, requested from ``dlccore.io`` and reported as findings.""" from __future__ import annotations @@ -9,18 +20,18 @@ from pydantic import Field -from dlc_octopus.content.reads import FailedRead, covered, present_files_in_scope -from dlc_octopus.io import UnreadableFileError, fingerprint_file -from dlc_octopus.schemas.base.core import FrozenModel, ProjectRelativePath, SchemaId, Sha256Hex -from dlc_octopus.schemas.base.filesystem import FileSchema, LayoutIndex -from dlc_octopus.schemas.base.finding_codes import FingerprintFindingCode -from dlc_octopus.schemas.base.findings import Finding -from dlc_octopus.schemas.base.observations import NodeStatus, walk_observed_nodes -from dlc_octopus.schemas.locations import node_location -from dlc_octopus.schemas.project_layout.project import PROJECT_INDEX -from dlc_octopus.schemas.scope import Scope -from dlc_octopus.schemas.snapshots import ProjectSnapshot -from dlc_octopus.validation.results import ValidationResult +from dlccore.io import UnreadableFileError, fingerprint_file +from dlccore.project.content.reads import FailedRead, covered, present_files_in_scope +from dlccore.project.schemas.base.core import FrozenModel, ProjectRelativePath, SchemaId, Sha256Hex +from dlccore.project.schemas.base.filesystem import FileSchema, LayoutIndex +from dlccore.project.schemas.base.finding_codes import FingerprintFindingCode +from dlccore.project.schemas.base.findings import Finding +from dlccore.project.schemas.base.observations import NodeStatus, walk_observed_nodes +from dlccore.project.schemas.locations import node_location +from dlccore.project.schemas.project_layout.project import PROJECT_INDEX +from dlccore.project.schemas.scope import Scope +from dlccore.project.schemas.snapshots import ProjectSnapshot +from dlccore.project.validation.results import ValidationResult class FileFingerprint(FrozenModel): diff --git a/dlccore/project/content/reads.py b/dlccore/project/content/reads.py index 30577d7..6fc15e4 100644 --- a/dlccore/project/content/reads.py +++ b/dlccore/project/content/reads.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 +# + """What every data entry point shares: which observed files it reads, and how it reports one it could not.""" from __future__ import annotations @@ -5,13 +16,13 @@ from collections.abc import Collection from dataclasses import dataclass -from dlc_octopus.schemas.base.core import ProjectRelativePath, SchemaId -from dlc_octopus.schemas.base.filesystem import LayoutIndex -from dlc_octopus.schemas.base.findings import Finding -from dlc_octopus.schemas.base.observations import NodeStatus, ObservedNode, walk_observed_nodes -from dlc_octopus.schemas.locations import node_location -from dlc_octopus.schemas.scope import Scope -from dlc_octopus.schemas.snapshots import ProjectSnapshot +from dlccore.project.schemas.base.core import ProjectRelativePath, SchemaId +from dlccore.project.schemas.base.filesystem import LayoutIndex +from dlccore.project.schemas.base.findings import Finding +from dlccore.project.schemas.base.observations import NodeStatus, ObservedNode, walk_observed_nodes +from dlccore.project.schemas.locations import node_location +from dlccore.project.schemas.scope import Scope +from dlccore.project.schemas.snapshots import ProjectSnapshot @dataclass(frozen=True) diff --git a/tests/io/test_boundaries.py b/tests/io/test_boundaries.py index c862e6b..1aefb1b 100644 --- a/tests/io/test_boundaries.py +++ b/tests/io/test_boundaries.py @@ -138,6 +138,11 @@ def test_the_human_labels_prefix_is_spelled_once_in_io() -> None: assert _modules_spelling("CollectedData_") == {"io/suffixes.py"} +def test_the_scan_sees_content_import_io() -> None: + # Control: content does import io, so the scan must report it, or "only content imports io" proves nothing. + assert any(_within(name, IO) for name in dict(_package_modules())[f"{CONTENT}.fingerprints"]) + + def test_the_scan_reaches_io() -> None: # Control: io's own __init__ imports its errors module, so an empty scan cannot pass the test above. assert f"{IO}.errors" in dict(_package_modules())[IO] diff --git a/tests/project/content/test_fingerprints.py b/tests/project/content/test_fingerprints.py index 4fe233f..d52e755 100644 --- a/tests/project/content/test_fingerprints.py +++ b/tests/project/content/test_fingerprints.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 +# + import hashlib from collections.abc import Callable from pathlib import Path @@ -5,16 +16,16 @@ import pytest from pydantic import ValidationError -from dlc_octopus.api import findings_in_scope, inspect_project -from dlc_octopus.api.helpers import get_blocking_findings -from dlc_octopus.content import FailedRead, FileFingerprint, compare_file_fingerprints, resources_file_fingerprint -from dlc_octopus.schemas.base.finding_codes import FingerprintFindingCode, Severity, StructureFindingCode -from dlc_octopus.schemas.base.findings import Reach -from dlc_octopus.schemas.base.observations import NodeStatus -from dlc_octopus.schemas.base.resources import FileResourceKind -from dlc_octopus.schemas.project_layout.project import PROJECT_CONFIG -from dlc_octopus.schemas.project_layout.videos import SOURCE_VIDEO, VIDEOS -from dlc_octopus.schemas.scope import Scope +from dlccore.project.api import findings_in_scope, inspect_project +from dlccore.project.api.helpers import get_blocking_findings +from dlccore.project.content import FailedRead, FileFingerprint, compare_file_fingerprints, resources_file_fingerprint +from dlccore.project.schemas.base.finding_codes import FingerprintFindingCode, Severity, StructureFindingCode +from dlccore.project.schemas.base.findings import Reach +from dlccore.project.schemas.base.observations import NodeStatus +from dlccore.project.schemas.base.resources import FileResourceKind +from dlccore.project.schemas.project_layout.project import PROJECT_CONFIG +from dlccore.project.schemas.project_layout.videos import SOURCE_VIDEO, VIDEOS +from dlccore.project.schemas.scope import Scope FAILED = FingerprintFindingCode.FILE_FINGERPRINT_FAILED CHANGED = FingerprintFindingCode.FILE_FINGERPRINT_CHANGED @@ -211,8 +222,8 @@ def test_a_byte_count_survives_a_json_round_trip() -> None: def test_the_public_api_reexports_file_fingerprinting() -> None: - import dlc_octopus.api as api - import dlc_octopus.content as content + import dlccore.project.api as api + import dlccore.project.content as content assert ( api.resources_file_fingerprint, diff --git a/tests/project/schemas/test_finding_codes.py b/tests/project/schemas/test_finding_codes.py index dd9683f..f080831 100644 --- a/tests/project/schemas/test_finding_codes.py +++ b/tests/project/schemas/test_finding_codes.py @@ -21,6 +21,7 @@ ConfigFindingCode, ConfiguredVideoFindingCode, FindingCode, + FingerprintFindingCode, Severity, StructureFindingCode, iter_finding_codes, @@ -203,7 +204,12 @@ 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, ConfiguredVideoFindingCode} + assert set(FindingCode.__subclasses__()) == { + StructureFindingCode, + ConfigFindingCode, + ConfiguredVideoFindingCode, + FingerprintFindingCode, + } def test_severity_has_three_rungs() -> None: