Compare commits

...
Author SHA1 Message Date
Andrew BeveridgeandClaude Fable 5 2e8e959010 review: enforce 95s total search budget below Cloudflare edge deadline
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-18 12:50:09 -04:00
Andrew BeveridgeandClaude Fable 5 da3c54b026 fix: retry flacfetch search on transient network errors (v0.230.2)
A single ReadTimeout on the remote flacfetch /search call surfaced as a
user-facing 500 (2026-09-18 15:21 UTC incident): the flacfetch server was
busy with an uncached provider sweep, the 60s client timeout fired, and
search() — unlike download()/download_by_id() — had no retry at all.

Search is idempotent, so give it a light retry profile (2 attempts, 1s
wait, configurable via FLACFETCH_SEARCH_RETRY_*). The retry typically
hits the server-side search cache warmed by the first attempt and
returns in seconds, while staying inside Cloudflare's ~100s edge limit.
Deliberately does NOT fall back to local search (fallback audit 2026-06-09).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-18 12:27:05 -04:00
4 changed files with 214 additions and 28 deletions

No files matched your search

+10
View File
@@ -263,6 +263,16 @@ class Settings(BaseSettings):
flacfetch_retry_min_wait: float = float(os.getenv("FLACFETCH_RETRY_MIN_WAIT", "10.0")) # seconds
flacfetch_retry_max_wait: float = float(os.getenv("FLACFETCH_RETRY_MAX_WAIT", "60.0")) # seconds
# Search retry settings are much lighter than the download defaults above:
# search is called synchronously from user-facing requests that sit behind
# Cloudflare's ~100s edge timeout, so there's only room for one quick retry
# (worst case: 60s timeout + 1s wait + fast cache-hit retry).
flacfetch_search_retry_max_attempts: int = int(os.getenv("FLACFETCH_SEARCH_RETRY_MAX_ATTEMPTS", "2"))
flacfetch_search_retry_wait: float = float(os.getenv("FLACFETCH_SEARCH_RETRY_WAIT", "1.0")) # seconds
# Total budget across all search attempts, kept under Cloudflare's ~100s edge
# deadline so callers get a clean FlacfetchServiceError instead of an edge 524.
flacfetch_search_total_timeout: float = float(os.getenv("FLACFETCH_SEARCH_TOTAL_TIMEOUT", "95.0")) # seconds
# Default distribution settings (can be overridden per-request)
default_dropbox_path: Optional[str] = os.getenv("DEFAULT_DROPBOX_PATH")
default_gdrive_folder_id: Optional[str] = os.getenv("DEFAULT_GDRIVE_FOLDER_ID")
+59 -27
View File
@@ -92,17 +92,21 @@ def should_retry_flacfetch_error(exception: Exception) -> bool:
return False
async def with_retry(func, *args, **kwargs):
async def with_retry(func, *args, retry_max_attempts=None, retry_min_wait=None, retry_max_wait=None, **kwargs):
"""
Execute an async function with retry logic using exponential backoff.
This implementation uses manual retry logic instead of tenacity decorators
for better testability and runtime configuration.
The retry_* keyword-only arguments override the FLACFETCH_RETRY_* settings
for callers that need a different retry profile (e.g. search, which sits on
a latency-sensitive user-facing path).
"""
settings = get_settings()
max_attempts = settings.flacfetch_retry_max_attempts
min_wait = settings.flacfetch_retry_min_wait
max_wait = settings.flacfetch_retry_max_wait
max_attempts = retry_max_attempts if retry_max_attempts is not None else settings.flacfetch_retry_max_attempts
min_wait = retry_min_wait if retry_min_wait is not None else settings.flacfetch_retry_min_wait
max_wait = retry_max_wait if retry_max_wait is not None else settings.flacfetch_retry_max_wait
last_exception = None
@@ -218,37 +222,65 @@ class FlacfetchClient:
Returns:
Search response dict with search_id and results list
Raises:
FlacfetchServiceError: On search failure
FlacfetchServiceError: On search failure (after all retries exhausted)
Search is idempotent, so transient network errors (e.g. a ReadTimeout
while the flacfetch server is busy with an uncached provider sweep) are
retried once with a short wait. The retry usually hits the server-side
search cache warmed by the first attempt and returns in seconds.
All attempts share a total time budget kept below Cloudflare's ~100s
edge deadline, so a slow retry surfaces as FlacfetchServiceError rather
than an opaque edge 524.
"""
settings = get_settings()
total_timeout = settings.flacfetch_search_total_timeout
try:
async with httpx.AsyncClient() as client:
resp = await client.post(
f"{self.base_url}/search",
headers=self._headers(),
json={"artist": artist, "title": title},
timeout=self.timeout,
)
if resp.status_code == 404:
# No results found - return empty results
return {
"search_id": None,
"artist": artist,
"title": title,
"results": [],
"results_count": 0,
}
resp.raise_for_status()
return resp.json()
return await asyncio.wait_for(
with_retry(
self._search_impl,
artist,
title,
retry_max_attempts=settings.flacfetch_search_retry_max_attempts,
retry_min_wait=settings.flacfetch_search_retry_wait,
retry_max_wait=settings.flacfetch_search_retry_wait,
),
timeout=total_timeout,
)
except asyncio.TimeoutError:
raise FlacfetchServiceError(
f"Search timed out after {total_timeout:.0f}s total (including retries)"
)
except httpx.RequestError as e:
raise FlacfetchServiceError(f"Search request failed: {_format_httpx_error(e)}")
except httpx.HTTPStatusError as e:
raise FlacfetchServiceError(f"Search failed: {e.response.status_code} - {e.response.text}")
async def _search_impl(self, artist: str, title: str) -> Dict[str, Any]:
"""Implementation of search without error wrapping - lets httpx exceptions bubble up."""
async with httpx.AsyncClient() as client:
resp = await client.post(
f"{self.base_url}/search",
headers=self._headers(),
json={"artist": artist, "title": title},
timeout=self.timeout,
)
if resp.status_code == 404:
# No results found - return empty results
return {
"search_id": None,
"artist": artist,
"title": title,
"results": [],
"results_count": 0,
}
resp.raise_for_status()
return resp.json()
async def download(
self,
search_id: str,
+144
View File
@@ -829,6 +829,150 @@ class TestFlacfetchRetryLogic:
assert mock_client.post.call_count == 3
class TestFlacfetchSearchRetryLogic:
"""Test retry logic for flacfetch search (lighter profile than downloads)."""
@staticmethod
def _mock_settings():
mock_settings = Mock()
# Heavy download retry settings - search must NOT use these
mock_settings.flacfetch_retry_max_attempts = 9
mock_settings.flacfetch_retry_min_wait = 10.0
mock_settings.flacfetch_retry_max_wait = 60.0
# Light search retry settings
mock_settings.flacfetch_search_retry_max_attempts = 2
mock_settings.flacfetch_search_retry_wait = 0.01 # Fast for testing
mock_settings.flacfetch_search_total_timeout = 5.0
return mock_settings
@pytest.mark.asyncio
async def test_search_retries_on_read_timeout(self):
"""Test search retries on ReadTimeout and succeeds on second attempt."""
with patch("backend.services.flacfetch_client.get_settings", return_value=self._mock_settings()):
client = FlacfetchClient(
base_url="http://test:8080",
api_key="test-key",
)
with patch("httpx.AsyncClient") as mock_client_cls:
mock_client = AsyncMock()
mock_client_cls.return_value.__aenter__.return_value = mock_client
mock_response = Mock()
mock_response.status_code = 200
mock_response.json.return_value = {"search_id": "s1", "results": [{"index": 0}]}
mock_response.raise_for_status = Mock()
mock_client.post.side_effect = [
httpx.ReadTimeout("timed out"),
mock_response,
]
result = await client.search("ABBA", "Waterloo")
assert result["search_id"] == "s1"
assert mock_client.post.call_count == 2
@pytest.mark.asyncio
async def test_search_fails_after_max_attempts(self):
"""Test search raises FlacfetchServiceError after exhausting its 2 attempts.
Also verifies search uses the light search retry settings (2 attempts),
not the heavy download settings (9 attempts).
"""
with patch("backend.services.flacfetch_client.get_settings", return_value=self._mock_settings()):
client = FlacfetchClient(
base_url="http://test:8080",
api_key="test-key",
)
with patch("httpx.AsyncClient") as mock_client_cls:
mock_client = AsyncMock()
mock_client_cls.return_value.__aenter__.return_value = mock_client
mock_client.post.side_effect = httpx.ReadTimeout("timed out")
with pytest.raises(FlacfetchServiceError, match="Search request failed"):
await client.search("ABBA", "Waterloo")
assert mock_client.post.call_count == 2
@pytest.mark.asyncio
async def test_search_no_retry_on_4xx(self):
"""Test search does NOT retry on 4xx client errors (other than 404)."""
with patch("backend.services.flacfetch_client.get_settings", return_value=self._mock_settings()):
client = FlacfetchClient(
base_url="http://test:8080",
api_key="test-key",
)
with patch("httpx.AsyncClient") as mock_client_cls:
mock_client = AsyncMock()
mock_client_cls.return_value.__aenter__.return_value = mock_client
mock_response = Mock()
mock_response.status_code = 400
mock_response.text = "Bad request"
mock_response.raise_for_status.side_effect = httpx.HTTPStatusError(
"Bad request",
request=Mock(),
response=mock_response,
)
mock_client.post.return_value = mock_response
with pytest.raises(FlacfetchServiceError, match="400"):
await client.search("ABBA", "Waterloo")
assert mock_client.post.call_count == 1
@pytest.mark.asyncio
async def test_search_total_timeout_enforced(self):
"""Test the total search budget caps retries below the Cloudflare edge
deadline, surfacing a clean FlacfetchServiceError instead of hanging."""
mock_settings = self._mock_settings()
mock_settings.flacfetch_search_total_timeout = 0.05
with patch("backend.services.flacfetch_client.get_settings", return_value=mock_settings):
client = FlacfetchClient(
base_url="http://test:8080",
api_key="test-key",
)
async def hang(*args, **kwargs):
await asyncio.sleep(10)
with patch("httpx.AsyncClient") as mock_client_cls:
mock_client = AsyncMock()
mock_client_cls.return_value.__aenter__.return_value = mock_client
mock_client.post.side_effect = hang
with pytest.raises(FlacfetchServiceError, match="timed out.*total"):
await asyncio.wait_for(client.search("ABBA", "Waterloo"), timeout=2)
@pytest.mark.asyncio
async def test_search_404_returns_empty_without_retry(self):
"""Test 404 (no results) still returns empty results, without retrying."""
with patch("backend.services.flacfetch_client.get_settings", return_value=self._mock_settings()):
client = FlacfetchClient(
base_url="http://test:8080",
api_key="test-key",
)
with patch("httpx.AsyncClient") as mock_client_cls:
mock_client = AsyncMock()
mock_client_cls.return_value.__aenter__.return_value = mock_client
mock_response = Mock()
mock_response.status_code = 404
mock_client.post.return_value = mock_response
result = await client.search("Unknown", "Nothing")
assert result["results"] == []
assert result["search_id"] is None
assert mock_client.post.call_count == 1
class TestFormatHttpxError:
"""Test _format_httpx_error helper for descriptive error messages."""
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.230.1"
version = "0.230.2"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"