Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(harness): preserve Claude turn ownership on cancellation (#1823)

Call White1aae3e0e02c1
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 1ef86e6f1..fc1f6267a 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -449,6 +449,7 @@ class SessionHandler(BaseHandler):
# when the current turn resolves to a different channel. Retire the
# cached generation's process credential before recreating it.
retire_model_hub_scope=True,
+ reason="cached_process_terminated",
)
return True
@@ -479,6 +480,7 @@ class SessionHandler(BaseHandler):
await self._cleanup_session_locked(
composite_key,
retire_model_hub_scope=model_hub_launch.channel == "direct",
+ reason="model_hub_channel_changed",
)
return None
@@ -499,6 +501,7 @@ class SessionHandler(BaseHandler):
await self._cleanup_session_locked(
composite_key,
retire_model_hub_scope=model_hub_launch.channel == "direct",
+ reason="system_prompt_changed",
)
return None
@@ -511,6 +514,7 @@ class SessionHandler(BaseHandler):
await self._cleanup_session_locked(
composite_key,
retire_model_hub_scope=model_hub_launch.channel == "direct",
+ reason="caller_env_changed",
)
return None
managed_skills_env = managed_skill_environment(
@@ -537,6 +541,7 @@ class SessionHandler(BaseHandler):
await self._cleanup_session_locked(
composite_key,
retire_model_hub_scope=model_hub_launch.channel == "direct",
+ reason="git_path_changed",
)
return None
@@ -592,6 +597,7 @@ class SessionHandler(BaseHandler):
await self._cleanup_session_locked(
composite_key,
retire_model_hub_scope=model_hub_launch.channel == "direct",
+ reason="subagent_model_hub_channel_changed",
)
return None
self.ensure_agent_session_id(
@@ -620,6 +626,7 @@ class SessionHandler(BaseHandler):
await self._cleanup_session_locked(
composite_key,
retire_model_hub_scope=model_hub_launch.channel == "direct",
+ reason="subagent_system_prompt_changed",
)
return None
caller_env = self._caller_env_for_context(context)
@@ -631,6 +638,7 @@ class SessionHandler(BaseHandler):
await self._cleanup_session_locked(
composite_key,
retire_model_hub_scope=model_hub_launch.channel == "direct",
+ reason="subagent_caller_env_changed",
)
return None
managed_skills_env = managed_skill_environment(
@@ -657,6 +665,7 @@ class SessionHandler(BaseHandler):
await self._cleanup_session_locked(
composite_key,
retire_model_hub_scope=model_hub_launch.channel == "direct",
+ reason="subagent_git_path_changed",
)
return None
if desired_model:
@@ -2014,6 +2023,7 @@ class SessionHandler(BaseHandler):
retire_model_hub_scope: bool = True,
activation_retired: bool = False,
expected_client=None,
+ reason: str = "unspecified",
):
"""Clean up one Claude generation under the same lock used by creation.
@@ -2030,6 +2040,7 @@ class SessionHandler(BaseHandler):
retire_model_hub_scope=retire_model_hub_scope,
activation_retired=activation_retired,
expected_client=expected_client,
+ reason=reason,
)
async def _cleanup_session_locked(
@@ -2040,6 +2051,7 @@ class SessionHandler(BaseHandler):
retire_model_hub_scope: bool = True,
activation_retired: bool = False,
expected_client=None,
+ reason: str = "unspecified",
):
"""Clean up a specific session by composite key"""
client = self.claude_sessions.get(composite_key)
@@ -2048,8 +2060,9 @@ class SessionHandler(BaseHandler):
# by a client that owns the key now. Containing a stale teardown
# must not become a second teardown.
logger.info(
- "Skipping Claude cleanup for session %s: the named generation no longer owns the key",
+ "Skipping Claude cleanup for session %s: reason=%s named generation no longer owns the key",
composite_key,
+ reason,
)
return
activation_retired = activation_retired or bool(
@@ -2062,6 +2075,22 @@ class SessionHandler(BaseHandler):
lambda: self.claude_sessions.get(composite_key) is client,
):
return
+ receiver_task = self.receiver_tasks.get(composite_key)
+ if client is not None or receiver_task is not None:
+ identity = self._claude_runtime_activation_identity(client)
+ logger.info(
+ "Retiring Claude runtime session=%s reason=%s busy=%s "
+ "runtime_generation=%s client_identity=%s receiver_identity=%s "
+ "receiver_done=%s pid=%s",
+ composite_key,
+ reason,
+ composite_key in self.active_sessions,
+ identity.generation if identity is not None else None,
+ id(client) if client is not None else None,
+ id(receiver_task) if receiver_task is not None else None,
+ receiver_task.done() if receiver_task is not None else None,
+ get_claude_client_pid(client),
+ )
receiver_task = self.receiver_tasks.pop(composite_key, None)
client = self.claude_sessions.pop(composite_key, None)
if client is not None and retire_model_hub_scope:
@@ -2084,9 +2113,18 @@ class SessionHandler(BaseHandler):
# retrying cancellation on every event-loop tick.
if client is not None:
if cleanup_from_receiver:
- self._disconnect_client_after_receiver(client, composite_key, receiver_task)
+ self._disconnect_client_after_receiver(
+ client,
+ composite_key,
+ receiver_task,
+ reason=reason,
+ )
else:
- await self._disconnect_client(client, composite_key)
+ await self._disconnect_client(
+ client,
+ composite_key,
+ reason=reason,
+ )
finally:
if not cleanup_from_receiver:
await self._stop_receiver_task(receiver_task, composite_key)
@@ -2144,14 +2182,32 @@ class SessionHandler(BaseHandler):
logger=logger,
)
- async def _disconnect_client(self, client, composite_key: str) -> None:
+ async def _disconnect_client(
+ self,
+ client,
+ composite_key: str,
+ *,
+ reason: str,
+ ) -> None:
try:
await client.disconnect()
except Exception as e:
logger.error(f"Error disconnecting Claude session {composite_key}: {e}")
- logger.info(f"Cleaned up Claude session {composite_key}")
+ logger.info(
+ "Cleaned up Claude session %s reason=%s client_identity=%s",
+ composite_key,
+ reason,
+ id(client),
+ )
- def _disconnect_client_after_receiver(self, client, composite_key: str, receiver_task) -> None:
+ def _disconnect_client_after_receiver(
+ self,
+ client,
+ composite_key: str,
+ receiver_task,
+ *,
+ reason: str,
+ ) -> None:
async def _run() -> None:
if receiver_task is not None:
try:
@@ -2160,7 +2216,7 @@ class SessionHandler(BaseHandler):
pass
except Exception as e:
logger.warning("Claude receiver ended with error before deferred disconnect: %s", e)
- await self._disconnect_client(client, composite_key)
+ await self._disconnect_client(client, composite_key, reason=reason)
asyncio.create_task(_run())
@@ -2570,6 +2626,7 @@ class SessionHandler(BaseHandler):
await self._cleanup_session_locked(
composite_key,
activation_retired=True,
+ reason="stuck_active_eviction",
)
else:
logger.info(
@@ -2580,6 +2637,7 @@ class SessionHandler(BaseHandler):
await self._cleanup_session_locked(
composite_key,
activation_retired=True,
+ reason="idle_eviction",
)
evicted += 1
@@ -2695,6 +2753,7 @@ class SessionHandler(BaseHandler):
# This failure may belong to a generation a replacement has
# already taken over from; retire that exact client or nothing.
expected_client=client,
+ reason="intentional_teardown_signal",
)
return True
if returncode is not None:
@@ -2715,6 +2774,7 @@ class SessionHandler(BaseHandler):
composite_key,
current_receiver_task=asyncio.current_task(),
expected_client=client,
+ reason="process_terminated",
)
await self._get_im_client(context).send_message(
context,
@@ -2725,7 +2785,11 @@ class SessionHandler(BaseHandler):
return False
if "read() called while another coroutine" in error_msg:
logger.error(f"Session {composite_key} has concurrent read error - cleaning up")
- await self.cleanup_session(composite_key, current_receiver_task=asyncio.current_task())
+ await self.cleanup_session(
+ composite_key,
+ current_receiver_task=asyncio.current_task(),
+ reason="concurrent_read",
+ )
# Notify user and suggest retry
await self._get_im_client(context).send_message(
@@ -2741,7 +2805,11 @@ class SessionHandler(BaseHandler):
or is_claude_sdk_buffer_error(error)
):
logger.error(f"Session {composite_key} is broken - cleaning up")
- await self.cleanup_session(composite_key, current_receiver_task=asyncio.current_task())
+ await self.cleanup_session(
+ composite_key,
+ current_receiver_task=asyncio.current_task(),
+ reason="connection_broken",
+ )
# Notify user
await self._get_im_client(context).send_message(
diff --git a/core/internal_server.py b/core/internal_server.py
index 3d960a57d..18c8c4dd7 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -532,20 +532,8 @@ def create_app(
"author_name": delivery_request.author_name,
}
)
- try:
- result = await manager.deliver(
- delivery_request,
- context=context,
- )
- except Exception:
- if not delivery_owner_transferred:
- raise
- logger.exception(
- "Delivery admission deferred to recovery after Agent Run ownership "
- "transfer: run=%s delivery=%s",
- execution_id,
- delivery_id,
- )
+
+ def _defer_transferred_delivery() -> TurnSubmissionResult:
delivery_status = "reserved"
try:
with run_update_event_transaction(get_cached_sqlite_engine()) as conn:
@@ -584,6 +572,38 @@ def create_app(
delivery_status=delivery_status,
delivery_owner_transferred=True,
)
+
+ try:
+ result = await manager.deliver(
+ delivery_request,
+ context=context,
+ )
+ except asyncio.CancelledError:
+ if not delivery_owner_transferred:
+ raise
+ # Once the Run points at this Delivery, the executor wrapper is no
+ # longer its lifecycle owner. In particular, cancellation can race
+ # a shielded native P1 write: the adapter may have accepted the
+ # steer even though admission has not projected that receipt yet.
+ # Leave the durable owner recoverable instead of letting the wrapper
+ # settle the Run before the native turn reaches terminal.
+ logger.warning(
+ "Delivery admission canceled after Agent Run ownership transfer; "
+ "deferring to recovery: run=%s delivery=%s",
+ execution_id,
+ delivery_id,
+ )
+ return _defer_transferred_delivery()
+ except Exception:
+ if not delivery_owner_transferred:
+ raise
+ logger.exception(
+ "Delivery admission deferred to recovery after Agent Run ownership "
+ "transfer: run=%s delivery=%s",
+ execution_id,
+ delivery_id,
+ )
+ return _defer_transferred_delivery()
delivery_state = str(result.state)
route = "enqueued" if delivery_state in {
"queued",
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index a486c26dc..a1f9ba685 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -5189,8 +5189,21 @@ class ScheduledTaskService:
return True
if runtime.current_process_owns_service_instance():
return True
- logger.error("Scheduled task service stopping because this process no longer owns the service lock")
- self._begin_stop()
+ logger.error(
+ "Scheduled task service lost the service lock; requesting controller shutdown"
+ )
+ self._running = False
+ request_shutdown = getattr(self.controller, "request_shutdown", None)
+ if callable(request_shutdown):
+ # Lease loss is process-wide. A service-local teardown would settle
+ # durable Turns and cancel their executor wrappers while backend
+ # receivers remain alive, splitting Run/Turn ownership from the
+ # native runtime. Let the controller stop all runtime owners as one
+ # generation instead.
+ request_shutdown("service lease lost")
+ else:
+ # Preserve standalone/lightweight controller behavior.
+ self._begin_stop()
return False
async def stop(self) -> None:
diff --git a/core/services/running_agents.py b/core/services/running_agents.py
index 8a38b8121..f8aa8601b 100644
--- a/core/services/running_agents.py
+++ b/core/services/running_agents.py
@@ -624,7 +624,7 @@ async def _end_claude(controller: "Controller", composite_key: Optional[str], ba
await client.interrupt()
except Exception: # noqa: BLE001
logger.debug("end: claude interrupt failed for %s", ck, exc_info=True)
- await session_handler.cleanup_session(ck)
+ await session_handler.cleanup_session(ck, reason="running_agent_end")
except Exception as exc: # noqa: BLE001
logger.warning("end: claude cleanup_session failed for %s: %s", ck, exc)
return {"ok": False, "error": "cleanup_failed", "detail": str(exc)}
diff --git a/docs/plans/issue-1810-claude-run-lifecycle.md b/docs/plans/issue-1810-claude-run-lifecycle.md
new file mode 100644
index 000000000..fce51ee66
--- /dev/null
+++ b/docs/plans/issue-1810-claude-run-lifecycle.md
@@ -0,0 +1,90 @@
+# Issue 1810: Claude Agent Run Lifecycle
+
+## Background
+
+Issue #1810 reports a Claude SDK client teardown during an active turn. The
+reported cache-invalidation asymmetry exists, but the incident timeline first
+shows a different invariant violation: an Agent Run became terminal while its
+native Claude turn and receiver continued producing output. The later
+caller-environment invalidation happened after that output completed and does
+not establish the teardown as the initiating cause.
+
+The historical session (`sesanmf2yy8nc`) and runs (`d83ef3101a01` and
+`ddb91779cbda`) are no longer present in the local Avibe state exposed by the
+CLI, so the investigation must rebuild the state transition in test-owned
+storage.
+
+## Goal
+
+Find and fix the lifecycle boundaries that can terminalize a P1 Agent Run or
+its durable Turn while the accepted Claude steer is still owned by the native
+receiver. Preserve one Claude client/receiver generation, prevent synthetic
+agent-initiated ownership, and keep the primary result and steered successor
+attached to their durable turn.
+
+## Investigation
+
+1. Trace Agent Run creation and its binding to Delivery and durable Turn rows.
+2. Trace P1 admission, native input receipt, durable materialization, and the
+ exact event that terminalizes the Run.
+3. Trace Claude primary-phase retirement, receiver generation, native EOF, and
+ agent-initiated fallback ownership.
+4. Enumerate cancellation and teardown paths that can leave the native receiver
+ live after local ownership is released.
+5. Reproduce the earliest invariant violation before changing production code.
+
+## Required Invariants
+
+- An accepted P1 Agent Run remains non-terminal until its owning durable turn
+ reaches native terminal evidence.
+- The accepted steer does not recreate or disconnect the Claude client or
+ receiver generation.
+- Pre-steer primary output and post-steer output remain owned by their respective
+ durable turns; no synthetic agent-initiated turn is opened.
+- Stop, P3 delivery, backend refresh, and service-restart recovery keep their
+ existing terminal semantics.
+- Every Claude teardown records a reason, busy state, and exact runtime
+ generation.
+
+## Causal Model
+
+Two independently reproducible cancellation boundaries could split durable and
+native ownership:
+
+1. The internal Session gate commits `agent_runs.delivery_id` before awaiting
+ delivery. Claude steering shields the native write so it can reconcile an
+ accepted receipt before propagating caller cancellation. The gate caught
+ ordinary exceptions after ownership transfer but not `CancelledError`, so
+ the canceled executor wrapper could settle the Run before Delivery recovery
+ or the native terminal result.
+2. Scheduled-service lease loss called the service-local stop path. That path
+ canceled executor wrappers and released active durable Turns, but did not
+ stop backend clients or receiver tasks. Lease loss is process-wide and was
+ already owned by the controller runtime supervisor; the second local owner
+ could therefore terminalize the Run/Turn while Claude kept producing.
+
+The caller-environment cache invalidation observed later in the incident is a
+consequence after the first result, not the initiating transition. No test
+evidence justifies adding an idle wait to cache invalidation, and doing so under
+the generation lock could deadlock receiver cleanup.
+
+## Fix
+
+- After a Run has transferred to Delivery, the internal gate converts caller
+ cancellation into the existing durable recovery result. Pre-transfer
+ cancellation still propagates normally.
+- Scheduled-service lease loss stops local admission and asks the controller to
+ shut down the complete runtime generation. Explicit service stop retains its
+ existing restart settlement behavior. Lightweight controllers without a
+ shutdown owner retain the previous local fallback.
+- Claude teardown now emits stable reason, busy, runtime generation,
+ client/receiver identity, receiver state, and PID evidence. Cache retirement
+ timing is otherwise unchanged.
+
+## Delivery
+
+- Add a deterministic failing regression before the fix.
+- Implement the smallest complete lifecycle correction at the authoritative
+ owner; harden cache retirement only if the reproducer proves it is needed.
+- Run focused and adjacent tests plus Ruff, then complete exact-head review and
+ CI before handoff.
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 54255984c..09a117b80 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -283,6 +283,7 @@ class ClaudeAgent(BaseAgent):
await self._cleanup_runtime_session(
runtime_session_key,
preserve_pending_request_state=True,
+ reason="query_auth_failure",
)
if not handled:
# Third and last emit site that can be holding a claimed
@@ -477,7 +478,10 @@ class ClaudeAgent(BaseAgent):
sessions_to_clear.append(composite_id)
for composite_id in sessions_to_clear:
- await self._cleanup_runtime_session(composite_id)
+ await self._cleanup_runtime_session(
+ composite_id,
+ reason="session_clear",
+ )
# Legacy session manager cleanup (best-effort)
await self.session_manager.clear_session(session_key)
@@ -586,7 +590,10 @@ class ClaudeAgent(BaseAgent):
session_ids = self.runtime_turn_keys()
for composite_id in session_ids:
- await self._cleanup_runtime_session(composite_id)
+ await self._cleanup_runtime_session(
+ composite_id,
+ reason="auth_refresh",
+ )
logger.info("Refreshed Claude auth state across %d runtime session(s)", len(session_ids))
@@ -611,7 +618,10 @@ class ClaudeAgent(BaseAgent):
if composite_key not in self.claude_sessions and composite_key not in self.receiver_tasks:
return
- await self._cleanup_runtime_session(composite_key)
+ await self._cleanup_runtime_session(
+ composite_key,
+ reason="resume_rebind",
+ )
logger.info("Prepared Claude runtime for resumed session %s", composite_key)
async def _disconnect_client(self, client, composite_key: str) -> None:
@@ -689,6 +699,7 @@ class ClaudeAgent(BaseAgent):
preserve_pending_request_state: bool = False,
runtime_lock_held: bool = False,
activation_retired: bool = False,
+ reason: str = "claude_agent_cleanup",
) -> None:
"""Drop Claude runtime state without canceling the current receiver task."""
@@ -700,6 +711,7 @@ class ClaudeAgent(BaseAgent):
preserve_pending_request_state=preserve_pending_request_state,
runtime_lock_held=runtime_lock_held,
activation_retired=activation_retired,
+ reason=reason,
)
finally:
self._retire_steering_state(composite_key)
@@ -712,6 +724,7 @@ class ClaudeAgent(BaseAgent):
preserve_pending_request_state: bool = False,
runtime_lock_held: bool = False,
activation_retired: bool = False,
+ reason: str = "claude_agent_cleanup",
) -> None:
self._last_assistant_text.pop(composite_key, None)
@@ -734,6 +747,7 @@ class ClaudeAgent(BaseAgent):
composite_key,
current_receiver_task=current_receiver_task,
activation_retired=activation_retired,
+ reason=reason,
)
return
receiver_task = self.receiver_tasks.pop(composite_key, None)
@@ -787,6 +801,7 @@ class ClaudeAgent(BaseAgent):
preserve_pending_request_state=True,
runtime_lock_held=runtime_lock_held,
activation_retired=activation_retired,
+ reason="stuck_active_eviction",
)
except Exception:
if context is not None:
@@ -1283,7 +1298,10 @@ class ClaudeAgent(BaseAgent):
self._suppress_receiver_runtime_release.add(composite_key)
try:
self._mark_session_idle_if_no_pending_requests(composite_key)
- await self._cleanup_runtime_session(composite_key)
+ await self._cleanup_runtime_session(
+ composite_key,
+ reason="user_stop",
+ )
except Exception as err:
logger.error("Failed to clean up stopped Claude session %s: %s", composite_key, err, exc_info=True)
self._release_service_runtime_turn(request.context)
@@ -1331,7 +1349,10 @@ class ClaudeAgent(BaseAgent):
composite_key,
exc_info=True,
)
- await self._cleanup_runtime_session(composite_key)
+ await self._cleanup_runtime_session(
+ composite_key,
+ reason="running_agent_end",
+ )
return True
async def _receive_messages(
@@ -1411,6 +1432,7 @@ class ClaudeAgent(BaseAgent):
composite_key,
current_receiver_task=asyncio.current_task(),
preserve_pending_request_state=True,
+ reason="ambiguous_primary_receiver_failure",
)
if settling_ambiguous_assistant_text:
self._last_assistant_text[composite_key] = (
@@ -2063,6 +2085,7 @@ class ClaudeAgent(BaseAgent):
composite_key,
current_receiver_task=asyncio.current_task(),
preserve_pending_request_state=True,
+ reason="receiver_eof",
)
return
await self._handle_receiver_eof(
@@ -2196,6 +2219,7 @@ class ClaudeAgent(BaseAgent):
composite_key,
current_receiver_task=asyncio.current_task(),
preserve_pending_request_state=True,
+ reason="receiver_auth_failure",
)
if pending_request is not None:
await self._remove_ack_reaction(pending_request)
@@ -2257,6 +2281,7 @@ class ClaudeAgent(BaseAgent):
composite_key,
current_receiver_task=asyncio.current_task(),
preserve_pending_request_state=True,
+ reason="receiver_eof_without_result",
)
try:
await self._emit_no_result_settlement(
@@ -2310,6 +2335,7 @@ class ClaudeAgent(BaseAgent):
composite_key,
current_receiver_task=asyncio.current_task(),
preserve_pending_request_state=True,
+ reason="receiver_error_auth_failure",
)
if pending_request is not None:
await self._remove_ack_reaction(pending_request)
@@ -2438,6 +2464,7 @@ class ClaudeAgent(BaseAgent):
composite_key,
current_receiver_task=asyncio.current_task(),
preserve_pending_request_state=True,
+ reason="transport_auth_failure",
)
if pending_request is not None:
await self._remove_ack_reaction(pending_request)
@@ -4081,6 +4108,7 @@ class ClaudeAgent(BaseAgent):
composite_key,
current_receiver_task=asyncio.current_task(),
preserve_pending_request_state=True,
+ reason="result_auth_failure",
)
return handled
diff --git a/tests/test_agent_steering.py b/tests/test_agent_steering.py
index c4bf8ac31..42382d918 100644
--- a/tests/test_agent_steering.py
+++ b/tests/test_agent_steering.py
@@ -566,6 +566,8 @@ async def test_shared_boundary_finishes_native_reconciliation_before_propagating
assert agent._steering_generation("runtime-key") == 1
assert agent._pending_steering_input_state("runtime-key") == "accepted"
+ assert agent.claude_sessions["runtime-key"] is client
+ assert agent.receiver_tasks["runtime-key"] is receiver_task
assert agent._pending_requests["runtime-key"] == [primary]
assert not receiver_task.done()
finally:
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index 2c62f2357..b02c3ff60 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -78,7 +78,9 @@ class _StubController:
*,
current_receiver_task=None,
activation_retired=False,
+ reason="unspecified",
):
+ del activation_retired, reason
receiver_task = self.receiver_tasks.pop(composite_key, None)
client = self.claude_sessions.pop(composite_key, None)
cleanup_from_receiver = receiver_task is not None and receiver_task is current_receiver_task
@@ -489,6 +491,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
runtime_key,
current_receiver_task=None,
activation_retired=False,
+ reason="user_stop",
)
self.assertFalse(service._turn_gates[runtime_key].lock.locked())
self.assertEqual(request.context.platform_specific["turn_token"], "T1")
@@ -676,6 +679,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
runtime_key,
current_receiver_task=None,
activation_retired=False,
+ reason="user_stop",
)
controller.processing_indicator.finish.assert_awaited_once_with(
pending_request, terminal_emoji=STOPPED_REACTION_EMOJI
@@ -2033,6 +2037,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
runtime_key,
current_receiver_task=None,
activation_retired=False,
+ reason="query_auth_failure",
)
self.assertEqual(agent._pending_requests[runtime_key], [queued_request])
controller.session_handler.handle_session_error.assert_not_awaited()
@@ -2345,6 +2350,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
session_key,
current_receiver_task=receiver_task,
activation_retired=False,
+ reason="claude_agent_cleanup",
)
self.assertNotIn(session_key, agent._last_assistant_text)
self.assertNotIn(session_key, agent._pending_assistant_message)
@@ -2423,6 +2429,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
composite_key,
current_receiver_task=asyncio.current_task(),
activation_retired=False,
+ reason="receiver_error_auth_failure",
)
self.assertFalse(agent._pending_requests.get(composite_key))
@@ -2987,6 +2994,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
composite_key,
current_receiver_task=asyncio.current_task(),
activation_retired=False,
+ reason="receiver_auth_failure",
)
self.assertFalse(agent._pending_requests.get(composite_key))
@@ -3151,6 +3159,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
composite_key,
current_receiver_task=asyncio.current_task(),
activation_retired=False,
+ reason="transport_auth_failure",
)
self.assertNotIn(composite_key, controller.receiver_tasks)
self.assertNotIn(composite_key, controller.claude_sessions)
@@ -3636,6 +3645,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
composite_key,
current_receiver_task=None,
activation_retired=False,
+ reason="stuck_active_eviction",
)
agent._remove_ack_reaction.assert_awaited_once_with(pending_request)
controller.emit_agent_message.assert_awaited_once_with(
@@ -3771,6 +3781,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
composite_key,
current_receiver_task=asyncio.current_task(),
activation_retired=False,
+ reason="transport_auth_failure",
)
self.assertEqual(agent._remove_ack_reaction.await_count, 2)
self.assertEqual(agent._remove_ack_reaction.await_args_list[0].args, (pending_request_1,))
diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.py
index 03f4042da..a5a3f4f65 100644
--- a/tests/test_claude_cli_path.py
+++ b/tests/test_claude_cli_path.py
@@ -898,6 +898,7 @@ def test_session_handler_retires_model_hub_scope_for_dead_cached_client(
handler._cleanup_session_locked.assert_awaited_once_with(
composite_key,
retire_model_hub_scope=True,
+ reason="cached_process_terminated",
)
asyncio.run(exercise())
@@ -2491,6 +2492,56 @@ def test_reap_orphaned_sessions_disables_in_tree_when_auth_client_pid_unknown(
assert captured["reap_in_tree"] is False
+def test_cleanup_session_logs_exact_runtime_generation(
+ monkeypatch,
+ tmp_path: Path,
+ caplog,
+) -> None:
+ captured: dict[str, Any] = {}
+
+ monkeypatch.setattr(
+ session_handler_module,
+ "ClaudeAgentOptions",
+ _StubClaudeAgentOptions,
+ )
+ monkeypatch.setattr(
+ session_handler_module,
+ "ClaudeSDKClient",
+ _disconnect_counting_client(captured),
+ )
+
+ controller = _Controller(tmp_path)
+ controller.runtime_activation = RuntimeActivationRegistry()
+ handler = SessionHandler(controller)
+ context = MessageContext(user_id="U123", channel_id="C123")
+ client = _run_session(handler, context)
+ composite_key = f"slack_C123:{tmp_path}"
+ identity = getattr(client, "_vibe_runtime_activation_identity")
+
+ async def _exercise_cleanup() -> int:
+ receiver = asyncio.create_task(asyncio.sleep(3600))
+ controller.receiver_tasks[composite_key] = receiver
+ handler.mark_session_active(composite_key)
+ receiver_identity = id(receiver)
+ with caplog.at_level("INFO", logger="core.handlers.session_handler"):
+ await handler.cleanup_session(
+ composite_key,
+ reason="test_requested_teardown",
+ )
+ return receiver_identity
+
+ receiver_identity = asyncio.run(_exercise_cleanup())
+
+ evidence = caplog.text
+ assert f"session={composite_key}" in evidence
+ assert "reason=test_requested_teardown" in evidence
+ assert "busy=True" in evidence
+ assert f"runtime_generation={identity.generation}" in evidence
+ assert f"client_identity={id(client)}" in evidence
+ assert f"receiver_identity={receiver_identity}" in evidence
+ assert "receiver_done=False" in evidence
+
+
def test_cleanup_session_swallows_cancelled_receiver_task(monkeypatch, tmp_path: Path) -> None:
events = []
diff --git a/tests/test_claude_receiver_result_settle.py b/tests/test_claude_receiver_result_settle.py
index 8b83d8019..984679cb2 100644
--- a/tests/test_claude_receiver_result_settle.py
+++ b/tests/test_claude_receiver_result_settle.py
@@ -953,6 +953,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):
composite_key,
current_receiver_task=receiver_task,
preserve_pending_request_state=True,
+ reason="receiver_eof_without_result",
)
agent._release_service_runtime_turn.assert_called_once_with(context)
@@ -1105,7 +1106,10 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):
self.assertIs(receipt.outcome, SteerOutcome.ACCEPTED)
self.assertTrue(ended)
self.assertEqual(events, ["query", "interrupt"])
- agent._cleanup_runtime_session.assert_awaited_once_with(composite_key)
+ agent._cleanup_runtime_session.assert_awaited_once_with(
+ composite_key,
+ reason="running_agent_end",
+ )
self.assertIn(composite_key, agent._steering_closing_keys())
receiver_task.cancel()
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index fae85b2f3..c6f31d4d0 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -6895,6 +6895,91 @@ def test_scheduled_gate_retry_preserves_existing_delivery_owner(monkeypatch, tmp
assert request_store.get_run(run.id)["status"] == "running"
+def test_scheduled_gate_cancellation_preserves_transferred_delivery_owner(
+ monkeypatch,
+ tmp_path,
+):
+ """A canceled executor cannot take a natively accepted steer back from Delivery."""
+ from core.scheduled_tasks import TaskExecutionStore
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session, _active_turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="proj_sched_canceled_handoff",
+ )
+ session_id = session["id"]
+ request_store = TaskExecutionStore()
+ run = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message="steer while active",
+ agent_name="worker",
+ )
+ assert request_store.claim(run.id) is not None
+
+ controller = _build_controller_double()
+ internal_server.create_app(controller)
+ manager = controller.session_turns
+ native_write_started = asyncio.Event()
+ release_native_write = asyncio.Event()
+
+ async def _natively_accepted_delivery(request, *, context):
+ del request, context
+ native_write = asyncio.create_task(release_native_write.wait())
+ native_write_started.set()
+ try:
+ await asyncio.shield(native_write)
+ except asyncio.CancelledError:
+ # Match the shared steering boundary: native receipt is reconciled
+ # before cancellation propagates to durable admission.
+ await native_write
+ raise
+
+ monkeypatch.setattr(manager, "deliver", _natively_accepted_delivery)
+ context = MessageContext(
+ user_id="workbench",
+ channel_id=session_id,
+ platform="avibe",
+ message_id=f"agent_run:{run.id}",
+ platform_specific={
+ "task_execution_id": run.id,
+ "task_trigger_kind": "agent_run",
+ },
+ )
+
+ async def _go():
+ submission = asyncio.create_task(
+ controller.session_turn_gate.submit_scheduled(
+ session_id,
+ context,
+ "steer while active",
+ )
+ )
+ await native_write_started.wait()
+ submission.cancel()
+ await asyncio.sleep(0)
+ assert not submission.done()
+ release_native_write.set()
+ return await submission
+
+ result = asyncio.run(_go())
+
+ assert result == session_turns.TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ target_was_busy=True,
+ delivery_status="reserved",
+ delivery_owner_transferred=True,
+ )
+ stored = request_store.get_run(run.id)
+ assert stored is not None
+ assert stored["status"] == "running"
+ assert stored["delivery_id"]
+ with engine.connect() as conn:
+ delivery = message_deliveries.get_delivery(conn, stored["delivery_id"])
+ assert delivery is not None
+ assert delivery["state"] == "reserved"
+
+
def test_scheduled_send_now_recovers_transferred_reservation(monkeypatch, tmp_path):
"""After ownership transfer, a pre-claim failure belongs to Delivery recovery."""
from core.scheduled_tasks import TaskExecutionStore
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index d1bf56843..2e4049f44 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -3093,7 +3093,7 @@ def test_service_teardown_terminalizes_transferred_turn_without_starting_queued_
shutdown_entrypoint: str,
user_stopped: bool,
) -> None:
- """HFR-103: every service teardown settles the transferred scheduled Run."""
+ """HFR-103: full teardown settles Runs; lease loss first stops the controller."""
from storage.background import attach_agent_run_delivery_in_connection
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
@@ -3270,10 +3270,12 @@ def test_service_teardown_terminalizes_transferred_turn_without_starting_queued_
raise AssertionError("unreachable")
monkeypatch.setattr("core.session_turns.dispatch_turn_with_outcome", _never_returns)
+ shutdown_reasons: list[str] = []
controller = SimpleNamespace(
config=SimpleNamespace(language="en"),
set_agent_status=lambda *_args, **_kwargs: None,
_get_session_key=lambda ctx: f"avibe::{ctx.channel_id}",
+ request_shutdown=shutdown_reasons.append,
)
service = ScheduledTaskService(
controller=controller,
@@ -3320,13 +3322,22 @@ def test_service_teardown_terminalizes_transferred_turn_without_starting_queued_
lambda: False,
)
assert service._owns_service_instance() is False
- teardown = service._service_teardown_task
- assert teardown is not None
+ assert shutdown_reasons == ["service lease lost"]
+ assert service._service_teardown_task is None
assert service._owns_service_instance() is False
- assert service._service_teardown_task is teardown
- await teardown
+ assert shutdown_reasons == ["service lease lost", "service lease lost"]
+ assert service._service_teardown_task is None
+ live_run = request_store.get_run(run_id)
+ assert live_run is not None
+ assert live_run["status"] == "running"
+ with engine.connect() as conn:
+ live_turn = message_deliveries.get_turn(conn, turn_id)
+ assert live_turn is not None
+ assert live_turn["state"] == "active"
+ assert session_id in manager.in_flight
+ assert not manager.in_flight[session_id].task.done()
await service.stop()
- assert service._service_teardown_task is teardown
+ assert service._service_teardown_task is not None
asyncio.run(_stop())
diff --git a/tests/test_session_handler_base_id.py b/tests/test_session_handler_base_id.py
index fd0234637..4793d500c 100644
--- a/tests/test_session_handler_base_id.py
+++ b/tests/test_session_handler_base_id.py
@@ -486,8 +486,13 @@ def test_claude_sdk_buffer_error_cleans_up_broken_session() -> None:
handler = SessionHandler(controller)
cleanup_calls = []
- async def _cleanup_session(composite_key: str, *, current_receiver_task=None) -> None:
- cleanup_calls.append((composite_key, current_receiver_task))
+ async def _cleanup_session(
+ composite_key: str,
+ *,
+ current_receiver_task=None,
+ reason=None,
+ ) -> None:
+ cleanup_calls.append((composite_key, current_receiver_task, reason))
handler.cleanup_session = _cleanup_session
context = MessageContext(user_id="U123", channel_id="C123", platform="slack")
@@ -501,9 +506,10 @@ def test_claude_sdk_buffer_error_cleans_up_broken_session() -> None:
)
assert len(cleanup_calls) == 1
- cleanup_key, cleanup_task = cleanup_calls[0]
+ cleanup_key, cleanup_task, cleanup_reason = cleanup_calls[0]
assert cleanup_key == "slack_C123:/tmp/workdir"
assert cleanup_task is not None
+ assert cleanup_reason == "connection_broken"
assert len(controller.im_client.sent_messages) == 1
_, message = controller.im_client.sent_messages[0]
assert message == "ERR:Connection to Claude was lost. Please try your message again."
@@ -520,8 +526,14 @@ def test_claude_terminated_process_cleans_up_and_reports_signal_diagnostic() ->
)
cleanup_calls = []
- async def _cleanup_session(key: str, *, current_receiver_task=None, expected_client=None) -> None:
- cleanup_calls.append((key, current_receiver_task))
+ async def _cleanup_session(
+ key: str,
+ *,
+ current_receiver_task=None,
+ expected_client=None,
+ reason=None,
+ ) -> None:
+ cleanup_calls.append((key, current_receiver_task, reason))
handler.cleanup_session = _cleanup_session
context = MessageContext(user_id="U123", channel_id="C123", platform="slack")
@@ -537,6 +549,7 @@ def test_claude_terminated_process_cleans_up_and_reports_signal_diagnostic() ->
assert len(cleanup_calls) == 1
assert cleanup_calls[0][0] == composite_key
assert cleanup_calls[0][1] is not None
+ assert cleanup_calls[0][2] == "process_terminated"
_, message = controller.im_client.sent_messages[0]
assert message == (
"ERR:Claude Code process terminated (SIGABRT (signal 6)); "
@@ -564,8 +577,14 @@ def test_service_initiated_teardown_signal_is_not_reported_as_session_error() ->
composite_key = "slack_C123:/tmp/workdir"
cleanup_calls = []
- async def _cleanup_session(key: str, *, current_receiver_task=None, expected_client=None) -> None:
- cleanup_calls.append(key)
+ async def _cleanup_session(
+ key: str,
+ *,
+ current_receiver_task=None,
+ expected_client=None,
+ reason=None,
+ ) -> None:
+ cleanup_calls.append((key, reason))
handler.cleanup_session = _cleanup_session
handler._mark_claude_teardown_intentional(composite_key, None)
@@ -579,7 +598,7 @@ def test_service_initiated_teardown_signal_is_not_reported_as_session_error() ->
)
)
- assert cleanup_calls == [composite_key]
+ assert cleanup_calls == [(composite_key, "intentional_teardown_signal")]
assert controller.im_client.sent_messages == []
@@ -589,7 +608,13 @@ def test_teardown_intent_does_not_suppress_errors_from_the_next_generation() ->
handler = SessionHandler(controller)
composite_key = "slack_C123:/tmp/workdir"
- async def _cleanup_session(key: str, *, current_receiver_task=None, expected_client=None) -> None:
+ async def _cleanup_session(
+ key: str,
+ *,
+ current_receiver_task=None,
+ expected_client=None,
+ reason=None,
+ ) -> None:
return None
handler.cleanup_session = _cleanup_session
@@ -618,7 +643,13 @@ def test_unrelated_error_during_teardown_window_is_still_reported() -> None:
handler = SessionHandler(controller)
composite_key = "slack_C123:/tmp/workdir"
- async def _cleanup_session(key: str, *, current_receiver_task=None, expected_client=None) -> None:
+ async def _cleanup_session(
+ key: str,
+ *,
+ current_receiver_task=None,
+ expected_client=None,
+ reason=None,
+ ) -> None:
return None
handler.cleanup_session = _cleanup_session
@@ -653,7 +684,13 @@ def test_client_teardown_marker_suppresses_signal_error_without_key_record() ->
)
controller.claude_sessions[composite_key] = client
- async def _cleanup_session(key: str, *, current_receiver_task=None, expected_client=None) -> None:
+ async def _cleanup_session(
+ key: str,
+ *,
+ current_receiver_task=None,
+ expected_client=None,
+ reason=None,
+ ) -> None:
return None
handler.cleanup_session = _cleanup_session
@@ -682,7 +719,13 @@ def test_teardown_containment_matches_colon_delimited_exit_code() -> None:
handler = SessionHandler(controller)
composite_key = "slack_C123:/tmp/workdir"
- async def _cleanup_session(key: str, *, current_receiver_task=None, expected_client=None) -> None:
+ async def _cleanup_session(
+ key: str,
+ *,
+ current_receiver_task=None,
+ expected_client=None,
+ reason=None,
+ ) -> None:
return None
handler.cleanup_session = _cleanup_session
@@ -741,7 +784,13 @@ def test_old_generation_teardown_is_contained_after_a_replacement_registers() ->
)
controller.claude_sessions[composite_key] = replacement
- async def _cleanup_session(key: str, *, current_receiver_task=None, expected_client=None) -> None:
+ async def _cleanup_session(
+ key: str,
+ *,
+ current_receiver_task=None,
+ expected_client=None,
+ reason=None,
+ ) -> None:
return None
handler.cleanup_session = _cleanup_session