Skip to content

Api retry on 502 - #1009

Merged
valyo merged 12 commits into
devfrom
api-retry-on-502
Nov 24, 2026
Merged

valyo merged 12 commits into
devfrom
api-retry-on-502

Conversation

@valyo

@valyo valyo commented Nov 16, 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

First of 4 PRs for the download problems seen with large deliveries. This one is only about API calls during upload/download. Range resume, disk flush, decrypt limit and --temp-dir come in the next PRs.

1. Retry once on a 502/503 from the proxy

A 502 from Traefik usually means that the backend (gunicorn) 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. Before this PR, one 502 in file/update made the download of that file fail, and one 502 in file/new made the upload go to the end-of-run file/addfailed path.

  • New utils.perform_request_with_retry(): retry once after 1 s.
  • A retry needs both: no JSON body (new NonJsonResponseError, subclass of ApiResponseError) and status in API_NON_JSON_RETRY_STATUS_CODES (502, 503). A 500/504 is not retried: the backend may have done the work.
  • Used in DataGetter.update_db and DataPutter.add_file_db.
  • update_db now also catches ApiResponseError, so a failed update does not stop the other downloads.

2. POST file/new that reached the backend

A proxy 502 is not always "request not received". If the first POST added the file, the retry fails because the file exists (500 from dds_web). After a failed POST, add_file_db asks file/match. If the file is in the DB with the name_in_bucket of this upload (random per upload), our own request added it, and the file counts as added. PUT (overwrite) is not checked: a repeated PUT adds one closed version row, the same as the existing retry_add_file_db fallback.

3. Stop the delivery on maintenance

A 503 with a JSON body comes from dds_web (MaintenanceOngoingException). It is raised as the new ServiceUnavailableError, is never retried, and stops the delivery:

Step What happens
File that gets the 503 Marked as failed (failed_op) and saved in the failed delivery log as before
Files not started yet Cancelled (same stop_doing flag as Ctrl+C)
Running download Stops at the next chunk, partial file removed, no retry
Running upload Not sent to S3 after encryption (no orphan object). An S3 upload that has already started is finished.
End of upload batch retry_add_file_db and touch_project_after_upload are skipped (API is down). The path to the failed delivery log is shown.
Exit The error is raised once, from the main thread, after the workers are done. Exit code 1.

Ctrl+C behaviour is not changed.

Related Issue/Ticket

HMS-2694

Testing

  • New tests/test_api_retry.py (28 tests, mocked requests):
    • retry on non-JSON 502/503, give up after the second one
    • no retry on 400, 500, JSON 502, or an ApiResponseError that is not NonJsonResponseError
    • backend 503 becomes ServiceUnavailableError and is not retried
    • update_db / add_file_db on maintenance: failure returned, failed_op set, delivery stopped
    • new files cancelled, running download stopped, S3 upload skipped after encryption
    • 502 then "file exists" with our name_in_bucket counts as added; other name_in_bucket or a failed file/match stays failed; PUT is not checked
    • end-of-batch DB calls skipped on maintenance, run as before without it
  • Full suite: 250 passed, 12 skipped. ruff format --check and ruff check are clean.

Reviewer Notes

  • The rule "retry only proxy answers" is in the exception type, not only the status code. See the comment at API_NON_JSON_RETRY_STATUS_CODES and the docstring of perform_request_with_retry.
  • On download, an update_db failure (maintenance included) is still not fatal: the file is decrypted and verified locally. file/update only sets time_latest_download. This is the same as before.
  • On maintenance the summary prints only "Upload cancelled." / "Download cancelled.", then the maintenance error.
  • PR2 (Range resume) rewrites get() and keeps the two maintenance checks.

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

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.
@codecov

codecov Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.38554% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 59.86%. Comparing base (46c1f5f) to head (d4081d7).

