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 <noreply@anthropic.com>
Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
Christin
2026-11-20 18:50:25 +01:00
committed by Bobby Noelte
co-authored by Claude Opus 5.5
parent c8f793c203
commit 14acf759a7
2 changed files with 24 additions and 2 deletions
+3 -2
View File
@@ -1096,7 +1096,9 @@ def cache_in_file(
# Fail gracefully - recreate the cache file in this call # Fail gracefully - recreate the cache file in this call
call_force_update = True call_force_update = True
if call_force_update or cache_file is None: 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__) logger.debug("Created cache file for function: " + func.__name__)
cache_file = CacheFileStore().create( cache_file = CacheFileStore().create(
key, key,
@@ -1107,7 +1109,6 @@ def cache_in_file(
until_date=expiry["until_date"], until_date=expiry["until_date"],
with_ttl=expiry["with_ttl"], with_ttl=expiry["with_ttl"],
) )
result = func(*args, **kwargs)
try: try:
# Assure we have an empty file # Assure we have an empty file
cache_file.truncate(0) cache_file.truncate(0)
+21
View File
@@ -904,6 +904,27 @@ class TestCacheFileDecorators:
assert f() == "result" assert f() == "result"
assert len(calls) == 2 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): def test_var_positional_arguments_are_part_of_the_key(self, cache_file_store):
cache_file_store.clear(clear_all=True) cache_file_store.clear(clear_all=True)