Skip to content

HMS-2695 download range resume - #1010

Open
valyo wants to merge 22 commits into
devfrom
HMS-2695-download-range-resume
Open

valyo wants to merge 22 commits into
devfrom
HMS-2695-download-range-resume

Conversation

@valyo

@valyo valyo commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Pull Request Template

Before Marking as Ready for Review

  • Add relevant information to the sections below (Summary etc)
  • Rebase or merge the latest dev (or other targeted branch)
  • Update documentation if needed
  • Add an entry to the SPRINTLOG.md if needed
  • Choose an appropriate label. See here for information on the labelling options
  • The code follows the style guidelines
  • Perform a self-review: read the diff as if reviewing someone else's code
  • I have commented the code, particularly in hard-to-understand areas
  • Verify that all checks and tests have passed

If the target branch is master:

Summary

A cut download used to start again from byte 0, and every failed attempt counted towards a limit of 5. For large files on a slow or unstable network, this meant downloads often failed in the end.

With this PR, a retry continues from where the download stopped:

Situation Behaviour
Retry after a cut Sends Range: bytes=N-, where N is the size of the partial file
Server answers 206 with a matching Content-Range (bytes N-(size-1)/size, total may be *) Appends to the partial file
Server answers 200 Ignores the Range and downloads the full file again
Content-Range does not match, or server answers 416 Deletes the partial file; the next attempt starts from 0
Other HTTP error on a resume (e.g. 503) Keeps the partial file; the next attempt resumes again
Partial file from an earlier run Never resumed: deleted at the start of get()
Truncated body (fewer bytes than expected) Counts as a failed attempt and is retried

Retry counting:

Before After
What counts every failed attempt only attempts in a row without progress
Progress – the partial file got larger than the largest size so far
Limit (DOWNLOAD_MAX_RETRIES) 5 7
Wait 1, 2, 4, 8 s 1, 2, 4, … 32 s; back to 1 s after progress, doubles only after an attempt without progress
Server that does not answer given up after 15 s given up after about 1 min (also when it goes down mid-download)
Big file with many cuts fails at the 5th cut continues as long as each attempt gets further

Comparing with the largest size so far (and not the size before the attempt) means that a 200 restart or a bad resume can't reset the counter by downloading the same bytes again.

Other changes:

  • RangeResumeError is added to exceptions.py.
  • The retry warning shows "received data, X of Y bytes" after an attempt with progress, and "n/7 without progress" otherwise.
  • The maintenance stop from Api retry on 502 #1009 is kept: it is checked before each attempt and in the chunk loop.

Safety: the files are encrypted with ChaCha20-Poly1305 and every chunk is authenticated. A resume at a wrong byte would make decryption fail, so a bad resume can't produce a corrupted file without an error.

Related Issue/Ticket

HMS-2695

Based on #1009 (api-retry-on-502), which is already merged.

Testing

  • New unit tests in tests/test_data_getter.py: resume, 200 fallback, Content-Range mismatch (parametrized), * total, 416, truncation in the resumed part, no resume from an earlier run, backoff cap, backoff reset after progress.
  • pytest: 263 passed, 12 skipped. ruff format / ruff check are clean.
  • Local end-to-end test against a test server that cuts the connection: resumed at the correct byte.
  • Real run against the test instance (dds data get -p datacentre00137 -a, 9 files, ~100 MB each): all 4 running downloads were cut at the same moment (BrokenPipeError at ~20 MB). Each resumed 1 s later with a Range request at its own byte offset, got 206, and finished. All files passed size checks, decryption (per-chunk authentication) and decrypted-size check.

Reviewer Notes

  • Main logic: get(), _resume_offset() and _check_content_range() in dds_cli/data_getter.py.
  • A resume is accepted only with a 206 and an exact Content-Range match. In every other case the code falls back to a full download, so it does not depend on the S3 provider supporting Range.
  • This PR does not include --sync-interval, --decrypt-threads or --temp-dir. Those come in the next two PRs, which are based on this one.

Once all boxes are checked, mark the PR as Ready for Review and tag at least one team member as the initial reviewer.

valyo and others added 7 commits November 16, 2026 11:05
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
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.
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.
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.
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.
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.
@codecov

codecov Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.50746% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 60.50%. Comparing base (2d98ae4) to head (c5a291d).

Files with missing lines Patch % Lines
dds_cli/data_getter.py 98.46% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              dev    #1010      +/-   ##
==========================================
+ Coverage   59.86%   60.50%   +0.63%     
==========================================
  Files          33       33              
  Lines        3179     3233      +54     
