Skip to content

The agent that grows with you

fix(gateway): the store-park reason reports the recorded open failure, never reopens

Teknium835b0fa4d739
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.py
index 43d9d120919..49f4233a47c 100644
--- a/gateway/run_runtime.py
+++ b/gateway/run_runtime.py
@@ -44,7 +44,7 @@ async def _build_profile_authority(runner, name, home, *, register):
with _profile_runtime_scope(home, hydrate_secrets=False):
db = getattr(runner._session_db, '_db', runner._session_db)
if db is None:
- raise RuntimeError(await asyncio.to_thread(_store_open_failure, home))
+ raise RuntimeError(_store_open_failure(runner, home))
if (await asyncio.to_thread(Path(db.db_path).resolve)).parent != home:
raise RuntimeError(f'session authority database does not belong to the reserved profile {home}')
registry.add(home, None, name=name)
@@ -58,17 +58,18 @@ async def _build_profile_authority(runner, name, home, *, register):
return authority
-def _store_open_failure(home):
- """Why *home*'s ``state.db`` has no handle: the scoped handle cache answers None for a failed open
- (and while it backs off), so the park reason named an ownership mismatch over the real cause, a
- legacy store that crashed its migration on every open (#141467)."""
- from hermes_state_registry import acquire, release
+def _store_open_failure(runner, home):
+ """Why *home*'s ``state.db`` has no handle: the scoped handle caches answer None for a failed open
+ (and while they back off), so the park reason named an ownership mismatch over the real cause, a
+ legacy store that crashed its migration on every open (#141467). The reason is the exception the
+ failed open recorded; reopening here to learn it could create or migrate the store, and would skip
+ the caches' backoff."""
path = home / 'state.db'
- try:
- release(acquire(path))
- except Exception as exc: # any open failure is the reason; the traceback goes to the log
- logger.warning("Session store %s did not open", path, exc_info=True)
- return f'{path} did not open: {type(exc).__name__}: {exc}'
+ caches = (getattr(getattr(runner, 'session_store', None), '_db_handle_cache', None),
+ getattr(runner, '_session_db_handle_cache', None))
+ error = next((e for e in (c.last_error(path) for c in caches if c is not None) if e), '')
+ if error:
+ return f'{path} did not open: {error}'
return f'{path} is unavailable (its last open failed; retry pending)'
diff --git a/gateway/session_db_recovery.py b/gateway/session_db_recovery.py
index 9360e1b6e5e..dcf2d9a6628 100644
--- a/gateway/session_db_recovery.py
+++ b/gateway/session_db_recovery.py
@@ -19,6 +19,7 @@ class _Unavailable:
failures: int = 0
next_retry_at: float = 0.0
in_flight: bool = False
+ error: str = ""
class _HealthSource:
@@ -121,6 +122,7 @@ class RecoverableHandleCache:
raise
if not stale:
unavailable.failures += 1
+ unavailable.error = f"{type(exc).__name__}: {exc}"
backoff = self._initial_retry_delay * (2 ** min(unavailable.failures - 1, 30))
unavailable.next_retry_at = self._clock() + min(backoff, self._max_retry_delay)
unavailable.in_flight = False
@@ -150,6 +152,12 @@ class RecoverableHandleCache:
on_recovered()
return handle
+ def last_error(self, path: Path) -> str:
+ """The exception the latest failed open of *path* raised (``''`` when none is recorded)."""
+ target = Path(path).resolve()
+ with self.lock:
+ return next((u.error for key, u in self._unavailable.items() if key.resolve() == target), "")
+
def close_all(self, close: Callable[[Any], None]) -> None:
"""Drain cached handles under the lock and close them outside it."""
with self.lock:
diff --git a/tests/gateway/test_profile_authority_park_reason.py b/tests/gateway/test_profile_authority_park_reason.py
index 93443ddfa0c..37d0651b61e 100644
--- a/tests/gateway/test_profile_authority_park_reason.py
+++ b/tests/gateway/test_profile_authority_park_reason.py
@@ -3,7 +3,8 @@
The runner's scoped handle cache answers None when a profile's ``state.db`` fails to open, and
``_build_profile_authority`` reported every None as "session authority database does not belong to
the reserved profile": a legacy store crashing its migration on every open was parked under a
-reason that sent the operator after the wrong problem (#141467).
+reason that sent the operator after the wrong problem (#141467). The reason is the exception the
+failed open recorded; building it never opens (so never creates or migrates) the store.
"""
from pathlib import Path
from types import SimpleNamespace
@@ -11,6 +12,7 @@ from types import SimpleNamespace
import pytest
from gateway import run_runtime
+from gateway.session_db_recovery import RecoverableHandleCache
class _Registry:
@@ -18,17 +20,35 @@ class _Registry:
raise AssertionError('an unusable store must not reach registration')
+def _runner(cache):
+ return SimpleNamespace(_session_db=None, session_authorities=_Registry(), _session_db_handle_cache=cache,
+ session_runtime_descriptor={'instance_id': 'owner'})
+
+
@pytest.mark.asyncio
async def test_an_unopenable_store_is_parked_under_its_open_failure(tmp_path, monkeypatch):
+ from hermes_state_registry import acquire
home = (tmp_path / 'profiles' / 'worker').resolve()
home.mkdir(parents=True)
(home / 'state.db').mkdir() # sqlite cannot open a directory: a store that fails on every open
monkeypatch.setenv('HERMES_HOME', str(tmp_path))
- runner = SimpleNamespace(_session_db=None, session_authorities=_Registry(),
- session_runtime_descriptor={'instance_id': 'owner'})
+ cache = RecoverableHandleCache()
+ assert cache.get(home / 'state.db', lambda: acquire(home / 'state.db')) is None # the runner's failed open
with pytest.raises(RuntimeError) as exc:
- await run_runtime._build_profile_authority(runner, 'worker', home, register=False)
+ await run_runtime._build_profile_authority(_runner(cache), 'worker', home, register=False)
reason = str(exc.value)
assert 'does not belong' not in reason
assert str(Path(home) / 'state.db') in reason and 'did not open' in reason, reason
+
+
+async def test_the_park_reason_never_creates_the_store(tmp_path, monkeypatch):
+ home = (tmp_path / 'profiles' / 'worker').resolve()
+ home.mkdir(parents=True)
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+
+ with pytest.raises(RuntimeError) as exc:
+ await run_runtime._build_profile_authority(_runner(RecoverableHandleCache()), 'worker', home, register=False)
+ assert 'is unavailable' in str(exc.value)
+ assert not (home / 'state.db').exists()