Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/ndi/cloud/orchestration.py
Original file line number Diff line number Diff line change
Expand Up @@ -984,7 +984,9 @@ def _sync_download_new(
failures: list[tuple[str, str]] = []
for doc in documents:
try:
dataset.database_add(doc)
# A cloud document is the same document coming back, so restore
# one that was deleted locally (NDI-matlab#1238).
dataset.database_add(doc, restore_deleted_id=True)
added += 1
except Exception as exc:
doc_id = getattr(doc, "id", None) or "<unknown>"
Expand Down
2 changes: 1 addition & 1 deletion src/ndi/cloud/sync/ndi_matlab_python_bridge.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -620,7 +620,7 @@ functions:

- name: downloadNdiDocuments
matlab_path: "+ndi/+cloud/+sync/+internal/downloadNdiDocuments.m"
matlab_last_sync_hash: "9467a0a7"
matlab_last_sync_hash: "4930b5dd"
python_path: "ndi/cloud/sync/operations.py"
input_arguments:
- name: cloud_dataset_id
Expand Down
7 changes: 6 additions & 1 deletion src/ndi/cloud/sync/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,12 @@ def _ingest_downloaded_docs(dataset: Any, saved_properties: list[dict[str, Any]]
from ..download import structsToNdiDocuments

try:
add(structsToNdiDocuments(saved_properties))
# restore_deleted_id: a document fetched from the cloud is the same
# document the remote holds, so if it was once here and was deleted
# locally, bringing it back is a restore, not a re-use of its id.
# Without it DID refuses the add and a mirror after a local delete
# fails (NDI-matlab#1238; downloadNdiDocuments does the same).
add(structsToNdiDocuments(saved_properties), restore_deleted_id=True)
except Exception as exc: # noqa: BLE001 - the JSON is already written
logger.warning(
"Downloaded %d document(s) but could not add them to the database: %s",
Expand Down
50 changes: 44 additions & 6 deletions src/ndi/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,19 @@ def _cloud_file_handler(dest_path, source_path, context=None):
download_file_from_cloud(dest_path, source_path, context)


def _on_deleted_id_kwargs(restore_deleted_id: bool) -> dict:
"""DID's ``OnDeletedId`` argument for a RestoreDeletedId request.

DID retires the id of a document removed from every branch and refuses
it ever after (``did.database.add_docs`` raises). A caller restoring that
same document -- the cloud sync re-downloading one deleted locally,
NDI-matlab#1238 -- asks for ``OnDeletedId="restore"``. Passed only when
requested, as NDI-matlab's didsqlite/do_add does, so the default call is
unchanged.
"""
return {"OnDeletedId": "restore"} if restore_deleted_id else {}


class SQLiteDriver:
"""SQLite database driver using DID-python's SQLiteDB.

Expand Down Expand Up @@ -109,11 +122,13 @@ def __init__(self, db_path: Path, branch_id: str = "a"):
f"{sorted(existing_branches)} but not {branch_id!r}."
)

def add(self, document: dict, *, validate: bool = True) -> None:
def add(
self, document: dict, *, validate: bool = True, restore_deleted_id: bool = False
) -> None:
"""Add a document to the database.

``validate`` is passed to ``did.database.add_docs``; see
:meth:`ndi_database.add`.
``validate`` and ``restore_deleted_id`` are passed to
``did.database.add_docs``; see :meth:`ndi_database.add`.
"""
doc_id = document.get("base", {}).get("id", "")
if not doc_id:
Expand All @@ -131,6 +146,7 @@ def add(self, document: dict, *, validate: bool = True) -> None:
self._branch_id,
validate=validate,
custom_file_handler=_cloud_file_handler,
**_on_deleted_id_kwargs(restore_deleted_id),
)

def bulk_add(self, documents: list[dict]) -> tuple[int, int]:
Expand Down Expand Up @@ -313,7 +329,13 @@ def binary_path(self) -> Path:

# === CRUD Operations ===

def add(self, document: ndi_document, *, validate: bool = True) -> ndi_document:
def add(
self,
document: ndi_document,
*,
validate: bool = True,
restore_deleted_id: bool = False,
) -> ndi_document:
"""Add a document to the database.

Args:
Expand All @@ -323,6 +345,12 @@ def add(self, document: ndi_document, *, validate: bool = True) -> ndi_document:
documents already known to be valid, such as those downloaded
from NDI Cloud. Mirrors MATLAB ``ndi.database/add``'s
``'Validate'`` name/value pair.
restore_deleted_id: If True, a document whose id was previously
removed from the database is restored rather than refused
(DID retires deleted ids). Use only when the document is the
same document coming back, e.g. re-downloaded from the cloud
(NDI-matlab#1238). Mirrors MATLAB ``ndi.database/add``'s
``'RestoreDeletedId'`` name/value pair.

Returns:
The added document.
Expand All @@ -335,7 +363,11 @@ def add(self, document: ndi_document, *, validate: bool = True) -> ndi_document:
db.add(doc)
"""
try:
self._driver.add(document.document_properties, validate=validate)
self._driver.add(
document.document_properties,
validate=validate,
restore_deleted_id=restore_deleted_id,
)
except FileExistsError as exc:
raise ValueError(
f"ndi_document with ID {document.id} already exists. "
Expand Down Expand Up @@ -530,7 +562,11 @@ def find_dependencies(self, document: ndi_document | str) -> list[ndi_document]:
# === Batch Operations ===

def add_many(
self, documents: list[ndi_document], *, validate: bool = True
self,
documents: list[ndi_document],
*,
validate: bool = True,
restore_deleted_id: bool = False,
) -> list[ndi_document]:
"""Add multiple documents.

Expand All @@ -541,6 +577,7 @@ def add_many(
for documents already known to be valid, such as those
downloaded from NDI Cloud. Mirrors MATLAB ``ndi.database/add``'s
``'Validate'`` name/value pair.
restore_deleted_id: As in :meth:`add`.

Returns:
List of added Documents.
Expand Down Expand Up @@ -569,6 +606,7 @@ def add_many(
self._driver._branch_id,
validate=validate,
custom_file_handler=_cloud_file_handler,
**_on_deleted_id_kwargs(restore_deleted_id),
)
return list(documents)

Expand Down
16 changes: 13 additions & 3 deletions src/ndi/dataset/_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,11 +537,21 @@ def session_list(
# ndi_database Operations (delegated to internal session)
# =========================================================================

def database_add(self, document: ndi_document | list[ndi_document]) -> ndi_dataset:
def database_add(
self,
document: ndi_document | list[ndi_document],
*,
restore_deleted_id: bool = False,
) -> ndi_dataset:
"""Add document(s) to the dataset database.

MATLAB equivalent: ``ndi.dataset/database_add``

``restore_deleted_id`` allows a document whose id was previously
deleted to be added again; use it only when restoring that same
document, e.g. from the cloud (NDI-matlab#1238). MATLAB's
``'RestoreDeletedId'``.

Routes documents to the appropriate session based on their
``base.session_id``. Documents whose session_id matches the
dataset's id go through the session's database_add (which
Expand All @@ -559,10 +569,10 @@ def database_add(self, document: ndi_document | list[ndi_document]) -> ndi_datas
sid = doc.session_id
if not sid or sid == empty_id() or sid == ds_id:
# Belongs to the dataset's own session
self._session.database_add(doc)
self._session.database_add(doc, restore_deleted_id=restore_deleted_id)
else:
# Belongs to another session - add directly to database
self._session._database.add(doc)
self._session._database.add(doc, restore_deleted_id=restore_deleted_id)
return self

def database_rm(
Expand Down
15 changes: 13 additions & 2 deletions src/ndi/dataset/ndi_matlab_python_bridge.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ classes:
- name: dataset
type: class
matlab_path: "+ndi/dataset.m"
matlab_last_sync_hash: "f3940dbc"
matlab_last_sync_hash: "4930b5dd"
python_path: "ndi/dataset/_dataset.py"
python_class: "ndi_dataset"
decision_log: >
Expand Down Expand Up @@ -235,10 +235,21 @@ classes:
- name: document
type_matlab: "ndi.document | cell"
type_python: "ndi_document | list[ndi_document]"
- name: RestoreDeletedId
type_matlab: "logical (name-value)"
type_python: "bool (keyword-only, spelled restore_deleted_id)"
default: "False"
output_arguments:
- name: ndi_dataset_obj
type_python: "ndi_dataset"
decision_log: "Exact match."
decision_log: >
Exact match. MATLAB's
'RestoreDeletedId' name-value pair (default false, NDI-matlab#1238)
is Python's keyword-only restore_deleted_id=False, snake_cased like
error_if_not_found. True lets a document whose id DID retired on
deletion be added again, for the same document being restored (the
cloud sync's downloads); it maps to DID's OnDeletedId="restore".
Synchronized 2026-11-13.

- name: database_rm
input_arguments:
Expand Down
14 changes: 12 additions & 2 deletions src/ndi/ndi_matlab_python_bridge_database.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ classes:
- name: database
type: class
matlab_path: "+ndi/database.m"
matlab_last_sync_hash: "400277e44"
matlab_last_sync_hash: "b5e629c0"
python_path: "ndi/database.py"
python_class: "ndi_database"

Expand Down Expand Up @@ -94,6 +94,10 @@ classes:
type_matlab: "logical (name-value)"
type_python: "bool (keyword-only, spelled validate)"
default: "True"
- name: RestoreDeletedId
type_matlab: "logical (name-value)"
type_python: "bool (keyword-only, spelled restore_deleted_id)"
default: "False"
output_arguments:
- name: ndi_database_obj
type_python: "ndi_database"
Expand All @@ -106,7 +110,13 @@ classes:
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.
valid (e.g. downloaded from NDI Cloud). Synchronized 2026-11-13. MATLAB's
'RestoreDeletedId' name-value pair (default false, NDI-matlab#1238)
is Python's keyword-only restore_deleted_id=False, snake_cased like
error_if_not_found. True lets a document whose id DID retired on
deletion be added again, for the same document being restored (the
cloud sync's downloads); it maps to DID's OnDeletedId="restore".
Synchronized 2026-11-13.

- name: read
input_arguments:
Expand Down
15 changes: 13 additions & 2 deletions src/ndi/session/ndi_matlab_python_bridge.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ classes:
- name: session
type: class
matlab_path: "+ndi/session.m"
matlab_last_sync_hash: "81cbfd61"
matlab_last_sync_hash: "4930b5dd"
python_path: "ndi/session/session_base.py"
python_class: "ndi_session"

Expand Down Expand Up @@ -182,10 +182,21 @@ classes:
- name: document
type_matlab: "ndi.document | cell"
type_python: "ndi_document | list[ndi_document]"
- name: RestoreDeletedId
type_matlab: "logical (name-value)"
type_python: "bool (keyword-only, spelled restore_deleted_id)"
default: "False"
output_arguments:
- name: ndi_session_obj
type_python: "ndi_session"
decision_log: "Exact match."
decision_log: >
Exact match. MATLAB's
'RestoreDeletedId' name-value pair (default false, NDI-matlab#1238)
is Python's keyword-only restore_deleted_id=False, snake_cased like
error_if_not_found. True lets a document whose id DID retired on
deletion be added again, for the same document being restored (the
cloud sync's downloads); it maps to DID's OnDeletedId="restore".
Synchronized 2026-11-13.

- name: database_rm
input_arguments:
Expand Down
15 changes: 13 additions & 2 deletions src/ndi/session/session_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,12 +409,23 @@ def daqsystem_clear(self) -> ndi_session:
# ndi_database Methods
# =========================================================================

def database_add(self, document: ndi_document | list[ndi_document]) -> ndi_session:
def database_add(
self,
document: ndi_document | list[ndi_document],
*,
restore_deleted_id: bool = False,
) -> ndi_session:
"""
Add a document to the session database.

MATLAB equivalent: ``ndi.session/database_add``

Args:
document: ndi_document or list of Documents to add
restore_deleted_id: Allow a document whose id was previously
deleted from this session to be added again. Use only when
restoring that same document, e.g. from the cloud
(NDI-matlab#1238). MATLAB's ``'RestoreDeletedId'``.

Returns:
self for chaining
Expand All @@ -440,7 +451,7 @@ def database_add(self, document: ndi_document | list[ndi_document]) -> ndi_sessi
if not session_id or session_id == empty_id():
doc = doc.set_session_id(self.id())

self._database.add(doc)
self._database.add(doc, restore_deleted_id=restore_deleted_id)

return self

Expand Down
2 changes: 1 addition & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def getpath(self):
def database_search(self, query=None):
return list(self.documents)

def database_add(self, document):
def database_add(self, document, *, restore_deleted_id=False):
"""Ingest downloaded documents, as ndi.dataset.database_add does.

A download that never reaches the database is not local, so without
Expand Down
69 changes: 69 additions & 0 deletions tests/test_restore_deleted_document.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"""A document deleted locally can be restored, for the cloud sync (NDI-matlab#1238).

DID retires the id of a document removed from every branch and refuses it
ever after. A cloud mirror that re-downloads a document deleted locally is
bringing back the SAME document, so the download path passes
``restore_deleted_id=True`` -- MATLAB's ``'RestoreDeletedId'`` -- which maps to
DID's ``OnDeletedId="restore"``.

MATLAB counterparts: ``tests/+ndi/+unittest/+database/TestRestoreDeletedDocument.m``
and ``MirrorFromRemoteTest/testMirrorRestoresLocallyDeletedDocument``.
"""

from __future__ import annotations

import pytest

from ndi.cloud.sync.operations import _ingest_downloaded_docs
from ndi.dataset import ndi_dataset_dir
from ndi.document import ndi_document
from ndi.query import ndi_query
from ndi.session.dir import ndi_session_dir


@pytest.fixture
def session(tmp_path):
session_dir = tmp_path / "session"
session_dir.mkdir()
return ndi_session_dir("restoreTest", session_dir)


def _found(container, doc_id):
return container.database_search(ndi_query("base.id") == doc_id)


class TestSessionDatabaseAdd:
def test_a_deleted_id_is_refused_by_default(self, session):
doc = session.newdocument("base", **{"base.name": "restoreMe"})
session.database_add(doc)
session.database_rm(doc.id)

with pytest.raises(ValueError, match="previously removed"):
session.database_add(doc)

def test_a_deleted_document_can_be_restored(self, session):
doc = session.newdocument("base", **{"base.name": "restoreMe"})
session.database_add(doc)
session.database_rm(doc.id)

session.database_add(doc, restore_deleted_id=True)

found = _found(session, doc.id)
assert len(found) == 1
assert found[0].document_properties["base"]["name"] == "restoreMe"


class TestCloudDownloadRestores:
def test_ingesting_a_download_restores_a_locally_deleted_document(self, tmp_path):
"""The ingestion step every cloud sync mode uses brings it back."""
dataset_dir = tmp_path / "ds"
dataset_dir.mkdir()
dataset = ndi_dataset_dir("restoreDs", str(dataset_dir))
doc = ndi_document("base", **{"base.name": "restoreMe"}).set_session_id(dataset.id())
dataset.database_add(doc)
dataset.database_rm(doc.id)
assert _found(dataset, doc.id) == []

_ingest_downloaded_docs(dataset, [doc.document_properties])

assert len(_found(dataset, doc.id)) == 1
Loading