Skip to content

The agent that grows with you

fix(gateway): contain a corrupt store in API image cleanup, not only a locked one

unsupportedpastels9566a1d86e4c
diff --git a/gateway/session_ingress_media.py b/gateway/session_ingress_media.py
index 3ba69a599e7..c6c5092c6ad 100644
--- a/gateway/session_ingress_media.py
+++ b/gateway/session_ingress_media.py
@@ -10,6 +10,7 @@ from contextlib import contextmanager
from contextvars import ContextVar
import hashlib
import json
+import logging
import os
from pathlib import Path
import re
@@ -22,6 +23,7 @@ from hermes_dir_acl import make_user_dir
from hermes_state_runtime import RuntimeStoreError
from utils import fsync_directory
+logger = logging.getLogger(__name__)
_API_IMAGE_NAME = re.compile(r'api_[0-9a-f]{32}\.(png|jpg|gif|webp)')
_SHA256_NAME = re.compile(r'[0-9a-f]{64}')
@@ -462,8 +464,7 @@ def collect_unheld_api_images(db):
unowned, so it collects nothing."""
from hermes_constants import get_hermes_home
if Path(db.db_path).resolve().parent != get_hermes_home().resolve():
- import logging
- logging.getLogger(__name__).warning(
+ logger.warning(
'Skipped retained API image collection: %s is not the active profile store', db.db_path)
return 0
root = _media_root()
@@ -471,10 +472,10 @@ def collect_unheld_api_images(db):
return release_unheld_media(db, [
{'path': str(path), 'sha256': path.parent.name} for path in (root.glob('*/api_*') if root.is_dir() else ())
if _API_IMAGE_NAME.fullmatch(path.name) and path.name[4:36] == path.parent.name[:32]])
- except sqlite3.OperationalError:
+ except sqlite3.DatabaseError:
# Callers run after a committed delete or during startup recovery: neither may fail on it.
- import logging
- logging.getLogger(__name__).exception('API image collection failed; files stay for the next sweep')
+ # ``DatabaseError`` also covers a corrupt store, not only ``OperationalError`` (locked, limits).
+ logger.exception('API image collection failed; files stay for the next sweep')
return 0
diff --git a/tests/gateway/test_api_image_delete_scale.py b/tests/gateway/test_api_image_delete_scale.py
index 9baf390d5be..e28aca86dc2 100644
--- a/tests/gateway/test_api_image_delete_scale.py
+++ b/tests/gateway/test_api_image_delete_scale.py
@@ -52,8 +52,15 @@ async def _delete(api, session_id):
return deleted.status, await deleted.text()
-def _explode(conn, references, after_id=0):
- raise sqlite3.OperationalError('database disk image is malformed')
+# A locked store raises ``OperationalError``; a corrupt one raises its parent ``DatabaseError``.
+_STORE_ERRORS = [sqlite3.OperationalError('database is locked'),
+ sqlite3.DatabaseError('database disk image is malformed')]
+
+
+def _exploding(error):
+ def explode(conn, references, after_id=0):
+ raise error
+ return explode
@pytest.mark.asyncio
@@ -72,12 +79,13 @@ async def test_delete_session_with_many_api_images_succeeds(api, owner, count):
@pytest.mark.asyncio
-async def test_a_cleanup_failure_after_the_delete_committed_is_not_a_500(api, owner, monkeypatch):
[email protected]('error', _STORE_ERRORS, ids=type)
+async def test_a_cleanup_failure_after_the_delete_committed_is_not_a_500(api, owner, monkeypatch, error):
"""The session is already gone when the image sweep runs: its failure is logged and the
files stay for the next sweep, but the finished delete answers 200."""
_settle_text(api, owner, 'chat')
planted = _plant(1)
- monkeypatch.setattr('gateway.session_ingress_media._history_mentions', _explode)
+ monkeypatch.setattr('gateway.session_ingress_media._history_mentions', _exploding(error))
status, body = await _delete(api, 'chat')
assert status == 200, body
assert owner.db.get_session('chat') is None
@@ -100,13 +108,14 @@ def test_startup_recovery_survives_a_thousand_api_images(api, owner, monkeypatch
assert _remaining(planted) == [kept_digest]
-def test_startup_recovery_continues_when_image_collection_fails(api, owner, monkeypatch, caplog):
[email protected]('error', _STORE_ERRORS, ids=type)
+def test_startup_recovery_continues_when_image_collection_fails(api, owner, monkeypatch, caplog, error):
"""A collection error is logged and skipped, never a reason to leave queued turns unscheduled."""
admit_api_turn(
api, session_id='queued', request_id='queued-turn',
user_message='pending', conversation_history=[])
_plant(1)
- monkeypatch.setattr('gateway.session_ingress_media._history_mentions', _explode)
+ monkeypatch.setattr('gateway.session_ingress_media._history_mentions', _exploding(error))
scheduled = []
monkeypatch.setattr(owner, '_schedule', lambda ref: scheduled.append(ref.session_id))
recover_api_turns(api)