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
25 changes: 25 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,31 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

### Fixed

- **A lightsheet build resumes from documents read back from the cloud**
(`ndi.cloud.session_writer.SessionWriter`,
`ndi.fun.doc_lightsheet.makePyramid`, MATLAB VH-Lab/NDI-matlab#1296).
DID strips series `ingest_locations` before storing, so an adopted
document downloaded from NDI Cloud showed no member uids:
`missingMembers` reported every chunk present and nothing lost was
rebuilt, and a level reduced from an adopted level could not open its
chunks. The writer now rebuilds the uids from each series' manifest
(downloaded into the cache; an error if it is missing or unreadable), and
a resumed build skips a reduced level whose chunks are all in the cloud
before resolving its source.

- **Bulk document uploads are split by size, and a failed ingestion is
reported** (`ndi.cloud.upload.uploadDocumentCollection`, MATLAB
VH-Lab/NDI-matlab#1247). A 100,000-document upload went out as one 638 MB
JSON file in one zip; the server's ingestion Lambda ran out of scratch disk
and ingested nothing, while the upload reported success. Batches now also
end at `max_bytes` of JSON (new preference
`Cloud.Upload.Max_Document_Batch_Size`, default 50 MB; helper
`documentBatchRanges`), each document is encoded once, and if the server
lists none of the stored documents when the ingestion wait ends, the report
says so: `status` `'partial'`, `uploaded` 0, the ids in `not_ingested`
instead of `manifest`, and `ingestion['state']` `'failed'`, so a sync does
not record them as uploaded.

- **Recomputing stimulus responses replaced nothing** when the prestimulus
parameters were empty (the default): the parameter document lookup never
matched, so each run added new responses beside the old ones. Empty
Expand Down
61 changes: 58 additions & 3 deletions src/ndi/cloud/ndi_matlab_python_bridge.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -897,7 +897,7 @@ functions:
# --- upload.py functions ---
- name: uploadDocumentCollection
matlab_path: "+ndi/+cloud/+upload/uploadDocumentCollection.m"
matlab_last_sync_hash: "004585c"
matlab_last_sync_hash: "ec25d3c"
python_path: "ndi/cloud/upload.py"
input_arguments:
- name: dataset_id
Expand All @@ -913,6 +913,10 @@ functions:
- name: max_chunk
type_python: "int | None"
default: "None"
- name: max_bytes
type_matlab: "double (maxDocumentBytes)"
type_python: "float | None"
default: "None"
- name: wait_for_ingestion
type_matlab: "logical"
type_python: "bool"
Expand Down Expand Up @@ -967,6 +971,21 @@ functions:
the others -- resolved to "", so the manifest came back as a list of empty
strings and no caller could tell which documents had landed. Found wiring
the sync path to send real documents (NDI-python#232).
2026-11-14: synchronized with NDI-matlab ec25d3c (VH-Lab/NDI-matlab#1247). A 100,000-document
upload went out as ONE 638 MB JSON file in one zip; the server's ingestion
Lambda ran out of scratch disk (ENOSPC) and ingested nothing, and the client
only warned that the server "may still be ingesting". Two changes, as in
MATLAB: (1) batches also end at max_bytes of encoded JSON (MATLAB
maxDocumentBytes; default the new preference Cloud.Upload.Max_Document_Batch_Size,
50 MB), split by documentBatchRanges; each document is encoded once and the
JSON passed to zip_documents_for_upload. max_bytes is keyword-only so the
existing positional order is unchanged. (2) If the ingestion wait ends with
the server listing no more documents than before, the ingestion is treated
as failed: MATLAB marks the stored batches 'failure' and returns b=false;
here status is 'partial', uploaded 0, manifest emptied (ids moved to
not_ingested -- sync's _upload_documents reads the manifest, as MATLAB's
uploadedDocumentIds reads the statuses), ingestion['state'] 'failed', and
the reason goes to errors and the log. A partial count still only warns.

- name: zipForUpload
matlab_path: "+ndi/+cloud/+upload/zipForUpload.m"
Expand Down Expand Up @@ -1932,9 +1951,36 @@ porting_deferred:
Python CLI session has no UI). The MATLAB profileEditor GUI is a
separate workstream.

- name: documentBatchRanges
matlab_path: "+ndi/+cloud/+upload/+internal/documentBatchRanges.m"
matlab_last_sync_hash: "ec25d3c"
python_path: "ndi/cloud/upload.py"
input_arguments:
- name: document_sizes
type_matlab: "double (1,:)"
type_python: "list[float]"
- name: max_count
type_matlab: "double"
type_python: "float"
- name: max_bytes
type_matlab: "double"
type_python: "float"
output_arguments:
- name: ranges
type_matlab: "cell (1,N) of index row vectors"
type_python: "list[list[int]]"
decision_log: >
2026-11-14: new in NDI-matlab ec25d3c (VH-Lab/NDI-matlab#1247). Splits a
bulk document upload into batches capped by count and by encoded JSON
size; an oversized document gets a batch of its own. Lives in
ndi.cloud.upload beside its one caller, like zip_documents_for_upload.
Indexes are 0-based here (internal data structure) where MATLAB's are
1-based; the batches themselves are identical. Non-positive caps raise
ValueError (MATLAB's arguments block rejects them with mustBePositive).

- name: zip_documents_for_upload
matlab_path: "+ndi/+cloud/+upload/+internal/zip_documents_for_upload.m"
matlab_last_sync_hash: "c6aef552"
matlab_last_sync_hash: "ec25d3c"
python_path: "ndi/cloud/upload.py"
input_arguments:
- name: documents
Expand All @@ -1947,6 +1993,10 @@ porting_deferred:
type_matlab: "string"
type_python: "str | Path | None"
default: "None"
- name: document_json
type_matlab: "cell (DocumentJson)"
type_python: "list[str] | None"
default: "None"
output_arguments:
- name: zip_path
type_python: "Path"
Expand All @@ -1963,6 +2013,11 @@ porting_deferred:
an internal subpackage, next to its one caller. Python's own zip entry
name is random hex rather than ndi.file.temp_name's; the server reads
the archive's single .json, whatever it is called.
2026-11-14: NDI-matlab ec25d3c (VH-Lab/NDI-matlab#1247) adds the DocumentJson option;
ported as keyword-only document_json (list[str]): the documents' already-
encoded JSON, joined into the same top-level array instead of encoding
again. A length mismatch raises ValueError (MATLAB: an assert with id
NDI:Cloud:Upload:DocumentJsonMismatch).
# =======================================================================
# +ndi/+cloud/+ui - MATLAB's cloud dialogs.
#
Expand Down Expand Up @@ -2210,7 +2265,7 @@ porting_deferred:
- name: SessionWriter
type: class
matlab_path: "+ndi/+cloud/+upload/SessionWriter.m"
matlab_last_sync_hash: "dab56894c"
matlab_last_sync_hash: "a469501c1"
python_path: "ndi/cloud/session_writer.py"
python_class: "SessionWriter"
properties:
Expand Down
83 changes: 77 additions & 6 deletions src/ndi/cloud/session_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,9 @@ def __init__(
self._lagging: list[dict] = []
self._warnedUrls = False
self._declaredUids: dict[str, list[str]] = {}
# docid -> series_info with member uids rebuilt from the manifests,
# for adopted documents read back from the cloud (see _seriesWithUids).
self._adoptedSeries: dict[str, list[dict]] = {}
self._retainedPaths: dict[str, list[str]] = {}
self._replaceAtCommit: list[Any] = []
self._fresh: set[str] = set()
Expand Down Expand Up @@ -770,10 +773,14 @@ def declare(self, doc: Any) -> None:
def adopt(self, doc: Any) -> None:
"""Take on a document an earlier run already put in the cloud.

For resuming: DOC (as it was declared or added, series member uids
included) is treated as uploaded -- a dependency other documents
may name and, if it has a series, a declared document whose members
streamMembers may send and COMMIT will check. Nothing is uploaded.
For resuming: DOC is treated as uploaded -- a dependency other
documents may name and, if it has a series, a declared document
whose members streamMembers may send, COMMIT will check and
database_openbinarydoc can download. Nothing is uploaded. DOC may be
the document as the earlier run declared it, or as read back from
the cloud: a stored document has its series' ingest_locations
stripped, so its member uids are rebuilt from each series' manifest
(see _seriesWithUids).
"""
doc = self._ownSession(doc)
self._registerSeries(doc)
Expand All @@ -785,7 +792,7 @@ def missingMembers(self, doc: Any, seriesName: str) -> list[int]:
Returns the one-based member indices whose uid the dataset does not
report as uploaded. A resumed run builds only these.
"""
si = next((s for s in _series_info_of(doc) if str(s.get("name")) == seriesName), None)
si = next((s for s in self._seriesWithUids(doc) if str(s.get("name")) == seriesName), None)
if si is None:
return []
locs = [L for L in _as_list(si.get("ingest_locations")) if isinstance(L, dict)]
Expand Down Expand Up @@ -901,7 +908,7 @@ def _registerSeries(self, doc: Any) -> None:
"""Record a document's series member uids as promised (declare, adopt)."""
docId = _doc_id(doc)
promised: list[str] = []
for si in _series_info_of(doc):
for si in self._seriesWithUids(doc):
for L in _as_list(si.get("ingest_locations")):
if not isinstance(L, dict):
continue
Expand All @@ -910,6 +917,70 @@ def _registerSeries(self, doc: Any) -> None:
promised.append(uid)
self._declaredUids[docId] = promised

def _seriesWithUids(self, doc: Any) -> list[dict]:
"""DOC's series_info with every present member's uid.

A document as declared carries them in ingest_locations; a document
read back from the cloud does not (DID strips ingest_locations
before storing), so for each series that has members but no uids
the manifest is downloaded into the cache and read, as a dataset
download does (:func:`ndi.cloud.filehandler.reconstructSeriesIngestLocations`).
Without this a resumed run saw no member uids, so missingMembers
reported every member present and nothing missing was rebuilt.
Raises rather than guess when a manifest cannot be read.
"""
si = _series_info_of(doc)
if not si:
return si
docId = _doc_id(doc)
if docId in self._adoptedSeries:
return self._adoptedSeries[docId]

def nPresent(s: dict) -> int:
try:
return int(s.get("n_present", 0) or 0)
except (TypeError, ValueError):
return 0

needs = [nPresent(s) > 0 and not s.get("ingest_locations") for s in si]
if not any(needs):
return si
from .filehandler import _manifest_uid, reconstructSeriesIngestLocations

props = copy.deepcopy(_props(doc))
fileInfo = _as_list(props.get("files", {}).get("file_info"))
for s, need in zip(si, needs):
if not need:
continue
name = str(s.get("name", ""))
manifestUid = _manifest_uid(fileInfo, name)
if not manifestUid:
raise SessionWriterError(
"NDI:cloud:SessionWriter:noManifest",
f"Series {name} of document {docId} has {nPresent(s)} member(s) but no "
"manifest in its file_info, so which members exist cannot be known.",
)
p = os.path.join(self.cacheDir, manifestUid)
if not os.path.isfile(p):
ok, msg = self._api["downloadFile"](self.cloudDatasetId, manifestUid, p)
if not ok or not os.path.isfile(p):
raise SessionWriterError(
"NDI:cloud:SessionWriter:downloadFailed",
f"Could not download the manifest {manifestUid} of series {name} of "
f"document {docId}: {_describe(msg)}",
)
reconstructSeriesIngestLocations(props, self.cacheDir, self.cloudDatasetId)
rebuilt = _series_info_of(props)
for s, need in zip(rebuilt, needs):
if need and not s.get("ingest_locations"):
raise SessionWriterError(
"NDI:cloud:SessionWriter:manifestUnreadable",
f"The manifest of series {s.get('name', '')} of document {docId} "
"could not be read.",
)
self._adoptedSeries[docId] = rebuilt
return rebuilt

def _addNow(self, doc: Any, k: int, n: int) -> None:
"""Upload one document's JSON (series member paths stripped)."""
ok, answer = self._api["addDocument"](self.cloudDatasetId, _stripped(doc))
Expand Down
Loading
Loading