Skip to content

The agent that grows with you

fix: require exclusive maintenance for legacy bulk session writes

Teknium7323773c0a13
diff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.py
index 0ade6726cfd..c78bce6eaa2 100644
--- a/hermes_cli/web_routers/sessions.py
+++ b/hermes_cli/web_routers/sessions.py
@@ -83,7 +83,7 @@ def _prune_sessions(body: SessionPrune):
if has_window or (attr_filters_set and "older_than_days" not in body.model_fields_set):
effective_older_than = None
profile_home = _cron_profile_home(body.profile)[1] if body.profile else get_hermes_home()
- db = _open_session_db_for_profile(body.profile, read_only=False)
+ db = _open_session_db_for_profile(body.profile, read_only=body.dry_run)
try:
filters = {
"older_than_days": effective_older_than, "started_before": body.started_before,
@@ -129,11 +129,16 @@ def _is_active(row: dict, now: float) -> bool:
def _with_db(profile: Optional[str], fn: Callable, *, read_only: bool):
"""Open the profile's session DB, run ``fn(db)``, always close."""
- db = _open_session_db_for_profile(profile, read_only=read_only)
- try:
- return fn(db)
- finally:
- db.close()
+ def run():
+ db = _open_session_db_for_profile(profile, read_only=read_only)
+ try:
+ return fn(db)
+ finally:
+ db.close()
+ if read_only:
+ return run()
+ from hermes_cli.web_server_sessions import _with_session_maintenance
+ return _with_session_maintenance(profile, run)
def _serving_profile(profile: Optional[str]) -> str:
@@ -659,7 +664,10 @@ async def export_session_endpoint(session_id: str, profile: Optional[str] = None
@manage_router.post("/api/sessions/prune")
async def prune_sessions_endpoint(body: SessionPrune):
"""Delete ended sessions matching filters without blocking the event loop."""
- return await asyncio.to_thread(_prune_sessions, body)
+ if body.dry_run:
+ return await asyncio.to_thread(_prune_sessions, body)
+ from hermes_cli.web_server_sessions import _with_session_maintenance
+ return await asyncio.to_thread(_with_session_maintenance, body.profile, _prune_sessions, body)
# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
diff --git a/hermes_cli/web_server_sessions.py b/hermes_cli/web_server_sessions.py
index 44b49fecefa..4f7d82631c1 100644
--- a/hermes_cli/web_server_sessions.py
+++ b/hermes_cli/web_server_sessions.py
@@ -128,6 +128,21 @@ async def _mutate_session_request(request, profile, session_id, *, request_id,
raise HTTPException(status_code=503, detail='storage_unavailable') from exc
+def _with_session_maintenance(profile, operation, *args):
+ """Offline bulk actions reserve the exact owner lock through final DB close."""
+ from fastapi import HTTPException
+ from gateway.runtime_ownership import OwnershipConflict, exclusive_maintenance
+ from hermes_cli.web_server_cron import _cron_profile_home
+ from hermes_state import _default_db_path
+
+ home = Path(_cron_profile_home(profile)[1]) if profile else Path(_default_db_path()).parent
+ try:
+ with exclusive_maintenance([home]):
+ return operation(*args)
+ except OwnershipConflict as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+
+
def _session_db_read_probe_statements() -> tuple:
"""Probe the declared schema without reconciling it on a browsing request."""
from hermes_state_schema import schema_read_probe_statements
diff --git a/tests/hermes_cli/test_session_maintenance_http.py b/tests/hermes_cli/test_session_maintenance_http.py
new file mode 100644
index 00000000000..ed01217d0d9
--- /dev/null
+++ b/tests/hermes_cli/test_session_maintenance_http.py
@@ -0,0 +1,50 @@
+"""Legacy bulk maintenance must exclude the real gateway owner reservation."""
+import httpx
+import pytest
+from fastapi import FastAPI
+
+from gateway.runtime_ownership import ProfileOwnership
+from hermes_cli.web_routers.sessions import manage_router
+from hermes_state import SessionDB
+
+
+async def test_maintenance_routes_refuse_live_owner_without_changing_rows(tmp_path, monkeypatch):
+ monkeypatch.setattr('hermes_state._default_db_path', lambda: tmp_path / 'state.db')
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ app = FastAPI()
+ app.include_router(manage_router)
+ with SessionDB(db_path=tmp_path / 'state.db') as db:
+ db.create_session('ended-empty', source='cli')
+ db.end_session('ended-empty', 'complete')
+ before = db.get_session('ended-empty')
+ owner = ProfileOwnership()
+ owner.reserve([tmp_path])
+ try:
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://localhost') as client:
+ for method, path, body in [('POST', 'bulk-delete', {'ids': ['ended-empty']}),
+ ('DELETE', 'empty', None), ('POST', 'owner-backfill', {}),
+ ('POST', 'prune', {'older_than_days': 1})]:
+ response = await client.request(method, '/api/sessions/' + path, json=body)
+ assert response.status_code == 409, (path, response.text)
+ assert 'maintenance' in response.json()['detail'].lower()
+ assert db.get_session('ended-empty') == before
+ finally:
+ owner.close()
+
+
+async def test_exclusive_offline_maintenance_preserves_bulk_behavior(tmp_path, monkeypatch):
+ monkeypatch.setattr('hermes_state._default_db_path', lambda: tmp_path / 'state.db')
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ app = FastAPI()
+ app.include_router(manage_router)
+ with SessionDB(db_path=tmp_path / 'state.db') as db:
+ db.create_session('parent', source='cli')
+ db.create_session('child', source='cli', parent_session_id='parent')
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://localhost') as client:
+ result = await client.post('/api/sessions/bulk-delete', json={'ids': ['parent', 'absent']})
+ assert result.status_code == 200, result.text
+ assert result.json() == {'ok': True, 'deleted': 1}
+ assert db.get_session('parent') is None
+ assert db.get_session('child')['parent_session_id'] is None