diff --git a/src/ndi/database.py b/src/ndi/database.py index 72f6327b..8aab7c6f 100644 --- a/src/ndi/database.py +++ b/src/ndi/database.py @@ -109,8 +109,12 @@ def __init__(self, db_path: Path, branch_id: str = "a"): f"{sorted(existing_branches)} but not {branch_id!r}." ) - def add(self, document: dict) -> None: - """Add a document to the database.""" + def add(self, document: dict, *, validate: bool = True) -> None: + """Add a document to the database. + + ``validate`` is passed to ``did.database.add_docs``; see + :meth:`ndi_database.add`. + """ doc_id = document.get("base", {}).get("id", "") if not doc_id: raise ValueError("ndi_document must have a base.id") @@ -122,7 +126,12 @@ def add(self, document: dict) -> None: # Create DID ndi_document and add (DID-python now populates doc_data) did_doc = self._DIDDocument(document) - self._db.add_docs([did_doc], self._branch_id, custom_file_handler=_cloud_file_handler) + self._db.add_docs( + [did_doc], + self._branch_id, + validate=validate, + custom_file_handler=_cloud_file_handler, + ) def bulk_add(self, documents: list[dict]) -> tuple[int, int]: """Add many documents at once, bypassing per-doc duplicate checks. @@ -304,11 +313,16 @@ def binary_path(self) -> Path: # === CRUD Operations === - def add(self, document: ndi_document) -> ndi_document: + def add(self, document: ndi_document, *, validate: bool = True) -> ndi_document: """Add a document to the database. Args: document: The ndi_document to add. + validate: If True (default), check the document against its schema + before adding it. Set False to skip this (slow) step for + documents already known to be valid, such as those downloaded + from NDI Cloud. Mirrors MATLAB ``ndi.database/add``'s + ``'Validate'`` name/value pair. Returns: The added document. @@ -321,7 +335,7 @@ def add(self, document: ndi_document) -> ndi_document: db.add(doc) """ try: - self._driver.add(document.document_properties) + self._driver.add(document.document_properties, validate=validate) except FileExistsError as exc: raise ValueError( f"ndi_document with ID {document.id} already exists. " @@ -515,11 +529,18 @@ def find_dependencies(self, document: ndi_document | str) -> list[ndi_document]: # === Batch Operations === - def add_many(self, documents: list[ndi_document]) -> list[ndi_document]: + def add_many( + self, documents: list[ndi_document], *, validate: bool = True + ) -> list[ndi_document]: """Add multiple documents. Args: documents: List of Documents to add. + validate: If True (default), check the documents against their + schemas before adding them. Set False to skip this (slow) step + for documents already known to be valid, such as those + downloaded from NDI Cloud. Mirrors MATLAB ``ndi.database/add``'s + ``'Validate'`` name/value pair. Returns: List of added Documents. @@ -546,6 +567,7 @@ def add_many(self, documents: list[ndi_document]) -> list[ndi_document]: self._driver._db.add_docs( did_docs, self._driver._branch_id, + validate=validate, custom_file_handler=_cloud_file_handler, ) return list(documents) diff --git a/src/ndi/dataset/_dataset.py b/src/ndi/dataset/_dataset.py index 001d5975..b5c7691e 100644 --- a/src/ndi/dataset/_dataset.py +++ b/src/ndi/dataset/_dataset.py @@ -1327,8 +1327,14 @@ def __init__( # A batch add is atomic, so on failure it falls back to per-document # adds to find out which ones are bad -- add_doc_failures has to # name them, not just report that something went wrong. + # + # Schema validation is skipped (validate=False), as MATLAB does + # (NDI-matlab#1240): these documents come from an existing dataset, + # e.g. one downloaded from NDI Cloud, and were validated when they + # were first added. Validating them again is slow for large + # datasets and unnecessary. try: - self._session._database.add_many(documents) + self._session._database.add_many(documents, validate=False) except Exception as batch_exc: # The batch is validated as a unit, so one bad document takes # the whole set down. Record *that* reason first: it is the @@ -1338,7 +1344,7 @@ def __init__( self.add_doc_failures.append(("", str(batch_exc))) for doc in documents: try: - self._session._database.add(doc) + self._session._database.add(doc, validate=False) except Exception as exc: doc_id = self._get_doc_id(doc) self.add_doc_failures.append((doc_id, str(exc))) diff --git a/src/ndi/dataset/ndi_matlab_python_bridge.yaml b/src/ndi/dataset/ndi_matlab_python_bridge.yaml index a085a2c2..52933e9d 100644 --- a/src/ndi/dataset/ndi_matlab_python_bridge.yaml +++ b/src/ndi/dataset/ndi_matlab_python_bridge.yaml @@ -388,7 +388,7 @@ classes: - name: dir type: class matlab_path: "+ndi/+dataset/dir.m" - matlab_last_sync_hash: "26d0638bf" + matlab_last_sync_hash: "400277e44" python_path: "ndi/dataset/_dataset.py" python_class: "ndi_dataset_dir" inherits: "ndi.dataset" @@ -430,6 +430,10 @@ classes: decision_log: > Python constructor supports MATLAB calling conventions: dir(path), dir(reference, path), dir(reference, path, docs). + The docs form adds the documents without schema validation + (add_many(..., validate=False)), as MATLAB does since + NDI-matlab#1240: they were validated when first added. + Synchronized 2026-11-13. static_methods: - name: dataset_erase diff --git a/src/ndi/ndi_matlab_python_bridge_database.yaml b/src/ndi/ndi_matlab_python_bridge_database.yaml index 1f2bc503..df9635c5 100644 --- a/src/ndi/ndi_matlab_python_bridge_database.yaml +++ b/src/ndi/ndi_matlab_python_bridge_database.yaml @@ -17,7 +17,7 @@ classes: - name: database type: class matlab_path: "+ndi/database.m" - matlab_last_sync_hash: "d3c556e89" + matlab_last_sync_hash: "400277e44" python_path: "ndi/database.py" python_class: "ndi_database" @@ -90,6 +90,10 @@ classes: type_matlab: "logical (name-value)" type_python: "bool" default: "True" + - name: Validate + type_matlab: "logical (name-value)" + type_python: "bool (keyword-only, spelled validate)" + default: "True" output_arguments: - name: ndi_database_obj type_python: "ndi_database" @@ -98,6 +102,11 @@ classes: that controls whether an existing document is updated or errors. Python separates this into add() (error on duplicate) and add_or_replace() (upsert). Synchronized 2026-03-13. + MATLAB's 'Validate' name-value pair (default 1, NDI-matlab#1240) + is Python's keyword-only validate=True, spelled to match the + validate parameter of DID-python's add_docs that it is passed to. + False skips schema validation, for documents already known to be + valid (e.g. downloaded from NDI Cloud). Synchronized 2026-11-13. - name: read input_arguments: @@ -273,12 +282,18 @@ classes: input_arguments: - name: documents type_python: "list[ndi_document]" + - name: validate + type_python: "bool (keyword-only)" + default: "True" output_arguments: - name: added_docs type_python: "list[ndi_document]" decision_log: > Python convenience. Batch add. Stops on first error. Synchronized 2026-03-13. + validate mirrors add()'s; ndi_dataset_dir(..., documents=...) + passes False, as MATLAB's ndi.dataset.dir(reference, path, docs) + does (NDI-matlab#1240). Synchronized 2026-11-13. - name: remove_many input_arguments: diff --git a/tests/test_add_validate.py b/tests/test_add_validate.py new file mode 100644 index 00000000..a8da208d --- /dev/null +++ b/tests/test_add_validate.py @@ -0,0 +1,101 @@ +"""Schema validation can be skipped on add; building a dataset from documents skips it. + +Mirrors NDI-matlab#1240: ``ndi.database/add`` takes a ``'Validate'`` name/value +pair (default 1) that is passed to ``did.database/add_docs``, and +``ndi.dataset.dir(reference, path_name, docs)`` -- the path ``downloadDataset`` +takes -- adds the documents with ``'Validate', false``. Those documents were +validated when they were first added; validating them again is slow for large +datasets and unnecessary. +""" + +from unittest.mock import patch + +import pytest + +from ndi.document import ndi_document + + +def _subject_and_element(): + """An element and the subject it requires. Added alone, the element fails + validation (dangling ``subject_id`` dependency), which makes the check + observable.""" + subject = ndi_document("subject", **{"base.name": "s"}) + element = ndi_document( + "element", + **{"base.name": "e", "element.type": "probe", "element.reference": 1}, + ) + element = element.set_dependency_value("subject_id", subject.id) + return subject, element + + +class TestValidateOption: + def test_add_validates_by_default(self, tmp_path): + from did.validate import ValidationError + + from ndi.database import ndi_database + + db = ndi_database(tmp_path) + _subject, element = _subject_and_element() + with pytest.raises(ValidationError): + db.add(element) + + def test_add_with_validate_false_skips_validation(self, tmp_path): + from ndi.database import ndi_database + + db = ndi_database(tmp_path) + _subject, element = _subject_and_element() + db.add(element, validate=False) + assert db.read(element.id) is not None + + @pytest.mark.parametrize("validate", [True, False]) + def test_add_many_passes_validate_to_did(self, tmp_path, validate): + from ndi.database import ndi_database + + db = ndi_database(tmp_path) + subject, element = _subject_and_element() + with patch.object(db._driver._db, "add_docs") as mock_add: + db.add_many([element, subject], validate=validate) + assert mock_add.call_args.kwargs.get("validate") is validate + + def test_add_many_validates_by_default(self, tmp_path): + from ndi.database import ndi_database + + db = ndi_database(tmp_path) + subject, element = _subject_and_element() + with patch.object(db._driver._db, "add_docs") as mock_add: + db.add_many([element, subject]) + assert mock_add.call_args.kwargs.get("validate") is True + + +class TestDatasetFromDocumentsSkipsValidation: + def test_dataset_build_does_not_validate_documents(self, tmp_path): + """The path downloadDataset takes: ndi_dataset_dir(..., documents=...).""" + from did.database import Database + + from ndi.dataset import ndi_dataset_dir + + subject, element = _subject_and_element() + target = tmp_path / "ds" + target.mkdir() + + offered = {subject.id, element.id} + validated_ids = set() + original = Database.validate_docs + + def spy(self, document_objs, *args, **kwargs): + for d in document_objs if isinstance(document_objs, list) else [document_objs]: + props = getattr(d, "document_properties", d) + validated_ids.add(props.get("base", {}).get("id", "")) + return original(self, document_objs, *args, **kwargs) + + with patch.object(Database, "validate_docs", spy): + dataset = ndi_dataset_dir("", target, documents=[element, subject]) + + assert dataset.add_doc_failures == [], dataset.add_doc_failures + assert not (validated_ids & offered), "downloaded documents were re-validated" + stored = set( + dataset._session._database._driver._db.get_doc_ids( + dataset._session._database._driver._branch_id + ) + ) + assert offered <= stored