Files with missing lines Patch % Lines
dds_cli/__main__.py 0.00% 1 Missing ⚠️
dds_cli/data_putter.py 96.66% 1 Missing ⚠️
dds_cli/utils.py 94.11% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              dev    #1009      +/-   ##
==========================================
+ Coverage   56.42%   59.86%   +3.43%     
==========================================
  Files          33       33              
  Lines        3105     3179      +74     
==========================================
+ Hits         1752     1903     +151     
+ Misses       1353     1276      -77     

☔ 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 added the type: bug Something isn't working label Nov 16, 2026
@valyo
valyo marked this pull request as ready for review November 16, 2026 10:52
@valyo
valyo requested a review from a team as a code owner November 16, 2026 10:52
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 16, 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-16T10:54:46.701597Z c5b927e 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 mentioned this pull request Nov 17, 2026
6 of 10 tasks

@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.

Nice! I tested it locally with maintenance turned on mid transfer. Upload works as described, but got crash on download.

dds_cli/custom_decorators.py:48
This crashes on download: the file keys there are pathlib.Path, so escape(file) raises TypeError. escape(str(file)) fixes it (tried locally). A test with a Path key would catch it.

Some questions:

dds_cli/data_getter.py: 296
Do we need to stop downloads on maintenance? They don't need the API, and file/update only sets time_latest_download.

dds_cli/data_putter.py:172
After maintenance every remaining file is still submitted and logs a cancel warning, so a big delivery gets a looooot of lines. Should we stop scheduling once stop_doing is set? Same in get_data.

super minor and non-blocking:
dds_cli/base.py: 135
This prints "ongoing.. Stopping", since the dds_web message already ends with a period.

dds_cli/utils.py:349
This is unreachable, we could just return perform_request(*args, **kwargs) after the loop.

I think HMS-2694 is missing from the description.

@valyo

valyo commented Nov 17, 2026

Copy link
Copy Markdown
Member Author

Nice! I tested it locally with maintenance turned on mid transfer. Upload works as described, but got crash on download.

dds_cli/custom_decorators.py:48 This crashes on download: the file keys there are pathlib.Path, so escape(file) raises TypeError. escape(str(file)) fixes it (tried locally). A test with a Path key would catch it.

this is a good catch; it was in fact an already existing bug but a download probably (almost) never reached this code.
I will push a fix

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.
@valyo

valyo commented Nov 17, 2026

Copy link
Copy Markdown
Member Author

Some questions:

dds_cli/data_getter.py: 296 Do we need to stop downloads on maintenance? They don't need the API, and file/update only sets time_latest_download.

technically probably a download can succeed, but there will be error messages and confusion. And one can ask the question why have maintenance mode at all.
We can have a short discussion about it.

dds_cli/data_putter.py:172 After maintenance every remaining file is still submitted and logs a cancel warning, so a big delivery gets a looooot of lines. Should we stop scheduling once stop_doing is set? Same in get_data.

Good point, I noticed this too and thought it can be better, but maybe better to do in a separate task/PR
This one was not about maintenance at all, and I probably shouldn't have put it here, but the 50X handling led to it.

The test compared against "dir/file.bin", but str(Path) uses the OS
separator, so on Windows the log shows "dir\file.bin".
@valyo

valyo commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

super minor and non-blocking: dds_cli/base.py: 135 This prints "ongoing.. Stopping", since the dds_web message already ends with a period.

strange, I get:

ERROR Failed to add file 'docs/_static/windows/python_install-2.png' to database: Maintenance of DDS is ongoing. Stopping: files not started yet are cancelled.
for upload

and

ERROR Failed to update file information: Maintenance of DDS is ongoing. Stopping: files not started yet are cancelled.
for download

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 requested a review from samanrassam November 18, 2026 13:22

@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 same tests and did not get any crash. The remaining files are cancelled and it exits with the maintenance error, nice!

Made a ticket for the issue with remaining files once stop_doing is set for a separate PR.

@valyo
valyo merged commit 2d98ae4 into dev Nov 24, 2026
15 checks passed
@valyo
valyo deleted the api-retry-on-502 branch November 24, 2026 08:05
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