The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): let a pruned secondary's shared routing fence age out by itself
unsupportedpastels2436726726ee
diff --git a/hermes_state_gateway.py b/hermes_state_gateway.pyindex c8f2f7a017a..bee90b994fb 100644--- a/hermes_state_gateway.py+++ b/hermes_state_gateway.py@@ -301,7 +301,7 @@ class SessionGatewayMixin:from hermes_state_mutation_retirement import route_namespace, route_retired_sqlself._write_sql(f"""INSERT INTO gateway_routing (scope, session_key, entry_json, updated_at)- SELECT ?1, ?2, ?3, ?4 WHERE NOT {route_retired_sql('?3', '?5')}+ SELECT ?1, ?2, ?3, ?4 WHERE NOT {route_retired_sql('?3', '?5', '?4')}ON CONFLICT(scope, session_key) DO UPDATE SETentry_json = excluded.entry_json,updated_at = excluded.updated_at""",@@ -320,7 +320,7 @@ class SessionGatewayMixin:if rows:conn.executemany("INSERT INTO gateway_routing (scope, session_key, entry_json, updated_at) "- f"SELECT ?1, ?2, ?3, ?4 WHERE NOT {route_retired_sql('?3', '?5')}",+ f"SELECT ?1, ?2, ?3, ?4 WHERE NOT {route_retired_sql('?3', '?5', '?4')}",rows)kept = {r[0] for r in conn.execute("SELECT session_key FROM gateway_routing WHERE scope = ?", (scope,))}return {row[1] for row in rows} - keptdiff --git a/hermes_state_mutation_retirement.py b/hermes_state_mutation_retirement.pyindex 9f425ca2086..98a2648984c 100644--- a/hermes_state_mutation_retirement.py+++ b/hermes_state_mutation_retirement.py@@ -321,25 +321,30 @@ def route_fence_key(namespace, session_id):return f'{ROUTE_FENCE_PREFIX}{namespace}:{session_id}'-def route_retired_sql(entry, namespace):- """SQL true when a routing save must skip an entry (SQL expressions *entry*: its JSON, and- *namespace*: its key's ``route_namespace``), checked only against the profile the route belongs- to: this store's own marker for a launch (``main``) route, that profile's fence for a- secondary's. A launch-keyed route to an id this store holds no session of can only name- another profile's session, so a secondary's fence covers it too (``fence_shared_routes``).- An unscoped marker (no ``own``: an earlier release's, written for either) still fences every route."""+def route_retired_sql(entry, namespace, now):+ """SQL true when a routing save must skip an entry (SQL expressions *entry*: its JSON,+ *namespace*: its key's ``route_namespace``, and *now*: the save's time), checked only against+ the profile the route belongs to: this store's own marker for a launch (``main``) route, that+ profile's fence for a secondary's. A launch-keyed route to an id this store holds no session of+ can only name another profile's session, so a secondary's fence covers it too+ (``fence_shared_routes``). A sweep's fence stops fencing at the horizon by itself: only the+ owner's own store sweeps the owner's marker, and nothing guarantees the launch profile ever+ sweeps this one. An unscoped marker (no ``own``: an earlier release's, written for either)+ still fences every route."""sid = f"json_extract({entry}, '$.session_id')"return (f"(EXISTS (SELECT 1 FROM state_meta m WHERE m.key = '{RETIRED_PREFIX}' || {sid} AND "f"({namespace} = 'main' OR NOT (json_valid(m.value) AND json_extract(m.value, '$.own') IS NOT NULL))) "f"OR EXISTS (SELECT 1 FROM state_meta f WHERE f.key = '{ROUTE_FENCE_PREFIX}' || {namespace} || ':' || {sid} "+ f"AND NOT (json_valid(f.value) AND json_extract(f.value, '$.expires') "+ f"AND json_extract(f.value, '$.retired_at') < {now} - {RETRY_HORIZON_S}) "f"AND ({namespace} != 'main' OR NOT EXISTS (SELECT 1 FROM sessions s WHERE s.id = {sid}))))")def route_retired(db, session_key, entry_json):"""A routing save (or the legacy sessions.json import) must skip this entry."""with db._read_ctx() as conn:- return bool(conn.execute(f"SELECT {route_retired_sql('?1', '?2')}",- (entry_json, route_namespace(session_key))).fetchone()[0])+ return bool(conn.execute(f"SELECT {route_retired_sql('?1', '?2', '?3')}",+ (entry_json, route_namespace(session_key), time.time())).fetchone()[0])def expiring_retirements(db, session_ids):@@ -356,7 +361,9 @@ def fence_shared_routes(conn, namespace, session_ids, *, expiring=()):profile whose routing keys use *namespace*, and drop them. The fence is keyed by (profile, id)and copies the owner's marker: permanent for a delete, aging out with an *expiring* sweep's.Unless this store holds a session of that id, the launch (``main``) namespace is fenced too: a- launch-keyed route to it names the retired session."""+ launch-keyed route to it names the retired session. The sweep fences that aged out here are+ reclaimed in the same write, so the owner's prunes bound them without the launch profile's sweep."""+ _reclaim_expired(conn, ROUTE_FENCE_PREFIX, time.time() - RETRY_HORIZON_S)expiring, owned = set(expiring), {}for sid in session_ids:names = {namespace}@@ -375,6 +382,12 @@ RETRY_HORIZON_S = 7 * 86400 # exact-retry horizon: a retry within it gets the b_EXPIRED = "json_valid(value) AND json_extract(value, '$.retired_at') < ?"+def _reclaim_expired(conn, prefix, cutoff):+ """Drop the sweep (``expires``) markers under *prefix* retired before *cutoff*."""+ conn.execute(f"DELETE FROM state_meta WHERE key GLOB ? AND {_EXPIRED} AND json_extract(value, '$.expires')",+ (prefix + '*', cutoff))++def prune_retired_tombstones(conn, older_than=RETRY_HORIZON_S):"""Reclaim deletion tombstones retired more than *older_than* seconds ago: the terminal admissionwith its identity pointer and compacted result, terminal workers and a sweep's (``expires``)@@ -396,5 +409,4 @@ def prune_retired_tombstones(conn, older_than=RETRY_HORIZON_S):identity_key(row['principal_id'], row['target_session_id'], row['request_id'])))conn.execute(f'DELETE FROM state_meta WHERE key GLOB ? AND {_EXPIRED}', (WORKER_PREFIX + '*', cutoff))for prefix in (RETIRED_PREFIX, ROUTE_FENCE_PREFIX):- conn.execute(f"DELETE FROM state_meta WHERE key GLOB ? AND {_EXPIRED} AND json_extract(value, '$.expires')",- (prefix + '*', cutoff))+ _reclaim_expired(conn, prefix, cutoff)diff --git a/tests/gateway/test_secondary_route_fence_scope.py b/tests/gateway/test_secondary_route_fence_scope.pyindex fd85e7536bf..3d49e17e38e 100644--- a/tests/gateway/test_secondary_route_fence_scope.py+++ b/tests/gateway/test_secondary_route_fence_scope.py@@ -246,6 +246,64 @@ async def test_a_delayed_snapshot_cannot_restore_a_pruned_route_once_its_fence_aassert store._entries[key].session_id == sid+def _age_retirements(*dbs, days=8):+ """Move every retirement marker and routing fence *days* into the past: the wall clock passing+ the horizon, with no sweep run anywhere."""+ from hermes_state_mutation_retirement import RETIRED_PREFIX, ROUTE_FENCE_PREFIX+ for db in dbs:+ db._execute_write(lambda conn: conn.execute(+ "UPDATE state_meta SET value=json_set(value, '$.retired_at', json_extract(value, '$.retired_at') - ?) "+ "WHERE (key GLOB ? OR key GLOB ?) AND json_valid(value)",+ (days * 86400, RETIRED_PREFIX + '*', ROUTE_FENCE_PREFIX + '*')))+++async def test_a_pruned_id_routes_again_after_the_owner_alone_sweeps_past_the_horizon(tmp_path, monkeypatch):+ """Only the owner's own housekeeping runs (the launch profile's auto-prune is off by default):+ once the horizon passes, the shared fence of alpha's prune no longer refuses the route of a+ session alpha recreates with that id, though nothing swept the launch database."""+ async with _served(tmp_path, monkeypatch) as served:+ store = served.store+ key, sid, _stale = await _pruned_alpha_route(served, tmp_path)+ _age_retirements(served.alpha.db, served.launch.db)+ served.alpha.db.prune_sessions(older_than_days=90) # alpha's auto-prune pass: its own db only+ assert _conflict(served.alpha.db, sid) is None++ served.alpha.db.create_session(sid, source='telegram')+ store._entries[key] = _entry(key, sid)+ with store._lock:+ store._save()+ assert key in _durable(store), 'an expired shared fence refused the recreated route'+ assert key in _mirror(store), 'an expired shared fence kept the recreated route out of sessions.json'+ _restart(store)+ assert store._entries[key].session_id == sid+++async def test_the_owners_next_prune_reclaims_its_expired_shared_fences(tmp_path, monkeypatch):+ """An owner's prune that fences new ids in the shared index also reclaims the fences there that+ aged out, so the index does not grow with every prune while the launch profile never sweeps.+ A delete's fence stays."""+ from gateway.run import _profile_runtime_scope+ from gateway.session_local import create_local_session+ async with _served(tmp_path, monkeypatch) as served:+ _key, sid, _stale = await _pruned_alpha_route(served, tmp_path)+ with _profile_runtime_scope(served.home, {}):+ kept = create_local_session(served.alpha, served.actor, {+ 'request_id': 'k', 'source': 'gui', 'cwd': str(tmp_path), 'model': 'frozen', 'toolsets': []})+ await _delete(served, kept)+ _age_retirements(served.alpha.db, served.launch.db)+ with _profile_runtime_scope(served.home, {}):+ later = create_local_session(served.alpha, served.actor, {+ 'request_id': 'l', 'source': 'gui', 'cwd': str(tmp_path), 'model': 'frozen', 'toolsets': []})+ await _prune(served, later)+ fence = 'gateway.retired_route.v1.{}:{}'.format+ assert served.launch.db.get_meta(fence('alpha', sid)) is None, 'an expired shared fence was never reclaimed'+ assert served.launch.db.get_meta(fence('main', sid)) is None+ assert served.launch.db.get_meta(fence('alpha', later.session_id)) is not None+ assert served.launch.db.get_meta(fence('alpha', kept.session_id)) is not None, "a delete's fence aged out"++@pytest.mark.asyncioasync def test_a_start_within_the_horizon_strips_a_pruned_route_from_an_older_mirror(tmp_path, monkeypatch):"""A sessions.json an earlier release wrote unfiltered (or one left by a crash before the next