==========================================
+ Hits         1903     1956      +53     
- Misses       1276     1277       +1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@valyo
valyo marked this pull request as ready for review November 17, 2026 10:59
@valyo
valyo requested a review from a team as a code owner November 17, 2026 10:59
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T11:02:29.874737Z a412742 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@valyo valyo added the type: bug Something isn't working label Nov 17, 2026

@samanrassam samanrassam left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good! I tested it by restarting Minio midway through an 800 mb download, and by stopping it for 6 sec. Both times it resumed at the right byte with a 206 (also the file matched the original checksum). I also checked the "a bad resume can't go unnoticed" part: with the nonce incrementation and the last nonce check a resume at the wrong byte fails decryption.

Some thoughts about the retrying mechanism in dds_cli/data_getter.py:
Attempts that made progress still count towards the 10, so a big file on a link that drops now and then fails at the 10th cut even if every resume worked. Shorter outages will eat into them too, for instance: stopping minio for 6 seconds used 4 of 10 tries.
At the same time, a file that can't be downloaded at all now waits about 4 min before it fails (was 15 sec), and with 4 threads that adds up on a large delivery. A suggestion is that we count only attempts without progress, and keep that number lower? A 200 starts from 0 again, so progress would have to mean that the partial file grew.

dds_cli/data_getter.py:42
All our other exceptions are in exceptions.py, should RangeResumeError go there too?

tests/test_data_getter.py
Maybe a test for an HTTP error other than 416 on a resumed request (e.g. a 503 from S3), checking that the partial is kept and the next attempt resumes again.

dds_cli/data_getter.py: 280, 338 and 402
These are included in my question in #1009 about stopping downloads on maintenance, so I suppose we can discuss it there first

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.
The test compared against "dir/file.bin", but str(Path) uses the OS
separator, so on Windows the log shows "dir\file.bin".
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.
@valyo
valyo changed the base branch from dev to api-retry-on-502 November 18, 2026 13:42
valyo and others added 4 commits November 18, 2026 14:43
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.
@valyo

valyo commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

Some thoughts about the retrying mechanism in dds_cli/data_getter.py:
Attempts that made progress still count towards the 10, so a big file on a link that drops now and then fails at the 10th cut even if every resume worked. Shorter outages will eat into them too, for instance: stopping minio for 6 seconds used 4 of 10 tries.
At the same time, a file that can't be downloaded at all now waits about 4 min before it fails (was 15 sec), and with 4 threads that adds up on a large delivery. A suggestion is that we count only attempts without progress, and keep that number lower? A 200 starts from 0 again, so progress would have to mean that the partial file grew.

Good point. I changed as follows:

  • Only attempts in a row without progress count now. Progress means the partial file got larger than the largest size so far. So a 200 restart counts only when it gets further, and a bad resume can't reset the count by downloading the same bytes again.
  • The limit is 7 attempts, about 1 min of waiting for a dead server. On dev it was 15 s, and I think that is too short for a MinIO or proxy restart.
  • DOWNLOAD_MAX_WAIT is removed, because the wait can no longer reach it.

@valyo

valyo commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

I've also pushed changes

dds_cli/data_getter.py:42 All our other exceptions are in exceptions.py, should RangeResumeError go there too?

tests/test_data_getter.py Maybe a test for an HTTP error other than 416 on a resumed request (e.g. a 503 from S3), checking that the partial is kept and the next attempt resumes again.

I've also pushed changes addressing these

@valyo
valyo requested a review from samanrassam November 23, 2026 12:18
Comment thread dds_cli/constants.py Outdated
# 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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only holds when the server is down from the start. If the download got some data first (like a Minio restart), that attempt sleeps 1 second and doubles the wait without counting as a failure, so the next waits are 2, 4, ..., 64 s and it gives up after about 2 min. I don't see it as a blocker, but figured either the comment should say so, or the wait shouldn't double after an attempt with progress.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed it so that the wait now doubles only after an attempt without progress. A server that goes down mid-download now gets the same ~1 min as one that is down from the start. Added a test for it.

Comment thread dds_cli/data_getter.py
wait = initial_wait
retry_messages = []
else:
failures += 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is what I'm referring to with my comment about 63s. If we have partial data then we go from 0-7 failures. (127s) If we have no data we go from 1-7 failures (63 s)

@samanrassam samanrassam left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ran the Minio test again with the new counting: 10 s down used 3 of 7 attempts, then it resumed correctly The new test and moving RangeResumeError look good. Good job!

Wrote two inline comments about the retry waiting where there is a difference (unless I'm mistaken) between how long we wait when there's partial data and when there's no data. Not blocking though.

Base automatically changed from api-retry-on-502 to dev November 24, 2026 08:05
…e-resume

# Conflicts:
#	dds_cli/data_getter.py
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.
@valyo
valyo requested a review from samanrassam November 25, 2026 09:59

@samanrassam samanrassam left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants