The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): drop a closed session's delegation refusal with its live state
unsupportedpastelsadb760a8f5d6
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.pyindex e81db1797c4..37542e2c820 100644--- a/gateway/session_mutations.py+++ b/gateway/session_mutations.py@@ -305,7 +305,10 @@ def retire_live_sessions(authority, session_ids):store.retire_runtime_sessions(session_ids)from gateway.session_policy import release_launch_secretsrelease_launch_secrets(authority, session_ids)+ from tools.async_delegation import allow_for_sessionfor sid in session_ids:+ # A closed session's refusal of new delegations (session_viewer_close) goes with its live state.+ allow_for_session((authority.profile_id, sid))candidate = authority.sessions.pop(sid, None)if candidate is not None:evict = getattr(authority.runner, '_evict_cached_agent', None)diff --git a/tests/gateway/test_session_end_delegations.py b/tests/gateway/test_session_end_delegations.pyindex 5ae70169a7f..7f2323ea35a 100644--- a/tests/gateway/test_session_end_delegations.py+++ b/tests/gateway/test_session_end_delegations.py@@ -167,6 +167,29 @@ async def test_delegation_started_after_the_close_is_refused_until_a_viewer_retuassert _dispatch(route, 'chat')['status'] == 'dispatched', 'a viewer that came back keeps its work'+async def test_a_closed_sessions_refusal_goes_with_its_live_state(tmp_path, monkeypatch):+ """A session closed and never resumed keeps refusing its still-running turn's dispatches until+ the owner retires its live state (delete, prune); then the refusal goes too, so closed sessions+ don't accumulate refusals. Another closed session keeps its own."""+ from gateway.session_mutations import retire_live_sessions+ db, authority = await _owner(tmp_path, monkeypatch)+ viewer, subscription = await _open(db, authority, tmp_path, 'chat')+ other, other_subscription = await _open(db, authority, tmp_path, 'other')+ route, other_route = authority.sessions['chat'].route, authority.sessions['other'].route+ await _call(viewer, 'session.detach', session_id='chat', subscription_id=subscription, end_reason='cli_close')+ await _call(other, 'session.detach', session_id='other', subscription_id=other_subscription,+ end_reason='new_session')+ assert _dispatch(route, 'chat')['status'] == 'rejected', 'its turn may still be running'++ retire_live_sessions(authority, ['chat'])++ assert (authority.profile_id, 'chat') not in delegation._refused, 'retired with its live state'+ assert _dispatch(route, 'chat')['status'] == 'dispatched'+ assert _dispatch(other_route, 'other')['status'] == 'rejected', 'other closed sessions keep theirs'+ assert list(delegation._refused) == [(authority.profile_id, 'other')]++# --- completions for a local session with no viewer --------------------------------------------async def _local(tmp_path, monkeypatch):diff --git a/tools/async_delegation.py b/tools/async_delegation.pyindex ccb6c285642..6caf2188f7b 100644--- a/tools/async_delegation.py+++ b/tools/async_delegation.py@@ -38,8 +38,10 @@ _executor_max_workers: int = 0_records_lock = threading.Lock()# delegation_id -> record dict; kept for the run plus a short completed tail._records: dict[str, dict[str, Any]] = {}-# A closed session's token -> the (field, value) selectors a new dispatch is refused for (``refuse_for_session``).+# A closed session's token -> the (field, value) selectors a new dispatch is refused for (``refuse_for_session``),+# and each selector -> the tokens refusing it, so a dispatch checks its own selectors, not every fence._refused: dict[Any, frozenset] = {}+_refused_by: dict[tuple, set] = {}_FENCED_FIELDS = ("session_key", "parent_session_id")_DEFAULT_MAX_ASYNC_CHILDREN = 3@@ -845,7 +847,7 @@ def _dispatch_admitted(# Stale-monitor bookkeeping (see _stale_monitor_loop)."_progress_token": None, "_progress_ts": dispatched_at, "_interrupted_at": None}with _records_lock:- if any((field, record[field]) in fence for fence in _refused.values() for field in _FENCED_FIELDS):+ if any((field, record[field]) in _refused_by for field in _FENCED_FIELDS):return {"status": "rejected", "error": "This session was closed (exit or /new): no new background work."}active_slots = {r.get("slot_key") or r["delegation_id"] for r in _records.values() if r.get("status") in _ACTIVE_STATES}if record["slot_key"] not in active_slots and len(active_slots) >= max_async_children:@@ -1293,12 +1295,25 @@ def refuse_for_session(token: Any, *, session_key: str = "", parent_session_ids=fence = {("session_key", session_key)} if session_key else set()fence.update(("parent_session_id", parent) for parent in parent_session_ids if parent)with _records_lock:+ _unfence(token)_refused[token] = frozenset(fence)+ for selector in fence:+ _refused_by.setdefault(selector, set()).add(token)def allow_for_session(token: Any) -> None:+ """Lift ONE session's refusal: a viewer attached again, or the owner retired its live state."""with _records_lock:- _refused.pop(token, None)+ _unfence(token)+++def _unfence(token: Any) -> None:+ """Drop *token*'s refusal; caller holds ``_records_lock``."""+ for selector in _refused.pop(token, ()):+ tokens = _refused_by[selector]+ tokens.discard(token)+ if not tokens:+ del _refused_by[selector]def _reset_for_tests() -> None:@@ -1317,6 +1332,7 @@ def _reset_for_tests() -> None:with _records_lock:_records.clear()_refused.clear()+ _refused_by.clear()with _orphan_lock:_offered.clear()_startup_replayed.clear()