Skip to content

The agent that grows with you

fix(gateway): a resume during another viewer's terminal cleanup waits for its refresh

unsupportedpastelsab69d13da05a
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index bf28109c800..802b22ffd90 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -494,7 +494,10 @@ class AuthorityConnection:
ref = resolve_titled_session(self.authority, self.actor, params['title'])
else:
from gateway.session_local_migration import resolve_local_target
+ from gateway.session_policy_refresh import refresh_settled
from hermes_state_local_migration import LEGACY_LOCAL_SOURCES
+ # Another viewer's refresh mid-cleanup has committed a policy it has not published yet.
+ await refresh_settled(self.authority, ref.session_id)
row = self.authority.db.get_session(ref.session_id)
if row and row['source'] in LEGACY_LOCAL_SOURCES:
ref = resolve_local_target(self.authority, self.actor,
diff --git a/gateway/session_policy_refresh.py b/gateway/session_policy_refresh.py
index 3ea925fef45..d5650be7bd6 100644
--- a/gateway/session_policy_refresh.py
+++ b/gateway/session_policy_refresh.py
@@ -152,9 +152,38 @@ def _rebind(authority, session_id, old, policy, fresh, replaced):
return bind_launch_key(authority, session_id, policy, launch_key(authority, old), config_secrets=secrets)
+def _in_flight(authority):
+ found = getattr(authority, '_policy_refreshes', None)
+ if found is None:
+ found = authority._policy_refreshes = {}
+ return found
+
+
+async def refresh_settled(authority, session_id):
+ """Wait out a refresh of *session_id* in flight. Its commit lands before its terminal cleanup (a sandbox
+ teardown can take 10-15 s) and its publication; an attach meanwhile would find the stored policy ahead
+ of the live one, which restore_local_session refuses."""
+ refreshes = _in_flight(authority)
+ while (running := refreshes.get(session_id)) is not None and not running.done():
+ logger.debug('Session %s waits for its policy refresh to publish', session_id)
+ await asyncio.wait({running}) # its outcome is its caller's; a cancelled waiter leaves it running
+
+
async def commit_refresh(authority, ref, *, mcp_only=False):
"""Commit an idle local session's refresh as its next policy generation: True when one was committed,
- False when nothing moved. Raises the store's refusal (``session_busy`` while a turn runs or waits)."""
+ False when nothing moved. Raises the store's refusal (``session_busy`` while a turn runs or waits).
+ One refresh per session at a time, run to its publication even when the caller is cancelled: a second
+ waits for the first, then usually finds nothing moved."""
+ from gateway.session_runtime_workers import track_mutation
+ await refresh_settled(authority, ref.session_id)
+ refreshes = _in_flight(authority)
+ task = refreshes[ref.session_id] = track_mutation(authority, _commit_refresh(authority, ref, mcp_only))
+ task.add_done_callback(lambda done: refreshes.pop(ref.session_id, None) if refreshes.get(ref.session_id)
+ is done else None)
+ return await asyncio.shield(task)
+
+
+async def _commit_refresh(authority, ref, mcp_only):
from gateway.session_runtime_workers import tracked_write
from hermes_state_mutation_prepared import commit_refreshed_policy
prepared = await asyncio.to_thread(_prepare, authority, ref.session_id, mcp_only)
diff --git a/tests/gateway/test_session_resume_config_refresh.py b/tests/gateway/test_session_resume_config_refresh.py
index 7a5afa3ce0c..561228ec2ca 100644
--- a/tests/gateway/test_session_resume_config_refresh.py
+++ b/tests/gateway/test_session_resume_config_refresh.py
@@ -559,6 +559,51 @@ async def test_the_next_command_after_a_terminal_refresh_runs_on_the_new_backend
store.close_all_db_handles()
+async def test_a_second_resume_during_terminal_cleanup_waits_for_the_refresh(tmp_path, monkeypatch, caplog):
+ """A refresh that moves the terminal binding commits, then tears the session's sandbox down (10-15 s on a
+ remote backend) before it publishes. A second viewer attaching meanwhile waits for that refresh instead of
+ failing ``storage_unavailable`` on a stored policy ahead of the live one, and commits nothing itself: one
+ generation, each environment torn down once."""
+ import logging
+ import threading
+ from tools import terminal_tool_lifecycle
+ home = _home(monkeypatch)
+ store, authority = await _owner_authority(home)
+ entered, release, cleaned = threading.Event(), threading.Event(), []
+
+ def held_cleanup(key):
+ cleaned.append(key)
+ entered.set()
+ assert release.wait(10)
+ monkeypatch.setattr(terminal_tool_lifecycle, 'cleanup_vm', held_cleanup)
+ owner, first, second = _connect(authority), _connect(authority), _connect(authority)
+ resumes = []
+ try:
+ sid = (await _call(owner, 'session.create', request_id='t', source='cli', cwd=str(tmp_path)))['session_id']
+ generation = store._db.get_session(sid)['runtime_generation']
+ (home / 'config.yaml').write_text(AFTER)
+ resume = {'id': 1, 'method': 'session.resume', 'params': {'session_id': sid}}
+ resumes.append(asyncio.create_task(first.dispatch(resume)))
+ await async_wait_until(entered.is_set, what='the first refresh to start its terminal cleanup')
+ with caplog.at_level(logging.DEBUG, logger='gateway.session_policy_refresh'):
+ resumes.append(asyncio.create_task(second.dispatch(resume)))
+ await async_wait_until(lambda: resumes[1].done() or 'waits for its policy refresh' in caplog.text,
+ what='the second resume to finish or wait')
+ assert not resumes[1].done(), resumes[1].result()
+ release.set()
+ replies = await asyncio.gather(*resumes)
+ assert [reply['result']['execution_generation'] for reply in replies] == [generation + 1] * 2, replies
+ assert store._db.get_session(sid)['runtime_generation'] == generation + 1
+ assert cleaned and len(cleaned) == len(set(cleaned)), cleaned
+ finally:
+ release.set()
+ await asyncio.gather(*resumes, return_exceptions=True)
+ for connection in (owner, first, second):
+ await connection.close()
+ store.close_all_db_handles()
+
+
def test_a_skipped_resume_refresh_warns_unless_the_session_is_busy(monkeypatch, caplog):
"""A turn running or queued is the expected skip; a revoked credential or an unreadable profile leaves a
silent no-refresh, so it is a WARNING."""