diff --git a/CHANGELOG.md b/CHANGELOG.md index 145f835e..331e7063 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/src/ndi/cloud/ndi_matlab_python_bridge.yaml b/src/ndi/cloud/ndi_matlab_python_bridge.yaml index ee01efda..ed8b8b66 100644 --- a/src/ndi/cloud/ndi_matlab_python_bridge.yaml +++ b/src/ndi/cloud/ndi_matlab_python_bridge.yaml @@ -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 @@ -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" @@ -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" @@ -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 @@ -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" @@ -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. # @@ -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: diff --git a/src/ndi/cloud/session_writer.py b/src/ndi/cloud/session_writer.py index 1b6ad89e..044ffd69 100644 --- a/src/ndi/cloud/session_writer.py +++ b/src/ndi/cloud/session_writer.py @@ -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() @@ -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) @@ -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)] @@ -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 @@ -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)) diff --git a/src/ndi/cloud/upload.py b/src/ndi/cloud/upload.py index 339373ad..f810dc69 100644 --- a/src/ndi/cloud/upload.py +++ b/src/ndi/cloud/upload.py @@ -10,11 +10,14 @@ from __future__ import annotations import logging +import math import tempfile import zipfile from pathlib import Path from typing import TYPE_CHECKING, Any +from pydantic import NonNegativeFloat, validate_call + from .client import _auto_client if TYPE_CHECKING: @@ -49,6 +52,7 @@ def uploadDocumentCollection( only_missing: bool = True, max_chunk: int | None = None, *, + max_bytes: float | None = None, wait_for_ingestion: bool = True, ingestion_timeout: float = 300.0, client: CloudClient | None = None, @@ -59,7 +63,9 @@ def uploadDocumentCollection( By default the documents go up in bulk: each chunk is written as one JSON array, zipped (:func:`zip_documents_for_upload`) and PUT to the URL - from :func:`ndi.cloud.api.documents.getBulkUploadURL`. If the environment + from :func:`ndi.cloud.api.documents.getBulkUploadURL`. A chunk ends at + *max_chunk* documents or *max_bytes* bytes of JSON, whichever comes + first (:func:`documentBatchRanges`). If the environment variable ``NDI_CLOUD_UPLOAD_NO_ZIP`` is ``'true'``, they are sent one at a time with :func:`ndi.cloud.api.documents.addDocument` instead. @@ -70,6 +76,13 @@ def uploadDocumentCollection( max_chunk: Maximum documents per chunk. ``None`` (default) reads the preference ``Cloud.Upload.Max_Document_Batch_Count``; ``0`` or a negative value means all at once. + max_bytes: Maximum bytes of encoded document JSON per bulk chunk; + a single document larger than this goes in a chunk of its own. + ``None`` (default) reads the preference + ``Cloud.Upload.Max_Document_Batch_Size`` (50 MB); ``0`` or a + negative value means no size cap. The server ingests each zip in + a Lambda with limited scratch disk, so one very large JSON file + can fail to ingest at all. wait_for_ingestion: If True (default), a bulk upload does not return until the server lists the uploaded documents, or until *ingestion_timeout* elapses. A bulk upload returns once each zip @@ -77,7 +90,14 @@ def uploadDocumentCollection( listing made straight afterwards can miss documents. Serial uploads are not affected. ingestion_timeout: Seconds to wait for ingestion. Default 300. A - timeout is logged as a warning and does not change ``status``. + timeout is logged as a warning and does not change ``status``, + unless the server lists NONE of the stored documents when the + wait ends: then the server-side ingestion is treated as failed -- + ``status`` is ``'partial'``, ``uploaded`` is 0, ``manifest`` is + emptied (its ids move to ``not_ingested``), ``ingestion['state']`` + is ``'failed'`` and the reason is in ``errors``, so a sync does + not record those documents as present. Uploading again with + *only_missing* sends only what the server still lacks. client: Authenticated cloud client (auto-created if omitted). Returns: @@ -86,7 +106,8 @@ def uploadDocumentCollection( documents sent), ``status`` (``'ok'`` or ``'partial'``) and, on a failure, ``errors``. When a bulk upload waited for ingestion, ``ingestion`` holds the result of - :func:`ndi.cloud.api.documents.waitForDocumentCount`. + :func:`ndi.cloud.api.documents.waitForDocumentCount` plus + ``countBefore``. """ import os @@ -165,10 +186,37 @@ def _fail(message: str) -> None: exc, ) - for n, chunk in enumerate(chunks, start=1): + # Encode each document once, both to size the batches and to write the + # zips. Batches end at max_chunk documents or max_bytes of JSON, + # whichever comes first. + from did.datastructures import json_encode_nan + + if max_bytes is None: + from .. import preferences + + max_bytes = float(preferences.get("Cloud.Upload.Max_Document_Batch_Size")) + + document_json = [json_encode_nan(doc) for doc in documents] + ranges = documentBatchRanges( + [len(j.encode("utf-8")) for j in document_json], + max_chunk if max_chunk and max_chunk > 0 else math.inf, + max_bytes if max_bytes and max_bytes > 0 else math.inf, + ) + if len(ranges) > 1: + logger.info( + "Sending %d documents (%.1f MB of JSON) in %d batches.", + len(documents), + sum(len(j) for j in document_json) / 1e6, + len(ranges), + ) + + for n, indexes in enumerate(ranges, start=1): + chunk = [documents[i] for i in indexes] zip_path: Path | None = None try: - zip_path, id_manifest = zip_documents_for_upload(chunk, dataset_id) + zip_path, id_manifest = zip_documents_for_upload( + chunk, dataset_id, document_json=[document_json[i] for i in indexes] + ) url = docs_api.getBulkUploadURL(dataset_id, client=client) if not url: raise RuntimeError("no bulk upload URL returned") @@ -200,8 +248,37 @@ def _fail(message: str) -> None: "elapsed": float("nan"), "message": str(exc), } + ingestion["countBefore"] = count_before report["ingestion"] = ingestion - if ingestion.get("state") != "complete": + count_after = ingestion.get("count") + nothing_ingested = ( + ingestion.get("state") != "complete" + and isinstance(count_after, (int, float)) + and math.isfinite(count_after) + and count_after <= count_before + ) + if nothing_ingested: + # The server stored the zips but listed none of their documents + # by the deadline: its ingestion failed (or has not started at + # all). Report the upload as failed so callers (e.g. sync) do not + # record these documents as present; uploading again sends only + # what is missing. + ingestion["state"] = "failed" + stored = report["uploaded"] + report["not_ingested"] = report["manifest"] + report["manifest"] = [] + report["uploaded"] = 0 + message = ( + f"Dataset {dataset_id} still lists {count_after:g} documents " + f"{float(ingestion.get('elapsed') or 0):.0f} s after {stored} documents were " + f"uploaded: the server ingested none of them. The server-side ingestion " + f"failed or is badly delayed; the upload is reported as failed. Run the " + f"upload again later (only missing documents are sent), and if it fails " + f"again ask an NDI Cloud administrator to check the bulk document upload logs." + ) + _fail(message) + logger.warning(message) + elif ingestion.get("state") != "complete": logger.warning( "Dataset %s lists %s of the %d documents expected after this upload " "(state: %s). The upload succeeded; the server may still be ingesting " @@ -215,11 +292,62 @@ def _fail(message: str) -> None: return report +@validate_call +def documentBatchRanges( + document_sizes: list[NonNegativeFloat], + max_count: float, + max_bytes: float, +) -> list[list[int]]: + """Split documents into upload batches by count and by JSON size. + + MATLAB equivalent: +ndi/+cloud/+upload/+internal/documentBatchRanges.m + + Walks the documents in order and starts a new batch whenever adding the + next document would put the current batch over *max_count* documents or + over *max_bytes* bytes of JSON. A document that is by itself larger than + *max_bytes* gets a batch of its own (it is never dropped). + + A bulk document upload is ingested by a server Lambda with limited + scratch disk; one very large JSON file per zip (100,000 documents, + 638 MB) failed there with nothing ingested. Capping each batch's size + keeps every zip small and limits what one failed batch can lose. + + Args: + document_sizes: Encoded JSON size of each document, in bytes, in + upload order. + max_count: Maximum documents per batch (positive; ``math.inf`` for + no cap). + max_bytes: Maximum JSON bytes per batch (positive; ``math.inf`` for + no cap). + + Returns: + One list per batch of the 0-based indexes into *document_sizes* of + its documents. Empty when *document_sizes* is empty. (MATLAB returns + the same batches with 1-based indexes.) + """ + if max_count <= 0 or max_bytes <= 0: + raise ValueError("max_count and max_bytes must be positive") + ranges: list[list[int]] = [] + current: list[int] = [] + current_bytes = 0.0 + for i, size in enumerate(document_sizes): + if current and (len(current) + 1 > max_count or current_bytes + size > max_bytes): + ranges.append(current) + current = [] + current_bytes = 0.0 + current.append(i) + current_bytes += size + if current: + ranges.append(current) + return ranges + + def zip_documents_for_upload( documents: list[dict[str, Any]], dataset_id: str, *, target_folder: str | Path | None = None, + document_json: list[str] | None = None, ) -> tuple[Path, list[str]]: """Write documents as one JSON array and zip it for a bulk upload. @@ -236,6 +364,10 @@ def zip_documents_for_upload( dataset_id: Cloud dataset ID (used in the zip's name). target_folder: Where to write the zip. Defaults to the system's temporary folder. + document_json: Optional. The already-encoded JSON of each document + (from ``json_encode_nan``), one per entry of *documents*. When + given, the documents are not encoded again; the file holds the + same JSON array either way. (MATLAB's ``DocumentJson``.) Returns: ``(zip_path, id_manifest)``: the zip's path, which the caller must @@ -246,7 +378,15 @@ def zip_documents_for_upload( from did.datastructures import json_encode_nan folder = Path(target_folder) if target_folder is not None else Path(tempfile.gettempdir()) - json_text = json_encode_nan(list(documents)) + if document_json is None: + json_text = json_encode_nan(list(documents)) + else: + if len(document_json) != len(documents): + raise ValueError( + f"document_json has {len(document_json)} entries but documents " + f"has {len(documents)}." + ) + json_text = "[" + ",".join(document_json) + "]" id_manifest = [document_id(doc) for doc in documents] zip_path = folder / f"{dataset_id}.{uuid.uuid4().hex}.zip" with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf: diff --git a/src/ndi/fun/doc_lightsheet/makePyramid.py b/src/ndi/fun/doc_lightsheet/makePyramid.py index ab7b68d5..5aacfb1b 100644 --- a/src/ndi/fun/doc_lightsheet/makePyramid.py +++ b/src/ndi/fun/doc_lightsheet/makePyramid.py @@ -1492,6 +1492,31 @@ def makePyramid( totalChunks, f"Level {idx + 1}/{len(po)} ({entry['name']}, {reductionFn}): starting", ) + # RESUMING a level reduced from another stored level: when the + # level the earlier run declared already has every chunk, adopt + # it and move on BEFORE resolving its source. Resolving a + # 'reduce' source opens every chunk of the level it is reduced + # from -- through the writer, which can only serve files this run + # sent or adopted -- to build nothing. (Such a level has no folded + # or twin levels, which only slice-read levels carry.) + fromLevel = _reducedFrom(levelSources, p) + if resuming and streaming and fromLevel: + existingLevel = _resumedLevel(resume, idx, reductionFn) + if existingLevel is not None: + session.adopt(existingLevel) + if not session.missingMembers(existingLevel, "chunk.bin"): + _say( + f"Level {idx + 1}/{len(po)} ({entry['name']}, {reductionFn}): " + "every chunk is already in the cloud; skipped." + ) + levelDocs[idx] = existingLevel + docByPath[p] = existingLevel + built[idx] = True + doneChunks += int(np.prod(b.levelGrids[idx])) + readers[fromLevel] -= 1 + if readers[fromLevel] == 0: + session.releaseMembers(docByPath[fromLevel]) + continue source = b.resolveLevelSource(p, entry, level, docByPath) if materializeChunks else None stream = b.newStream(p, idx, reductionFn, readers) if streaming else None diff --git a/src/ndi/fun/doc_lightsheet/ndi_matlab_python_bridge.yaml b/src/ndi/fun/doc_lightsheet/ndi_matlab_python_bridge.yaml index 8a6e081d..508f80c0 100644 --- a/src/ndi/fun/doc_lightsheet/ndi_matlab_python_bridge.yaml +++ b/src/ndi/fun/doc_lightsheet/ndi_matlab_python_bridge.yaml @@ -80,7 +80,7 @@ functions: - name: makePyramid matlab_path: "+ndi/+fun/+doc/+lightsheet/makePyramid.m" - matlab_last_sync_hash: "a3fcbbc48" + matlab_last_sync_hash: "a469501c1" python_path: "ndi/fun/doc_lightsheet/makePyramid.py" decision_log: >- The worker fromOMEZarr calls; writes one lightsheetZarrPyramid diff --git a/src/ndi/ndi_matlab_python_bridge.yaml b/src/ndi/ndi_matlab_python_bridge.yaml index 27e7018f..373a8e14 100644 --- a/src/ndi/ndi_matlab_python_bridge.yaml +++ b/src/ndi/ndi_matlab_python_bridge.yaml @@ -1159,7 +1159,7 @@ classes: - name: preferences type: class matlab_path: "+ndi/preferences.m" - matlab_last_sync_hash: "f9878d584" + matlab_last_sync_hash: "ec25d3c" python_path: "ndi/preferences.py" python_class: "ndi_preferences" inherits: "" @@ -1237,6 +1237,10 @@ classes: keys, defaults and descriptions as MATLAB. Only GUI.LightsheetManager.ViewerLauncher stays unregistered (read only by the MATLAB-only LightsheetManager). + 2026-11-14: NDI-matlab ec25d3c (VH-Lab/NDI-matlab#1247) registers + Cloud.Upload.Max_Document_Batch_Size (default 50 MB): the byte cap on one bulk + document upload batch. Ported with the same key and default (type float, + like Max_File_Batch_Size); ndi.cloud.upload.uploadDocumentCollection reads it. properties: - name: Items diff --git a/src/ndi/preferences.py b/src/ndi/preferences.py index 365879c2..03cb5eaf 100644 --- a/src/ndi/preferences.py +++ b/src/ndi/preferences.py @@ -206,6 +206,16 @@ def _register_defaults(self) -> None: "int", "Maximum number of documents uploaded per batch.", ) + self._add_item( + "Cloud", + "Upload", + "Max_Document_Batch_Size", + 50_000_000, + "float", + "Maximum size in bytes of the document JSON in one bulk document upload " + "batch (default 50 MB). Batches end at this size or at " + "Max_Document_Batch_Count documents, whichever comes first.", + ) self._add_item( "Cloud", "Upload", diff --git a/tests/test_cloud_session_writer.py b/tests/test_cloud_session_writer.py index 69c6e61a..3c0046e4 100644 --- a/tests/test_cloud_session_writer.py +++ b/tests/test_cloud_session_writer.py @@ -227,6 +227,21 @@ def fileBytes(self, uid): with open(os.path.join(self.fileDir, uid), "rb") as f: return f.read() + def dropFile(self, uid): + """Lose a stored file, as a dropped upload batch did in prod: + lookupFiles no longer reports it.""" + p = os.path.join(self.fileDir, uid) + if os.path.isfile(p): + os.remove(p) + + def storedDocument(self, ndiId): + """The document as stored (series ingest_locations stripped), as a + download from NDI Cloud returns it.""" + for d in self.docs: + if d["base"]["id"] == ndiId: + return ndi_document(copy.deepcopy(d)) + return None + def _store(self, uid, p): dest = os.path.join(self.fileDir, uid) shutil.copyfile(p, dest) @@ -755,6 +770,72 @@ def test_adopt_and_missing_members_for_a_resume(cloud, make_writer, series_doc): assert W2.missingMembers(d, "nope") == [] +def test_adopting_a_document_read_back_from_the_cloud_finds_its_missing_members( + cloud, make_writer, series_doc +): + # A resume usually adopts documents downloaded from the cloud, whose + # series ingest_locations DID stripped before storing. Their member uids + # must be rebuilt from the manifest: without them every member looked + # present, and a resume rebuilt nothing (a prod pyramid kept 327 lost + # chunks this way). + W = make_writer() + d, data = series_doc(W, cloud.subjectId, 3) + W.declare(d) + L = locs_of(d) + W.streamMembers(d, "chunk.bin", [L[1]["index"]], [L[1]["location"]]) + W.streamMembers(d, "chunk.bin", [], []) + + stored = cloud.storedDocument(d.id) + storedSeries = stored.document_properties["files"]["series_info"] + storedSeries = storedSeries[0] if isinstance(storedSeries, list) else storedSeries + assert not storedSeries.get("ingest_locations"), "the stored document carries no member uids" + W2 = make_writer() + W2.adopt(stored) + missing = W2.missingMembers(stored, "chunk.bin") + assert sorted(missing) == sorted([L[0]["index"], L[2]["index"]]) + W2.streamMembers( + stored, "chunk.bin", [L[0]["index"], L[2]["index"]], [L[0]["location"], L[2]["location"]] + ) + W2.commit() + for x in L: + assert cloud.fileBytes(x["uid"]) == data[int(x["index"]) - 1] + assert len(cloud.docsOfClass("lightsheetZarrLevel")) == 1, "adopt does not re-upload" + + +def test_a_member_of_an_adopted_stored_document_can_be_opened(cloud, make_writer, series_doc): + # A later level reads an adopted level's chunks through + # database_openbinarydoc; for a document read back from the cloud that + # needs the rebuilt member uids too. + W = make_writer() + d, data = series_doc(W, cloud.subjectId, 2) + W.declare(d) + L = locs_of(d) + W.streamMembers(d, "chunk.bin", [x["index"] for x in L], [x["location"] for x in L]) + W.commit() + + stored = cloud.storedDocument(d.id) + W2 = make_writer() + W2.adopt(stored) + assert W2.missingMembers(stored, "chunk.bin") == [] + i = int(L[1]["index"]) + f = W2.database_openbinarydoc(stored, f"chunk.bin_{i}") + with open(f.name, "rb") as h: + assert h.read() == data[i - 1] + + +def test_a_stored_series_without_its_manifest_is_refused(cloud, make_writer, series_doc): + # Which members exist cannot be known without the manifest: an error, + # not a guess that every member is present. + W = make_writer() + d, _ = series_doc(W, cloud.subjectId, 2) + W.declare(d) + stored = cloud.storedDocument(d.id) + cloud.dropFile(manifest_uid(d)) + W2 = make_writer() + with pytest.raises(SessionWriterError, match="manifest"): + W2.adopt(stored) + + def test_a_cached_copy_a_power_cut_shortened_is_fetched_again(cloud, make_writer, series_doc): W = make_writer(keepLocalCopies=True) d, data = series_doc(W, cloud.subjectId, 2) diff --git a/tests/test_cloud_upload_bulk_documents.py b/tests/test_cloud_upload_bulk_documents.py index 3f56ad1e..76b13531 100644 --- a/tests/test_cloud_upload_bulk_documents.py +++ b/tests/test_cloud_upload_bulk_documents.py @@ -320,3 +320,133 @@ def test_a_negative_target_is_rejected(self, monkeypatch): with pytest.raises(ValidationError): docs_api.waitForDocumentCount(CLOUD_ID, -1, client=_make_client()) + + +# --------------------------------------------------------------------------- +# Size-capped batches (documentBatchRanges.m, DocumentBatchRangesTest.m) +# +# 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 client reported success. +# --------------------------------------------------------------------------- + + +class TestDocumentBatchRanges: + def test_empty_input_gives_no_batches(self): + assert upload.documentBatchRanges([], 10, 100) == [] + + def test_count_cap_only(self): + assert upload.documentBatchRanges([1] * 5, 2, math.inf) == [[0, 1], [2, 3], [4]] + + def test_byte_cap_only(self): + assert upload.documentBatchRanges([40, 40, 40, 40], math.inf, 100) == [[0, 1], [2, 3]] + + def test_byte_cap_is_inclusive(self): + assert upload.documentBatchRanges([50, 50, 1], math.inf, 100) == [[0, 1], [2]] + + def test_whichever_cap_comes_first(self): + assert upload.documentBatchRanges([10, 10, 10, 95, 10], 3, 100) == [[0, 1, 2], [3], [4]] + + def test_oversized_document_gets_its_own_batch(self): + assert upload.documentBatchRanges([10, 500, 10], math.inf, 100) == [[0], [1], [2]] + + def test_every_document_appears_once_in_order(self): + import random + + rng = random.Random(7) + sizes = [rng.randint(1, 300) for _ in range(1000)] + ranges = upload.documentBatchRanges(sizes, 37, 2000) + assert [i for r in ranges for i in r] == list(range(1000)) + for r in ranges: + assert len(r) <= 37 + if len(r) > 1: + assert sum(sizes[i] for i in r) <= 2000 + + def test_non_positive_caps_are_rejected(self): + with pytest.raises(ValueError): + upload.documentBatchRanges([1], 0, 100) + + +class TestZipWithDocumentJson: + def test_precomputed_json_writes_the_same_array(self, tmp_path): + from did.datastructures import json_encode_nan + + docs = [{"base": {"id": "a"}, "x": float("nan")}, {"base": {"id": "b"}, "y": [1, 2]}] + p1, ids1 = upload.zip_documents_for_upload(docs, CLOUD_ID, target_folder=tmp_path) + p2, ids2 = upload.zip_documents_for_upload( + docs, + CLOUD_ID, + target_folder=tmp_path, + document_json=[json_encode_nan(d) for d in docs], + ) + assert ids1 == ids2 == ["a", "b"] + with zipfile.ZipFile(p1) as z1, zipfile.ZipFile(p2) as z2: + a = json.loads(z1.read(z1.namelist()[0])) + b = json.loads(z2.read(z2.namelist()[0])) + assert isinstance(b, list) and len(b) == 2 + assert math.isnan(b[0]["x"]) and b[1] == a[1] + + def test_count_mismatch_is_an_error(self, tmp_path): + with pytest.raises(ValueError): + upload.zip_documents_for_upload( + _docs("a", "b"), CLOUD_ID, target_folder=tmp_path, document_json=["{}"] + ) + + +class TestSizeCappedBulkUpload: + def test_byte_cap_splits_the_zips(self, bulk, monkeypatch): + monkeypatch.setattr(docs_api, "countDocuments", _ScriptedCount([0, 4])) + docs = [{"base": {"id": i}, "pad": "x" * 100} for i in "abcd"] + report = upload.uploadDocumentCollection( + CLOUD_ID, docs, only_missing=False, max_chunk=100, max_bytes=350, client=_make_client() + ) + assert bulk.batches == [docs[0:2], docs[2:4]] + assert report["status"] == "ok" and report["uploaded"] == 4 + + def test_default_size_cap_is_the_preference(self): + from ndi import preferences + + assert float(preferences.get("Cloud.Upload.Max_Document_Batch_Size")) == 50_000_000 + + def test_nothing_ingested_is_a_failure(self, bulk, monkeypatch, caplog): + monkeypatch.setattr(docs_api, "countDocuments", _ScriptedCount([3])) + monkeypatch.setattr( + docs_api, + "waitForDocumentCount", + lambda d, expected, **k: { + "state": "timeout", + "count": 3, + "expectedCount": expected, + "elapsed": 300.0, + }, + ) + with caplog.at_level("WARNING", logger="ndi.cloud.upload"): + report = upload.uploadDocumentCollection( + CLOUD_ID, _docs("a", "b"), only_missing=False, client=_make_client() + ) + assert report["status"] == "partial" + assert report["ingestion"]["state"] == "failed" + assert report["ingestion"]["countBefore"] == 3 + assert report["uploaded"] == 0 + assert report["manifest"] == [] + assert report["not_ingested"] == ["a", "b"] + assert "ingested none of them" in report["errors"][0] + assert "ingested none of them" in caplog.text + + def test_unknown_final_count_is_only_a_timeout(self, bulk, monkeypatch): + monkeypatch.setattr(docs_api, "countDocuments", _ScriptedCount([3])) + monkeypatch.setattr( + docs_api, + "waitForDocumentCount", + lambda d, expected, **k: { + "state": "timeout", + "count": float("nan"), + "expectedCount": expected, + }, + ) + report = upload.uploadDocumentCollection( + CLOUD_ID, _docs("a"), only_missing=False, client=_make_client() + ) + assert report["status"] == "ok" + assert report["ingestion"]["state"] == "timeout" + assert report["manifest"] == ["a"] diff --git a/tests/test_fun_doc_lightsheet_build.py b/tests/test_fun_doc_lightsheet_build.py index bf339675..954dc226 100644 --- a/tests/test_fun_doc_lightsheet_build.py +++ b/tests/test_fun_doc_lightsheet_build.py @@ -405,6 +405,56 @@ def spy(doc, name, idxs, paths, retain): for key, d in zip(ORDER, levelDocs): np.testing.assert_array_equal(cloud.level(d), exp[key], err_msg=key) + def test_a_resume_rebuilds_only_lost_chunks_and_skips_complete_reduced_levels( + self, vol, capsys + ): + # A finished build loses three level-0 chunks (a dropped upload + # batch). The resume sends exactly those back, declares no new level + # documents, and skips each level reduced from a stored level whose + # chunks are all present without opening the level it reduces. + s, subj = new_session() + cloud = FakeCloud(s) + pyr, src, exp = ladder(vol, write_slices(vol), toCloud=True) + args = dict(subjectID=subj, materializeChunks=True, levelSources=src, + codec="blosc-zstd", numWorkers=2, **BUILD) # fmt: skip + pyramidDoc, firstDocs, _ = makePyramid(cloud, pyr, ["mean", "max"], **args) + level0 = firstDocs[0] + lost = [1, 2, 3] + for i in lost: + del cloud.members[level0.id][i] + + def levelIds(): + return {k for k, d in cloud.declared.items() if d.doc_class() == "lightsheetZarrLevel"} + + levelsBefore = levelIds() + assert len(levelsBefore) == 5 + + resume = {"pyramidDoc": pyramidDoc, "levelDocs": list(cloud.declared.values())} + resent, opened = [], [] + origStream, origOpen = cloud.streamMembers, cloud.database_openbinarydoc + + def spyStream(doc, name, idxs, paths, retain): + resent.extend((doc.id, int(i)) for i in idxs) + origStream(doc, name, idxs, paths, retain) + + def spyOpen(doc, filename): + opened.append(doc.id) + return origOpen(doc, filename) + + cloud.streamMembers = spyStream + cloud.database_openbinarydoc = spyOpen + capsys.readouterr() + _, levelDocs, _ = makePyramid(cloud, pyr, ["mean", "max"], resume=resume, **args) + out = capsys.readouterr().out + + assert sorted(resent) == [(level0.id, i) for i in lost] + assert levelIds() == levelsBefore, "no new level documents" + assert opened == [], "a skipped level does not open the level it reduces" + assert out.count("every chunk is already in the cloud; skipped.") == 2 + assert f"Resuming: {len(lost)} of " in out + for key, d in zip(ORDER, levelDocs): + np.testing.assert_array_equal(cloud.level(d), exp[key], err_msg=key) + def test_resume_needs_a_streaming_target(self, vol): s, subj = new_session() pyr, src, _ = ladder(vol, write_slices(vol), toCloud=False) diff --git a/tests/test_gui_preferences_editor.py b/tests/test_gui_preferences_editor.py index f56132e0..45550004 100644 --- a/tests/test_gui_preferences_editor.py +++ b/tests/test_gui_preferences_editor.py @@ -242,6 +242,7 @@ def test_rows_cover_the_whole_category(self, tmp_path): assert [r.path for r in state.rows()] == [ "Cloud.Download.Max_Document_Batch_Count", "Cloud.Upload.Max_Document_Batch_Count", + "Cloud.Upload.Max_Document_Batch_Size", "Cloud.Upload.Max_File_Batch_Size", "Cloud.Upload.Send_Batches_As_Zip", "Cloud.Upload.Parallel_Uploads", @@ -252,6 +253,7 @@ def test_selecting_a_subcategory_narrows_the_rows(self, tmp_path): state.select("Cloud", "Upload") assert [r.label for r in state.rows()] == [ "Max_Document_Batch_Count", + "Max_Document_Batch_Size", "Max_File_Batch_Size", "Send_Batches_As_Zip", "Parallel_Uploads",