Skip to content

The agent that grows with you

fix(gateway): let API binding replace a history mount; check full delete scope

unsupportedpastelsbc629f94e0c0
diff --git a/gateway/session_api.py b/gateway/session_api.py
index 6efec5f40e3..46b1d99c03f 100644
--- a/gateway/session_api.py
+++ b/gateway/session_api.py
@@ -171,7 +171,8 @@ def bind_api_steps(authority, session_id, *, hosted_dispatch=None, declared_key=
if expected != session_id:
raise RuntimeStoreError('admission_conflict')
storage_source, title = 'bot_room', f'Group: {dispatch.room_id}'
- if session_id in authority.sessions:
+ from gateway.session_history_mount import is_history_mount
+ if session_id in authority.sessions and not is_history_mount(authority.sessions[session_id]):
if (authority.sessions[session_id].source.platform != Platform.API_SERVER
or authority.db.get_session(session_id)['source'] != storage_source):
raise RuntimeStoreError('permission_denied')
@@ -331,5 +332,9 @@ def restore_api_session(authority, session_id):
if not _heal_replacement(conn, session_id, current.session_id):
raise RuntimeStoreError('admission_conflict')
store._entries[entry.session_key] = current if current is not None and current.session_id == target else entry
- authority.sessions.setdefault(session_id, LiveSession(source, entry.session_key))
+ from gateway.session_history_mount import is_history_mount
+ live = authority.sessions.get(session_id)
+ if live is None or is_history_mount(live):
+ # A read-only view opened while the row had no binding gives way to the bound conversation.
+ authority.sessions[session_id] = LiveSession(source, entry.session_key)
return SessionRef(authority.profile_id, session_id)
diff --git a/gateway/session_history_mount.py b/gateway/session_history_mount.py
index 661e822a774..e93e78ecd66 100644
--- a/gateway/session_history_mount.py
+++ b/gateway/session_history_mount.py
@@ -52,12 +52,18 @@ def is_history_mount(live):
def require_history_leaf(authority, sid):
- """A delete takes a row's delegate subtree and detaches its other children, and a history mount
- shows the owner neither, so it deletes only a leaf (as #140692 by @pnpwin did for subagents)."""
+ """A delete takes its whole compression chain, every chain row's delegate subtree, and detaches
+ their other children, and a history mount shows the owner only the chain, so it deletes only a
+ chain nothing else hangs off (as #140692 by @pnpwin did for subagents)."""
if not is_history_mount(authority.sessions[sid]):
return
+ from hermes_state_mutation_guards import delete_targets
+ chain = set(authority.db.get_compression_lineage(sid))
with authority.db._read_ctx() as conn:
- if conn.execute('SELECT 1 FROM sessions WHERE parent_session_id=? LIMIT 1', (sid,)).fetchone():
+ targets = delete_targets(conn, sid)
+ children = conn.execute(f"SELECT id FROM sessions WHERE parent_session_id IN ({','.join('?' * len(targets))})",
+ targets).fetchall()
+ if not chain.issuperset([*targets, *(row[0] for row in children)]):
raise RuntimeStoreError('session_has_children', field='session_id',
detail='this stored conversation has child sessions a delete would take with it')
diff --git a/tests/gateway/test_stored_history_mount.py b/tests/gateway/test_stored_history_mount.py
index bda4565c45a..252444a2e24 100644
--- a/tests/gateway/test_stored_history_mount.py
+++ b/tests/gateway/test_stored_history_mount.py
@@ -115,3 +115,37 @@ async def test_a_stored_history_with_child_sessions_is_not_deleted(tmp_path, mon
with pytest.raises(RuntimeStoreError, match='session_has_children'):
await _mutate(conn, ref, 'delete', 'delete', {})
assert db.get_session('sub-child')['parent_session_id'] == ref.session_id
+
+
+async def test_a_childless_continuation_whose_chain_has_a_delegate_is_not_deleted(tmp_path, monkeypatch):
+ """The delete walks back to the compression parent and took that parent's delegate child too."""
+ conn, root = await _connect(tmp_path, monkeypatch, 'api-1')
+ db = conn.authority.db
+ db._write_sql("UPDATE sessions SET end_reason='compression', ended_at=1 WHERE id=?", (root.session_id,))
+ db.create_session('api-1b', source='api_server', model='m-old', parent_session_id=root.session_id)
+ db.create_session('sub-child', source='subagent', model='m-old')
+ db._write_sql('UPDATE sessions SET session_key=?, chat_id=? WHERE id=?',
+ (ROWS['api-1'][1]['session_key'], 'api-1', 'api-1b'))
+ db._write_sql('UPDATE sessions SET parent_session_id=?, model_config=? WHERE id=?',
+ (root.session_id, json.dumps({'_delegate_from': root.session_id}), 'sub-child'))
+ tip = SessionRef(root.profile_id, 'api-1b')
+ await conn.resume(tip, {})
+ with pytest.raises(RuntimeStoreError, match='session_has_children'):
+ await _mutate(conn, tip, 'delete', 'delete', {})
+ assert db.get_session('sub-child')['parent_session_id'] == root.session_id
+
+
+async def test_an_api_chat_opened_read_only_still_continues_through_the_api(tmp_path, monkeypatch):
+ """Binding the viewed row replaced nothing: the read-only mount had no source to check."""
+ from gateway.config import Platform
+ from gateway.session_api import bind_api_session
+ from gateway.session_history_mount import is_history_mount
+ conn, ref = await _connect(tmp_path, monkeypatch, 'api-1')
+ await conn.resume(ref, {})
+
+ assert bind_api_session(conn.authority, 'api-1', caller_key='agent:main:api_server:dm:api-1') == ref
+
+ live = conn.authority.sessions['api-1']
+ assert live.source.platform == Platform.API_SERVER and not is_history_mount(live) and not live.superseded