fix(requests): retrying a request after its client failed offers the same release again (#1677)

When a request's download fails in a way the queue can't resume, the
request is reopened and its Retry button opens the release list. The
release that just failed was drawn there as a red, disabled "Failed"
button for as long as the failed task stayed in the queue status, so you
couldn't pick it again even when the release was fine and the download
client was the problem. A bad qBittorrent password is the easy way to
hit it. Thanks @joshft91 for the report and the steps.

What changes:

- In the release list, a failed request download now shows Retry, the
same as a failure the queue can retry already does. A direct download
with nothing to retry from still shows Failed. The rule lives in one
small helper used by the release modal and both button-state paths in
`useDownloadTracking`.
- A client that refuses the login is no longer held against the release.
qbittorrent-api raises `LoginFailed` with no message for a wrong
password, and only "Forbidden" or "Unauthorized" for a bad session or
API key, so none of it matched the unreachable-client markers from #1655
and the release went into `failed_releases`. The qBittorrent client now
says "qBittorrent authentication failed (...)" for these.
- The request reopen and the auto-download retry used two copies of the
same marker list. They now share one in `status_messages.py`, which also
counts an explicit authentication failure as the client's fault. A bare
403 or 401 is not on it, since a dead .torrent link fails that way too
and that one is the release's. Genuine release failures (no seeders, a
rejected torrent, a dead .torrent link) are still remembered as #1655
intended.

Tested with a scratch instance against a mock Prowlarr and a fake
qBittorrent that rejects the login: before, the request's Retry opened
the list with the failed release as a red X; after, it shows Retry,
picking it fulfils the request again, and the request reopens without
the release in `failed_releases`. New tests cover the qBittorrent
messages, both reopen paths and the button state.

Fixes #1674


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Failed releases are no longer skipped after download-client connection
or login failures; download failures and stall cancellations remain
eligible to be skipped on the next search.
* Failed requests with an associated request can now show a retry
option, while direct downloads without retries remain marked as failed.
* qBittorrent login and authorization errors are reported more clearly.

* **Documentation**
* Clarified which failures cause a release to be skipped on a later
search.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
splitsec2 authored and GitHub committed 2026-11-08 23:11:25 -07:00
1 parent efc0f3df6b
commit 76d7df306f
12 files changed
+375 -43

No files matched your search

