From 7e571f2ea6ced12b85308935ed470e5c4343bdd3 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:05:16 +0100 Subject: [PATCH 01/15] Retry API calls once on proxy 502/503, stop delivery on maintenance update_db (download) and add_file_db (upload) now retry once, after 1 s, when the API answers 502 or 503 without a JSON body. Such an answer comes from the proxy (Traefik), e.g. when the backend closed an idle connection, so the request did not reach the backend and a retry is safe. A 503 with a JSON body comes from dds_web (maintenance). It is raised as the new ServiceUnavailableError and is not retried. The delivery stops: - the failing file is marked as failed and saved in the failed delivery log as before, so retry_add_file_db can still add uploaded files - files not started yet are cancelled (same flag as Ctrl+C) - files already running finish their current step - the error is raised once from the main thread after the workers are done, and the command exits with 1 update_db now also catches ApiResponseError, so a failed update does not stop the other downloads. Changes: - utils: perform_request_with_retry(), backend 503 -> ServiceUnavailableError - constants: API_TRANSIENT_STATUS_CODES, API_RETRY_WAIT - base: stop_for_maintenance(), raise_if_service_unavailable() - custom_decorators: cancel message says "Service unavailable" on maintenance - tests/test_api_retry.py: mocked 502/503/500/400 and maintenance cases --- dds_cli/__main__.py | 3 + dds_cli/base.py | 20 +++ dds_cli/constants.py | 9 + dds_cli/custom_decorators.py | 7 +- dds_cli/data_getter.py | 15 +- dds_cli/data_putter.py | 11 +- dds_cli/exceptions.py | 7 + dds_cli/utils.py | 41 +++++ tests/test_api_retry.py | 309 +++++++++++++++++++++++++++++++++++ 9 files changed, 417 insertions(+), 5 deletions(-) create mode 100644 tests/test_api_retry.py diff --git a/dds_cli/__main__.py b/dds_cli/__main__.py index 1aca90c6b..f28fadcd7 100644 --- a/dds_cli/__main__.py +++ b/dds_cli/__main__.py @@ -1922,6 +1922,9 @@ def get_data( progress=progress, ) ] = next_file + + # Maintenance stopped the download: exit with the error + getter.raise_if_service_unavailable() except ( dds_cli.exceptions.InvalidMethodError, OSError, diff --git a/dds_cli/base.py b/dds_cli/base.py index 74dfd73da..806aede77 100644 --- a/dds_cli/base.py +++ b/dds_cli/base.py @@ -62,6 +62,8 @@ def __init__( # Keyboardinterrupt self.stop_doing = False + # Set when the DDS backend answers 503 (maintenance), see 'stop_for_maintenance' + self.service_unavailable = None # Authenticate the user and get the token if authenticate: @@ -117,6 +119,24 @@ def __exit__(self, exception_type, exception_value, traceback, max_fileerrs: int # Public methods ############################### Public methods # + def stop_for_maintenance(self, err: exceptions.ServiceUnavailableError) -> None: + """Stop the delivery because the DDS backend is unavailable (e.g. maintenance). + + Called from the worker threads. Files not yet started are cancelled (same flag + as Ctrl+C), ongoing files finish their current step. The caller marks its own + file as failed, so it is saved in the failed delivery log as usual. + Call 'raise_if_service_unavailable' after the threads are done. + """ + if self.service_unavailable is None: + self.service_unavailable = err + LOG.error("%s. Stopping: files not started yet are cancelled.", err) + self.stop_doing = True + + def raise_if_service_unavailable(self) -> None: + """Raise the error saved by 'stop_for_maintenance', if any.""" + if self.service_unavailable is not None: + raise self.service_unavailable + def set_token(self, token_dict: dict) -> None: """Sets the token for the base class. Called from auth class to set the token when authenticating diff --git a/dds_cli/constants.py b/dds_cli/constants.py index 538f0d218..0cc5e2263 100644 --- a/dds_cli/constants.py +++ b/dds_cli/constants.py @@ -6,6 +6,13 @@ TODO: Move other constants here from __init__.py. """ +# Retry once on these API status codes, but only if the answer came from the proxy +# (Traefik, no JSON body). A 502 there usually means the backend closed an idle +# connection, i.e. the request did not reach the backend, so a retry is safe. +# A 503 from the DDS backend (maintenance) is never retried. +API_TRANSIENT_STATUS_CODES = (502, 503) +API_RETRY_WAIT = 1 # seconds + # Timeout settings for upload and download READ_TIMEOUT = 300 CONNECT_TIMEOUT = 60 @@ -17,6 +24,8 @@ # Import these constants when using '*' __all__ = [ + "API_TRANSIENT_STATUS_CODES", + "API_RETRY_WAIT", "READ_TIMEOUT", "CONNECT_TIMEOUT", "DOWNLOAD_MAX_RETRIES", diff --git a/dds_cli/custom_decorators.py b/dds_cli/custom_decorators.py index a26048fa3..e0556abc8 100644 --- a/dds_cli/custom_decorators.py +++ b/dds_cli/custom_decorators.py @@ -40,7 +40,12 @@ def wrapped(self, file, *args, **kwargs): # Check if keyboardinterrupt in dds if self.stop_doing: # TODO (ina): Add save to status here - message = f"KeyboardInterrupt - cancelling file {escape(file)}" + reason = ( + "Service unavailable" + if getattr(self, "service_unavailable", None) + else "KeyboardInterrupt" + ) + message = f"{reason} - cancelling file {escape(file)}" LOG.warning(message) return False # Do not proceed diff --git a/dds_cli/data_getter.py b/dds_cli/data_getter.py index 3df12826a..cd30825fe 100644 --- a/dds_cli/data_getter.py +++ b/dds_cli/data_getter.py @@ -387,9 +387,11 @@ def update_db(self, file): filename = {"name": fileinfo["name_in_db"]} params = {"project": self.project} - # Send file info to API + # Send file info to API. + # Catch all API errors: a failed update must not stop the other downloads. + # Exception: maintenance (ServiceUnavailableError) stops the files not started yet. try: - response_json, _ = dds_cli.utils.perform_request( + response_json, _ = dds_cli.utils.perform_request_with_retry( DDSEndpoint.FILE_UPDATE, method="put", params=params, @@ -397,7 +399,14 @@ def update_db(self, file): headers=self.token, error_message="Failed to update file information", ) - except dds_cli.exceptions.ApiRequestError as err: + except dds_cli.exceptions.ServiceUnavailableError as err: + self.stop_for_maintenance(err) + message = str(err) + except ( + dds_cli.exceptions.ApiRequestError, + dds_cli.exceptions.ApiResponseError, + dds_cli.exceptions.DDSCLIException, + ) as err: updated_in_db = False message = str(err) else: diff --git a/dds_cli/data_putter.py b/dds_cli/data_putter.py index e3ab3a2fe..7c9c9ecbf 100644 --- a/dds_cli/data_putter.py +++ b/dds_cli/data_putter.py @@ -191,6 +191,9 @@ def put( # Single project metadata refresh after batch (date_updated / last_updated_by) putter.touch_project_after_upload() + # Maintenance stopped the upload: exit with the error + putter.raise_if_service_unavailable() + ############################################################################### # CLASSES ########################################################### CLASSES # @@ -453,7 +456,8 @@ def add_file_db(self, file): # Send file info to API - post if new file, put if overwrite request_method = "put" if fileinfo["overwrite"] else "post" try: - response_json, _ = dds_cli.utils.perform_request( + # Retry once on 502/503 before we fall back to 'retry_add_file_db' at the end. + response_json, _ = dds_cli.utils.perform_request_with_retry( DDSEndpoint.FILE_NEW, method=request_method, params=params, @@ -465,6 +469,11 @@ def add_file_db(self, file): LOG.debug("API call for file '%s: Adding to database'", fileinfo["path_raw"]) with self._db_add_lock: self.any_successful_db_add = True + except dds_cli.exceptions.ServiceUnavailableError as err: + # Maintenance: stop the upload. Don't raise here: this file is in the bucket, + # so it must be saved in the failed delivery log ('add_file_db' failed). + self.stop_for_maintenance(err) + message = str(err) except ( dds_cli.exceptions.ApiRequestError, dds_cli.exceptions.ApiResponseError, diff --git a/dds_cli/exceptions.py b/dds_cli/exceptions.py index 43ed664fc..b53d8ad82 100644 --- a/dds_cli/exceptions.py +++ b/dds_cli/exceptions.py @@ -44,6 +44,13 @@ def __str__(self): return msg +class ServiceUnavailableError(DDSCLIException): + """The DDS backend answered 503 Service Unavailable, e.g. because maintenance is ongoing. + + Ongoing deliveries must stop: this is not retried and not ignored. + """ + + class AuthenticationError(click.ClickException): """Errors due to user authentication.""" diff --git a/dds_cli/utils.py b/dds_cli/utils.py index 2751d7e81..336a42696 100644 --- a/dds_cli/utils.py +++ b/dds_cli/utils.py @@ -6,6 +6,7 @@ import http from typing import Dict, List, Union import logging +import time from datetime import datetime import requests @@ -19,6 +20,9 @@ import dds_cli.exceptions from dds_cli import __version__, DDSEndpoint +from dds_cli import constants + +LOG = logging.getLogger(__name__) console = rich.console.Console() stderr_console = rich.console.Console(stderr=True) @@ -298,6 +302,14 @@ def transform_paths(json_input): message=message, status_code=response.status_code ) + # Handle 503 from the DDS backend itself, e.g. maintenance. + # (A 503 from the proxy has no JSON body and is raised as ApiResponseError above.) + if response.status_code == http.HTTPStatus.SERVICE_UNAVAILABLE: + raise dds_cli.exceptions.ServiceUnavailableError( + message=f"{message}: {response_json.get('message', 'Service unavailable')}", + status_code=response.status_code, + ) + raise dds_cli.exceptions.DDSCLIException( message=f"{message}: {response_json.get('message', 'Unexpected error!')}", status_code=response.status_code, @@ -306,6 +318,35 @@ def transform_paths(json_input): return response_json, additional_errors +def perform_request_with_retry(*args, retries: int = 1, **kwargs): + """Same as perform_request, but retry on a transient error from the proxy (502, 503). + + A 502 from Traefik usually means that the backend closed an idle keep-alive + connection just before the request was sent. The request did not reach the + backend, so it is safe to send it again. + + Only answers without a JSON body are retried (raised as ApiResponseError), i.e. + answers from the proxy. A 503 from the DDS backend (maintenance) has a JSON body, + is raised as ServiceUnavailableError and is not retried. + """ + for attempt in range(retries + 1): + try: + return perform_request(*args, **kwargs) + except dds_cli.exceptions.ApiResponseError as err: + status_code = getattr(err, "status_code", None) + if status_code not in constants.API_TRANSIENT_STATUS_CODES or attempt >= retries: + raise + LOG.warning( + "API request failed with status %s, retrying in %ss: %s", + status_code, + constants.API_RETRY_WAIT, + err, + ) + time.sleep(constants.API_RETRY_WAIT) + # Not reached: the last attempt either returns or raises. + raise RuntimeError("perform_request_with_retry: no attempts made") + + def parse_project_errors(errors): """Parse all errors related to projects.""" msg = "" diff --git a/tests/test_api_retry.py b/tests/test_api_retry.py new file mode 100644 index 000000000..c509a3ece --- /dev/null +++ b/tests/test_api_retry.py @@ -0,0 +1,309 @@ +"""Tests for retrying API requests on 502/503 (update_db, add_file_db).""" + +# IMPORTS ###################################################################### + +import pathlib +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest + +import dds_cli.exceptions +import dds_cli.utils +from dds_cli import constants +from dds_cli.data_getter import DataGetter +from dds_cli.data_putter import DataPutter + +# HELPERS ###################################################################### + + +def _prepare_data_getter(file_name): + """DataGetter with one file, without running __init__.""" + getter = DataGetter.__new__(DataGetter) + getter.filehandler = SimpleNamespace( + data={file_name: {"name_in_db": file_name, "path_downloaded": pathlib.Path(file_name)}} + ) + return getter + + +def _api_response(status_code, json_body=None): + """Mock API response. Without json_body, .json() fails like the 11-byte 'Bad Gateway'.""" + import simplejson + + response = MagicMock() + response.status_code = status_code + response.ok = status_code < 400 + response.reason = "Bad Gateway" if status_code == 502 else "OK" + if json_body is None: + response.json.side_effect = simplejson.JSONDecodeError("Expecting value", "Bad Gateway", 0) + else: + response.json.return_value = json_body + return response + + +def _update_db_getter(): + getter = _prepare_data_getter("file.bin") + getter.project = "proj00001" + getter.token = {"Authorization": "Bearer x"} + getter.stop_doing = False + getter.service_unavailable = None + return getter + + +# TESTS ######################################################################## + + +def test_update_db_retries_once_on_502(monkeypatch): + """A 502 from the proxy is retried once, and the second try succeeds.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + responses = iter([_api_response(502), _api_response(200, {"message": "File info updated."})]) + mock_put = MagicMock(side_effect=lambda **_: next(responses)) + monkeypatch.setattr("dds_cli.utils.requests.put", mock_put) + + updated, message = DataGetter.update_db.__wrapped__(_update_db_getter(), file="file.bin") + + assert (updated, message) == (True, "File info updated.") + assert mock_put.call_count == 2 + + +def test_update_db_502_does_not_raise(monkeypatch): + """Two 502s in a row: report the failure, but never stop the whole download.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + mock_put = MagicMock(side_effect=lambda **_: _api_response(502)) + monkeypatch.setattr("dds_cli.utils.requests.put", mock_put) + + updated, message = DataGetter.update_db.__wrapped__(_update_db_getter(), file="file.bin") + + assert updated is False + assert "502" in message + assert mock_put.call_count == 2 + + +def test_update_db_no_retry_on_500(monkeypatch): + """A 500 comes from the backend itself, so it is not retried (but still caught).""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + mock_put = MagicMock(side_effect=lambda **_: _api_response(500, {"message": "Something broke"})) + monkeypatch.setattr("dds_cli.utils.requests.put", mock_put) + + updated, message = DataGetter.update_db.__wrapped__(_update_db_getter(), file="file.bin") + + assert updated is False + assert "Something broke" in message + assert mock_put.call_count == 1 + + +def _putter_with_one_file(): + import threading + from types import SimpleNamespace + + putter = DataPutter.__new__(DataPutter) + putter.project = "proj00001" + putter.token = {"Authorization": "Bearer x"} + putter._db_add_lock = threading.Lock() + putter.any_successful_db_add = False + putter.stop_doing = False + putter.service_unavailable = None + putter.filehandler = SimpleNamespace( + data={ + "file.txt": { + "path_remote": "bucketname", + "subpath": ".", + "size_raw": 4, + "size_processed": 40, + "compressed": False, + "salt": "salt", + "public_key": "key", + "checksum": "abc", + "overwrite": False, + "path_raw": "file.txt", + } + } + ) + return putter + + +def test_add_file_db_retries_once_on_502(monkeypatch): + """POST /file/new that gets a 502 is sent once more right away.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + responses = iter([_api_response(502), _api_response(200, {"message": "File added"})]) + mock_post = MagicMock(side_effect=lambda **_: next(responses)) + monkeypatch.setattr("dds_cli.utils.requests.post", mock_post) + + putter = _putter_with_one_file() + added, _ = DataPutter.add_file_db.__wrapped__(putter, file="file.txt") + + assert added is True + assert putter.any_successful_db_add is True + assert mock_post.call_count == 2 + + +def test_add_file_db_gives_up_after_second_502(monkeypatch): + """Two 502s: return False, so the file is handled by retry_add_file_db at the end.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + mock_post = MagicMock(side_effect=lambda **_: _api_response(502)) + monkeypatch.setattr("dds_cli.utils.requests.post", mock_post) + + added, message = DataPutter.add_file_db.__wrapped__(_putter_with_one_file(), file="file.txt") + + assert added is False + assert "502" in message + assert mock_post.call_count == 2 + + +def test_add_file_db_no_retry_on_400(monkeypatch): + """A 400 (e.g. file already exists) is not a proxy error and is not retried.""" + mock_post = MagicMock( + side_effect=lambda **_: _api_response(400, {"message": "File already exists"}) + ) + monkeypatch.setattr("dds_cli.utils.requests.post", mock_post) + + added, _ = DataPutter.add_file_db.__wrapped__(_putter_with_one_file(), file="file.txt") + + assert added is False + assert mock_post.call_count == 1 + + +def test_perform_request_with_retry_gives_up_after_retries(monkeypatch): + """The last error is raised when all attempts fail.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + err = dds_cli.exceptions.ApiResponseError("Bad Gateway", status_code=502) + mock_request = MagicMock(side_effect=err) + monkeypatch.setattr(dds_cli.utils, "perform_request", mock_request) + + with pytest.raises(dds_cli.exceptions.ApiResponseError): + dds_cli.utils.perform_request_with_retry("url", method="put", retries=2) + + assert mock_request.call_count == 3 + + +def test_perform_request_with_retry_no_retry_on_request_error(monkeypatch): + """A connection error is not retried here (the request may have reached the backend).""" + err = dds_cli.exceptions.ApiRequestError("timeout") + mock_request = MagicMock(side_effect=err) + monkeypatch.setattr(dds_cli.utils, "perform_request", mock_request) + + with pytest.raises(dds_cli.exceptions.ApiRequestError): + dds_cli.utils.perform_request_with_retry("url", method="post") + + assert mock_request.call_count == 1 + + +# MAINTENANCE (503 FROM THE DDS BACKEND) ####################################### + +MAINTENANCE = {"message": "Maintenance of DDS is ongoing."} + + +def test_perform_request_backend_503_is_service_unavailable(monkeypatch): + """A 503 with a JSON body comes from dds_web (maintenance) -> ServiceUnavailableError.""" + monkeypatch.setattr( + "dds_cli.utils.requests.put", MagicMock(return_value=_api_response(503, MAINTENANCE)) + ) + + with pytest.raises(dds_cli.exceptions.ServiceUnavailableError, match="Maintenance") as err: + dds_cli.utils.perform_request("url", method="put") + + # Still a DDSCLIException, so existing callers behave as before. + assert isinstance(err.value, dds_cli.exceptions.DDSCLIException) + assert err.value.status_code == 503 + + +def test_retry_skips_backend_503(monkeypatch): + """Maintenance is not retried.""" + mock_put = MagicMock(return_value=_api_response(503, MAINTENANCE)) + monkeypatch.setattr("dds_cli.utils.requests.put", mock_put) + + with pytest.raises(dds_cli.exceptions.ServiceUnavailableError): + dds_cli.utils.perform_request_with_retry("url", method="put") + + assert mock_put.call_count == 1 + + +def test_retry_proxy_503(monkeypatch): + """A 503 without a JSON body comes from the proxy and is retried once.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + responses = iter([_api_response(503), _api_response(200, {"message": "ok"})]) + mock_put = MagicMock(side_effect=lambda **_: next(responses)) + monkeypatch.setattr("dds_cli.utils.requests.put", mock_put) + + response_json, _ = dds_cli.utils.perform_request_with_retry("url", method="put") + + assert response_json == {"message": "ok"} + assert mock_put.call_count == 2 + + +def test_update_db_stops_download_on_maintenance(monkeypatch): + """update_db on maintenance: no retry, returns failure and stops the files not started.""" + mock_put = MagicMock(return_value=_api_response(503, MAINTENANCE)) + monkeypatch.setattr("dds_cli.utils.requests.put", mock_put) + + getter = _update_db_getter() + updated, message = DataGetter.update_db.__wrapped__(getter, file="file.bin") + + assert updated is False + assert "Maintenance" in message + assert mock_put.call_count == 1 + assert getter.stop_doing is True + assert isinstance(getter.service_unavailable, dds_cli.exceptions.ServiceUnavailableError) + + +def test_add_file_db_stops_upload_on_maintenance(monkeypatch): + """add_file_db on maintenance: no retry, returns failure and stops the files not started.""" + mock_post = MagicMock(return_value=_api_response(503, MAINTENANCE)) + monkeypatch.setattr("dds_cli.utils.requests.post", mock_post) + + putter = _putter_with_one_file() + added, message = DataPutter.add_file_db.__wrapped__(putter, file="file.txt") + + assert added is False + assert "Maintenance" in message + assert mock_post.call_count == 1 + assert putter.any_successful_db_add is False + assert putter.stop_doing is True + assert isinstance(putter.service_unavailable, dds_cli.exceptions.ServiceUnavailableError) + + +def test_add_file_db_maintenance_marks_failed_op(monkeypatch): + """The file is in the bucket: it must get failed_op 'add_file_db', so it is saved in the + failed delivery log and 'retry_add_file_db' can add it later.""" + monkeypatch.setattr( + "dds_cli.utils.requests.post", MagicMock(return_value=_api_response(503, MAINTENANCE)) + ) + putter = _putter_with_one_file() + putter.status = {"file.txt": {"add_file_db": {"started": False, "done": False}}} + + added, _ = DataPutter.add_file_db(putter, file="file.txt") # with @update_status + + assert added is False + assert putter.status["file.txt"]["failed_op"] == "add_file_db" + + +def test_verify_proceed_cancels_new_files_on_maintenance(caplog): + """After maintenance is seen, files not started yet are not started.""" + from dds_cli.custom_decorators import verify_proceed + + called = MagicMock(return_value=(True, "")) + + @verify_proceed + def work(self, file): + return called(file) + + putter = _putter_with_one_file() + putter.stop_for_maintenance(dds_cli.exceptions.ServiceUnavailableError("Maintenance")) + + assert work(putter, "file.txt") is False + called.assert_not_called() + assert "Service unavailable - cancelling file" in caplog.text + + +def test_stop_for_maintenance_keeps_first_error_and_raises_later(): + """The error is raised once, from the main thread, after the workers are done.""" + putter = _putter_with_one_file() + putter.raise_if_service_unavailable() # nothing saved: no error + + first = dds_cli.exceptions.ServiceUnavailableError("first") + putter.stop_for_maintenance(first) + putter.stop_for_maintenance(dds_cli.exceptions.ServiceUnavailableError("second")) + + with pytest.raises(dds_cli.exceptions.ServiceUnavailableError) as err: + putter.raise_if_service_unavailable() + assert err.value is first From b8471b41e882e2609acfbe8c0b183afb53973098 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:10:50 +0100 Subject: [PATCH 02/15] Stop running transfers when maintenance is detected When another thread has seen a backend 503 (maintenance): - running downloads stop at the next chunk, the partial file is removed and no retry is made - no new download attempt is started - an upload that has finished encryption is not sent to S3, so no orphan object is left in the bucket (failed_op "put") An S3 upload that has already started is finished. If add_file_db then fails, the file is in the failed delivery log as before. Ctrl+C behaviour is unchanged. --- dds_cli/base.py | 11 +++-- dds_cli/data_getter.py | 18 +++++++- dds_cli/data_putter.py | 9 +++- tests/test_api_retry.py | 95 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 127 insertions(+), 6 deletions(-) diff --git a/dds_cli/base.py b/dds_cli/base.py index 806aede77..bb7b408ac 100644 --- a/dds_cli/base.py +++ b/dds_cli/base.py @@ -40,6 +40,9 @@ class DDSBaseClass: """Data Delivery System base class. For common operations.""" + # Set when the DDS backend answers 503 (maintenance), see 'stop_for_maintenance' + service_unavailable: typing.Optional[exceptions.ServiceUnavailableError] = None + def __init__( self, project=None, @@ -62,8 +65,6 @@ def __init__( # Keyboardinterrupt self.stop_doing = False - # Set when the DDS backend answers 503 (maintenance), see 'stop_for_maintenance' - self.service_unavailable = None # Authenticate the user and get the token if authenticate: @@ -123,8 +124,10 @@ def stop_for_maintenance(self, err: exceptions.ServiceUnavailableError) -> None: """Stop the delivery because the DDS backend is unavailable (e.g. maintenance). Called from the worker threads. Files not yet started are cancelled (same flag - as Ctrl+C), ongoing files finish their current step. The caller marks its own - file as failed, so it is saved in the failed delivery log as usual. + as Ctrl+C). Ongoing downloads stop at the next chunk, ongoing uploads stop + before the S3 upload; an S3 upload that has already started is finished. + The caller marks its own file as failed, so it is saved in the failed + delivery log as usual. Call 'raise_if_service_unavailable' after the threads are done. """ if self.service_unavailable is None: diff --git a/dds_cli/data_getter.py b/dds_cli/data_getter.py index cd30825fe..588f239ea 100644 --- a/dds_cli/data_getter.py +++ b/dds_cli/data_getter.py @@ -257,9 +257,14 @@ def get(self, file, progress, task): backoff_factor = constants.DOWNLOAD_BACKOFF_FACTOR wait = constants.DOWNLOAD_INITIAL_WAIT retry_messages = [] + cancelled = False for attempt in range(1, max_retries + 1): error = "" + if self.service_unavailable: + # Maintenance seen by another thread: don't start a new attempt. + cancelled = True + break if attempt > 1: progress.reset(task, completed=0) # Drop the partial file from the previous attempt before retrying. @@ -287,10 +292,17 @@ def get(self, file, progress, task): content_length = 0 with file_local.open(mode="wb") as new_file: for chunk in req.iter_content(chunk_size=FileSegment.SEGMENT_SIZE_CIPHER): + if self.service_unavailable: + # Maintenance seen by another thread: stop this download. + cancelled = True + break progress.update(task, advance=len(chunk)) new_file.write(chunk) bytes_written += len(chunk) + if cancelled: + break + # Guard against silent truncation: requests/urllib3 do not # validate that bytes received == Content-Length. A clean TCP # FIN mid-stream otherwise looks like an EOF and the loop exits @@ -340,7 +352,11 @@ def get(self, file, progress, task): ) break - if not downloaded and error: + if cancelled: + error = f"Service unavailable - download of '{file_name_in_db}' cancelled" + LOG.warning(error) + self._remove_partial(file_local, file_name_in_db) + elif not downloaded and error: if retry_messages: error = " | ".join(retry_messages) + f" | Final error: {error}" LOG.error( diff --git a/dds_cli/data_putter.py b/dds_cli/data_putter.py index 7c9c9ecbf..4c53799cc 100644 --- a/dds_cli/data_putter.py +++ b/dds_cli/data_putter.py @@ -344,7 +344,14 @@ def protect_and_upload(self, file, progress): file_info["path_processed"].stat().st_size, ) - if saved: + if saved and self.service_unavailable: + # Maintenance seen by another thread: don't upload. The file could not be + # added to the database, so it would only be an orphan object in the bucket. + message = f"Service unavailable - upload of '{file_path_raw}' cancelled" + LOG.warning(message) + self.status[file]["failed_op"] = "put" + dr.DataRemover.delete_tempfile(file=file_info["path_processed"]) + elif saved: LOG.debug( "File successfully encrypted: '%s'", file_path_raw, diff --git a/tests/test_api_retry.py b/tests/test_api_retry.py index c509a3ece..a43527158 100644 --- a/tests/test_api_retry.py +++ b/tests/test_api_retry.py @@ -307,3 +307,98 @@ def test_stop_for_maintenance_keeps_first_error_and_raises_later(): with pytest.raises(dds_cli.exceptions.ServiceUnavailableError) as err: putter.raise_if_service_unavailable() assert err.value is first + + +# IN-FLIGHT FILES ON MAINTENANCE ############################################### + + +def _download_response(chunks): + response = MagicMock() + response.__enter__.return_value = response + response.__exit__.return_value = False + response.iter_content.return_value = chunks + response.raise_for_status.return_value = None + response.headers.get.return_value = 8 + return response + + +def _getter_for_download(tmp_path): + getter = _update_db_getter() + getter.filehandler.data["file.bin"].update( + {"path_downloaded": tmp_path / "file.bin", "url": "https://example.com/f", "size_stored": 8} + ) + return getter + + +def test_get_stops_running_download_on_maintenance(monkeypatch, tmp_path, caplog): + """Maintenance seen by another thread stops a running download at the next chunk.""" + getter = _getter_for_download(tmp_path) + + def chunks(): + yield b"data" + getter.stop_for_maintenance(dds_cli.exceptions.ServiceUnavailableError("Maintenance")) + yield b"more" + + mock_get = MagicMock(return_value=_download_response(chunks())) + monkeypatch.setattr("dds_cli.data_getter.requests.get", mock_get) + + downloaded, message = DataGetter.get.__wrapped__( + getter, file="file.bin", progress=MagicMock(), task=1 + ) + + assert downloaded is False + assert "Service unavailable" in message + assert mock_get.call_count == 1 # no retry + assert not (tmp_path / "file.bin").exists() # partial file removed + assert "could not be completed" not in caplog.text # no network advice + + +def test_get_not_started_on_maintenance(monkeypatch, tmp_path): + """No GET is sent once maintenance is known.""" + getter = _getter_for_download(tmp_path) + getter.stop_for_maintenance(dds_cli.exceptions.ServiceUnavailableError("Maintenance")) + mock_get = MagicMock() + monkeypatch.setattr("dds_cli.data_getter.requests.get", mock_get) + + downloaded, message = DataGetter.get.__wrapped__( + getter, file="file.bin", progress=MagicMock(), task=1 + ) + + assert downloaded is False + assert "Service unavailable" in message + mock_get.assert_not_called() + + +def test_upload_skips_s3_put_on_maintenance(monkeypatch, tmp_path): + """A file encrypted after maintenance is known is not uploaded (no orphan object).""" + processed = tmp_path / "file.txt.ccp" + processed.write_bytes(b"encrypted") + + putter = _putter_with_one_file() + putter.filehandler.data["file.txt"]["path_processed"] = processed + putter.filehandler.stream_from_file = MagicMock() + putter.keys = None + putter.silent = True + putter.method = "put" + putter.status = {"file.txt": {}} + putter.put = MagicMock() + putter.add_file_db = MagicMock() + + encryptor = MagicMock() + encryptor.encrypt_filechunks.return_value = (True, "") + encryptor_cm = MagicMock() + encryptor_cm.__enter__.return_value = encryptor + monkeypatch.setattr("dds_cli.data_putter.fe.Encryptor", MagicMock(return_value=encryptor_cm)) + + putter.stop_for_maintenance(dds_cli.exceptions.ServiceUnavailableError("Maintenance")) + # Skip @verify_proceed (stop_doing would cancel before encryption) and @subpath_required + ok, message = DataPutter.protect_and_upload.__wrapped__.__wrapped__( + putter, file="file.txt", progress=MagicMock() + ) + + assert ok is False + assert "Service unavailable" in message + putter.put.assert_not_called() + putter.add_file_db.assert_not_called() + assert putter.status["file.txt"]["failed_op"] == "put" + assert not processed.exists() From 966e1df70da6fce282163f54ce33839ded423fc4 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:16:09 +0100 Subject: [PATCH 03/15] Detect a POST file/new that reached the backend before a proxy 502 A proxy 502/503 does not always mean that the backend did not get the request. If the first POST added the file, the retry fails because the file exists (500 from dds_web) and the file was reported as failed, although S3 and the database were fine. After a failed POST, ask file/match: if the file is in the database with the name_in_bucket of this upload, it was added by our own request and is treated as added. PUT (overwrite) is not checked. --- dds_cli/data_putter.py | 38 ++++++++++++++++++++- tests/test_api_retry.py | 75 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+), 1 deletion(-) diff --git a/dds_cli/data_putter.py b/dds_cli/data_putter.py index 4c53799cc..b2d4b7069 100644 --- a/dds_cli/data_putter.py +++ b/dds_cli/data_putter.py @@ -487,10 +487,46 @@ def add_file_db(self, file): dds_cli.exceptions.DDSCLIException, ) as err: message = str(err) - LOG.warning(message) + if request_method == "post" and self._added_by_earlier_request(file=file): + # The first POST got a proxy 502/503 but did reach the backend, so the + # retry failed because the file already exists. The file is added. + added_to_db, message = (True, f"File '{file}' added to db.") + with self._db_add_lock: + self.any_successful_db_add = True + else: + LOG.warning(message) return added_to_db, message + def _added_by_earlier_request(self, file) -> bool: + """Check if the file is in the database with the name in bucket of this upload. + + 'name_in_bucket' is new for each upload, so a match means that one of our own + requests added the file. Any error here: return False (the file stays failed). + """ + try: + response_json, _ = dds_cli.utils.perform_request( + DDSEndpoint.FILE_MATCH, + method="get", + params={"project": self.project}, + headers=self.token, + json=[file], + error_message="Failed to check if the file is in the database", + ) + except ( + dds_cli.exceptions.ApiRequestError, + dds_cli.exceptions.ApiResponseError, + dds_cli.exceptions.DDSCLIException, + ) as err: + LOG.debug("Could not check if '%s' is in the database: %s", escape(file), err) + return False + + files_in_db = response_json.get("files") or {} + added = files_in_db.get(file) == self.filehandler.data[file]["path_remote"] + if added: + LOG.info("File '%s' was added to the database by an earlier request.", escape(file)) + return added + def retry_add_file_db(self): """Attempting to save the files to the database. diff --git a/tests/test_api_retry.py b/tests/test_api_retry.py index a43527158..636129f5f 100644 --- a/tests/test_api_retry.py +++ b/tests/test_api_retry.py @@ -53,6 +53,14 @@ def _update_db_getter(): # TESTS ######################################################################## +@pytest.fixture(autouse=True) +def file_match_empty(monkeypatch): + """GET file/match (used after a failed POST file/new): no files in the database.""" + mock_get = MagicMock(return_value=_api_response(200, {"files": None})) + monkeypatch.setattr("dds_cli.utils.requests.get", mock_get) + return mock_get + + def test_update_db_retries_once_on_502(monkeypatch): """A 502 from the proxy is retried once, and the second try succeeds.""" monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) @@ -402,3 +410,70 @@ def test_upload_skips_s3_put_on_maintenance(monkeypatch, tmp_path): putter.add_file_db.assert_not_called() assert putter.status["file.txt"]["failed_op"] == "put" assert not processed.exists() + + +# POST REACHED THE BACKEND BUT THE CLIENT GOT A 502 ############################ + +FILE_EXISTS_500 = {"message": "Internal Server Error"} # FileExistsError is not handled + + +def test_add_file_db_502_then_exists_is_added(monkeypatch, file_match_empty): + """First POST added the row but the client got a 502; the retry fails because the + file exists. file/match shows our name_in_bucket, so the file is added.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + responses = iter([_api_response(502), _api_response(500, FILE_EXISTS_500)]) + mock_post = MagicMock(side_effect=lambda **_: next(responses)) + monkeypatch.setattr("dds_cli.utils.requests.post", mock_post) + file_match_empty.return_value = _api_response(200, {"files": {"file.txt": "bucketname"}}) + + putter = _putter_with_one_file() + added, _ = DataPutter.add_file_db.__wrapped__(putter, file="file.txt") + + assert added is True + assert putter.any_successful_db_add is True + assert mock_post.call_count == 2 + assert file_match_empty.call_args.kwargs["json"] == ["file.txt"] + + +def test_add_file_db_exists_with_other_name_in_bucket_fails(monkeypatch, file_match_empty): + """The file is in the database, but from another upload: still a failure.""" + monkeypatch.setattr( + "dds_cli.utils.requests.post", + MagicMock(return_value=_api_response(500, FILE_EXISTS_500)), + ) + file_match_empty.return_value = _api_response(200, {"files": {"file.txt": "other"}}) + + putter = _putter_with_one_file() + added, _ = DataPutter.add_file_db.__wrapped__(putter, file="file.txt") + + assert added is False + assert putter.any_successful_db_add is False + + +def test_add_file_db_match_check_fails(monkeypatch, file_match_empty): + """If file/match fails too, the file stays failed with the original error.""" + monkeypatch.setattr( + "dds_cli.utils.requests.post", + MagicMock(return_value=_api_response(500, FILE_EXISTS_500)), + ) + file_match_empty.return_value = _api_response(502) + + added, message = DataPutter.add_file_db.__wrapped__(_putter_with_one_file(), file="file.txt") + + assert added is False + assert "Internal Server Error" in message + + +def test_add_file_db_put_is_not_checked(monkeypatch, file_match_empty): + """Overwrite (PUT): the file was in the database before, so file/match tells nothing.""" + monkeypatch.setattr( + "dds_cli.utils.requests.put", + MagicMock(return_value=_api_response(500, FILE_EXISTS_500)), + ) + putter = _putter_with_one_file() + putter.filehandler.data["file.txt"]["overwrite"] = True + + added, _ = DataPutter.add_file_db.__wrapped__(putter, file="file.txt") + + assert added is False + file_match_empty.assert_not_called() From 91ece164d67e290b7838fbc027985fb018954810 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:28:11 +0100 Subject: [PATCH 04/15] Make the API retry rule explicit: no JSON body and 502/503 An answer without a JSON body is now raised as NonJsonResponseError (subclass of ApiResponseError, so existing callers are not affected). perform_request_with_retry retries only this error, and only for the status codes in API_NON_JSON_RETRY_STATUS_CODES (renamed from API_TRANSIENT_STATUS_CODES). Before, the rule depended on which exception type perform_request happened to raise: any ApiResponseError with status 502/503 would have been retried, while a 503 from the DDS API (maintenance) must never be. --- dds_cli/constants.py | 14 ++++++++------ dds_cli/exceptions.py | 7 +++++++ dds_cli/utils.py | 18 ++++++++++-------- tests/test_api_retry.py | 37 ++++++++++++++++++++++++++++++++++++- 4 files changed, 61 insertions(+), 15 deletions(-) diff --git a/dds_cli/constants.py b/dds_cli/constants.py index 0cc5e2263..f7d708a1f 100644 --- a/dds_cli/constants.py +++ b/dds_cli/constants.py @@ -6,11 +6,13 @@ TODO: Move other constants here from __init__.py. """ -# Retry once on these API status codes, but only if the answer came from the proxy -# (Traefik, no JSON body). A 502 there usually means the backend closed an idle -# connection, i.e. the request did not reach the backend, so a retry is safe. -# A 503 from the DDS backend (maintenance) is never retried. -API_TRANSIENT_STATUS_CODES = (502, 503) +# perform_request_with_retry retries once on an answer with one of these status codes +# AND without a JSON body (NonJsonResponseError). Such an answer comes from the proxy +# (Traefik), not from the DDS API: a 502 there usually means the backend closed an idle +# connection, i.e. the request did not reach the backend. +# The status code alone is not enough: a 503 WITH a JSON body comes from the DDS API +# (maintenance, ServiceUnavailableError) and must never be retried. +API_NON_JSON_RETRY_STATUS_CODES = (502, 503) API_RETRY_WAIT = 1 # seconds # Timeout settings for upload and download @@ -24,7 +26,7 @@ # Import these constants when using '*' __all__ = [ - "API_TRANSIENT_STATUS_CODES", + "API_NON_JSON_RETRY_STATUS_CODES", "API_RETRY_WAIT", "READ_TIMEOUT", "CONNECT_TIMEOUT", diff --git a/dds_cli/exceptions.py b/dds_cli/exceptions.py index b53d8ad82..b195ed35c 100644 --- a/dds_cli/exceptions.py +++ b/dds_cli/exceptions.py @@ -106,6 +106,13 @@ def __init__(self, message, status_code=None): super().__init__(message) +class NonJsonResponseError(ApiResponseError): + """The answer has no valid JSON body, so it did not come from the DDS API. + + Usually an error page from the proxy (Traefik), e.g. 502 Bad Gateway. + """ + + class UploadError(Exception): """Errors relating to file uploads.""" diff --git a/dds_cli/utils.py b/dds_cli/utils.py index 336a42696..9ec51cfec 100644 --- a/dds_cli/utils.py +++ b/dds_cli/utils.py @@ -243,7 +243,7 @@ def transform_paths(json_input): ) response_json = response.json() except simplejson.JSONDecodeError as err: - raise dds_cli.exceptions.ApiResponseError( + raise dds_cli.exceptions.NonJsonResponseError( message=( f"Response code: {response.status_code}. " f"The request did not return a valid JSON response. Details: {err}" @@ -303,7 +303,7 @@ def transform_paths(json_input): ) # Handle 503 from the DDS backend itself, e.g. maintenance. - # (A 503 from the proxy has no JSON body and is raised as ApiResponseError above.) + # (A 503 from the proxy has no JSON body and is raised as NonJsonResponseError above.) if response.status_code == http.HTTPStatus.SERVICE_UNAVAILABLE: raise dds_cli.exceptions.ServiceUnavailableError( message=f"{message}: {response_json.get('message', 'Service unavailable')}", @@ -319,22 +319,24 @@ def transform_paths(json_input): def perform_request_with_retry(*args, retries: int = 1, **kwargs): - """Same as perform_request, but retry on a transient error from the proxy (502, 503). + """Same as perform_request, but retry on a 502/503 from the proxy. A 502 from Traefik usually means that the backend closed an idle keep-alive connection just before the request was sent. The request did not reach the backend, so it is safe to send it again. - Only answers without a JSON body are retried (raised as ApiResponseError), i.e. - answers from the proxy. A 503 from the DDS backend (maintenance) has a JSON body, - is raised as ServiceUnavailableError and is not retried. + Both conditions are needed for a retry: + - the answer has no JSON body (NonJsonResponseError), i.e. it is from the proxy + - the status code is in API_NON_JSON_RETRY_STATUS_CODES + A 503 from the DDS API (maintenance) has a JSON body, is raised as + ServiceUnavailableError and is never retried. """ for attempt in range(retries + 1): try: return perform_request(*args, **kwargs) - except dds_cli.exceptions.ApiResponseError as err: + except dds_cli.exceptions.NonJsonResponseError as err: status_code = getattr(err, "status_code", None) - if status_code not in constants.API_TRANSIENT_STATUS_CODES or attempt >= retries: + if status_code not in constants.API_NON_JSON_RETRY_STATUS_CODES or attempt >= retries: raise LOG.warning( "API request failed with status %s, retrying in %ss: %s", diff --git a/tests/test_api_retry.py b/tests/test_api_retry.py index 636129f5f..27f43668f 100644 --- a/tests/test_api_retry.py +++ b/tests/test_api_retry.py @@ -174,7 +174,7 @@ def test_add_file_db_no_retry_on_400(monkeypatch): def test_perform_request_with_retry_gives_up_after_retries(monkeypatch): """The last error is raised when all attempts fail.""" monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) - err = dds_cli.exceptions.ApiResponseError("Bad Gateway", status_code=502) + err = dds_cli.exceptions.NonJsonResponseError("Bad Gateway", status_code=502) mock_request = MagicMock(side_effect=err) monkeypatch.setattr(dds_cli.utils, "perform_request", mock_request) @@ -477,3 +477,38 @@ def test_add_file_db_put_is_not_checked(monkeypatch, file_match_empty): assert added is False file_match_empty.assert_not_called() + + +# THE RETRY NEEDS BOTH: NO JSON BODY AND 502/503 ############################### + + +def test_no_json_body_is_non_json_response_error(monkeypatch): + """An answer without a JSON body is NonJsonResponseError (still an ApiResponseError).""" + monkeypatch.setattr("dds_cli.utils.requests.put", MagicMock(return_value=_api_response(502))) + with pytest.raises(dds_cli.exceptions.NonJsonResponseError) as err: + dds_cli.utils.perform_request("https://x/file/update", method="put", headers={}) + assert isinstance(err.value, dds_cli.exceptions.ApiResponseError) + assert err.value.status_code == 502 + + +def test_retry_skips_json_502(monkeypatch): + """A 502 WITH a JSON body comes from the DDS API: not retried.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + mock_put = MagicMock(return_value=_api_response(502, {"message": "from the API"})) + monkeypatch.setattr("dds_cli.utils.requests.put", mock_put) + + with pytest.raises(dds_cli.exceptions.DDSCLIException): + dds_cli.utils.perform_request_with_retry("https://x/file/update", method="put", headers={}) + assert mock_put.call_count == 1 + + +def test_retry_skips_api_response_error_with_502_status(monkeypatch): + """Only NonJsonResponseError is retried, not any ApiResponseError with status 502.""" + monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) + err = dds_cli.exceptions.ApiResponseError("JSON error", status_code=502) + mock_request = MagicMock(side_effect=err) + monkeypatch.setattr("dds_cli.utils.perform_request", mock_request) + + with pytest.raises(dds_cli.exceptions.ApiResponseError): + dds_cli.utils.perform_request_with_retry("https://x", method="put", headers={}) + assert mock_request.call_count == 1 From c5b927e7aa930364c71df6e238cbd7b43eb4cef3 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:39:07 +0100 Subject: [PATCH 05/15] Skip the end-of-batch DB calls when maintenance stopped the upload If maintenance (backend 503) stopped the upload, put() no longer calls retry_add_file_db and touch_project_after_upload: the API is down and these calls only add more 503 errors. The path to the failed delivery log is still shown, then the maintenance error is raised. --- dds_cli/data_putter.py | 12 ++++++--- tests/test_api_retry.py | 59 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 3 deletions(-) diff --git a/dds_cli/data_putter.py b/dds_cli/data_putter.py index b2d4b7069..a654d3cc8 100644 --- a/dds_cli/data_putter.py +++ b/dds_cli/data_putter.py @@ -169,6 +169,15 @@ def put( for x in [y.id for y in progress.tasks if y.fields.get("step") != "put"] ] + # Maintenance stopped the upload: the API is down, don't call it again. + if putter.service_unavailable is not None: + if putter.failed_delivery_log.is_file(): + LOG.warning( + "The files that failed are listed in: %s", + str(putter.failed_delivery_log), + ) + putter.raise_if_service_unavailable() + # Make a single database update for files that have failed # Json file for failed files should only be created if there has been an error if putter.failed_delivery_log.is_file(): @@ -191,9 +200,6 @@ def put( # Single project metadata refresh after batch (date_updated / last_updated_by) putter.touch_project_after_upload() - # Maintenance stopped the upload: exit with the error - putter.raise_if_service_unavailable() - ############################################################################### # CLASSES ########################################################### CLASSES # diff --git a/tests/test_api_retry.py b/tests/test_api_retry.py index 27f43668f..71f3f7d1b 100644 --- a/tests/test_api_retry.py +++ b/tests/test_api_retry.py @@ -512,3 +512,62 @@ def test_retry_skips_api_response_error_with_502_status(monkeypatch): with pytest.raises(dds_cli.exceptions.ApiResponseError): dds_cli.utils.perform_request_with_retry("https://x", method="put", headers={}) assert mock_request.call_count == 1 + + +# END OF UPLOAD BATCH ########################################################## + + +def _run_put_with(monkeypatch, putter): + """Run data_putter.put() with a mocked DataPutter and no files to upload.""" + import dds_cli.data_putter + + putter_cm = MagicMock() + putter_cm.__enter__.return_value = putter + putter_cm.__exit__.return_value = False + monkeypatch.setattr(dds_cli.data_putter, "DataPutter", MagicMock(return_value=putter_cm)) + monkeypatch.setattr(dds_cli.data_putter, "Progress", MagicMock()) + dds_cli.data_putter.put( + project="proj00001", + source=(), + source_path_file=None, + break_on_fail=False, + overwrite=False, + num_threads=1, + silent=True, + no_prompt=True, + token_path=None, + destination=None, + staging_dir=None, + ) + + +def _batch_putter(service_unavailable): + putter = MagicMock() + putter.filehandler.data = {} + putter.failed_delivery_log.is_file.return_value = True + putter.service_unavailable = service_unavailable + putter.raise_if_service_unavailable.side_effect = ( + service_unavailable if service_unavailable else None + ) + return putter + + +def test_put_skips_db_retry_on_maintenance(monkeypatch): + """Known maintenance: no retry_add_file_db and no timestamp refresh, just the error.""" + putter = _batch_putter(dds_cli.exceptions.ServiceUnavailableError("Maintenance")) + + with pytest.raises(dds_cli.exceptions.ServiceUnavailableError): + _run_put_with(monkeypatch, putter) + + putter.retry_add_file_db.assert_not_called() + putter.touch_project_after_upload.assert_not_called() + + +def test_put_runs_db_retry_without_maintenance(monkeypatch): + """No maintenance: the end-of-batch retry and timestamp refresh run as before.""" + putter = _batch_putter(None) + + _run_put_with(monkeypatch, putter) + + putter.retry_add_file_db.assert_called_once() + putter.touch_project_after_upload.assert_called_once() From d3d873dc6b9d4f50443c1c52d3ab3b24b190c1e8 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:38:47 +0100 Subject: [PATCH 06/15] Resume interrupted downloads with HTTP Range requests When a download attempt is cut, keep the partial file and ask for the rest with 'Range: bytes=N-'. The answer is used only if it is 206 with a Content-Range that starts at N and ends at the last byte (total size may be '*'). On 200 the whole file is downloaded again. On a bad Content-Range or 416 the partial file is deleted and the next attempt starts from byte 0. A file left by an earlier run is never resumed. A wrong resume can not give a bad file: decryption authenticates every chunk, and size and checksum are still checked. Retries: DOWNLOAD_MAX_RETRIES 5 -> 10, wait between attempts capped at DOWNLOAD_MAX_WAIT (60 s), and reset to 1 s after an attempt that received data. Maintenance still stops a running download. --- dds_cli/constants.py | 7 +- dds_cli/data_getter.py | 123 ++++++++++++++--- tests/test_data_getter.py | 273 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 381 insertions(+), 22 deletions(-) diff --git a/dds_cli/constants.py b/dds_cli/constants.py index f7d708a1f..5d03f0c5c 100644 --- a/dds_cli/constants.py +++ b/dds_cli/constants.py @@ -19,10 +19,12 @@ READ_TIMEOUT = 300 CONNECT_TIMEOUT = 60 -# Retry settings for download -DOWNLOAD_MAX_RETRIES = 5 +# Retry settings for download. +# With Range resume a retry only costs a reconnect, so we can afford more of them. +DOWNLOAD_MAX_RETRIES = 10 DOWNLOAD_BACKOFF_FACTOR = 2 DOWNLOAD_INITIAL_WAIT = 1 # seconds +DOWNLOAD_MAX_WAIT = 60 # seconds, upper limit for the wait between two attempts # Import these constants when using '*' __all__ = [ @@ -33,4 +35,5 @@ "DOWNLOAD_MAX_RETRIES", "DOWNLOAD_BACKOFF_FACTOR", "DOWNLOAD_INITIAL_WAIT", + "DOWNLOAD_MAX_WAIT", ] diff --git a/dds_cli/data_getter.py b/dds_cli/data_getter.py index 588f239ea..3f4012b78 100644 --- a/dds_cli/data_getter.py +++ b/dds_cli/data_getter.py @@ -7,6 +7,7 @@ # Standard library import logging import pathlib +import re import time # Installed @@ -38,6 +39,10 @@ ############################################################################### +class RangeResumeError(requests.exceptions.RequestException): + """The server answered a Range request, but not with the part we asked for.""" + + class DataGetter(base.DDSBaseClass): """Data getter class.""" @@ -230,7 +235,13 @@ def download_and_verify(self, file, progress): @update_status def get(self, file, progress, task): - """Download files from the cloud and verify the byte count.""" + """Download files from the cloud and verify the byte count. + + If an attempt is cut, the partial file is kept and the next attempt asks for the + rest of the file with a Range request. The server must answer 206 with a matching + Content-Range. If it answers 200, the whole file is downloaded again. + A bad resume can not go unnoticed: decryption authenticates every chunk. + """ downloaded = False error = "" file_info = self.filehandler.data[file] @@ -251,33 +262,37 @@ def get(self, file, progress, task): requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.ChunkedEncodingError, + RangeResumeError, ) max_retries = constants.DOWNLOAD_MAX_RETRIES backoff_factor = constants.DOWNLOAD_BACKOFF_FACTOR - wait = constants.DOWNLOAD_INITIAL_WAIT + initial_wait = constants.DOWNLOAD_INITIAL_WAIT + wait = initial_wait retry_messages = [] cancelled = False + # Never resume from a file left by an earlier run: the object may have changed. + self._remove_partial(file_local, file_name_in_db) + for attempt in range(1, max_retries + 1): error = "" if self.service_unavailable: # Maintenance seen by another thread: don't start a new attempt. cancelled = True break + offset = 0 if attempt > 1: - progress.reset(task, completed=0) - # Drop the partial file from the previous attempt before retrying. - # We don't (yet) support Range-based resume, so a fresh GET starts - # at byte zero; leaving the old bytes around would just confuse - # the size check below. - self._remove_partial(file_local, file_name_in_db) + offset = self._resume_offset(file_local, expected_size, file_name_in_db) + progress.reset(task, completed=offset) bytes_written = 0 try: + headers = {"Range": f"bytes={offset}-"} if offset else {} with requests.get( file_remote, stream=True, + headers=headers, timeout=(constants.CONNECT_TIMEOUT, constants.READ_TIMEOUT), ) as req: req.raise_for_status() @@ -286,11 +301,39 @@ def get(self, file, progress, task): # transfer encoding (no Content-Length) or send a malformed # value. Treat both as "unknown" and rely on the size_stored # check below to catch truncation in that case. + # For a 206 response this is the size of the rest of the file. try: content_length = int(req.headers.get("Content-Length", 0)) except (TypeError, ValueError): content_length = 0 - with file_local.open(mode="wb") as new_file: + + mode = "wb" + if offset: + if req.status_code == 206: + self._check_content_range( + content_range=req.headers.get("Content-Range"), + offset=offset, + expected_size=expected_size, + file_name_in_db=file_name_in_db, + ) + mode = "ab" + LOG.info( + "Resuming download of '%s' at byte %s of %s.", + file_name_in_db, + offset, + expected_size, + ) + else: + LOG.warning( + "Server did not resume the download of '%s' (HTTP %s). " + "Downloading the whole file again.", + file_name_in_db, + req.status_code, + ) + offset = 0 + progress.reset(task, completed=0) + + with file_local.open(mode=mode) as new_file: for chunk in req.iter_content(chunk_size=FileSegment.SEGMENT_SIZE_CIPHER): if self.service_unavailable: # Maintenance seen by another thread: stop this download. @@ -311,13 +354,12 @@ def get(self, file, progress, task): raise requests.exceptions.ChunkedEncodingError( f"Truncated download for '{file_name_in_db}': " f"got {bytes_written} of {content_length} bytes" + + (f" (resumed at byte {offset})" if offset else "") ) # Cross-check against the size DDS recorded for the encrypted - # blob. This used to live in download_and_verify() (outside the - # retry loop), which made truncation unrecoverable in a single - # run. Doing it here means a mismatch retries like any other - # transport error. + # blob. Doing it inside the retry loop means a mismatch retries + # like any other transport error. actual_size = file_local.stat().st_size if actual_size != expected_size: raise requests.exceptions.ChunkedEncodingError( @@ -325,16 +367,21 @@ def get(self, file, progress, task): f"expected {expected_size} bytes, got {actual_size} bytes" ) except (requests.exceptions.HTTPError, *retryable_exceptions) as err: - if ( - isinstance(err, requests.exceptions.HTTPError) - and hasattr(err, "response") - and hasattr(err.response, "status_code") - and err.response.status_code == 404 - ): + status_code = getattr(getattr(err, "response", None), "status_code", None) + if isinstance(err, requests.exceptions.HTTPError) and status_code == 404: error = "File not found! Please contact support." break + if isinstance(err, RangeResumeError) or ( + isinstance(err, requests.exceptions.HTTPError) and status_code == 416 + ): + # The partial file can not be trusted: start from byte zero next time. + self._remove_partial(file_local, file_name_in_db) error = str(err) if attempt < max_retries: + if bytes_written: + # The attempt made progress, so this is a new cut and not + # a server that is down. Start the backoff again. + wait = initial_wait retry_msg = ( f"Download attempt {attempt}/{max_retries} failed for " f"'{file_name_in_db}': {error}. Retrying in {wait}s..." @@ -342,7 +389,7 @@ def get(self, file, progress, task): retry_messages.append(retry_msg) LOG.warning(retry_msg) time.sleep(wait) - wait *= backoff_factor + wait = min(wait * backoff_factor, constants.DOWNLOAD_MAX_WAIT) else: downloaded = True LOG.debug( @@ -378,6 +425,42 @@ def get(self, file, progress, task): return downloaded, error + @classmethod + def _resume_offset(cls, file_local, expected_size, file_name_in_db): + """Return the number of bytes we can keep from an earlier attempt (0 = start over).""" + try: + size = file_local.stat().st_size + except OSError: + return 0 + if 0 < size < expected_size: + return size + if size: + # Same size or larger, but the attempt still failed: don't trust it. + cls._remove_partial(file_local, file_name_in_db) + return 0 + + @staticmethod + def _check_content_range(content_range, offset, expected_size, file_name_in_db): + """Check that a 206 response starts at `offset` and covers the rest of the file. + + Expected format: 'bytes -/' (RFC 9110). + """ + match = re.fullmatch(r"\s*bytes\s+(\d+)-(\d+)/(\d+|\*)\s*", content_range or "") + if not match: + raise RangeResumeError( + f"Unexpected Content-Range for '{file_name_in_db}': {content_range!r}" + ) + start, end, total = match.groups() + if ( + int(start) != offset + or int(end) != expected_size - 1 + or (total != "*" and int(total) != expected_size) + ): + raise RangeResumeError( + f"Content-Range mismatch for '{file_name_in_db}': got {content_range!r}, " + f"expected 'bytes {offset}-{expected_size - 1}/{expected_size}'" + ) + @staticmethod def _remove_partial(file_local, file_name_in_db): """Delete a partial download. Best-effort — never raises.""" diff --git a/tests/test_data_getter.py b/tests/test_data_getter.py index 022ec7f19..4ebab854f 100644 --- a/tests/test_data_getter.py +++ b/tests/test_data_getter.py @@ -92,6 +92,7 @@ def test_get_uses_timeout(monkeypatch, tmp_path): mock_get.assert_called_once_with( "https://example.com/file", stream=True, + headers={}, timeout=(constants.CONNECT_TIMEOUT, constants.READ_TIMEOUT), ) @@ -521,3 +522,275 @@ def test_download_and_verify_raises_on_size_contract_violation(tmp_path): getter, file=file_name, progress=progress ) assert message == "" + + +# RANGE RESUME ################################################################# + + +def _response(body=b"data", status_code=200, headers=None, chunks=None): + """Mock response with a real headers dict, so each header can have its own value.""" + response = MagicMock() + response.__enter__.return_value = response + response.__exit__.return_value = False + response.status_code = status_code + response.headers = {"Content-Length": str(len(body))} if headers is None else headers + response.iter_content.return_value = chunks if chunks is not None else [body] + if status_code >= 400: + response.raise_for_status.side_effect = requests.exceptions.HTTPError(response=response) + else: + response.raise_for_status.return_value = None + return response + + +def _truncated(body, advertised): + """A response that advertises `advertised` bytes but only sends `body`.""" + return _response(body=body, headers={"Content-Length": str(advertised)}) + + +def _fake_get(responses, calls): + """Return a fake requests.get that records the Range header and serves `responses`.""" + responses = iter(responses) + + def fake_get(*_, headers=None, **__): + calls.append(dict(headers or {})) + return next(responses) + + return fake_get + + +@pytest.fixture +def no_wait(monkeypatch): + """Retry without sleeping.""" + monkeypatch.setattr(constants, "DOWNLOAD_INITIAL_WAIT", 0) + monkeypatch.setattr("dds_cli.data_getter.time.sleep", lambda _: None) + + +def test_get_resumes_with_range_on_206(monkeypatch, tmp_path, no_wait): + """After a cut, the next attempt asks for the rest of the file and appends it.""" + file_path = tmp_path / "file.bin" + getter = _prepare_data_getter("file.bin", download_path=file_path, size_stored=8) + + calls = [] + resumed = _response( + body=b"EFGH", + status_code=206, + headers={"Content-Length": "4", "Content-Range": "bytes 4-7/8"}, + ) + monkeypatch.setattr( + "dds_cli.data_getter.requests.get", + _fake_get([_truncated(b"ABCD", advertised=8), resumed], calls), + ) + + progress = MagicMock() + downloaded, message = DataGetter.get.__wrapped__( + getter, file="file.bin", progress=progress, task=1 + ) + + assert (downloaded, message) == (True, "") + assert file_path.read_bytes() == b"ABCDEFGH" + assert calls == [{}, {"Range": "bytes=4-"}] + # Progress continues from the kept bytes instead of starting at zero. + progress.reset.assert_called_once_with(1, completed=4) + + +def test_get_falls_back_to_full_download_on_200(monkeypatch, tmp_path, no_wait): + """If the server ignores Range and sends 200, the whole file is written again.""" + file_path = tmp_path / "file.bin" + getter = _prepare_data_getter("file.bin", download_path=file_path, size_stored=8) + + calls = [] + monkeypatch.setattr( + "dds_cli.data_getter.requests.get", + _fake_get([_truncated(b"ABCD", advertised=8), _response(b"ABCDEFGH")], calls), + ) + + downloaded, _ = DataGetter.get.__wrapped__( + getter, file="file.bin", progress=MagicMock(), task=1 + ) + + assert downloaded is True + assert file_path.read_bytes() == b"ABCDEFGH" # not b"ABCDABCDEFGH" + assert calls == [{}, {"Range": "bytes=4-"}] + + +@pytest.mark.parametrize( + "content_range", + [ + "bytes 0-7/8", # wrong start + "bytes 4-7/9", # wrong total size: the object changed + "bytes 4-5/8", # does not cover the rest of the file + None, # missing + "garbage", + ], +) +def test_get_content_range_mismatch_starts_over(monkeypatch, tmp_path, no_wait, content_range): + """A 206 with an unexpected Content-Range must not be appended; start from byte 0.""" + file_path = tmp_path / "file.bin" + getter = _prepare_data_getter("file.bin", download_path=file_path, size_stored=8) + + headers = {"Content-Length": "4"} + if content_range is not None: + headers["Content-Range"] = content_range + bad_resume = _response(body=b"XXXX", status_code=206, headers=headers) + + calls = [] + monkeypatch.setattr( + "dds_cli.data_getter.requests.get", + _fake_get([_truncated(b"ABCD", advertised=8), bad_resume, _response(b"ABCDEFGH")], calls), + ) + + downloaded, _ = DataGetter.get.__wrapped__( + getter, file="file.bin", progress=MagicMock(), task=1 + ) + + assert downloaded is True + assert file_path.read_bytes() == b"ABCDEFGH" + # The third attempt is a plain GET: the partial file was dropped. + assert calls == [{}, {"Range": "bytes=4-"}, {}] + + +def test_get_content_range_with_unknown_total_is_accepted(): + """'bytes 4-7/*' is valid (RFC 9110) and must not raise.""" + DataGetter._check_content_range( + content_range="bytes 4-7/*", offset=4, expected_size=8, file_name_in_db="f" + ) + + +def test_get_416_starts_over(monkeypatch, tmp_path, no_wait): + """416 Range Not Satisfiable: drop the partial file and do a full GET.""" + file_path = tmp_path / "file.bin" + getter = _prepare_data_getter("file.bin", download_path=file_path, size_stored=8) + + calls = [] + monkeypatch.setattr( + "dds_cli.data_getter.requests.get", + _fake_get( + [ + _truncated(b"ABCD", advertised=8), + _response(b"", status_code=416, headers={}), + _response(b"ABCDEFGH"), + ], + calls, + ), + ) + + downloaded, _ = DataGetter.get.__wrapped__( + getter, file="file.bin", progress=MagicMock(), task=1 + ) + + assert downloaded is True + assert file_path.read_bytes() == b"ABCDEFGH" + assert calls == [{}, {"Range": "bytes=4-"}, {}] + + +def test_get_resumes_after_truncation_in_resumed_part(monkeypatch, tmp_path, no_wait): + """A resumed response can also be cut; the next resume starts at the new offset.""" + file_path = tmp_path / "file.bin" + getter = _prepare_data_getter("file.bin", download_path=file_path, size_stored=8) + + calls = [] + cut_resume = _response( + body=b"EF", + status_code=206, + headers={"Content-Length": "4", "Content-Range": "bytes 4-7/8"}, + ) + last_resume = _response( + body=b"GH", + status_code=206, + headers={"Content-Length": "2", "Content-Range": "bytes 6-7/8"}, + ) + monkeypatch.setattr( + "dds_cli.data_getter.requests.get", + _fake_get([_truncated(b"ABCD", advertised=8), cut_resume, last_resume], calls), + ) + + downloaded, _ = DataGetter.get.__wrapped__( + getter, file="file.bin", progress=MagicMock(), task=1 + ) + + assert downloaded is True + assert file_path.read_bytes() == b"ABCDEFGH" + assert calls == [{}, {"Range": "bytes=4-"}, {"Range": "bytes=6-"}] + + +def test_get_does_not_resume_from_earlier_run(monkeypatch, tmp_path, no_wait): + """A file left by an earlier run is not trusted: the first attempt is a full GET.""" + file_path = tmp_path / "file.bin" + file_path.write_bytes(b"OLD") + getter = _prepare_data_getter("file.bin", download_path=file_path, size_stored=8) + + calls = [] + monkeypatch.setattr( + "dds_cli.data_getter.requests.get", _fake_get([_response(b"ABCDEFGH")], calls) + ) + + downloaded, _ = DataGetter.get.__wrapped__( + getter, file="file.bin", progress=MagicMock(), task=1 + ) + + assert downloaded is True + assert file_path.read_bytes() == b"ABCDEFGH" + assert calls == [{}] + + +# BACKOFF ###################################################################### + + +def test_get_backoff_is_capped(monkeypatch): + """The wait between attempts never goes above DOWNLOAD_MAX_WAIT.""" + getter = _prepare_data_getter("file.txt") + monkeypatch.setattr(constants, "DOWNLOAD_MAX_RETRIES", 6) + monkeypatch.setattr(constants, "DOWNLOAD_INITIAL_WAIT", 1) + monkeypatch.setattr(constants, "DOWNLOAD_BACKOFF_FACTOR", 2) + monkeypatch.setattr(constants, "DOWNLOAD_MAX_WAIT", 5) + + err = requests.exceptions.ConnectionError("reset") + monkeypatch.setattr(requests, "get", lambda *_, **__: (_ for _ in ()).throw(err)) + sleep_calls = [] + monkeypatch.setattr("dds_cli.data_getter.time.sleep", sleep_calls.append) + + DataGetter.get.__wrapped__(getter, file="file.txt", progress=MagicMock(), task=None) + + assert sleep_calls == [1, 2, 4, 5, 5] + + +def test_get_backoff_restarts_after_progress(monkeypatch, tmp_path): + """An attempt that received data is a new cut, so the wait starts from the beginning.""" + file_path = tmp_path / "file.bin" + getter = _prepare_data_getter("file.bin", download_path=file_path, size_stored=8) + monkeypatch.setattr(constants, "DOWNLOAD_MAX_RETRIES", 5) + monkeypatch.setattr(constants, "DOWNLOAD_INITIAL_WAIT", 1) + monkeypatch.setattr(constants, "DOWNLOAD_BACKOFF_FACTOR", 2) + sleep_calls = [] + monkeypatch.setattr("dds_cli.data_getter.time.sleep", sleep_calls.append) + + def resume(body, start): + return _response( + body=body, + status_code=206, + headers={"Content-Length": str(8 - start), "Content-Range": f"bytes {start}-7/8"}, + ) + + err = requests.exceptions.ConnectionError("reset") + + def raise_err(): + raise err + + steps = iter( + [ + raise_err, # no data -> wait 1 + raise_err, # no data -> wait 2 + lambda: _truncated(b"AB", advertised=8), # data -> wait 1 again + lambda: resume(b"CDEF", 2), # data -> wait 1 + lambda: resume(b"GH", 6), + ] + ) + monkeypatch.setattr("dds_cli.data_getter.requests.get", lambda *_, **__: next(steps)()) + + downloaded, _ = DataGetter.get.__wrapped__( + getter, file="file.bin", progress=MagicMock(), task=1 + ) + + assert downloaded is True + assert file_path.read_bytes() == b"ABCDEFGH" + assert sleep_calls == [1, 2, 1, 1] From 6928dfc2ee63537a25ac133bc8d8f19fc46bdb70 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:21:49 +0100 Subject: [PATCH 07/15] Fix crash when maintenance cancels downloads not started yet Download file keys are pathlib.Path objects, and rich's escape() needs a str, so the cancel message in verify_proceed raised a TypeError. Also remove the double period in the maintenance log line. --- dds_cli/base.py | 2 +- dds_cli/custom_decorators.py | 4 ++-- tests/test_api_retry.py | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/dds_cli/base.py b/dds_cli/base.py index bb7b408ac..b236a62bb 100644 --- a/dds_cli/base.py +++ b/dds_cli/base.py @@ -132,7 +132,7 @@ def stop_for_maintenance(self, err: exceptions.ServiceUnavailableError) -> None: """ if self.service_unavailable is None: self.service_unavailable = err - LOG.error("%s. Stopping: files not started yet are cancelled.", err) + LOG.error("%s. Stopping: files not started yet are cancelled.", str(err).rstrip(".")) self.stop_doing = True def raise_if_service_unavailable(self) -> None: diff --git a/dds_cli/custom_decorators.py b/dds_cli/custom_decorators.py index e0556abc8..0b9f9f903 100644 --- a/dds_cli/custom_decorators.py +++ b/dds_cli/custom_decorators.py @@ -45,13 +45,13 @@ def wrapped(self, file, *args, **kwargs): if getattr(self, "service_unavailable", None) else "KeyboardInterrupt" ) - message = f"{reason} - cancelling file {escape(file)}" + message = f"{reason} - cancelling file {escape(str(file))}" LOG.warning(message) return False # Do not proceed # Return if file cancelled by another file if self.status[file]["cancel"]: - message = f"File already cancelled, stopping file {escape(file)}" + message = f"File already cancelled, stopping file {escape(str(file))}" LOG.warning(message) return False diff --git a/tests/test_api_retry.py b/tests/test_api_retry.py index 71f3f7d1b..4a35cdce6 100644 --- a/tests/test_api_retry.py +++ b/tests/test_api_retry.py @@ -303,6 +303,39 @@ def work(self, file): assert "Service unavailable - cancelling file" in caplog.text +@pytest.mark.parametrize("already_cancelled", [False, True]) +def test_verify_proceed_cancels_download_file_with_path_key(caplog, already_cancelled): + """Download file keys are pathlib.Path objects: the cancel message must not crash.""" + from dds_cli.custom_decorators import verify_proceed + + called = MagicMock(return_value=(True, "")) + + @verify_proceed + def work(self, file): + return called(file) + + getter = _update_db_getter() + file = pathlib.Path("dir/file.bin") + getter.status = {file: {"cancel": already_cancelled, "started": False}} + if not already_cancelled: + getter.stop_for_maintenance(dds_cli.exceptions.ServiceUnavailableError("Maintenance")) + + assert work(getter, file) is False + called.assert_not_called() + assert "dir/file.bin" in caplog.text + + +def test_stop_for_maintenance_log_has_no_double_period(caplog): + """The API message ends with a period; the log line must not get two.""" + putter = _putter_with_one_file() + putter.stop_for_maintenance( + dds_cli.exceptions.ServiceUnavailableError("Maintenance of DDS is ongoing.") + ) + + assert "Maintenance of DDS is ongoing. Stopping:" in caplog.text + assert ".." not in caplog.text + + def test_stop_for_maintenance_keeps_first_error_and_raises_later(): """The error is raised once, from the main thread, after the workers are done.""" putter = _putter_with_one_file() From d09968b7cd1262156e75a30e7c78b958f1f0d1aa Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:11:01 +0100 Subject: [PATCH 08/15] Make the Path-key cancel test pass on Windows The test compared against "dir/file.bin", but str(Path) uses the OS separator, so on Windows the log shows "dir\file.bin". --- tests/test_api_retry.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_api_retry.py b/tests/test_api_retry.py index 4a35cdce6..7c73759fa 100644 --- a/tests/test_api_retry.py +++ b/tests/test_api_retry.py @@ -322,7 +322,7 @@ def work(self, file): assert work(getter, file) is False called.assert_not_called() - assert "dir/file.bin" in caplog.text + assert str(file) in caplog.text # dir\file.bin on Windows def test_stop_for_maintenance_log_has_no_double_period(caplog): From f3f25c9614ce371b0b205259791929a9e5b82135 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:21:31 +0100 Subject: [PATCH 09/15] Move the last API attempt out of the retry loop The raise after the loop could not be reached. Now the loop only runs the attempts that can be retried, and the last attempt runs after it, so its error goes to the caller. --- dds_cli/utils.py | 8 ++++---- tests/test_api_retry.py | 9 +++++---- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/dds_cli/utils.py b/dds_cli/utils.py index 9ec51cfec..38633ac9a 100644 --- a/dds_cli/utils.py +++ b/dds_cli/utils.py @@ -331,12 +331,12 @@ def perform_request_with_retry(*args, retries: int = 1, **kwargs): A 503 from the DDS API (maintenance) has a JSON body, is raised as ServiceUnavailableError and is never retried. """ - for attempt in range(retries + 1): + for _ in range(retries): try: return perform_request(*args, **kwargs) except dds_cli.exceptions.NonJsonResponseError as err: status_code = getattr(err, "status_code", None) - if status_code not in constants.API_NON_JSON_RETRY_STATUS_CODES or attempt >= retries: + if status_code not in constants.API_NON_JSON_RETRY_STATUS_CODES: raise LOG.warning( "API request failed with status %s, retrying in %ss: %s", @@ -345,8 +345,8 @@ def perform_request_with_retry(*args, retries: int = 1, **kwargs): err, ) time.sleep(constants.API_RETRY_WAIT) - # Not reached: the last attempt either returns or raises. - raise RuntimeError("perform_request_with_retry: no attempts made") + # Last attempt: any error goes to the caller + return perform_request(*args, **kwargs) def parse_project_errors(errors): diff --git a/tests/test_api_retry.py b/tests/test_api_retry.py index 7c73759fa..1e5f017ae 100644 --- a/tests/test_api_retry.py +++ b/tests/test_api_retry.py @@ -171,17 +171,18 @@ def test_add_file_db_no_retry_on_400(monkeypatch): assert mock_post.call_count == 1 -def test_perform_request_with_retry_gives_up_after_retries(monkeypatch): - """The last error is raised when all attempts fail.""" +@pytest.mark.parametrize("retries", [0, 2]) +def test_perform_request_with_retry_gives_up_after_retries(monkeypatch, retries): + """The last error is raised when all attempts fail; retries=0 sends one request.""" monkeypatch.setattr(constants, "API_RETRY_WAIT", 0) err = dds_cli.exceptions.NonJsonResponseError("Bad Gateway", status_code=502) mock_request = MagicMock(side_effect=err) monkeypatch.setattr(dds_cli.utils, "perform_request", mock_request) with pytest.raises(dds_cli.exceptions.ApiResponseError): - dds_cli.utils.perform_request_with_retry("url", method="put", retries=2) + dds_cli.utils.perform_request_with_retry("url", method="put", retries=retries) - assert mock_request.call_count == 3 + assert mock_request.call_count == retries + 1 def test_perform_request_with_retry_no_retry_on_request_error(monkeypatch): From 9b8385fa0be34beffafe6c31f07654cb0ed0779a Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:26:49 +0100 Subject: [PATCH 10/15] sprintlog --- SPRINTLOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/SPRINTLOG.md b/SPRINTLOG.md index 5487c11ec..7d335a755 100644 --- a/SPRINTLOG.md +++ b/SPRINTLOG.md @@ -613,3 +613,4 @@ _Empty sprint_ - Fix --no-prompt silently skipping user activation and deactivation ([#1008](https://github.com/ScilifelabDataCentre/dds_cli/pull/1008)) - Remove resolved entries from dds_failed_delivery.json after retry ([#999](https://github.com/ScilifelabDataCentre/dds_cli/pull/999)) +- Retry API calls once on a 502/503 from the proxy, and stop uploads/downloads during maintenance ([#1009](https://github.com/ScilifelabDataCentre/dds_cli/pull/1009)) From 6a0328fa20521fde31d366b9b8ba78480c7e19e5 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:06:13 +0100 Subject: [PATCH 11/15] Count only download attempts without progress An attempt that received new data no longer counts towards DOWNLOAD_MAX_RETRIES, so a big file can be resumed any number of times. Progress means the partial file got larger than the largest size so far, so a restart from zero that does not get further still counts, and a bad resume can not loop forever. DOWNLOAD_MAX_RETRIES is now 7: a server that does not answer is given up after about one minute of waiting (was 15 s on dev, about 4 min before this change). DOWNLOAD_MAX_WAIT is removed because the wait can no longer reach it. --- dds_cli/constants.py | 10 +-- dds_cli/data_getter.py | 63 ++++++++++++------- tests/test_data_getter.py | 124 +++++++++++++++++++++++++++++++++----- 3 files changed, 158 insertions(+), 39 deletions(-) diff --git a/dds_cli/constants.py b/dds_cli/constants.py index 5d03f0c5c..9c1d7c166 100644 --- a/dds_cli/constants.py +++ b/dds_cli/constants.py @@ -20,11 +20,14 @@ CONNECT_TIMEOUT = 60 # Retry settings for download. -# With Range resume a retry only costs a reconnect, so we can afford more of them. -DOWNLOAD_MAX_RETRIES = 10 +# DOWNLOAD_MAX_RETRIES counts only attempts in a row without progress: an attempt that +# received new data starts the count (and the wait) again, so a file can be resumed +# any number of times. With these values a server that does not answer at all is +# given up after 7 attempts and 1 + 2 + 4 + 8 + 16 + 32 = 63 seconds of waiting, +# enough to ride out a short restart of the storage or the proxy. +DOWNLOAD_MAX_RETRIES = 7 DOWNLOAD_BACKOFF_FACTOR = 2 DOWNLOAD_INITIAL_WAIT = 1 # seconds -DOWNLOAD_MAX_WAIT = 60 # seconds, upper limit for the wait between two attempts # Import these constants when using '*' __all__ = [ @@ -35,5 +38,4 @@ "DOWNLOAD_MAX_RETRIES", "DOWNLOAD_BACKOFF_FACTOR", "DOWNLOAD_INITIAL_WAIT", - "DOWNLOAD_MAX_WAIT", ] diff --git a/dds_cli/data_getter.py b/dds_cli/data_getter.py index 3f4012b78..a17eb04ce 100644 --- a/dds_cli/data_getter.py +++ b/dds_cli/data_getter.py @@ -241,6 +241,10 @@ def get(self, file, progress, task): rest of the file with a Range request. The server must answer 206 with a matching Content-Range. If it answers 200, the whole file is downloaded again. A bad resume can not go unnoticed: decryption authenticates every chunk. + + Only attempts without progress count towards DOWNLOAD_MAX_RETRIES. Progress means + that the partial file grew past the largest size reached so far, so a 200 that + starts from zero again only counts as progress once it gets further than before. """ downloaded = False error = "" @@ -265,17 +269,21 @@ def get(self, file, progress, task): RangeResumeError, ) - max_retries = constants.DOWNLOAD_MAX_RETRIES + max_failures = constants.DOWNLOAD_MAX_RETRIES backoff_factor = constants.DOWNLOAD_BACKOFF_FACTOR initial_wait = constants.DOWNLOAD_INITIAL_WAIT wait = initial_wait retry_messages = [] cancelled = False + attempt = 0 + failures = 0 # attempts in a row without progress + largest_size = 0 # largest size of the partial file so far # Never resume from a file left by an earlier run: the object may have changed. self._remove_partial(file_local, file_name_in_db) - for attempt in range(1, max_retries + 1): + while True: + attempt += 1 error = "" if self.service_unavailable: # Maintenance seen by another thread: don't start a new attempt. @@ -377,19 +385,27 @@ def get(self, file, progress, task): # The partial file can not be trusted: start from byte zero next time. self._remove_partial(file_local, file_name_in_db) error = str(err) - if attempt < max_retries: - if bytes_written: - # The attempt made progress, so this is a new cut and not - # a server that is down. Start the backoff again. - wait = initial_wait - retry_msg = ( - f"Download attempt {attempt}/{max_retries} failed for " - f"'{file_name_in_db}': {error}. Retrying in {wait}s..." - ) - retry_messages.append(retry_msg) - LOG.warning(retry_msg) - time.sleep(wait) - wait = min(wait * backoff_factor, constants.DOWNLOAD_MAX_WAIT) + size_now = self._partial_size(file_local) + if size_now > largest_size: + # The attempt made progress, so this is a new cut and not a server + # that is down: start counting and the backoff again. + largest_size = size_now + failures = 0 + wait = initial_wait + retry_messages = [] + else: + failures += 1 + if failures >= max_failures: + break + retry_msg = ( + f"Download attempt {attempt} failed for '{file_name_in_db}' " + f"({failures}/{max_failures} without progress): {error}. " + f"Retrying in {wait}s..." + ) + retry_messages.append(retry_msg) + LOG.warning(retry_msg) + time.sleep(wait) + wait *= backoff_factor else: downloaded = True LOG.debug( @@ -409,7 +425,7 @@ def get(self, file, progress, task): LOG.error( "Download failed for '%s' after %d attempts: %s", file_name_in_db, - max_retries, + attempt, error, ) LOG.warning( @@ -417,7 +433,7 @@ def get(self, file, progress, task): "Please ensure your internet connection is stable and that your " "computer does not enter sleep mode during large file transfers.", file_name_in_db, - max_retries, + attempt, ) # Don't leave a partial blob on disk after we've given up — it just # consumes space and risks being mistaken for a complete file. @@ -428,10 +444,7 @@ def get(self, file, progress, task): @classmethod def _resume_offset(cls, file_local, expected_size, file_name_in_db): """Return the number of bytes we can keep from an earlier attempt (0 = start over).""" - try: - size = file_local.stat().st_size - except OSError: - return 0 + size = cls._partial_size(file_local) if 0 < size < expected_size: return size if size: @@ -439,6 +452,14 @@ def _resume_offset(cls, file_local, expected_size, file_name_in_db): cls._remove_partial(file_local, file_name_in_db) return 0 + @staticmethod + def _partial_size(file_local): + """Return the size of the partial file, 0 if it does not exist.""" + try: + return file_local.stat().st_size + except OSError: + return 0 + @staticmethod def _check_content_range(content_range, offset, expected_size, file_name_in_db): """Check that a 206 response starts at `offset` and covers the rest of the file. diff --git a/tests/test_data_getter.py b/tests/test_data_getter.py index 4ebab854f..fe82a8969 100644 --- a/tests/test_data_getter.py +++ b/tests/test_data_getter.py @@ -205,8 +205,8 @@ def test_get_fails_after_max_retries(monkeypatch): assert downloaded is False assert "Final error:" in message - assert "attempt 1/3" in message - assert "attempt 2/3" in message + assert "(1/3 without progress)" in message + assert "(2/3 without progress)" in message def test_get_no_retry_on_404(monkeypatch): @@ -349,7 +349,9 @@ def test_get_detects_truncated_stream_via_content_length(monkeypatch, tmp_path): # The retry path engaged on every attempt and ultimately gave up. assert downloaded is False assert "Truncated download" in message - assert "attempt 1/3" in message + # The first attempt received data; the later ones did not get further. + assert "(0/3 without progress)" in message + assert "(2/3 without progress)" in message def test_get_detects_size_mismatch_against_size_stored(monkeypatch, tmp_path): @@ -736,22 +738,22 @@ def test_get_does_not_resume_from_earlier_run(monkeypatch, tmp_path, no_wait): # BACKOFF ###################################################################### -def test_get_backoff_is_capped(monkeypatch): - """The wait between attempts never goes above DOWNLOAD_MAX_WAIT.""" +def test_get_gives_up_after_about_a_minute_on_dead_server(monkeypatch): + """A server that does not answer at all is given up after 7 attempts and 63 s.""" getter = _prepare_data_getter("file.txt") - monkeypatch.setattr(constants, "DOWNLOAD_MAX_RETRIES", 6) - monkeypatch.setattr(constants, "DOWNLOAD_INITIAL_WAIT", 1) - monkeypatch.setattr(constants, "DOWNLOAD_BACKOFF_FACTOR", 2) - monkeypatch.setattr(constants, "DOWNLOAD_MAX_WAIT", 5) - - err = requests.exceptions.ConnectionError("reset") - monkeypatch.setattr(requests, "get", lambda *_, **__: (_ for _ in ()).throw(err)) + err = requests.exceptions.ConnectionError("refused") + mock_get = MagicMock(side_effect=err) + monkeypatch.setattr(requests, "get", mock_get) sleep_calls = [] monkeypatch.setattr("dds_cli.data_getter.time.sleep", sleep_calls.append) - DataGetter.get.__wrapped__(getter, file="file.txt", progress=MagicMock(), task=None) + downloaded, _ = DataGetter.get.__wrapped__( + getter, file="file.txt", progress=MagicMock(), task=None + ) - assert sleep_calls == [1, 2, 4, 5, 5] + assert downloaded is False + assert mock_get.call_count == 7 + assert sleep_calls == [1, 2, 4, 8, 16, 32] def test_get_backoff_restarts_after_progress(monkeypatch, tmp_path): @@ -794,3 +796,97 @@ def raise_err(): assert downloaded is True assert file_path.read_bytes() == b"ABCDEFGH" assert sleep_calls == [1, 2, 1, 1] + + +def _resume(body, start, size=8): + """A 206 from `start` to the end; a short `body` means the attempt is cut.""" + return _response( + body=body, + status_code=206, + headers={ + "Content-Length": str(size - start), + "Content-Range": f"bytes {start}-{size - 1}/{size}", + }, + ) + + +def test_get_cuts_with_progress_do_not_count(monkeypatch, tmp_path, no_wait): + """More cuts than DOWNLOAD_MAX_RETRIES still finish, as long as each one got further.""" + file_path = tmp_path / "file.bin" + getter = _prepare_data_getter("file.bin", download_path=file_path, size_stored=8) + monkeypatch.setattr(constants, "DOWNLOAD_MAX_RETRIES", 2) + + calls = [] + responses = [ + _truncated(b"AB", advertised=8), + _resume(b"C", 2), + _resume(b"D", 3), + _resume(b"EF", 4), + _resume(b"GH", 6), + ] + monkeypatch.setattr("dds_cli.data_getter.requests.get", _fake_get(responses, calls)) + + downloaded, message = DataGetter.get.__wrapped__( + getter, file="file.bin", progress=MagicMock(), task=1 + ) + + assert (downloaded, message) == (True, "") + assert file_path.read_bytes() == b"ABCDEFGH" + assert len(calls) == 5 + + +def test_get_restart_from_zero_counts_only_when_it_gets_further(monkeypatch, tmp_path, no_wait): + """A 200 starts from byte 0: it is progress only when the file gets larger than before.""" + file_path = tmp_path / "file.bin" + getter = _prepare_data_getter("file.bin", download_path=file_path, size_stored=8) + monkeypatch.setattr(constants, "DOWNLOAD_MAX_RETRIES", 2) + + calls = [] + responses = [ + _truncated(b"ABCD", advertised=8), # 4 bytes: progress + _truncated(b"AB", advertised=8), # 200 again, 2 bytes: no progress (1/2) + _truncated(b"ABCDEF", advertised=8), # 200 again, 6 bytes: progress, count reset + _truncated(b"ABCD", advertised=8), # 200, 4 bytes: no progress (1/2) + _truncated(b"ABC", advertised=8), # 200, 3 bytes: no progress (2/2) -> give up + ] + monkeypatch.setattr("dds_cli.data_getter.requests.get", _fake_get(responses, calls)) + + downloaded, message = DataGetter.get.__wrapped__( + getter, file="file.bin", progress=MagicMock(), task=1 + ) + + assert downloaded is False + assert len(calls) == 5 + # Only the messages from the last progress on are kept in the error. + assert "attempt 1 failed" not in message + assert "attempt 2 failed" not in message + assert "attempt 3 failed" in message + assert not file_path.exists() + + +def test_get_bad_resume_then_same_size_is_not_progress(monkeypatch, tmp_path, no_wait): + """A partial file removed after a bad resume and downloaded again to the same size + is not progress, so this can not loop forever.""" + file_path = tmp_path / "file.bin" + getter = _prepare_data_getter("file.bin", download_path=file_path, size_stored=8) + monkeypatch.setattr(constants, "DOWNLOAD_MAX_RETRIES", 2) + + bad_range = _response( + body=b"EFGH", + status_code=206, + headers={"Content-Length": "4", "Content-Range": "bytes 0-3/8"}, + ) + calls = [] + responses = [ + _truncated(b"ABCD", advertised=8), # progress + bad_range, # partial removed: no progress (1/2) + _truncated(b"ABCD", advertised=8), # back to 4 bytes: no progress (2/2) + ] + monkeypatch.setattr("dds_cli.data_getter.requests.get", _fake_get(responses, calls)) + + downloaded, _ = DataGetter.get.__wrapped__( + getter, file="file.bin", progress=MagicMock(), task=1 + ) + + assert downloaded is False + assert len(calls) == 3 From 9601b27eb52a4d8304c0da3f5dfc6a8412fa7dd1 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:11:13 +0100 Subject: [PATCH 12/15] Move RangeResumeError to exceptions.py --- dds_cli/data_getter.py | 12 ++++-------- dds_cli/exceptions.py | 7 +++++++ 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/dds_cli/data_getter.py b/dds_cli/data_getter.py index a17eb04ce..124d6f51c 100644 --- a/dds_cli/data_getter.py +++ b/dds_cli/data_getter.py @@ -39,10 +39,6 @@ ############################################################################### -class RangeResumeError(requests.exceptions.RequestException): - """The server answered a Range request, but not with the part we asked for.""" - - class DataGetter(base.DDSBaseClass): """Data getter class.""" @@ -266,7 +262,7 @@ def get(self, file, progress, task): requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.ChunkedEncodingError, - RangeResumeError, + dds_cli.exceptions.RangeResumeError, ) max_failures = constants.DOWNLOAD_MAX_RETRIES @@ -379,7 +375,7 @@ def get(self, file, progress, task): if isinstance(err, requests.exceptions.HTTPError) and status_code == 404: error = "File not found! Please contact support." break - if isinstance(err, RangeResumeError) or ( + if isinstance(err, dds_cli.exceptions.RangeResumeError) or ( isinstance(err, requests.exceptions.HTTPError) and status_code == 416 ): # The partial file can not be trusted: start from byte zero next time. @@ -468,7 +464,7 @@ def _check_content_range(content_range, offset, expected_size, file_name_in_db): """ match = re.fullmatch(r"\s*bytes\s+(\d+)-(\d+)/(\d+|\*)\s*", content_range or "") if not match: - raise RangeResumeError( + raise dds_cli.exceptions.RangeResumeError( f"Unexpected Content-Range for '{file_name_in_db}': {content_range!r}" ) start, end, total = match.groups() @@ -477,7 +473,7 @@ def _check_content_range(content_range, offset, expected_size, file_name_in_db): or int(end) != expected_size - 1 or (total != "*" and int(total) != expected_size) ): - raise RangeResumeError( + raise dds_cli.exceptions.RangeResumeError( f"Content-Range mismatch for '{file_name_in_db}': got {content_range!r}, " f"expected 'bytes {offset}-{expected_size - 1}/{expected_size}'" ) diff --git a/dds_cli/exceptions.py b/dds_cli/exceptions.py index b195ed35c..b5ec1ddd4 100644 --- a/dds_cli/exceptions.py +++ b/dds_cli/exceptions.py @@ -121,6 +121,13 @@ class DownloadError(Exception): """Errors relating to file download.""" +class RangeResumeError(requests.exceptions.RequestException): + """The server answered a Range request, but not with the part we asked for. + + A RequestException, so the download retry loop handles it like a network error. + """ + + class NoDataError(Exception): """Errors when there is no data to do anything with.""" From b3ff4f0b703e3b664fcd9d2f4a16300371ef9705 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:12:38 +0100 Subject: [PATCH 13/15] Test that a non-416 HTTP error on a resume keeps the partial file --- tests/test_data_getter.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tests/test_data_getter.py b/tests/test_data_getter.py index fe82a8969..8ccac20a1 100644 --- a/tests/test_data_getter.py +++ b/tests/test_data_getter.py @@ -685,6 +685,34 @@ def test_get_416_starts_over(monkeypatch, tmp_path, no_wait): assert calls == [{}, {"Range": "bytes=4-"}, {}] +def test_get_keeps_partial_on_other_http_error(monkeypatch, tmp_path, no_wait): + """Another HTTP error on a resumed request (e.g. a 503 from S3) keeps the partial + file, and the next attempt resumes from the same byte.""" + file_path = tmp_path / "file.bin" + getter = _prepare_data_getter("file.bin", download_path=file_path, size_stored=8) + + calls = [] + monkeypatch.setattr( + "dds_cli.data_getter.requests.get", + _fake_get( + [ + _truncated(b"ABCD", advertised=8), + _response(b"", status_code=503, headers={}), + _resume(b"EFGH", 4), + ], + calls, + ), + ) + + downloaded, _ = DataGetter.get.__wrapped__( + getter, file="file.bin", progress=MagicMock(), task=1 + ) + + assert downloaded is True + assert file_path.read_bytes() == b"ABCDEFGH" + assert calls == [{}, {"Range": "bytes=4-"}, {"Range": "bytes=4-"}] + + def test_get_resumes_after_truncation_in_resumed_part(monkeypatch, tmp_path, no_wait): """A resumed response can also be cut; the next resume starts at the new offset.""" file_path = tmp_path / "file.bin" From 8ee235597ed1d37b403da611cc03a755ce486e88 Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:16:46 +0100 Subject: [PATCH 14/15] Show progress instead of 0/N in the retry warning --- dds_cli/data_getter.py | 8 ++++++-- tests/test_data_getter.py | 5 +++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/dds_cli/data_getter.py b/dds_cli/data_getter.py index 124d6f51c..85b67ae61 100644 --- a/dds_cli/data_getter.py +++ b/dds_cli/data_getter.py @@ -393,10 +393,14 @@ def get(self, file, progress, task): failures += 1 if failures >= max_failures: break + status = ( + f"{failures}/{max_failures} without progress" + if failures + else f"received data, {size_now} of {expected_size} bytes" + ) retry_msg = ( f"Download attempt {attempt} failed for '{file_name_in_db}' " - f"({failures}/{max_failures} without progress): {error}. " - f"Retrying in {wait}s..." + f"({status}): {error}. Retrying in {wait}s..." ) retry_messages.append(retry_msg) LOG.warning(retry_msg) diff --git a/tests/test_data_getter.py b/tests/test_data_getter.py index 8ccac20a1..2262e6c9f 100644 --- a/tests/test_data_getter.py +++ b/tests/test_data_getter.py @@ -350,7 +350,7 @@ def test_get_detects_truncated_stream_via_content_length(monkeypatch, tmp_path): assert downloaded is False assert "Truncated download" in message # The first attempt received data; the later ones did not get further. - assert "(0/3 without progress)" in message + assert "(received data, 4 of 100 bytes)" in message assert "(2/3 without progress)" in message @@ -888,7 +888,8 @@ def test_get_restart_from_zero_counts_only_when_it_gets_further(monkeypatch, tmp # Only the messages from the last progress on are kept in the error. assert "attempt 1 failed" not in message assert "attempt 2 failed" not in message - assert "attempt 3 failed" in message + assert "attempt 3 failed for 'file.bin' (received data, 6 of 8 bytes)" in message + assert "0/2 without progress" not in message assert not file_path.exists() From c5a291dfd17693913285a998e1c5a1385cc33fea Mon Sep 17 00:00:00 2001 From: valyo <582646+valyo@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:53:04 +0100 Subject: [PATCH 15/15] Double the download wait only after an attempt without progress An attempt that was cut after receiving data reset the wait to 1 s but still doubled it, so a server that went down mid-download was given up after about 2 min instead of 1 min. --- dds_cli/constants.py | 8 +++++--- dds_cli/data_getter.py | 4 +++- tests/test_data_getter.py | 26 ++++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/dds_cli/constants.py b/dds_cli/constants.py index 9c1d7c166..a9ab9bc7d 100644 --- a/dds_cli/constants.py +++ b/dds_cli/constants.py @@ -22,9 +22,11 @@ # Retry settings for download. # DOWNLOAD_MAX_RETRIES counts only attempts in a row without progress: an attempt that # received new data starts the count (and the wait) again, so a file can be resumed -# any number of times. With these values a server that does not answer at all is -# given up after 7 attempts and 1 + 2 + 4 + 8 + 16 + 32 = 63 seconds of waiting, -# enough to ride out a short restart of the storage or the proxy. +# any number of times. With these values a server that does not answer is given up +# after 7 attempts without progress and 1 + 2 + 4 + 8 + 16 + 32 = 63 seconds of +# waiting, enough to ride out a short restart of the storage or the proxy. This also +# holds when the server goes down in the middle of a download: the attempt that was +# cut waits 1 second, and the wait only doubles after an attempt without progress. DOWNLOAD_MAX_RETRIES = 7 DOWNLOAD_BACKOFF_FACTOR = 2 DOWNLOAD_INITIAL_WAIT = 1 # seconds diff --git a/dds_cli/data_getter.py b/dds_cli/data_getter.py index 85b67ae61..3185b6366 100644 --- a/dds_cli/data_getter.py +++ b/dds_cli/data_getter.py @@ -405,7 +405,9 @@ def get(self, file, progress, task): retry_messages.append(retry_msg) LOG.warning(retry_msg) time.sleep(wait) - wait *= backoff_factor + if failures: + # Only an attempt without progress makes the next wait longer. + wait *= backoff_factor else: downloaded = True LOG.debug( diff --git a/tests/test_data_getter.py b/tests/test_data_getter.py index 2262e6c9f..70a4a64d9 100644 --- a/tests/test_data_getter.py +++ b/tests/test_data_getter.py @@ -784,6 +784,32 @@ def test_get_gives_up_after_about_a_minute_on_dead_server(monkeypatch): assert sleep_calls == [1, 2, 4, 8, 16, 32] +def test_get_gives_up_after_about_a_minute_when_server_dies_mid_download(monkeypatch, tmp_path): + """A server that goes down after sending some data gets the same 63 s, plus the + 1 s wait after the cut: an attempt with progress does not double the wait.""" + file_path = tmp_path / "file.bin" + getter = _prepare_data_getter("file.bin", download_path=file_path, size_stored=8) + err = requests.exceptions.ConnectionError("refused") + responses = iter([_truncated(b"AB", advertised=8)]) + + def fake_get(*_, **__): + response = next(responses, None) + if response is None: + raise err + return response + + monkeypatch.setattr("dds_cli.data_getter.requests.get", fake_get) + sleep_calls = [] + monkeypatch.setattr("dds_cli.data_getter.time.sleep", sleep_calls.append) + + downloaded, _ = DataGetter.get.__wrapped__( + getter, file="file.bin", progress=MagicMock(), task=1 + ) + + assert downloaded is False + assert sleep_calls == [1, 1, 2, 4, 8, 16, 32] + + def test_get_backoff_restarts_after_progress(monkeypatch, tmp_path): """An attempt that received data is a new cut, so the wait starts from the beginning.""" file_path = tmp_path / "file.bin"