diff --git a/CHANGELOG.md b/CHANGELOG.md index 331e7063..1c1341f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,27 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Added +- **File uploads confirm NDI Cloud recorded every file, and resend what it + did not** (`ndi.cloud.upload.confirmFilesRecorded`, + `uploadFilesForDatasetDocuments(verify_uploads=..., verify_stall_timeout=...)`, + MATLAB VH-Lab/NDI-matlab#1297). A batch (zip) upload reported success once + the zips reached S3, but the server records their files in a later step + that can fail unheard (a dataset lost 327 files this way, + ndi-cloud-node#175). After both the `'batch'` and `'serial'` strategies the + sent files are now waited for while records keep arriving (up to + `verify_stall_timeout`, default 900 s, without progress), any still + unrecorded are uploaded again one at a time, and files never recorded + count as failed, so their documents are kept out of the sync index. + `'serial'` previously waited 120 s and failed without resending. + +- **File batch uploads are capped at 2000 files** (new preference + `Cloud.Upload.Max_File_Batch_Count`; `zipForUpload(count_limit=...)`, MATLAB + VH-Lab/NDI-matlab#1297). Batches were capped only by bytes (250 MB), so + 10,000 small files went up as one zip, and NDI Cloud never recorded any of + them: it unpacks and records a batch in one time-limited step. Files still + unrecorded after an upload are resent as capped zip batches, or one at a + time when there are at most 20. + - **Navigator: NDI Cloud login indicator** (`ndi.gui.nav.cloud_pane`, MATLAB VH-Lab/NDI-matlab@579176c88). The NDI Cloud pane gains a small button that is green when logged in (an unexpired `NDI_CLOUD_TOKEN`), yellow when a profile diff --git a/src/ndi/cloud/ndi_matlab_python_bridge.yaml b/src/ndi/cloud/ndi_matlab_python_bridge.yaml index ed8b8b66..f94ce2da 100644 --- a/src/ndi/cloud/ndi_matlab_python_bridge.yaml +++ b/src/ndi/cloud/ndi_matlab_python_bridge.yaml @@ -989,7 +989,7 @@ functions: - name: zipForUpload matlab_path: "+ndi/+cloud/+upload/zipForUpload.m" - matlab_last_sync_hash: "7180cc8" + matlab_last_sync_hash: "0be6cfed3" python_path: "ndi/cloud/upload.py" input_arguments: - name: file_manifest @@ -1005,6 +1005,10 @@ functions: type_matlab: "double (SizeLimit)" type_python: "float | None" default: "None" + - name: count_limit + type_matlab: "double (CountLimit)" + type_python: "int | None" + default: "None" - name: number_retries type_matlab: "double (numberRetries)" type_python: "int" @@ -1026,6 +1030,11 @@ functions: - name: report type_python: "dict[str, Any]" decision_log: > + 2026-11-21: NDI-matlab 0be6cfed3 (VH-Lab/NDI-matlab#1297). A batch also ends + at count_limit files (None = the Cloud.Upload.Max_File_Batch_Count + preference, 2000): NDI Cloud never recorded a zip of 10,165 small + files (84 MB, under the size cap). MATLAB also dropped an unused read + of D.path; Python's port never took a dataset. 2026-10-17: REPLACED. The function that lived here zipped document JSON, had no caller in src, and so was a port of nothing (see the 2026-09-08 note below). It is now a port of what MATLAB's zipForUpload actually @@ -1075,7 +1084,7 @@ functions: - name: uploadFilesForDatasetDocuments matlab_path: "+ndi/+cloud/+sync/+internal/uploadFilesForDatasetDocuments.m" - matlab_last_sync_hash: "293ec411" + matlab_last_sync_hash: "63e56ae14" python_path: "ndi/cloud/upload.py" input_arguments: - name: org_id @@ -1102,6 +1111,14 @@ functions: type_matlab: "logical (Verbose)" type_python: "bool" default: "False" + - name: verify_uploads + type_matlab: "logical (VerifyUploads)" + type_python: "bool" + default: "True" + - name: verify_stall_timeout + type_matlab: "double (VerifyStallTimeout)" + type_python: "float" + default: "900.0" - name: client type_python: "CloudClient | None" default: "None" @@ -1109,6 +1126,12 @@ functions: - name: result type_python: "dict[str, Any]" decision_log: > + 2026-11-20: NDI-matlab 63e56ae14 (VH-Lab/NDI-matlab#1297). After both + strategies the files sent are checked with confirmFilesRecorded (a + zip reaching S3 is not the server recording its files, + ndi-cloud-node#175); files still unrecorded after a resend count as + failed and their documents go into failed_document_ids. For 'batch', + the files of batches zipForUpload already failed are not checked. 2026-10-18: NDI-matlab 293ec411 (VH-Lab/NDI-matlab#1037) only rewrote a Verbose error message (it now names the user's organizations instead of NDI_CLOUD_ORGANIZATION_ID). Python's org_id may now be "" to look the @@ -1978,6 +2001,73 @@ porting_deferred: 1-based; the batches themselves are identical. Non-positive caps raise ValueError (MATLAB's arguments block rejects them with mustBePositive). + - name: confirmFilesRecorded + matlab_path: "+ndi/+cloud/+upload/+internal/confirmFilesRecorded.m" + matlab_last_sync_hash: "0be6cfed3" + python_path: "ndi/cloud/upload.py" + input_arguments: + - name: dataset_id + type_matlab: "string" + type_python: "str" + - name: uids + type_matlab: "string (1,:)" + type_python: "list[str]" + - name: paths + type_matlab: "cell" + type_python: "list[str]" + - name: org_id + type_python: "str" + default: "''" + - name: stall_timeout + type_matlab: "double (StallTimeout)" + type_python: "float" + default: "900.0" + - name: resend_timeout + type_matlab: "double (ResendTimeout)" + type_python: "float" + default: "300.0" + - name: single_file_limit + type_matlab: "double (SingleFileLimit)" + type_python: "int" + default: "20" + - name: verbose + type_matlab: "logical (Verbose)" + type_python: "bool" + default: "False" + - name: wait_fcn + type_matlab: "function_handle (WaitFcn)" + type_python: "Callable | None" + default: "None" + - name: resend_fcn + type_matlab: "function_handle (ResendFcn)" + type_python: "Callable | None" + default: "None" + - name: resend_batch_fcn + type_matlab: "function_handle (ResendBatchFcn)" + type_python: "Callable | None" + default: "None" + - name: client + type_python: "CloudClient | None" + default: "None" + output_arguments: + - name: result + type_matlab: "[ok, report]" + type_python: "dict[str, Any]" + decision_log: > + 2026-11-21: NDI-matlab 0be6cfed3. More than single_file_limit unrecorded + files are resent as zip batches (zipForUpload, capped by count and + size) instead of one at a time, which did not finish 10,165 files in + 40 minutes; after resending it waits while records keep arriving. + 2026-11-20: new in NDI-matlab 63e56ae14 (VH-Lab/NDI-matlab#1297). Waits + while NDI Cloud keeps recording the files an upload sent, uploads again + (one at a time) any it stops recording, and reports those still + missing. MATLAB returns [ok, report]; Python returns one dict with ok + folded in, and resend_errors for MATLAB's resendErrors. wait_fcn + returns waitForFileUpload's dict (state, pending) where MATLAB's + WaitFcn returns [b, answer]. org_id is Python-only: the resend's + upload URL needs it, and "" looks it up from the dataset record. Lives + in ndi.cloud.upload beside its caller, like documentBatchRanges. + - name: zip_documents_for_upload matlab_path: "+ndi/+cloud/+upload/+internal/zip_documents_for_upload.m" matlab_last_sync_hash: "ec25d3c" diff --git a/src/ndi/cloud/upload.py b/src/ndi/cloud/upload.py index f810dc69..c186035c 100644 --- a/src/ndi/cloud/upload.py +++ b/src/ndi/cloud/upload.py @@ -13,6 +13,7 @@ import math import tempfile import zipfile +from collections.abc import Callable from pathlib import Path from typing import TYPE_CHECKING, Any @@ -400,6 +401,7 @@ def zipForUpload( *, org_id: str = "", size_limit: float | None = None, + count_limit: int | None = None, number_retries: int = 3, completion_timeout: float = 300.0, retry_pause: float = 5.0, @@ -437,6 +439,10 @@ def zipForUpload( *dataset_id*, read from the dataset record. size_limit: Maximum batch size in bytes. ``None`` (default) reads the preference ``Cloud.Upload.Max_File_Batch_Size``. + count_limit: Maximum number of files in a batch. ``None`` (default) + reads the preference ``Cloud.Upload.Max_File_Batch_Count`` (2000). + NDI Cloud unpacks and records a batch in one time-limited step; + a zip of ~10,000 small files outran it. number_retries: Attempts at getting the upload URL and at the PUT. completion_timeout: Seconds to wait for each batch's server-side extraction job. @@ -460,6 +466,12 @@ def zipForUpload( size_limit = float(preferences.get("Cloud.Upload.Max_File_Batch_Size")) if size_limit <= 0: raise ValueError(f"size_limit must be positive (got {size_limit!r})") + if count_limit is None: + from .. import preferences + + count_limit = int(preferences.get("Cloud.Upload.Max_File_Batch_Count")) + if count_limit <= 0: + raise ValueError(f"count_limit must be positive (got {count_limit!r})") report: dict[str, Any] = { "uploaded": 0, @@ -497,7 +509,7 @@ def _size(entry: dict[str, Any]) -> int: current_size = 0 for entry in file_manifest: fb = _size(entry) - if current and current_size + fb > size_limit: + if current and (current_size + fb > size_limit or len(current) >= count_limit): batches.append(current) current, current_size = [], 0 current.append(entry) @@ -593,6 +605,209 @@ def _size(entry: dict[str, Any]) -> int: return report +def confirmFilesRecorded( + dataset_id: str, + uids: list[str], + paths: list[str], + *, + org_id: str = "", + stall_timeout: float = 900.0, + resend_timeout: float = 300.0, + single_file_limit: int = 20, + verbose: bool = False, + wait_fcn: Callable[[list[str], float], dict[str, Any]] | None = None, + resend_fcn: Callable[[str, str], tuple[bool, str]] | None = None, + resend_batch_fcn: Callable[[list[str], list[str]], tuple[bool, str]] | None = None, + client: CloudClient | None = None, +) -> dict[str, Any]: + """Make sure NDI Cloud recorded every file an upload sent. + + MATLAB equivalent: +ndi/+cloud/+upload/+internal/confirmFilesRecorded.m + + A batch (zip) upload succeeding only means S3 has the zip. The server + then unpacks it and records each file in a separate step, and that step + can fail after the client has moved on: a dataset lost 327 files this + way (ndi-cloud-node#175), and a zip of ~10,000 small files outran the + step's time limit with none recorded. Since that fix the server keeps + such files as not uploaded, so the loss is visible -- this function is + where the client looks. + + 1. Wait until every uid is recorded as uploaded. Waiting goes on while + the count still to record keeps falling, and stops after + *stall_timeout* seconds in which none was recorded. + 2. Upload the files still unrecorded again from *paths* (``paths[k]`` + is the local copy of ``uids[k]``): one at a time when there are at + most *single_file_limit*, otherwise as zip batches + (:func:`zipForUpload`, capped by ``Cloud.Upload.Max_File_Batch_Count`` + and ``Max_File_Batch_Size``). + 3. Wait for those the same way, with *resend_timeout* as the stall + limit; any still unrecorded is a failure, listed in ``pending``. + + Args: + dataset_id: Cloud dataset ID. + uids: The file uids the upload sent. + paths: Their local paths. + org_id: Organisation ID for the resend URLs; ``""`` looks it up. + stall_timeout: Seconds without a single newly recorded file before + resending. Default 900, the server's batch step's own time limit. + resend_timeout: The same, after resending. Default 300. + single_file_limit: Resend one at a time up to this many files; more + go as zip batches. Default 20. + verbose: Print progress. + wait_fcn: Seam for tests: ``wait_fcn(uids, timeout)`` returning a dict + with ``state`` and ``pending``, as + :func:`ndi.cloud.api.files.waitForFileUpload`. + resend_fcn: Seam for tests: ``resend_fcn(uid, path)`` returning + ``(ok, message)``; by default a single-file upload. + resend_batch_fcn: Seam for tests: ``resend_batch_fcn(uids, paths)`` + returning ``(ok, message)``; by default :func:`zipForUpload`. + client: Authenticated cloud client (auto-created if omitted). + + Returns: + ``{"ok", "resent", "pending", "resend_errors", "message"}``: ``ok`` is + true iff every uid ended up recorded; ``resent`` the uids uploaded + again; ``pending`` those still unrecorded; ``resend_errors`` messages + from uploads that failed outright; ``message`` empty when ok. + """ + from .api import files as files_api + + uids = [str(u) for u in uids] + paths = [str(p) for p in paths] + if len(uids) != len(paths): + raise ValueError(f"uids has {len(uids)} entries but paths has {len(paths)}.") + path_of: dict[str, str] = {} + for u, p in zip(uids, paths): + path_of.setdefault(u, p) + uids = list(path_of) + + if wait_fcn is None: + + def wait_fcn(ids: list[str], t: float) -> dict[str, Any]: + return files_api.waitForFileUpload(dataset_id, ids, timeout=t, client=client) + + if resend_fcn is None: + + def resend_fcn(uid: str, path: str) -> tuple[bool, str]: + nonlocal org_id + if not org_id: + from .internal import _datasetOrganizationId + + org_id = _datasetOrganizationId(dataset_id, client=client) + url = files_api.getFileUploadURL(org_id, dataset_id, uid, client=client) + files_api.putFiles(url, path) + return True, "" + + if resend_batch_fcn is None: + + def resend_batch_fcn(ids: list[str], ps: list[str]) -> tuple[bool, str]: + # A zip entry is named by its uid, as in any batch upload. + sent = zipForUpload( + [{"file_uid": u, "file_path": p} for u, p in zip(ids, ps)], + dataset_id, + org_id=org_id, + verbose=verbose, + client=client, + ) + return (not sent["failed"]), "; ".join(sent["errors"]) + + def say(text: str) -> None: + if verbose: + print(f"[confirmFilesRecorded] {text}", flush=True) + + def wait_while_recording(ids: list[str], timeout: float) -> list[str]: + # Wait for as long as the count still pending keeps falling; return + # those still pending after *timeout* seconds with none recorded. + pending = list(ids) + while True: + answer = wait_fcn(pending, timeout) + if answer.get("state") == "complete": + return [] + still = [str(u) for u in answer.get("pending", [])] + if len(still) >= len(pending): + return still + pending = still + say( + f"{len(ids) - len(pending)} of {len(ids)} file(s) recorded by NDI Cloud " + "so far; waiting." + ) + + result: dict[str, Any] = { + "ok": True, + "resent": [], + "pending": [], + "resend_errors": [], + "message": "", + } + if not uids: + return result + + # 1. Wait while the server keeps recording. + pending = wait_while_recording(uids, stall_timeout) + if not pending: + return result + + # 2. Upload the unrecorded files again. + sent: list[str] = [] + how = "one at a time" if len(pending) <= single_file_limit else "in zip batches" + say( + f"NDI Cloud has not recorded {len(pending)} of {len(uids)} uploaded file(s) after " + f"{stall_timeout:.0f} s without progress; uploading them again {how}." + ) + if len(pending) <= single_file_limit: + for uid in pending: + try: + ok, msg = resend_fcn(uid, path_of.get(uid, "")) + except Exception as exc: # noqa: BLE001 - e.g. the local copy is gone + ok, msg = False, str(exc) + if ok: + sent.append(uid) + else: + result["resend_errors"].append(f"{uid}: {msg}") + else: + try: + ok, msg = resend_batch_fcn(pending, [path_of.get(u, "") for u in pending]) + except Exception as exc: # noqa: BLE001 + ok, msg = False, str(exc) + if not ok: + # A failed batch may have sent some of them; wait for all. + result["resend_errors"].append(f"zip batch resend: {msg}") + sent = list(pending) + result["resent"] = sent + + # 3. Wait for the resent files. + still = wait_while_recording(sent, resend_timeout) if sent else [] + result["pending"] = [u for u in pending if u not in sent] + still + result["ok"] = not result["pending"] + if result["ok"]: + say(f"All {len(sent)} resent file(s) are now recorded by NDI Cloud.") + else: + result["message"] = ( + f"{len(result['pending'])} of {len(uids)} uploaded file(s) were not recorded by " + f"NDI Cloud, even after uploading them again (first: {result['pending'][0]}). " + "Run the upload again with only_missing to retry them." + ) + if result["resend_errors"]: + result["message"] += f" First upload error: {result['resend_errors'][0]}" + say(result["message"]) + return result + + +def _apply_confirmation( + report: dict[str, Any], confirmation: dict[str, Any], owner: dict[str, str] +) -> None: + """Count the files NDI Cloud never recorded as failed, and their + documents as not synced (NDI-matlab#805).""" + if confirmation["ok"]: + return + report["errors"].append(confirmation["message"]) + for uid in confirmation["pending"]: + report["uploaded"] -= 1 + report["failed"] += 1 + d = owner.get(uid, "") + if d and d not in report["failed_document_ids"]: + report["failed_document_ids"].append(d) + + def uploadFilesForDatasetDocuments( org_id: str, dataset_id: str, @@ -602,6 +817,8 @@ def uploadFilesForDatasetDocuments( file_upload_strategy: str = "batch", file_batch_size_limit: float | None = None, verbose: bool = False, + verify_uploads: bool = True, + verify_stall_timeout: float = 900.0, client: CloudClient | None = None, ) -> dict[str, Any]: """Upload associated binary files for a list of documents. @@ -626,6 +843,12 @@ def uploadFilesForDatasetDocuments( ``None`` (default) uses the preference ``Cloud.Upload.Max_File_Batch_Size``. Ignored for ``'serial'``. verbose: Print progress. + verify_uploads: After uploading, confirm NDI Cloud recorded every + file sent, and upload again any it did not + (:func:`confirmFilesRecorded`). Files still unrecorded count as + failed. Default ``True``. + verify_stall_timeout: Seconds with no newly recorded file before the + unrecorded ones are uploaded again. Default 900. client: Authenticated cloud client (auto-created if omitted). Returns: @@ -668,6 +891,29 @@ def uploadFilesForDatasetDocuments( client=client, ) report.pop("batches", None) + if verify_uploads: + # The zips reached S3; the server records their files in a later + # step that can fail without the upload hearing of it. Check the + # files of every batch that did not already fail. + failed_docs = set(report["failed_document_ids"]) + sent_entries = [ + e for e in manifest if not e["document_id"] or e["document_id"] not in failed_docs + ] + if sent_entries: + confirmation = confirmFilesRecorded( + dataset_id, + [str(e["file_uid"]) for e in sent_entries], + [str(e["file_path"]) for e in sent_entries], + org_id=org_id, + stall_timeout=verify_stall_timeout, + verbose=verbose, + client=client, + ) + _apply_confirmation( + report, + confirmation, + {str(e["file_uid"]): e["document_id"] for e in sent_entries}, + ) return report report: dict[str, Any] = { @@ -682,6 +928,7 @@ def uploadFilesForDatasetDocuments( } sent: dict[str, str] = {} # uid -> the document that owns it + sent_paths: dict[str, str] = {} for doc in documents: doc_id = document_id(doc) for file_uid, file_path in file_uploads_for_document(doc, dataset=dataset): @@ -694,6 +941,7 @@ def uploadFilesForDatasetDocuments( files_api.putFiles(url, file_path) report["uploaded"] += 1 sent[str(file_uid)] = doc_id + sent_paths[str(file_uid)] = file_path except Exception as exc: report["failed"] += 1 report["errors"].append(str(exc)) @@ -702,22 +950,20 @@ def uploadFilesForDatasetDocuments( # Wait once, for all of them, for NDI Cloud to record the uploads (a PUT # returning 200 only means S3 has the object), as NDI-matlab's serial - # path does (VH-Lab/NDI-matlab#1027). A file not recorded in time counts - # as failed, so its document is not recorded as synced. - if sent: - waited = files_api.waitForFileUpload(dataset_id, list(sent), client=client) - if waited.get("state") != "complete": - pending = [str(u) for u in waited.get("pending", [])] - report["errors"].append( - f"{len(pending)} of {len(sent)} uploaded files were not recorded by NDI Cloud " - f"within {waited.get('elapsed', 0):.0f} s (first: {pending[0] if pending else ''})." - ) - for uid in pending: - report["uploaded"] -= 1 - report["failed"] += 1 - d = sent.get(uid, "") - if d and d not in report["failed_document_ids"]: - report["failed_document_ids"].append(d) + # path does (VH-Lab/NDI-matlab#1027), and upload again any it never + # records. A file still not recorded counts as failed, so its document is + # not recorded as synced. + if sent and verify_uploads: + confirmation = confirmFilesRecorded( + dataset_id, + list(sent), + [sent_paths[u] for u in sent], + org_id=org_id, + stall_timeout=verify_stall_timeout, + verbose=verbose, + client=client, + ) + _apply_confirmation(report, confirmation, sent) return report diff --git a/src/ndi/ndi_matlab_python_bridge.yaml b/src/ndi/ndi_matlab_python_bridge.yaml index 373a8e14..452ce0f9 100644 --- a/src/ndi/ndi_matlab_python_bridge.yaml +++ b/src/ndi/ndi_matlab_python_bridge.yaml @@ -1159,12 +1159,14 @@ classes: - name: preferences type: class matlab_path: "+ndi/preferences.m" - matlab_last_sync_hash: "ec25d3c" + matlab_last_sync_hash: "0be6cfed3" python_path: "ndi/preferences.py" python_class: "ndi_preferences" inherits: "" decision_log: > + 2026-11-21: NDI-matlab 0be6cfed3 adds Cloud.Upload.Max_File_Batch_Count + (2000), ported with the same key and default. matlab and python both persist to ~/.ndi/NDI_Preferences.json on all platforms (synchronized 2026-05-11). NDI-matlab 9a9150e7c and the two commits before it add preference items: diff --git a/src/ndi/preferences.py b/src/ndi/preferences.py index 03cb5eaf..35b45e24 100644 --- a/src/ndi/preferences.py +++ b/src/ndi/preferences.py @@ -224,6 +224,18 @@ def _register_defaults(self) -> None: "float", "Maximum size of file batch upload in bytes (default 250 MB).", ) + self._add_item( + "Cloud", + "Upload", + "Max_File_Batch_Count", + 2000, + "int", + "Maximum number of files in one file batch (zip) upload (default " + "2000). A batch ends at this many files or at Max_File_Batch_Size " + "bytes, whichever comes first. NDI Cloud unpacks and records each " + "batch in one step with a time limit; a zip of ~10,000 small files " + "outran it and none of its files were recorded.", + ) # The two streamed-upload items NDI-matlab registers for # ndi.cloud.upload.SessionWriter, same keys and defaults, so one # setting governs either language's writer. diff --git a/tests/test_cloud_upload_confirm_recorded.py b/tests/test_cloud_upload_confirm_recorded.py new file mode 100644 index 00000000..6970d5f2 --- /dev/null +++ b/tests/test_cloud_upload_confirm_recorded.py @@ -0,0 +1,220 @@ +"""confirmFilesRecorded: make sure NDI Cloud recorded every file an upload sent. + +MATLAB counterpart: tests/+ndi/+unittest/+cloud/+upload/ConfirmFilesRecordedTest.m +(with the fake ndi.test.helper.FakeRecordingServer, mirrored here). + +A batch (zip) upload's success only means S3 has the zip; the server records +the files in a later step that can fail without the client hearing of it (a +dataset lost 327 files this way, ndi-cloud-node#175). confirmFilesRecorded +waits for the records, uploads again what is never recorded, and reports +what is still missing. Needs no cloud access. +""" + +from __future__ import annotations + +import pytest + +from ndi.cloud import upload +from ndi.cloud.api import files as files_api + +UIDS = ["a", "b", "c"] +PATHS = ["/p/a", "/p/b", "/p/c"] + + +class FakeRecordingServer: + """NDI Cloud's file-recording step, scripted. + + Each wait call first records the uids scheduled for it (schedule[n] for + the n-th call), then reports which of the uids asked about are still + unrecorded. resend records a uid at once unless it is in never_record (a + server that keeps failing), refuses it if in refuse_resend, and raises if + in throw_on_resend (as an upload of a missing local file does). + """ + + def __init__( + self, + schedule=(), + never_record=(), + refuse_resend=(), + throw_on_resend=(), + fail_batch_resend=False, + ): + self.schedule = [list(s) for s in schedule] + self.fail_batch_resend = fail_batch_resend + self.batch_resends: list[list[str]] = [] + self.never_record = set(never_record) + self.refuse_resend = set(refuse_resend) + self.throw_on_resend = set(throw_on_resend) + self.recorded: set[str] = set() + self.wait_calls = 0 + self.wait_timeouts: list[float] = [] + self.resent: list[str] = [] + + def wait(self, ids, timeout): + self.wait_calls += 1 + self.wait_timeouts.append(timeout) + if self.wait_calls <= len(self.schedule): + self.recorded.update(self.schedule[self.wait_calls - 1]) + pending = [u for u in ids if u not in self.recorded] + return {"state": "timeout" if pending else "complete", "pending": pending} + + def resend(self, uid, path): + if uid in self.throw_on_resend: + raise FileNotFoundError(f"No such file: {path}") + if uid in self.refuse_resend: + return False, "refused by the fake" + self.resent.append(uid) + if uid not in self.never_record: + self.recorded.add(uid) + return True, "" + + def resend_batch(self, ids, paths): + self.batch_resends.append(list(ids)) + self.resent.extend(ids) + self.recorded.update(u for u in ids if u not in self.never_record) + if self.fail_batch_resend: + return False, "batch refused by the fake" + return True, "" + + +def confirm(S, uids=UIDS, paths=PATHS, **kw): + return upload.confirmFilesRecorded( + "d", + uids, + paths, + wait_fcn=S.wait, + resend_fcn=S.resend, + resend_batch_fcn=S.resend_batch, + **kw, + ) + + +def test_everything_recorded_needs_one_look(): + S = FakeRecordingServer(schedule=[UIDS]) + r = confirm(S) + assert r["ok"] and r["pending"] == [] and r["message"] == "" + assert S.wait_calls == 1 and S.resent == [] + + +def test_waiting_goes_on_while_records_arrive(): + # A slow server that keeps recording is waited for, not duplicated. + S = FakeRecordingServer(schedule=[["a"], ["b"], ["c"]]) + assert confirm(S)["ok"] + assert S.wait_calls == 3 and S.resent == [] + + +def test_a_file_the_server_dropped_is_sent_again(): + S = FakeRecordingServer(schedule=[["a"], ["b"]]) + r = confirm(S, stall_timeout=7, resend_timeout=3) + assert r["ok"] + assert S.resent == ["c"] and r["resent"] == ["c"] and r["pending"] == [] + assert S.wait_timeouts == [ + 7, + 7, + 7, + 3, + ], "stall_timeout while the batch is being recorded, resend_timeout after resending" + + +def test_a_file_never_recorded_is_a_failure(): + S = FakeRecordingServer(schedule=[["a"]], never_record=["c"]) + r = confirm(S) + assert not r["ok"] + assert sorted(S.resent) == ["b", "c"] + assert r["pending"] == ["c"] + assert "1 of 3" in r["message"] and "only_missing" in r["message"] + + +def test_a_resend_that_fails_is_reported(): + S = FakeRecordingServer(schedule=[["a"]], refuse_resend=["b"]) + r = confirm(S) + assert not r["ok"] + assert r["pending"] == ["b"] and S.resent == ["c"] + assert len(r["resend_errors"]) == 1 + assert "refused by the fake" in r["message"] + + +def test_a_resend_that_raises_is_reported_not_raised(): + S = FakeRecordingServer(schedule=[["a", "b"]], throw_on_resend=["c"]) + r = confirm(S) + assert not r["ok"] + assert r["pending"] == ["c"] + assert "/p/c" in r["resend_errors"][0] + + +def test_many_unrecorded_files_are_resent_as_zip_batches(): + # One at a time is far too slow at scale (10,165 files did not finish in + # 40 minutes); past single_file_limit they go as zips. + S = FakeRecordingServer(schedule=[["a"]]) + r = confirm(S, single_file_limit=1) + assert r["ok"] + assert S.batch_resends == [["b", "c"]] + assert r["resent"] == ["b", "c"] + + +def test_a_failed_zip_resend_is_reported_but_still_waited_for(): + # A failed batch may have sent some files: what did arrive counts. + S = FakeRecordingServer(never_record=["c"], fail_batch_resend=True) + r = confirm(S, single_file_limit=0) + assert not r["ok"] + assert r["pending"] == ["c"] + assert "batch refused by the fake" in r["resend_errors"][0] + + +def test_resent_files_are_waited_for_while_records_arrive(): + S = FakeRecordingServer(schedule=[["a"], [], ["b"], ["c"]], never_record=["b", "c"]) + r = confirm(S, stall_timeout=7, resend_timeout=3) + assert r["ok"] + assert S.wait_timeouts == [7, 7, 3, 3] + + +def test_the_default_batch_resend_is_a_capped_zip_upload(monkeypatch, tmp_path): + for u in UIDS: + (tmp_path / u).write_bytes(b"x") + calls = [] + + def _zip(manifest, dataset_id, **kw): + calls.append(([e["file_uid"] for e in manifest], kw.get("org_id"))) + return {"uploaded": len(manifest), "failed": 0, "errors": [], "failed_document_ids": []} + + monkeypatch.setattr(upload, "zipForUpload", _zip) + S = FakeRecordingServer(schedule=[[], UIDS]) + r = upload.confirmFilesRecorded( + "d", + UIDS, + [str(tmp_path / u) for u in UIDS], + org_id="org-1", + wait_fcn=S.wait, + single_file_limit=1, + ) + assert r["ok"] + assert calls == [(UIDS, "org-1")] + + +def test_duplicate_uids_are_checked_once(): + S = FakeRecordingServer(schedule=[["a"]]) + assert confirm(S, uids=["a", "b", "b"], paths=["/p/a", "/p/b", "/p/b"])["ok"] + assert S.resent == ["b"] + + +def test_no_uids_is_nothing_to_do(): + S = FakeRecordingServer() + assert confirm(S, uids=[], paths=[])["ok"] + assert S.wait_calls == 0 + + +def test_paths_must_match_uids(): + with pytest.raises(ValueError): + upload.confirmFilesRecorded("d", ["a", "b"], ["/p/a"]) + + +def test_the_default_resend_is_a_single_file_upload(monkeypatch): + sent = [] + monkeypatch.setattr( + files_api, "getFileUploadURL", lambda org, ds, uid, client=None: f"https://s3/{org}/{uid}" + ) + monkeypatch.setattr(files_api, "putFiles", lambda url, path, **k: sent.append((url, path))) + S = FakeRecordingServer(schedule=[["a", "b"], [], ["c"]]) + r = upload.confirmFilesRecorded("d", UIDS, PATHS, org_id="org-1", wait_fcn=S.wait) + assert r["ok"] + assert sent == [("https://s3/org-1/c", "/p/c")] diff --git a/tests/test_cloud_upload_file_batches.py b/tests/test_cloud_upload_file_batches.py index 028e31bd..88da0042 100644 --- a/tests/test_cloud_upload_file_batches.py +++ b/tests/test_cloud_upload_file_batches.py @@ -104,6 +104,18 @@ def _dataset_org(dataset_id, client=None): monkeypatch.setattr(files_api, "putFiles", _put) monkeypatch.setattr(files_api, "waitForBulkUpload", _wait) + # The server records every file of the zips it unpacked; a test can + # make it drop some (self.unrecorded) to stand for a failed batch step. + self.unrecorded: set[str] = set() + self.record_waits: list[list[str]] = [] + + def _wait_records(dataset_id, uids, timeout=120.0, client=None, **kwargs): + self.record_waits.append(list(uids)) + pending = [u for u in uids if u in self.unrecorded] + return {"state": "timeout" if pending else "complete", "pending": pending} + + monkeypatch.setattr(files_api, "waitForFileUpload", _wait_records) + def _zip(manifest, **kwargs): kwargs.setdefault("retry_pause", 0) @@ -122,6 +134,20 @@ def test_files_fill_a_batch_until_the_next_would_overflow(self, monkeypatch, tmp assert report["uploaded"] == 3 assert report["failed"] == 0 + def test_a_batch_ends_at_the_count_limit(self, monkeypatch, tmp_path): + # NDI Cloud never recorded a zip of 10,165 small files (84 MB, well + # under the size cap); batches are capped by count too. + server = _Server(monkeypatch) + manifest = _manifest(tmp_path, dict.fromkeys("abcde", 1)) + report = _zip(manifest, size_limit=1e9, count_limit=2) + assert [len(z) for z in server.zips] == [2, 2, 1] + assert report["uploaded"] == 5 + + def test_a_non_positive_count_limit_is_refused(self, monkeypatch, tmp_path): + _Server(monkeypatch) + with pytest.raises(ValueError): + _zip(_manifest(tmp_path, {"a": 1}), count_limit=0) + def test_a_file_bigger_than_the_limit_goes_up_alone(self, monkeypatch, tmp_path): server = _Server(monkeypatch) manifest = _manifest(tmp_path, {"a": 10, "big": 500, "c": 10}) @@ -175,6 +201,21 @@ def test_the_default_preference_is_250_mb(self, tmp_path): prefs = ndi.preferences.ndi_preferences(tmp_path / "prefs.json") assert prefs.get("Cloud.Upload.Max_File_Batch_Size") == 250_000_000 + def test_the_default_count_preference_is_2000(self, tmp_path): + prefs = ndi.preferences.ndi_preferences(tmp_path / "prefs.json") + assert prefs.get("Cloud.Upload.Max_File_Batch_Count") == 2000 + + def test_no_count_limit_reads_max_file_batch_count(self, monkeypatch, tmp_path): + server = _Server(monkeypatch) + real_get = ndi.preferences.get + monkeypatch.setattr( + ndi.preferences, + "get", + lambda path: 2 if path == "Cloud.Upload.Max_File_Batch_Count" else real_get(path), + ) + _zip(_manifest(tmp_path, {"a": 1, "b": 1, "c": 1})) + assert [sorted(z) for z in server.zips] == [["uid-a", "uid-b"], ["uid-c"]] + class TestFailuresNameTheirDocuments: def test_an_extraction_job_that_fails_fails_its_batch_only(self, monkeypatch, tmp_path): @@ -318,6 +359,71 @@ def test_serial_counts_a_file_cloud_never_recorded_as_failed(self, monkeypatch, assert "not recorded by NDI Cloud" in report["errors"][0] assert len(report["failed_document_ids"]) == 1 + def _single_file_resends(self, monkeypatch, server, *, records=True): + """Single-file uploads (the resends) next to the server's zip PUTs.""" + resent = [] + zip_put = files_api.putFiles + monkeypatch.setattr( + files_api, "getFileUploadURL", lambda org, ds, uid, client=None: f"https://s3/{uid}" + ) + + def _put(url, path, **kwargs): + if not url.startswith("https://s3/"): + return zip_put(url, path, **kwargs) + uid = url.rsplit("/", 1)[1] + resent.append(uid) + if records: + server.unrecorded.discard(uid) + return True + + monkeypatch.setattr(files_api, "putFiles", _put) + return resent + + def test_batch_confirms_every_file_was_recorded(self, monkeypatch, tmp_path): + server = _Server(monkeypatch) + upload.uploadFilesForDatasetDocuments( + "org-1", CLOUD_ID, self._docs(tmp_path), client=_Client() + ) + assert server.record_waits == [["uid-a", "uid-b"]] + + def test_batch_resends_a_file_the_server_dropped(self, monkeypatch, tmp_path): + """ndi-cloud-node#175: the zip arrived, but the server never recorded uid-b.""" + server = _Server(monkeypatch) + server.unrecorded = {"uid-b"} + resent = self._single_file_resends(monkeypatch, server) + report = upload.uploadFilesForDatasetDocuments( + "org-1", CLOUD_ID, self._docs(tmp_path), client=_Client() + ) + assert resent == ["uid-b"] + assert report["uploaded"] == 2 and report["failed"] == 0 + assert report["failed_document_ids"] == [] + + def test_batch_counts_a_file_never_recorded_as_failed(self, monkeypatch, tmp_path): + server = _Server(monkeypatch) + server.unrecorded = {"uid-b"} + resent = self._single_file_resends(monkeypatch, server, records=False) + report = upload.uploadFilesForDatasetDocuments( + "org-1", CLOUD_ID, self._docs(tmp_path), client=_Client() + ) + assert resent == ["uid-b"] + assert report["uploaded"] == 1 and report["failed"] == 1 + assert report["failed_document_ids"] == ["b"] + assert "not recorded by NDI Cloud" in report["errors"][-1] + + def test_batch_does_not_confirm_files_of_a_failed_batch(self, monkeypatch, tmp_path): + server = _Server(monkeypatch, job_states=["failed"]) + upload.uploadFilesForDatasetDocuments( + "org-1", CLOUD_ID, self._docs(tmp_path), client=_Client() + ) + assert server.record_waits == [], "a failed batch is already reported" + + def test_verification_can_be_turned_off(self, monkeypatch, tmp_path): + server = _Server(monkeypatch) + upload.uploadFilesForDatasetDocuments( + "org-1", CLOUD_ID, self._docs(tmp_path), verify_uploads=False, client=_Client() + ) + assert server.record_waits == [] + def test_an_unknown_strategy_is_refused(self, tmp_path): with pytest.raises(ValueError): upload.uploadFilesForDatasetDocuments( diff --git a/tests/test_gui_preferences_editor.py b/tests/test_gui_preferences_editor.py index 45550004..1ecef14d 100644 --- a/tests/test_gui_preferences_editor.py +++ b/tests/test_gui_preferences_editor.py @@ -244,6 +244,7 @@ def test_rows_cover_the_whole_category(self, tmp_path): "Cloud.Upload.Max_Document_Batch_Count", "Cloud.Upload.Max_Document_Batch_Size", "Cloud.Upload.Max_File_Batch_Size", + "Cloud.Upload.Max_File_Batch_Count", "Cloud.Upload.Send_Batches_As_Zip", "Cloud.Upload.Parallel_Uploads", ] @@ -255,6 +256,7 @@ def test_selecting_a_subcategory_narrows_the_rows(self, tmp_path): "Max_Document_Batch_Count", "Max_Document_Batch_Size", "Max_File_Batch_Size", + "Max_File_Batch_Count", "Send_Batches_As_Zip", "Parallel_Uploads", ] @@ -442,6 +444,7 @@ def test_selecting_a_subcategory_redraws_the_rows(self, tmp_path): assert [lbl.text() for lbl in editor.row_labels.values()] == [ "Max_Document_Batch_Count", "Max_File_Batch_Size", + "Max_File_Batch_Count", "Send_Batches_As_Zip", "Parallel_Uploads", ]