diff --git a/dlccore/project/errors.py b/dlccore/project/errors.py new file mode 100644 index 0000000..5ae8ff1 --- /dev/null +++ b/dlccore/project/errors.py @@ -0,0 +1,52 @@ +# +# 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 +# + +"""Data validation-specific errors.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from dlccore.project.schemas.base.findings import Severity + +if TYPE_CHECKING: + from dlccore.project.schemas.base.findings import Finding + from dlccore.project.schemas.snapshots import ProjectSnapshot + + +class ConfigUnavailableError(RuntimeError): + """Raised when canonical project config data is unavailable.""" + + +BLOCKING_SEVERITIES = frozenset({Severity.ERROR}) + + +class ProjectValidationError(RuntimeError): + """Raised when an inspected project contains blocking findings.""" + + def __init__( + self, + snapshot: ProjectSnapshot, + ) -> None: + self.snapshot = snapshot + self.findings = _blocking_findings(snapshot) + + codes = ", ".join(finding.code for finding in self.findings) + + super().__init__(f"Project validation failed with {len(self.findings)} blocking finding(s): {codes}.") + + +def _blocking_findings( + snapshot: ProjectSnapshot, +) -> tuple[Finding, ...]: + """Return the snapshot's findings whose severity is in ``BLOCKING_SEVERITIES``.""" + + return tuple(finding for finding in snapshot.findings if finding.severity in BLOCKING_SEVERITIES) diff --git a/dlccore/project/policy.py b/dlccore/project/policy.py new file mode 100644 index 0000000..ac33035 --- /dev/null +++ b/dlccore/project/policy.py @@ -0,0 +1,78 @@ +# +# 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 +# + +"""A consumer's policy over findings: the severity default, adjusted by the consumer's own finding codes. + +The codes are the consumer's decision; these helpers only apply them. +""" + +from __future__ import annotations + +from collections.abc import Collection, Iterable + +from dlccore.project.errors import BLOCKING_SEVERITIES +from dlccore.project.schemas.base.finding_codes import FindingCode +from dlccore.project.schemas.base.findings import Finding + + +def get_blocking_findings( + findings: Iterable[Finding], + *, + block: Collection[FindingCode] = (), + allow: Collection[FindingCode] = (), +) -> tuple[Finding, ...]: + """Return the findings that block, in order: blocking severity by default, plus ``block``, minus ``allow``. + + Args: + findings: The findings to filter, e.g. from ``findings_in_scope``. + block: Codes that block whatever their severity. + allow: Codes that never block, even at blocking severity. + + Raises: + TypeError: If a code is not a ``FindingCode`` member, so that a renamed code fails where it is named. + ValueError: If a code is both blocked and allowed. + """ + + _members(block) + _members(allow) + + both = set(block) & set(allow) + if both: + raise ValueError(f"Codes both blocked and allowed: {sorted(both)}.") + + return tuple( + finding + for finding in findings + if finding.code not in allow and (finding.severity in BLOCKING_SEVERITIES or finding.code in block) + ) + + +def unhandled(findings: Iterable[Finding], handled: Collection[FindingCode]) -> tuple[Finding, ...]: + """Return the findings whose code is not in ``handled``, in order. + + Args: + findings: The findings to check. + handled: The codes the consumer maps; a mapping from each code to how it is handled also works, and only its + keys are read. + + Raises: + TypeError: If a code is not a ``FindingCode`` member, so that a renamed code fails where it is named. + """ + + _members(handled) + + return tuple(finding for finding in findings if finding.code not in handled) + + +def _members(codes: Collection[FindingCode]) -> None: + strays = [code for code in codes if not isinstance(code, FindingCode)] + if strays: + raise TypeError(f"Name finding codes by their FindingCode members, not {strays!r}.") diff --git a/dlccore/project/schemas/base/finding_codes.py b/dlccore/project/schemas/base/finding_codes.py new file mode 100644 index 0000000..5c786e8 --- /dev/null +++ b/dlccore/project/schemas/base/finding_codes.py @@ -0,0 +1,83 @@ +# +# 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 +# + +"""Finding vocabulary: severities, and the stable codes to emit. + +Validation-check, baseline-check and validator-suite identifiers share the +same naming style but are separate namespaces. + +Codes are grouped by subject rather than by emitting module, following the +``_`` convention. +""" + +from __future__ import annotations + +from enum import Enum +from itertools import chain + + +class Severity(str, Enum): + NOTE = "note" + WARNING = "warning" + ERROR = "error" + + +class FindingCode(str, Enum): + """Base for every ``Finding.code`` namespace; declares no codes itself.""" + + # Render as the bare code, as ``enum.StrEnum`` would; it is 3.11+. + __str__ = str.__str__ + + description: str + severity: Severity + evidence_keys: tuple[str, ...] + + def __new__( + cls, + code: str, + description: str, + severity: Severity, + evidence_keys: tuple[str, ...], + ) -> FindingCode: + member = str.__new__(cls, code) + member._value_ = code + member.description = description + member.severity = severity + member.evidence_keys = tuple(evidence_keys) + + return member + + +def iter_finding_codes() -> tuple[FindingCode, ...]: + """Return every declared finding code, namespace by namespace.""" + + return tuple(chain.from_iterable(FindingCode.__subclasses__())) + + +def finding_code(value: str | FindingCode) -> FindingCode: + """Return the declared code for one value, as read from serialized output. + + Raises: + ValueError: If no namespace declares the value. + """ + + if isinstance(value, FindingCode): + return value + + for namespace in FindingCode.__subclasses__(): + try: + return namespace(value) + except ValueError: + continue + + declared = ", ".join(code.value for code in iter_finding_codes()) + + raise ValueError(f"Unknown finding code {value!r}. Declared codes are: {declared or ''}.") diff --git a/dlccore/project/schemas/base/findings.py b/dlccore/project/schemas/base/findings.py new file mode 100644 index 0000000..f5a7f83 --- /dev/null +++ b/dlccore/project/schemas/base/findings.py @@ -0,0 +1,102 @@ +# +# 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 +# + +"""Simple diagnostic facts generated from walking through the project structure. + +These are the main enablers for downstream reporting, consumption by GUI/CLI/LLM agents, +and offering actions based on the findings (e.g., "PROJECT_REQUIRED_NODE_MISSING" could trigger a prompt to +locate or create the missing file). +""" + +from __future__ import annotations + +from enum import Enum +from pathlib import Path + +from pydantic import Field, JsonValue, model_validator +from typing_extensions import Self + +from dlccore.project.schemas.base.core import FrozenModel, LayoutInstance, SchemaId +from dlccore.project.schemas.base.finding_codes import FindingCode, Severity, finding_code + + +class Reach(str, Enum): + """Which instances of its layout node a finding is about.""" + + ONE_PER_PROJECT = "one_per_project" + ONE_OF = "one_of" + ALL_OF = "all_of" + # Outside any known project: the instance holds only the segments that are certain. Never in a snapshot. + UNROOTED = "unrooted" + + +class Finding(FrozenModel): + """A structured diagnostic produced while inspecting or validating a project item. + + Findings describe observable issues, warnings, or informational conditions + without modifying project data. + - Stable ``code`` values support programmatic handling, and carry the + human-readable text as ``code.description`` + - ``schema_id``: the layout node it is about; consumers scope by it, never by ``path`` + - ``reach``: whether it is about the only node of its kind, one instance, or every instance + - ``instance``: which instance of a repeated layout node it is about, as + project-relative path segments; ``()`` for ``ONE_PER_PROJECT``, a prefix for ``ALL_OF``, the certain + trailing segments for ``UNROOTED`` + - ``path`` and ``field_location``: where in the project it was observed + - ``evidence``: the observations supporting it, e.g. "actual" vs "expected" + """ + + code: FindingCode + severity: Severity + schema_id: SchemaId + reach: Reach + instance: LayoutInstance = () + path: Path | None = None + field_location: tuple[str | int, ...] = () + evidence: dict[str, JsonValue] = Field(default_factory=dict) + + @model_validator(mode="before") + @classmethod + def _resolve_evidence(cls, data: object) -> object: + """Resolve the code, take its severity, and require its declared evidence. + + Raises: + ValueError: If the evidence the code declares is not all present. + """ + + if not isinstance(data, dict) or data.get("code") is None: + return data + + code = finding_code(data["code"]) + evidence = data.get("evidence") + present = evidence.keys() if isinstance(evidence, dict) else () + missing = tuple(key for key in code.evidence_keys if key not in present) + + if missing: + raise ValueError(f"Finding {code.value} requires evidence keys {missing}.") + + return {**data, "code": code, "severity": code.severity} + + @model_validator(mode="after") + def _check_reach(self) -> Self: + """Refuse a reach the instance contradicts. + + Raises: + ValueError: If ``ONE_PER_PROJECT`` names an instance, or ``ONE_OF`` or ``UNROOTED`` names none. + """ + + if self.reach is Reach.ONE_PER_PROJECT and self.instance: + raise ValueError(f"Reach ONE_PER_PROJECT names no instance, but got {self.instance!r}.") + + if self.reach in {Reach.ONE_OF, Reach.UNROOTED} and not self.instance: + raise ValueError(f"Reach {self.reach.name} names one instance, but got none.") + + return self diff --git a/pyproject.toml b/pyproject.toml index debf6c6..a54dffd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,7 +24,7 @@ dynamic = [ "version" ] dependencies = [ "numpy>=1.22.4", "pandas>=2.3.3", - "pydantic>=2.1,<3", + "pydantic>=2.5.2,<3", "ruamel-yaml>=0.16", "typing-extensions", ] diff --git a/tests/conftest.py b/tests/conftest.py index d52b0a8..c048e39 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -9,12 +9,15 @@ # Licensed under GNU Lesser General Public License v3.0 # +import gc import os from collections.abc import Callable from pathlib import Path import pytest +from dlccore.project.schemas.base.finding_codes import FindingCode, Severity + def _create_symlink_or_skip( link: Path, @@ -54,3 +57,46 @@ def stat_without_file_id(path: object, *args: object, **kwargs: object) -> os.st return os.stat_result((result[0], 0, *result[2:])) monkeypatch.setattr(os, "stat", stat_without_file_id) + + +def _declare_example_codes() -> type[FindingCode]: + class ExampleFindingCode(FindingCode): + """Declared for one test; each real namespace lands with the check that first emits it.""" + + TEST_NODE_WRONG_TYPE = ( + "TEST_NODE_WRONG_TYPE", + "A project resource exists at the expected location but has the wrong filesystem type.", + Severity.ERROR, + ("resource_kind", "expected_type"), + ) + TEST_NODE_UNREADABLE = ( + "TEST_NODE_UNREADABLE", + "A project-layout node could not be read.", + Severity.ERROR, + ("resource_kind", "error_type", "error_message"), + ) + + return ExampleFindingCode + + +_example_codes_declared = False + + +@pytest.fixture +def example_codes() -> type[FindingCode]: + """A finding-code namespace that exists for one test only, so the catalogue every other test sees stays closed.""" + + global _example_codes_declared + _example_codes_declared = True + + return _declare_example_codes() + + +def pytest_runtest_setup() -> None: + """Collect the example namespace an earlier test declared; an enum class lingers in a reference cycle.""" + + global _example_codes_declared + + if _example_codes_declared: + gc.collect() + _example_codes_declared = False diff --git a/tests/project/inspection/test_validation_error.py b/tests/project/inspection/test_validation_error.py new file mode 100644 index 0000000..db65e64 --- /dev/null +++ b/tests/project/inspection/test_validation_error.py @@ -0,0 +1,19 @@ +# +# 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 dlccore.project.errors import BLOCKING_SEVERITIES +from dlccore.project.schemas.base.finding_codes import Severity + + +def test_only_error_blocks() -> None: + assert {Severity.ERROR} == BLOCKING_SEVERITIES diff --git a/tests/project/schemas/test_finding_codes.py b/tests/project/schemas/test_finding_codes.py new file mode 100644 index 0000000..47c163b --- /dev/null +++ b/tests/project/schemas/test_finding_codes.py @@ -0,0 +1,254 @@ +# +# 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 json +import weakref + +import pytest +from pydantic import ValidationError + +from dlccore.project.schemas.base.finding_codes import FindingCode, Severity, iter_finding_codes +from dlccore.project.schemas.base.findings import Finding, Reach + +_SCHEMA_ID = "dlc.videos.source_video" + + +def _declared_evidence(code: FindingCode) -> dict[str, str]: + """Return placeholder evidence satisfying one code's declared keys.""" + + return dict.fromkeys(code.evidence_keys, "placeholder") + + +def test_finding_keeps_a_declared_code_as_its_enum_member(example_codes: type[FindingCode]) -> None: + code = example_codes.TEST_NODE_WRONG_TYPE + + finding = Finding( + code=code, + schema_id=_SCHEMA_ID, + reach=Reach.ONE_PER_PROJECT, + evidence=_declared_evidence(code), + ) + + assert finding.code is code + assert finding.code == "TEST_NODE_WRONG_TYPE" + + +def test_finding_code_renders_as_the_bare_code(example_codes: type[FindingCode]) -> None: + code = example_codes.TEST_NODE_WRONG_TYPE + + assert str(code) == "TEST_NODE_WRONG_TYPE" + assert f"{code}" == "TEST_NODE_WRONG_TYPE" + assert ", ".join([code]) == "TEST_NODE_WRONG_TYPE" + + +def test_finding_rejects_an_undeclared_code() -> None: + with pytest.raises(ValidationError): + Finding( + code="NOT_A_DECLARED_CODE", + schema_id=_SCHEMA_ID, + reach=Reach.ONE_PER_PROJECT, + ) + + +def test_finding_severity_comes_from_its_code(example_codes: type[FindingCode]) -> None: + finding = Finding( + code=example_codes.TEST_NODE_UNREADABLE, + schema_id=_SCHEMA_ID, + reach=Reach.ONE_PER_PROJECT, + evidence=_declared_evidence(example_codes.TEST_NODE_UNREADABLE), + ) + + assert finding.severity is Severity.ERROR + assert finding.model_dump()["severity"] == Severity.ERROR + + +def test_finding_ignores_a_caller_supplied_severity(example_codes: type[FindingCode]) -> None: + finding = Finding( + code=example_codes.TEST_NODE_UNREADABLE, + schema_id=_SCHEMA_ID, + reach=Reach.ONE_PER_PROJECT, + severity=Severity.NOTE, + evidence=_declared_evidence(example_codes.TEST_NODE_UNREADABLE), + ) + + assert finding.severity is Severity.ERROR + + +def test_finding_requires_the_evidence_its_code_declares(example_codes: type[FindingCode]) -> None: + with pytest.raises(ValidationError, match="requires evidence keys"): + Finding( + code=example_codes.TEST_NODE_UNREADABLE, + schema_id=_SCHEMA_ID, + reach=Reach.ONE_PER_PROJECT, + ) + + +def test_finding_reports_only_the_missing_evidence_keys(example_codes: type[FindingCode]) -> None: + partial = _declared_evidence(example_codes.TEST_NODE_UNREADABLE) + del partial["error_message"] + + with pytest.raises(ValidationError, match=r"\('error_message',\)"): + Finding( + code=example_codes.TEST_NODE_UNREADABLE, + schema_id=_SCHEMA_ID, + reach=Reach.ONE_PER_PROJECT, + evidence=partial, + ) + + +def test_finding_accepts_declared_evidence_that_was_not_observed(example_codes: type[FindingCode]) -> None: + evidence: dict[str, str | None] = dict.fromkeys(example_codes.TEST_NODE_UNREADABLE.evidence_keys, None) + + finding = Finding( + code=example_codes.TEST_NODE_UNREADABLE, + schema_id=_SCHEMA_ID, + reach=Reach.ONE_PER_PROJECT, + evidence=evidence, + ) + + assert finding.evidence["error_message"] is None + + +def test_finding_round_trips_through_serialized_form(example_codes: type[FindingCode]) -> None: + finding = Finding( + code=example_codes.TEST_NODE_UNREADABLE, + schema_id=_SCHEMA_ID, + reach=Reach.ONE_PER_PROJECT, + evidence=_declared_evidence(example_codes.TEST_NODE_UNREADABLE), + ) + + restored = Finding.model_validate(json.loads(finding.model_dump_json())) + + assert restored == finding + assert restored.code is example_codes.TEST_NODE_UNREADABLE + + +def test_finding_rejects_an_undeclared_code_from_serialized_form() -> None: + with pytest.raises(ValidationError, match="Unknown finding code"): + Finding.model_validate({"code": "NOT_A_DECLARED_CODE"}) + + +@pytest.mark.parametrize("code", iter_finding_codes(), ids=str) +def test_every_finding_code_is_described(code: FindingCode) -> None: + assert code.value == code.name + assert code.description + assert isinstance(code.severity, Severity) + + +@pytest.mark.parametrize("code", iter_finding_codes(), ids=str) +def test_every_finding_code_declares_well_formed_evidence_keys(code: FindingCode) -> None: + """A code may declare none: ``path`` and ``field_location`` carry the location, and evidence never repeats it.""" + + assert len(set(code.evidence_keys)) == len(code.evidence_keys) + assert all(key and key.islower() for key in code.evidence_keys) + + +@pytest.mark.usefixtures("example_codes") +def test_finding_code_values_are_unique_across_namespaces() -> None: + codes = iter_finding_codes() + + assert len({code.value for code in codes}) == len(codes) + + +@pytest.mark.usefixtures("example_codes") +def test_iter_finding_codes_covers_every_namespace() -> None: + namespaces = {type(code) for code in iter_finding_codes()} + + assert namespaces == set(FindingCode.__subclasses__()) + + +@pytest.mark.xfail( + reason="the train-side split reconciliation is not built; when it is, delete this and add " + "a test under tests/upstream/ recording where ours intentionally differs from DeepLabCut's " + "`_validate_dataframes`, which is disabled and known incomplete", + strict=True, + raises=AssertionError, +) +def test_training_split_reconciliation_declares_a_finding_code() -> None: + assert "TRAINING_SPLIT_TABLE_MISMATCH" in {code.value for code in iter_finding_codes()} + + +_example_namespace: list[weakref.ref[type[FindingCode]]] = [] + + +def test_an_example_namespace_is_in_the_catalogue_during_its_test(example_codes: type[FindingCode]) -> None: + _example_namespace.append(weakref.ref(example_codes)) + + assert example_codes in FindingCode.__subclasses__() + + +def test_an_example_namespace_leaves_the_catalogue_after_its_test() -> None: + # Control for the closed-catalogue test below: the previous test's namespace is gone, not exempted. + assert _example_namespace + assert _example_namespace[0]() is 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__()) == set() + + +def test_severity_has_three_rungs() -> None: + assert {member.name for member in Severity} == {"NOTE", "WARNING", "ERROR"} + + +def test_schema_id_is_a_required_finding_field() -> None: + field = Finding.model_fields.get("schema_id") + + assert field is not None + assert field.is_required() + + +def test_instance_is_a_finding_field() -> None: + assert "instance" in Finding.model_fields + + +def test_a_finding_states_its_reach(example_codes: type[FindingCode]) -> None: + evidence = _declared_evidence(example_codes.TEST_NODE_UNREADABLE) + + def finding(reach: Reach, instance: tuple[str, ...]) -> Finding: + return Finding( + code=example_codes.TEST_NODE_UNREADABLE, + schema_id=_SCHEMA_ID, + reach=reach, + instance=instance, + evidence=evidence, + ) + + assert {member.name for member in Reach} == {"ONE_PER_PROJECT", "ONE_OF", "ALL_OF", "UNROOTED"} + + with pytest.raises(ValidationError): + finding(Reach.ONE_PER_PROJECT, ("videos", "m1.mp4")) + + with pytest.raises(ValidationError): + finding(Reach.ONE_OF, ()) + + with pytest.raises(ValidationError): + finding(Reach.UNROOTED, ()) + + assert finding(Reach.ONE_OF, ("videos", "m1.mp4")).reach is Reach.ONE_OF + assert finding(Reach.ALL_OF, ()).instance == () + assert finding(Reach.ALL_OF, ("labeled-data", "m2")).instance == ("labeled-data", "m2") + + +@pytest.mark.xfail( + reason="a released code must never disappear silently: renamed, merged or split codes are to " + "declare what they supersede; once they do, replace this with a tripwire over the released " + "code list that also requires a version bump whenever the catalogue changes", + strict=True, + raises=AssertionError, +) +@pytest.mark.usefixtures("example_codes") +def test_a_released_code_cannot_disappear_without_a_successor() -> None: + assert all(hasattr(code, "supersedes") for code in iter_finding_codes()) diff --git a/tests/project/schemas/test_layout_instance.py b/tests/project/schemas/test_layout_instance.py new file mode 100644 index 0000000..4f8d406 --- /dev/null +++ b/tests/project/schemas/test_layout_instance.py @@ -0,0 +1,87 @@ +# +# 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 json +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from dlccore.project.schemas.base.core import instance_from_path +from dlccore.project.schemas.base.finding_codes import FindingCode +from dlccore.project.schemas.base.findings import Finding, Reach + +_SCHEMA_ID = "dlc.labeled_data.dataset" + + +@pytest.fixture +def code(example_codes: type[FindingCode]) -> FindingCode: + return example_codes.TEST_NODE_UNREADABLE + + +@pytest.fixture +def evidence(code: FindingCode) -> dict[str, str]: + return dict.fromkeys(code.evidence_keys, "placeholder") + + +def test_a_finding_has_no_instance_by_default(code: FindingCode, evidence: dict[str, str]) -> None: + assert Finding(code=code, schema_id=_SCHEMA_ID, reach=Reach.ONE_PER_PROJECT, evidence=evidence).instance == () + + +def test_an_instance_serializes_as_a_plain_list(code: FindingCode, evidence: dict[str, str]) -> None: + finding = Finding( + code=code, schema_id=_SCHEMA_ID, reach=Reach.ONE_OF, instance=("labeled-data", "ds1"), evidence=evidence + ) + + assert json.loads(finding.model_dump_json())["instance"] == ["labeled-data", "ds1"] + + +@pytest.mark.parametrize("segment", ["", "labeled-data/ds1"], ids=["empty", "joined"]) +def test_an_instance_refuses_a_segment_only_a_caller_can_produce( + segment: str, code: FindingCode, evidence: dict[str, str] +) -> None: + with pytest.raises(ValidationError, match="project-relative path segment"): + Finding( + code=code, schema_id=_SCHEMA_ID, reach=Reach.ONE_OF, instance=("labeled-data", segment), evidence=evidence + ) + + +@pytest.mark.parametrize("segment", ["..", "12:30.mp4", "a\\b.mp4"]) +def test_an_instance_keeps_user_data_segments(segment: str, code: FindingCode, evidence: dict[str, str]) -> None: + assert Finding( + code=code, schema_id=_SCHEMA_ID, reach=Reach.ONE_OF, instance=("videos", segment), evidence=evidence + ).instance == ( + "videos", + segment, + ) + + +@pytest.mark.parametrize( + "instance", + [("C:\\", "x.mp4"), ("\\\\server\\share\\", "x.mp4"), ("C:rel", "x.mp4")], + ids=["drive-root", "unc-share", "drive-relative"], +) +def test_an_instance_refuses_segments_that_carry_a_drive_or_root( + instance: tuple[str, ...], code: FindingCode, evidence: dict[str, str] +) -> None: + with pytest.raises(ValidationError, match="project-relative"): + Finding(code=code, schema_id=_SCHEMA_ID, reach=Reach.ONE_OF, instance=instance, evidence=evidence) + + +def test_instance_from_path_splits_a_project_relative_path() -> None: + assert instance_from_path(Path("labeled-data/ds1/img001.png")) == ("labeled-data", "ds1", "img001.png") + + +def test_instance_from_path_refuses_an_anchored_path() -> None: + with pytest.raises(ValueError, match="project-relative"): + instance_from_path(Path("Z:/shared/DLC/videos/a.mp4"))