From 14acf759a7600ba649e408c982d496cabb2380ef Mon Sep 17 00:00:00 2001 From: Christin Date: Fri, 20 Nov 2026 18:08:12 +0100 Subject: [PATCH] fix(cache): leave no empty cache file after a failed cached call cache_in_file created the cache file before it called the function. When the call raised, e.g. a provider request answered with HTTP 500, the empty file stayed in the store until it expired, and the next call logged "Read failed: Ran out of input" before it called the function again. The function is now called first; a failed call leaves the store unchanged. Refs #1571 Co-Authored-By: Claude Opus 5.5 Assisted-by: Claude Code (claude-opus-5-5) --- src/akkudoktoreos/core/cache.py | 5 +++-- tests/test_cache.py | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/akkudoktoreos/core/cache.py b/src/akkudoktoreos/core/cache.py index 108bc9d6..dcaa0a6a 100644 --- a/src/akkudoktoreos/core/cache.py +++ b/src/akkudoktoreos/core/cache.py @@ -1096,7 +1096,9 @@ def cache_in_file( # Fail gracefully - recreate the cache file in this call call_force_update = True if call_force_update or cache_file is None: - # Otherwise, call the function and save its result to the cache + # Otherwise, call the function and save its result to the cache. + # Call first: a call that raises leaves no empty cache file behind. + result = func(*args, **kwargs) logger.debug("Created cache file for function: " + func.__name__) cache_file = CacheFileStore().create( key, @@ -1107,7 +1109,6 @@ def cache_in_file( until_date=expiry["until_date"], with_ttl=expiry["with_ttl"], ) - result = func(*args, **kwargs) try: # Assure we have an empty file cache_file.truncate(0) diff --git a/tests/test_cache.py b/tests/test_cache.py index 0ef2c645..97864e0b 100644 --- a/tests/test_cache.py +++ b/tests/test_cache.py @@ -904,6 +904,27 @@ class TestCacheFileDecorators: assert f() == "result" assert len(calls) == 2 + def test_failed_call_leaves_no_cache_file(self, cache_file_store, caplog) -> None: + """A call that raises caches nothing, so the next call reads no empty file (#1571).""" + cache_file_store.clear(clear_all=True) + responses: list[Exception | str] = [RuntimeError("500 Server Error"), "result"] + + @cache_in_file(with_ttl="1 hour") + def fetch() -> str: + response = responses.pop(0) + if isinstance(response, Exception): + raise response + return response + + with pytest.raises(RuntimeError, match="500 Server Error"): + fetch() + assert len(cache_file_store._store) == 0 + + assert fetch() == "result" + assert "Read failed" not in caplog.text + assert fetch() == "result" + assert responses == [] + def test_var_positional_arguments_are_part_of_the_key(self, cache_file_store): cache_file_store.clear(clear_all=True)