+3
View File
@@ -2621,6 +2621,9 @@ class TestRetryAfterCooldown:
"Failed to add to qbittorrent: Failed to connect to qBittorrent. This i",
"Cannot connect to qBittorrent at http://x",
"Connection refused",
"Failed to add to qbittorrent: qBittorrent authentication failed (HTTP 403)",
"Failed to add to qbittorrent: qBittorrent authentication failed (HTTP 401)",
"Failed to add to deluge: Deluge Web UI authentication failed",
],
)
def test_a_download_whose_client_was_down_is_not_held_against_its_release(
+80
View File
@@ -835,6 +835,86 @@ def test_sync_delivery_states_does_not_blame_the_release_when_the_client_was_unr
assert "failed_releases" not in refreshed["book_data"] # but the release is not held against
@pytest.mark.parametrize(
"message",
[
"Failed to add to qbittorrent: qBittorrent authentication failed (HTTP 403)",
"Failed to add to qbittorrent: qBittorrent authentication failed (HTTP 401)",
"Failed to add to qbittorrent: qBittorrent authentication failed (login rejected)",
"Failed to add to deluge: Deluge Web UI authentication failed",
],
)
def test_sync_delivery_states_does_not_blame_the_release_when_the_client_refused_the_login(
user_db, message
):
user = user_db.create_user(username="alice")
fulfilled_request = user_db.create_request(
user_id=user["id"],
source_hint="prowlarr",
content_type="audiobook",
request_level="release",
policy_mode="request_release",
book_data=_book_data(),
release_data={"source": "prowlarr", "source_id": "fine-rel", "title": "Fine"},
status="fulfilled",
delivery_state="queued",
)
sync_delivery_states_from_queue_status(
user_db,
queue_status={
"error": {
"fine-rel": {
"id": "fine-rel",
"request_id": fulfilled_request["id"],
"retry_available": False,
"status_message": message,
},
},
},
user_id=user["id"],
)
refreshed = user_db.get_request(fulfilled_request["id"])
assert refreshed["status"] == "pending"
assert "failed_releases" not in refreshed["book_data"]
def test_sync_delivery_states_still_blames_a_release_whose_link_is_forbidden(user_db):
"""A tracker's 403 on the .torrent link is the release's fault, so it is remembered."""
user = user_db.create_user(username="alice")
fulfilled_request = user_db.create_request(
user_id=user["id"],
source_hint="prowlarr",
content_type="audiobook",
request_level="release",
policy_mode="request_release",
book_data=_book_data(),
release_data={"source": "prowlarr", "source_id": "dead-link", "title": "Dead"},
status="fulfilled",
delivery_state="queued",
)
sync_delivery_states_from_queue_status(
user_db,
queue_status={
"error": {
"dead-link": {
"id": "dead-link",
"request_id": fulfilled_request["id"],
"retry_available": False,
"status_message": "403 Client Error: Forbidden for url: https://tracker.example/t/1",
},
},
},
user_id=user["id"],
)
refreshed = user_db.get_request(fulfilled_request["id"])
assert refreshed["status"] == "pending"
assert [r.get("source_id") for r in refreshed["book_data"]["failed_releases"]] == ["dead-link"]
def test_sync_delivery_states_preserves_retryable_error_state(user_db):
user = user_db.create_user(username="alice")
fulfilled_request = user_db.create_request(
+114
View File
@@ -1617,6 +1617,120 @@ class TestQBittorrentClientAddDownload:
with pytest.raises(RuntimeError, match="Failed to add torrent: Fails\\."):
client.add_download(magnet, "Test")
@pytest.mark.parametrize(
("error_name", "error_text", "expected"),
[
("LoginFailed", "", "qBittorrent authentication failed (login rejected)"),
("Forbidden403Error", "Forbidden", "qBittorrent authentication failed (HTTP 403)"),
(
"Unauthorized401Error",
"Unauthorized",
"qBittorrent authentication failed (HTTP 401)",
),
],
)
def test_add_download_names_a_rejected_login(
self, monkeypatch, error_name, error_text, expected
):
"""A login qBittorrent refuses is reported as an authentication failure, not bare text."""
import qbittorrentapi as real_qbittorrentapi
config_values = {
"QBITTORRENT_URL": "http://localhost:8080",
"QBITTORRENT_USERNAME": "admin",
"QBITTORRENT_PASSWORD": "wrong",
"QBITTORRENT_CATEGORY": "books",
}
monkeypatch.setattr(
"shelfmark.download.clients.qbittorrent.config.get",
lambda key, default="": config_values.get(key, default),
)
valid_hash = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"
mock_client_instance = MagicMock()
error_type = getattr(real_qbittorrentapi, error_name)
mock_client_instance.torrents_add.side_effect = error_type(error_text)
fake_module = MagicMock(
Client=MagicMock(return_value=mock_client_instance),
APIError=real_qbittorrentapi.APIError,
LoginFailed=real_qbittorrentapi.LoginFailed,
HTTP401Error=real_qbittorrentapi.HTTP401Error,
HTTP403Error=real_qbittorrentapi.HTTP403Error,
)
with patch.dict("sys.modules", {"qbittorrentapi": fake_module}):
import importlib
import shelfmark.download.clients.qbittorrent as qb_module
importlib.reload(qb_module)
client = qb_module.QBittorrentClient()
magnet = f"magnet:?xt=urn:btih:{valid_hash}&dn=test"
with pytest.raises(RuntimeError) as raised:
client.add_download(magnet, "Test")
assert str(raised.value) == expected
@staticmethod
def _client_with_real_errors(monkeypatch, mock_client_instance):
"""A QBittorrentClient over a mock session, with qbittorrent-api's real error types."""
import importlib
import qbittorrentapi as real_qbittorrentapi
config_values = {
"QBITTORRENT_URL": "http://localhost:8080",
"QBITTORRENT_USERNAME": "admin",
"QBITTORRENT_PASSWORD": "wrong",
"QBITTORRENT_CATEGORY": "books",
}
monkeypatch.setattr(
"shelfmark.download.clients.qbittorrent.config.get",
lambda key, default="": config_values.get(key, default),
)
fake_module = MagicMock(
Client=MagicMock(return_value=mock_client_instance),
APIError=real_qbittorrentapi.APIError,
LoginFailed=real_qbittorrentapi.LoginFailed,
HTTP401Error=real_qbittorrentapi.HTTP401Error,
HTTP403Error=real_qbittorrentapi.HTTP403Error,
)
with patch.dict("sys.modules", {"qbittorrentapi": fake_module}):
import shelfmark.download.clients.qbittorrent as qb_module
importlib.reload(qb_module)
return qb_module.QBittorrentClient()
def test_a_refused_login_while_checking_a_torrent_is_named_as_one(self, monkeypatch):
"""A status check whose login is refused reports an authentication failure."""
import qbittorrentapi as real_qbittorrentapi
mock_client_instance = MagicMock()
mock_client_instance.auth_log_in.side_effect = real_qbittorrentapi.LoginFailed("")
client = self._client_with_real_errors(monkeypatch, mock_client_instance)
torrents, error = client._request_torrent_info_records({"hashes": "abc"})
assert torrents == []
assert error == "qBittorrent authentication failed (login rejected)"
def test_a_401_while_checking_a_torrent_is_an_authentication_failure(self, monkeypatch):
"""HTTP 401 on the info call is the client's login, not the torrent."""
import requests
response = MagicMock(status_code=401)
response.raise_for_status.side_effect = requests.exceptions.HTTPError(response=response)
mock_client_instance = MagicMock()
mock_client_instance._session.get.return_value = response
client = self._client_with_real_errors(monkeypatch, mock_client_instance)
torrents, error = client._request_torrent_info_records({"hashes": "abc"})
assert torrents == []
assert error == "qBittorrent authentication failed (HTTP 401)"
def test_add_download_omits_empty_category(self, monkeypatch):
"""Avoid sending empty category values to qBittorrent-compatible clients."""
config_values = {