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(agent): protect live-owned pids from the duplicate Claude reaper (#1202)

Qi Qi435eeb3a1a2d
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 9418e7faa..32b38fcd6 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -55,6 +55,18 @@ from .base import BaseHandler
logger = logging.getLogger(__name__)
+# A Claude CLI process the service terminated on purpose surfaces as SIGTERM
+# (-15) or the SIGKILL escalation (-9). The SDK may report it as a returncode
+# or only as text on the transport error, so both shapes are recognized. The
+# text arrives in two shapes: the SDK transport reader raises "Command failed
+# with exit code -9", while write failures raise "Cannot write to terminated
+# process (exit code: -9)".
+CLAUDE_TEARDOWN_RETURNCODES = frozenset({-9, -15})
+CLAUDE_TEARDOWN_EXIT_PATTERN = re.compile(r"exit code:?\s*(-9|-15)\b")
+# Teardown intent is dropped as soon as a new client takes the key; this bound
+# only limits how long a stale record can survive when that never happens.
+CLAUDE_INTENTIONAL_TEARDOWN_TTL_SECONDS = 120.0
+
if TYPE_CHECKING:
from core.runtime_ownership import RuntimeResourceTarget
from modules.agents.model_hub import ModelHubLaunch
@@ -105,12 +117,18 @@ class SessionHandler(BaseHandler):
"claude_runtime_generation_locks",
{},
)
+ self.claude_intentional_teardowns = getattr(
+ controller,
+ "claude_intentional_teardowns",
+ {},
+ )
controller.session_last_activity = self.session_last_activity
controller.session_turn_started = self.session_turn_started
controller.claude_active_sessions = self.active_sessions
controller.claude_system_prompts = self.claude_system_prompts
controller.claude_session_creates = self.claude_session_creates
controller.claude_runtime_generation_locks = self.claude_runtime_generation_locks
+ controller.claude_intentional_teardowns = self.claude_intentional_teardowns
@staticmethod
def _cached_claude_subagent_model(
@@ -161,6 +179,110 @@ class SessionHandler(BaseHandler):
self.session_turn_started.pop(composite_key, None)
self.claude_system_prompts.pop(composite_key, None)
+ def _live_claude_client_pids(self) -> tuple[set[int], bool]:
+ """Claude CLI pids owned by registered clients, and whether that set is whole.
+
+ The duplicate reaper matches on the native ``--resume`` id, which is
+ reused across reconnects and therefore cannot distinguish a leaked
+ generation from a live client for the same session. Membership in
+ ``claude_sessions`` is the authoritative ownership signal, so these
+ pids are never eligible for a duplicate reap.
+
+ A registered client whose pid cannot be resolved is still an owner — it
+ just cannot be named — so the second element reports whether every
+ owner is accounted for. ``reap_orphaned_claude_sessions`` already draws
+ this distinction with ``owner_set_complete``; without it a partial set
+ reads as the whole ownership picture and a live replacement resuming
+ this native id can be selected by the process-table scan.
+ """
+ pids: set[int] = set()
+ complete = True
+ for client in list(self.claude_sessions.values()):
+ pid = get_claude_client_pid(client)
+ if pid:
+ pids.add(pid)
+ else:
+ complete = False
+ return pids, complete
+
+ def _mark_claude_teardown_intentional(self, composite_key: str, client) -> None:
+ """Record that this generation is being torn down by the service."""
+ if client is not None:
+ setattr(client, "_vibe_intentional_teardown", True)
+ if not composite_key:
+ return
+ now = time.monotonic()
+ # Keys that never get a replacement client would otherwise keep their
+ # record forever; drop expired ones on the way in.
+ for key, started_at in list(self.claude_intentional_teardowns.items()):
+ if now - started_at > CLAUDE_INTENTIONAL_TEARDOWN_TTL_SECONDS:
+ self.claude_intentional_teardowns.pop(key, None)
+ self.claude_intentional_teardowns[composite_key] = now
+
+ def _clear_claude_teardown_intent(self, composite_key: str) -> None:
+ """Drop the teardown record once a new generation owns the key.
+
+ A fresh client must never inherit the previous generation's teardown
+ marker, otherwise its own failures would be silently swallowed.
+
+ The key-level record is therefore the *replacement's* view, not the
+ torn-down generation's: an in-flight query from the old generation can
+ still reach ``handle_session_error`` after this runs. That case is
+ carried by the per-client ``_vibe_intentional_teardown`` attribute
+ instead, which is why callers pass the exact client whose failure they
+ observed rather than letting the handler re-read ``claude_sessions``.
+ """
+ if composite_key:
+ self.claude_intentional_teardowns.pop(composite_key, None)
+
+ def _is_intentional_teardown_signal(
+ self,
+ composite_key: str,
+ error: Exception,
+ returncode: Optional[int],
+ client=None,
+ ) -> bool:
+ """Was this failure our own SIGTERM/SIGKILL against a torn-down client?
+
+ Cleanup escalates SIGTERM to SIGKILL, so the SDK reports ``exit code
+ -15``/``-9`` for a process the service killed on purpose. Reporting
+ that as a session error makes a deliberate teardown look like a backend
+ crash.
+ """
+ if not getattr(client, "_vibe_intentional_teardown", False):
+ started_at = self.claude_intentional_teardowns.get(composite_key)
+ if started_at is None:
+ return False
+ if time.monotonic() - started_at > CLAUDE_INTENTIONAL_TEARDOWN_TTL_SECONDS:
+ self.claude_intentional_teardowns.pop(composite_key, None)
+ return False
+ if returncode is not None:
+ return returncode in CLAUDE_TEARDOWN_RETURNCODES
+ return bool(CLAUDE_TEARDOWN_EXIT_PATTERN.search(str(error)))
+
+ def claude_teardown_is_intentional(
+ self,
+ composite_key: str,
+ error: Exception,
+ *,
+ client=None,
+ ) -> bool:
+ """Public probe: is this failure a teardown the service performed itself?
+
+ Callers need the answer *before* they record backend-health evidence.
+ ``record_model_hub_native_failure`` converts the pending attempt into a
+ failed one, so classifying only afterwards lets operational cleanup
+ settle a Model Hub source as unhealthy for a process nobody reported a
+ fault in.
+ """
+ resolved = client if client is not None else self.claude_sessions.get(composite_key)
+ return self._is_intentional_teardown_signal(
+ composite_key,
+ error,
+ get_claude_client_returncode(resolved),
+ resolved,
+ )
+
async def _wait_for_claude_session_idle(self, composite_key: str) -> None:
while composite_key in self.active_sessions:
await asyncio.sleep(0.05)
@@ -519,6 +641,15 @@ class SessionHandler(BaseHandler):
def _track_claude_session_create(self, composite_key: str) -> asyncio.Future:
future = asyncio.get_running_loop().create_future()
self.claude_session_creates[composite_key] = future
+ # Retire the key-level teardown record as soon as a replacement starts
+ # being built, not once it registers. A new generation that dies with
+ # ``-9`` inside ``connect()`` never reaches registration, so the caller
+ # reports it with ``client=None`` — and a marker still standing from the
+ # previous teardown would classify that genuine crash as our own
+ # cleanup, suppressing both the IM notification and the durable Web Chat
+ # error row. The old generation keeps its own coverage through the
+ # per-client ``_vibe_intentional_teardown`` attribute.
+ self._clear_claude_teardown_intent(composite_key)
return future
def _untrack_claude_session_create(self, composite_key: str, future: asyncio.Future) -> None:
@@ -1454,6 +1585,10 @@ class SessionHandler(BaseHandler):
),
)
self.claude_sessions[composite_key] = client
+ # Normally already cleared when the create was tracked; kept as the
+ # backstop for any path that builds a client without going through
+ # ``_track_claude_session_create``.
+ self._clear_claude_teardown_intent(composite_key)
logger.info(f"Created new Claude SDK client for {base_session_id} at {working_path}")
return client
@@ -1736,8 +1871,15 @@ class SessionHandler(BaseHandler):
current_receiver_task=None,
retire_model_hub_scope: bool = True,
activation_retired: bool = False,
+ expected_client=None,
):
- """Clean up one Claude generation under the same lock used by creation."""
+ """Clean up one Claude generation under the same lock used by creation.
+
+ ``expected_client`` names the generation the caller means to retire.
+ Cleanup resolves the composite key again under the lock, so a caller
+ acting on a client that has since been replaced would otherwise tear
+ down the healthy replacement instead.
+ """
async with self._claude_runtime_generation_lock(composite_key):
await self._cleanup_session_locked(
@@ -1745,6 +1887,7 @@ class SessionHandler(BaseHandler):
current_receiver_task=current_receiver_task,
retire_model_hub_scope=retire_model_hub_scope,
activation_retired=activation_retired,
+ expected_client=expected_client,
)
async def _cleanup_session_locked(
@@ -1754,9 +1897,19 @@ class SessionHandler(BaseHandler):
current_receiver_task=None,
retire_model_hub_scope: bool = True,
activation_retired: bool = False,
+ expected_client=None,
):
"""Clean up a specific session by composite key"""
client = self.claude_sessions.get(composite_key)
+ if expected_client is not None and client is not expected_client:
+ # The named generation is gone: either already retired, or replaced
+ # 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",
+ composite_key,
+ )
+ return
activation_retired = activation_retired or bool(
getattr(client, "_vibe_runtime_activation_retired", False)
)
@@ -1775,6 +1928,13 @@ class SessionHandler(BaseHandler):
native_session_id = getattr(client, "_vibe_native_session_id", None)
keep_pid = get_claude_client_pid(client)
self.clear_session_tracking(composite_key)
+ if client is not None or receiver_task is not None:
+ # Only a generation that actually existed can produce the signal the
+ # marker explains. Recording one for an already-empty key leaves a
+ # 120s window in which the NEXT client's genuine ``-9`` — say, dying
+ # inside ``connect()`` before registration can clear the record — is
+ # suppressed as though the service had killed it.
+ self._mark_claude_teardown_intentional(composite_key, client)
try:
# Close the SDK client first so its receive stream can finish normally.
@@ -1788,13 +1948,60 @@ class SessionHandler(BaseHandler):
finally:
if not cleanup_from_receiver:
await self._stop_receiver_task(receiver_task, composite_key)
- await reap_duplicate_claude_resume_processes(
+ # ``disconnect()`` on a hung client can block for seconds, so the
+ # owner set is re-read here rather than before it: by now another
+ # client may legitimately own a process resuming the same native
+ # session id, and it must not be reaped as a duplicate.
+ await self._reap_duplicate_resume_processes(
+ composite_key,
native_session_id,
keep_pid=keep_pid if cleanup_from_receiver else None,
- cli_path=self._get_claude_cli_path_override(),
- logger=logger,
)
+ async def _reap_duplicate_resume_processes(
+ self,
+ composite_key: str,
+ native_session_id: Optional[str],
+ *,
+ keep_pid: Optional[int],
+ ) -> None:
+ """Reap leftover processes for one native session id, ownership-first.
+
+ Generation locks are per composite key, so another key can be starting
+ a client for the same native session id right now. Between
+ ``connect()`` and registration that client owns a live subprocess that
+ ``claude_sessions`` cannot yet report, and ``keep_pid`` is ``None`` on
+ every cleanup that does not run from the receiver task — so the reap is
+ deferred rather than run against an incomplete owner set. The same
+ applies when a registered client's pid cannot be resolved. The periodic
+ orphan reaper, which reconciles against the persisted ownership
+ registry, remains the backstop for anything left behind.
+ """
+ if not native_session_id:
+ return
+ creates_in_flight = [key for key in self.claude_session_creates if key != composite_key]
+ if creates_in_flight:
+ logger.info(
+ "Deferring duplicate Claude reap for session %s: %d client create(s) in flight",
+ composite_key,
+ len(creates_in_flight),
+ )
+ return
+ owned_pids, owner_set_complete = self._live_claude_client_pids()
+ if not owner_set_complete:
+ logger.info(
+ "Deferring duplicate Claude reap for session %s: a registered client's pid is unresolved",
+ composite_key,
+ )
+ return
+ await reap_duplicate_claude_resume_processes(
+ native_session_id,
+ keep_pid=keep_pid,
+ exclude_pids=owned_pids,
+ cli_path=self._get_claude_cli_path_override(),
+ logger=logger,
+ )
+
async def _disconnect_client(self, client, composite_key: str) -> None:
try:
await client.disconnect()
@@ -2286,8 +2493,27 @@ class SessionHandler(BaseHandler):
exclude_pids=exclude_pids,
)
- async def handle_session_error(self, composite_key: str, context: MessageContext, error: Exception):
- """Handle session-related errors"""
+ async def handle_session_error(
+ self,
+ composite_key: str,
+ context: MessageContext,
+ error: Exception,
+ *,
+ client=None,
+ ) -> bool:
+ """Handle session-related errors.
+
+ Returns ``True`` when the failure was contained (already explained to
+ the user, or deliberately silenced), so callers can skip persisting a
+ durable failure notification for it.
+
+ ``client`` is the exact client whose failure the caller observed. It
+ matters when a replacement has already registered under the same
+ composite key: the torn-down client was popped from ``claude_sessions``
+ and only it carries the teardown marker, so re-reading the map here
+ would classify a delayed old-generation ``-9`` against the healthy
+ replacement and report it as a genuine failure.
+ """
error_msg = str(error)
# Check for specific error types
@@ -2307,10 +2533,28 @@ class SessionHandler(BaseHandler):
)
),
)
- return
+ return False
- client = self.claude_sessions.get(composite_key)
+ if client is None:
+ client = self.claude_sessions.get(composite_key)
returncode = get_claude_client_returncode(client)
+ if self._is_intentional_teardown_signal(composite_key, error, returncode, client):
+ # The service killed this process itself (idle eviction, duplicate
+ # reap, shutdown). Surfacing it would report a deliberate teardown
+ # as an unexplained backend failure.
+ logger.warning(
+ "Claude session %s ended on a service-initiated teardown signal: %s",
+ composite_key,
+ error_msg,
+ )
+ await self.cleanup_session(
+ composite_key,
+ current_receiver_task=asyncio.current_task(),
+ # This failure may belong to a generation a replacement has
+ # already taken over from; retire that exact client or nothing.
+ expected_client=client,
+ )
+ return True
if returncode is not None:
reason_key, reason_values = claude_process_exit_reason_i18n(returncode)
reason = self._t(reason_key, **reason_values)
@@ -2321,14 +2565,22 @@ class SessionHandler(BaseHandler):
reason,
diagnostic,
)
- await self.cleanup_session(composite_key, current_receiver_task=asyncio.current_task())
+ # Same generation guard as the contained branch above: this branch is
+ # reached off the CALLER's client, which a replacement may already
+ # have superseded. Reporting a stale crash is right; retiring the
+ # live client that replaced it is not.
+ await self.cleanup_session(
+ composite_key,
+ current_receiver_task=asyncio.current_task(),
+ expected_client=client,
+ )
await self._get_im_client(context).send_message(
context,
self._get_formatter(context).format_error(
self._t("error.claudeProcessTerminated", reason=reason)
),
)
- return
+ 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())
@@ -2361,6 +2613,7 @@ class SessionHandler(BaseHandler):
context,
self._get_formatter(context).format_error(self._t("error.sessionGeneric", error=error_msg)),
)
+ return False
def claude_error_diagnostic(self, composite_key: str, error: Exception) -> str:
"""Add process state and captured stderr to a Claude failure diagnostic."""
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index bc3f433d4..a99d42ae5 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -232,7 +232,15 @@ class ClaudeAgent(BaseAgent):
except Exception as e:
logger.error(f"Error processing Claude message: {e}", exc_info=True)
diagnostic = self._claude_error_diagnostic(runtime_session_key, e)
- await self.record_model_hub_native_failure(context, diagnostic)
+ # Classify BEFORE recording: ``record_model_hub_native_failure``
+ # turns the pending native/hub attempt into a failed one, so a
+ # process the service killed on purpose would settle that source's
+ # provenance as exhausted with no backend fault behind it.
+ intentional_teardown = self._teardown_is_intentional(
+ runtime_session_key, e, client=client
+ )
+ if not intentional_teardown:
+ await self.record_model_hub_native_failure(context, diagnostic)
# Clean up the specific reaction for this request (not FIFO)
await self._remove_specific_pending_reaction(runtime_session_key, context, request)
self._remove_pending_request(runtime_session_key, request)
@@ -258,28 +266,38 @@ class ClaudeAgent(BaseAgent):
preserve_pending_request_state=True,
)
if not handled:
- await self.session_handler.handle_session_error(runtime_session_key, context, e)
+ contained = await self.session_handler.handle_session_error(
+ runtime_session_key, context, e, client=client
+ )
# ``handle_session_error`` sends through the IM client, which doesn't
# write to ``messages``, and the web Chat renders only durable
# ``message.new`` rows. The auth branch persists its recovery text.
- try:
- from core.message_mirror import persist_agent_message
+ # A contained failure (a teardown the service performed itself)
+ # must stay silent on every surface, so skip the durable row too.
+ # Only an explicit ``True`` suppresses: the session handler is
+ # duck-typed here, and a handler that returns anything else must
+ # keep the failure visible.
+ if contained is not True:
+ try:
+ from core.message_mirror import persist_agent_message
- notification = backend_failure_notification_output(
- context,
- "claude",
- request=request,
- output=terminal_output_for(request),
- )
- persist_agent_message(
- context,
- "notify",
- error_notify,
- metadata=notification.metadata,
- native_message_id=notification.idempotency_key,
- )
- except Exception:
- logger.debug("claude: failed to persist terminal error row", exc_info=True)
+ notification = backend_failure_notification_output(
+ context,
+ "claude",
+ request=request,
+ output=terminal_output_for(request),
+ )
+ persist_agent_message(
+ context,
+ "notify",
+ error_notify,
+ metadata=notification.metadata,
+ native_message_id=notification.idempotency_key,
+ )
+ except Exception:
+ logger.debug(
+ "claude: failed to persist terminal error row", exc_info=True
+ )
# No async receiver result is coming. Auth recovery settles its
# own failure; otherwise do that here without another bubble.
await self.controller.emit_agent_message(
@@ -296,6 +314,23 @@ class ClaudeAgent(BaseAgent):
finally:
await self._delete_ack(context, request)
+ def _teardown_is_intentional(self, composite_key: str, error: Exception, *, client=None) -> bool:
+ """Did the service kill this Claude process itself?
+
+ The session handler owns the classification; this only reaches it.
+ Duck-typed like the other handler calls here, and failure-closed: an
+ unknown answer must record the failure rather than silently drop
+ backend-health evidence.
+ """
+ probe = getattr(self.session_handler, "claude_teardown_is_intentional", None)
+ if not callable(probe):
+ return False
+ try:
+ return probe(composite_key, error, client=client) is True
+ except Exception:
+ logger.debug("claude: teardown classification failed", exc_info=True)
+ return False
+
def _release_service_runtime_turn(self, context: MessageContext) -> None:
service = getattr(self.controller, "agent_service", None)
release = getattr(service, "release_runtime_turn", None)
@@ -1901,7 +1936,11 @@ class ClaudeAgent(BaseAgent):
error_notify = self._format_error_notify(eof_error, composite_key=composite_key)
diagnostic = self._claude_error_diagnostic(composite_key, eof_error)
failure_context = getattr(pending_request, "context", context)
- await self.record_model_hub_native_failure(failure_context, diagnostic)
+ intentional_teardown = self._teardown_is_intentional(
+ composite_key, eof_error, client=client
+ )
+ if not intentional_teardown:
+ await self.record_model_hub_native_failure(failure_context, diagnostic)
auth_handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(
context,
"claude",
@@ -1929,28 +1968,34 @@ class ClaudeAgent(BaseAgent):
self._requeue_request_activity(pending_request)
handle_session_error = getattr(self.session_handler, "handle_session_error", None)
if callable(handle_session_error):
- await handle_session_error(composite_key, context, eof_error)
- try:
- from core.message_mirror import persist_agent_message
+ contained = await handle_session_error(
+ composite_key, context, eof_error, client=client
+ )
+ # A teardown the service performed itself is already
+ # explained in the log; do not leave a durable failure row
+ # for the web Chat to render.
+ if contained is not True:
+ try:
+ from core.message_mirror import persist_agent_message
- notification = backend_failure_notification_output(
- context,
- "claude",
- request=pending_request,
- output=terminal_output_for(pending_request),
- )
- persist_agent_message(
- context,
- "notify",
- error_notify,
- metadata=notification.metadata,
- native_message_id=notification.idempotency_key,
- )
- except Exception:
- logger.debug(
- "claude: failed to persist terminated EOF notification",
- exc_info=True,
- )
+ notification = backend_failure_notification_output(
+ context,
+ "claude",
+ request=pending_request,
+ output=terminal_output_for(pending_request),
+ )
+ persist_agent_message(
+ context,
+ "notify",
+ error_notify,
+ metadata=notification.metadata,
+ native_message_id=notification.idempotency_key,
+ )
+ except Exception:
+ logger.debug(
+ "claude: failed to persist terminated EOF notification",
+ exc_info=True,
+ )
else:
diagnostic = terminal_error
else:
@@ -2005,7 +2050,15 @@ class ClaudeAgent(BaseAgent):
diagnostic = self._claude_error_diagnostic(composite_key, error)
error_notify = self._format_error_notify(error, composite_key=composite_key)
failure_context = getattr(pending_request, "context", context)
- await self.record_model_hub_native_failure(failure_context, diagnostic)
+ # Read the client once and reuse it for both the health gate and the
+ # handler, so a replacement registering in between cannot make the
+ # two disagree about which generation actually failed.
+ errored_client = self.claude_sessions.get(composite_key)
+ intentional_teardown = self._teardown_is_intentional(
+ composite_key, error, client=errored_client
+ )
+ if not intentional_teardown:
+ await self.record_model_hub_native_failure(failure_context, diagnostic)
handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(
context,
"claude",
@@ -2026,32 +2079,36 @@ class ClaudeAgent(BaseAgent):
await self._clear_pending_reactions(composite_key, context)
self._mark_session_idle_if_no_pending_requests(composite_key)
else:
- await self.session_handler.handle_session_error(
+ contained = await self.session_handler.handle_session_error(
composite_key,
context,
error,
+ client=errored_client,
)
- try:
- from core.message_mirror import persist_agent_message
+ # A teardown the service performed itself is contained: no IM
+ # message and no durable failure row on any surface.
+ if contained is not True:
+ try:
+ from core.message_mirror import persist_agent_message
- notification = backend_failure_notification_output(
- context,
- "claude",
- request=pending_request,
- output=terminal_output_for(pending_request),
- )
- persist_agent_message(
- context,
- "notify",
- error_notify,
- metadata=notification.metadata,
- native_message_id=notification.idempotency_key,
- )
- except Exception:
- logger.debug(
- "claude: failed to persist terminal receiver-error row",
- exc_info=True,
- )
+ notification = backend_failure_notification_output(
+ context,
+ "claude",
+ request=pending_request,
+ output=terminal_output_for(pending_request),
+ )
+ persist_agent_message(
+ context,
+ "notify",
+ error_notify,
+ metadata=notification.metadata,
+ native_message_id=notification.idempotency_key,
+ )
+ except Exception:
+ logger.debug(
+ "claude: failed to persist terminal receiver-error row",
+ exc_info=True,
+ )
await self.controller.emit_agent_message(
context,
"result",
diff --git a/modules/agents/claude_process_reaper.py b/modules/agents/claude_process_reaper.py
index 838eac316..bda002a22 100644
--- a/modules/agents/claude_process_reaper.py
+++ b/modules/agents/claude_process_reaper.py
@@ -357,6 +357,7 @@ async def reap_duplicate_claude_resume_processes(
native_session_id: str | None,
*,
keep_pid: int | None = None,
+ exclude_pids: set[int] | None = None,
cli_path: str | None = None,
logger: logging.Logger,
terminate_timeout: float = 2.0,
@@ -366,6 +367,14 @@ async def reap_duplicate_claude_resume_processes(
This is intentionally conservative: it only matches a full ``--resume`` id
and only reaps when more than one matching process exists, or when the
caller no longer has a tracked PID to keep.
+
+ A native session id is stable and reused across reconnects, so a matching
+ process may belong to a *newer* client for the same session rather than to
+ a leaked generation. ``keep_pid`` alone cannot express that: cleanup paths
+ that do not run from the receiver task pass ``keep_pid=None``, which drops
+ the duplicate guard entirely. ``exclude_pids`` carries the stronger
+ invariant — never signal a pid (or descendant of a pid) owned by a client
+ that is still registered — and holds regardless of the initiating path.
"""
if not native_session_id or os.name == "nt":
return 0
@@ -376,6 +385,19 @@ async def reap_duplicate_claude_resume_processes(
logger.debug("Failed to read process table for Claude duplicate cleanup", exc_info=True)
return 0
+ children = _build_children_map(all_rows)
+ protected_pids: set[int] = {
+ pid for pid in (exclude_pids or set()) if isinstance(pid, int) and pid > 0
+ }
+ for pid in list(protected_pids):
+ protected_pids.update(_descendant_pids(all_rows, pid, children))
+
+ # Protected rows stay in ``matches`` so the duplicate guard below can still
+ # see them: they are evidence that the session really is running more than
+ # one resume process. Dropping them here instead would let a keep_pid that
+ # has already left the process table hide a genuine orphan behind a single
+ # surviving owned replacement — one scoped match, guard satisfied, orphan
+ # left alive. Ownership decides what gets *signalled*, not what counts.
matches = [
row
for row in all_rows
@@ -388,27 +410,32 @@ async def reap_duplicate_claude_resume_processes(
keep_pid = keep_pid if isinstance(keep_pid, int) and keep_pid > 0 else None
scoped_matches = _same_runtime_rows(all_rows, matches, keep_pid=keep_pid)
- target_rows = [row for row in scoped_matches if row.pid != keep_pid]
if keep_pid is not None and len(scoped_matches) <= 1:
return 0
+ target_rows = [
+ row for row in scoped_matches if row.pid != keep_pid and row.pid not in protected_pids
+ ]
if not target_rows:
return 0
target_pids = {row.pid for row in target_rows}
for row in target_rows:
- target_pids.update(_descendant_pids(all_rows, row.pid))
+ target_pids.update(_descendant_pids(all_rows, row.pid, children))
target_pids.discard(os.getpid())
if keep_pid is not None:
target_pids.discard(keep_pid)
+ target_pids -= protected_pids
if not target_pids:
return 0
logger.warning(
- "Reaping %d duplicate Claude resume process(es) for native session %s (keep_pid=%s)",
+ "Reaping %d duplicate Claude resume process(es) for native session %s "
+ "(keep_pid=%s, owned_pids_protected=%d)",
len(target_pids),
native_session_id,
keep_pid,
+ len(protected_pids),
)
return await _reap_pid_set(target_pids, terminate_timeout=terminate_timeout, logger=logger)
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index 7dc521e68..ccb4b6791 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -1719,7 +1719,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
agent._remove_ack_reaction = AsyncMock()
agent.session_handler = SimpleNamespace(
handle_session_error=AsyncMock(
- side_effect=lambda *_args: settlement_order.append("handle")
+ side_effect=lambda *_args, **_kwargs: settlement_order.append("handle")
),
cleanup_session=AsyncMock(),
claude_error_diagnostic=lambda _key, _error: "Claude process terminated: SIGABRT",
@@ -1745,6 +1745,94 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("SIGABRT", terminal_call.kwargs["terminal_error"])
self.assertFalse(agent._pending_requests.get(composite_key))
+ async def test_receiver_eof_contained_teardown_skips_durable_failure_row(self):
+ """A contained teardown must stay silent on every surface.
+
+ ``handle_session_error`` only suppresses the IM send; the durable
+ ``notify`` row is what the web Chat renders, so a contained failure has
+ to skip that too or the containment is surface-specific.
+ """
+ controller = _StubController()
+ controller.emit_agent_message = AsyncMock()
+ controller._get_session_key = lambda context: "telegram::user::U1"
+ agent = ClaudeAgent(controller)
+ agent.record_model_hub_native_failure = AsyncMock()
+ composite_key = "session-eof-contained:/tmp/work"
+ pending_request = SimpleNamespace(
+ context=SimpleNamespace(
+ platform_specific={
+ "turn_token": "eof-turn",
+ "agent_runtime_turn_token": "eof-runtime",
+ }
+ ),
+ )
+ agent._pending_requests[composite_key] = [pending_request]
+ agent._remove_specific_pending_reaction = AsyncMock()
+ agent._remove_ack_reaction = AsyncMock()
+ agent.session_handler = SimpleNamespace(
+ handle_session_error=AsyncMock(return_value=True),
+ cleanup_session=AsyncMock(),
+ claude_error_diagnostic=lambda _key, _error: "Command failed with exit code -9",
+ )
+ controller.claude_sessions[composite_key] = SimpleNamespace(
+ _transport=SimpleNamespace(_process=SimpleNamespace(returncode=-9)),
+ )
+ controller.receiver_tasks[composite_key] = asyncio.current_task()
+
+ with patch("core.message_mirror.persist_agent_message") as persist:
+ await agent._handle_receiver_eof(composite_key, pending_request.context)
+
+ agent.session_handler.handle_session_error.assert_awaited_once()
+ persist.assert_not_called()
+
+ async def test_contained_teardown_records_no_model_hub_failure(self):
+ """Operational cleanup is not evidence about a Model Hub source.
+
+ ``record_model_hub_native_failure`` converts the pending attempt into a
+ failed one — ``unclassified_error`` for ``-9`` — and the silent result
+ can then settle that provenance as exhausted. Classifying the teardown
+ only after the recording has already run corrupts source health for a
+ process the service killed itself, so the probe has to come first.
+ """
+ controller = _StubController()
+ controller.emit_agent_message = AsyncMock()
+ controller._get_session_key = lambda context: "telegram::user::U1"
+ agent = ClaudeAgent(controller)
+ agent.record_model_hub_native_failure = AsyncMock()
+ composite_key = "session-eof-teardown:/tmp/work"
+ pending_request = SimpleNamespace(
+ context=SimpleNamespace(
+ platform_specific={
+ "turn_token": "eof-turn",
+ "agent_runtime_turn_token": "eof-runtime",
+ }
+ ),
+ )
+ agent._pending_requests[composite_key] = [pending_request]
+ agent._remove_specific_pending_reaction = AsyncMock()
+ agent._remove_ack_reaction = AsyncMock()
+ probed: list[object] = []
+
+ def _is_intentional(_key, _error, *, client=None):
+ probed.append(client)
+ return True
+
+ agent.session_handler = SimpleNamespace(
+ handle_session_error=AsyncMock(return_value=True),
+ claude_teardown_is_intentional=_is_intentional,
+ cleanup_session=AsyncMock(),
+ claude_error_diagnostic=lambda _key, _error: "Command failed with exit code -9",
+ )
+ client = SimpleNamespace(_transport=SimpleNamespace(_process=SimpleNamespace(returncode=-9)))
+ controller.claude_sessions[composite_key] = client
+ controller.receiver_tasks[composite_key] = asyncio.current_task()
+
+ await agent._handle_receiver_eof(composite_key, pending_request.context)
+
+ agent.record_model_hub_native_failure.assert_not_awaited()
+ # The exact client whose returncode was read, not a fresh lookup.
+ self.assertEqual(probed, [client])
+
async def test_receiver_eof_terminated_auth_adopts_turn_before_recovery(self):
controller = _StubController()
controller._get_session_key = lambda context: "telegram::user::U1"
diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.py
index 2afb2b0ec..5f7d83a6b 100644
--- a/tests/test_claude_cli_path.py
+++ b/tests/test_claude_cli_path.py
@@ -2592,8 +2592,17 @@ def test_evict_idle_sessions_reaps_native_resume_processes(monkeypatch, tmp_path
async def disconnect(self) -> None:
self.disconnects += 1
- async def fake_reap(native_session_id, *, keep_pid=None, cli_path=None, logger, terminate_timeout=2.0):
+ async def fake_reap(
+ native_session_id,
+ *,
+ keep_pid=None,
+ exclude_pids=None,
+ cli_path=None,
+ logger,
+ terminate_timeout=2.0,
+ ):
captured["reap_calls"].append((native_session_id, keep_pid, cli_path))
+ captured["exclude_pids"] = exclude_pids
return 2
monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
@@ -2616,3 +2625,274 @@ def test_evict_idle_sessions_reaps_native_resume_processes(monkeypatch, tmp_path
assert client.disconnects == 1
assert getattr(client, "_vibe_native_session_id") == "native-session-1"
assert captured["reap_calls"] == [("native-session-1", None, "/usr/local/bin/claude-proxy")]
+ # The evicted client is gone from the registry, so its own pid stays reapable.
+ assert captured["exclude_pids"] == set()
+
+
+def test_cleanup_defers_duplicate_reap_while_a_client_create_is_in_flight(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """An in-flight create owns a subprocess that is not yet registered.
+
+ Generation locks are per composite key, so another key can be inside
+ ``connect()`` for the same native resume id. Its pid cannot appear in
+ ``claude_sessions`` yet, so the reap must be deferred instead of running
+ against a knowingly incomplete owner set.
+ """
+ captured: dict[str, Any] = {"reap_calls": 0}
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ self.disconnects = 0
+ self._transport = type(
+ "Transport",
+ (),
+ {"_process": type("Process", (), {"pid": 4321})()},
+ )()
+
+ async def connect(self) -> None:
+ return None
+
+ async def disconnect(self) -> None:
+ self.disconnects += 1
+
+ async def fake_reap(*args, **kwargs):
+ captured["reap_calls"] += 1
+ return 0
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+ monkeypatch.setattr(session_handler_module, "reap_duplicate_claude_resume_processes", fake_reap)
+ monkeypatch.setattr(session_handler_module.time, "monotonic", lambda: 1000.0)
+
+ controller = _Controller(tmp_path)
+ handler = SessionHandler(controller)
+ context = MessageContext(user_id="U123", channel_id="C123")
+ client = _run_session(handler, context)
+ composite_key = f"slack_C123:{tmp_path}"
+ setattr(client, "_vibe_native_session_id", "native-session-1")
+ handler.claude_session_creates["slack_C999:other"] = object()
+
+ asyncio.run(handler.cleanup_session(composite_key))
+
+ assert captured["reap_calls"] == 0
+ assert client.disconnects == 1
+
+
+def test_evict_idle_sessions_protects_pids_of_other_live_sessions(monkeypatch, tmp_path: Path) -> None:
+ """The duplicate reap must never target a still-registered client's pid.
+
+ ``force_cleanup_stuck_active_session`` reaches cleanup without a receiver
+ task, so ``keep_pid`` is dropped and the reaper falls back to "kill every
+ process matching this native session id". Ownership of live pids is the
+ guard that survives that path.
+ """
+ captured: dict[str, Any] = {}
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ self.disconnects = 0
+ self._transport = type(
+ "Transport",
+ (),
+ {"_process": type("Process", (), {"pid": 4321})()},
+ )()
+
+ async def connect(self) -> None:
+ return None
+
+ async def disconnect(self) -> None:
+ self.disconnects += 1
+
+ async def fake_reap(
+ native_session_id,
+ *,
+ keep_pid=None,
+ exclude_pids=None,
+ cli_path=None,
+ logger,
+ terminate_timeout=2.0,
+ ):
+ captured["exclude_pids"] = exclude_pids
+ return 0
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+ monkeypatch.setattr(session_handler_module, "reap_duplicate_claude_resume_processes", fake_reap)
+ monkeypatch.setattr(session_handler_module.time, "monotonic", lambda: 1000.0)
+
+ controller = _Controller(tmp_path)
+ handler = SessionHandler(controller)
+ context = MessageContext(user_id="U123", channel_id="C123")
+ client = _run_session(handler, context)
+ composite_key = f"slack_C123:{tmp_path}"
+ setattr(client, "_vibe_native_session_id", "native-session-1")
+
+ # A second live client resuming the same native session id, as created by
+ # the turn that follows a force eviction.
+ replacement = _StubClaudeSDKClient(None)
+ replacement._transport._process.pid = 9876
+ setattr(replacement, "_vibe_native_session_id", "native-session-1")
+ controller.claude_sessions["slack_C999:other"] = replacement
+
+ asyncio.run(handler.cleanup_session(composite_key))
+
+ assert captured["exclude_pids"] == {9876}
+
+
+def test_cleanup_defers_duplicate_reap_when_a_live_client_pid_is_unresolved(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """An owner whose pid cannot be read still owns its process.
+
+ ``_live_claude_client_pids`` can only name the pids it can resolve. If a
+ registered client is not among them the exclusion set is knowingly partial,
+ and running the process-table scan against it can select that live client's
+ process. ``reap_orphaned_claude_sessions`` already defers on the same
+ signal; duplicate cleanup must not treat a partial set as authoritative.
+ """
+ captured: dict[str, Any] = {"reap_calls": 0}
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ self.disconnects = 0
+ self._transport = type(
+ "Transport",
+ (),
+ {"_process": type("Process", (), {"pid": 4321})()},
+ )()
+
+ async def connect(self) -> None:
+ return None
+
+ async def disconnect(self) -> None:
+ self.disconnects += 1
+
+ async def fake_reap(*args, **kwargs):
+ captured["reap_calls"] += 1
+ return 0
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+ monkeypatch.setattr(session_handler_module, "reap_duplicate_claude_resume_processes", fake_reap)
+ monkeypatch.setattr(session_handler_module.time, "monotonic", lambda: 1000.0)
+
+ controller = _Controller(tmp_path)
+ handler = SessionHandler(controller)
+ context = MessageContext(user_id="U123", channel_id="C123")
+ client = _run_session(handler, context)
+ composite_key = f"slack_C123:{tmp_path}"
+ setattr(client, "_vibe_native_session_id", "native-session-1")
+
+ # Registered, live, and resuming the same native id — but its pid cannot be
+ # resolved, so it cannot be named in ``exclude_pids``.
+ replacement = _StubClaudeSDKClient(None)
+ replacement._transport._process.pid = None
+ setattr(replacement, "_vibe_native_session_id", "native-session-1")
+ controller.claude_sessions["slack_C999:other"] = replacement
+
+ asyncio.run(handler.cleanup_session(composite_key))
+
+ assert captured["reap_calls"] == 0
+ assert client.disconnects == 1
+
+
+def test_cleanup_skips_a_generation_a_replacement_already_took_over(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """Containing a stale teardown must not become a second teardown.
+
+ ``cleanup_session`` resolves the composite key again under the generation
+ lock. A caller acting on a client that has since been replaced would
+ otherwise disconnect the healthy replacement that now owns the key.
+ """
+ captured: dict[str, Any] = {"reap_calls": 0}
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ self.disconnects = 0
+ self._transport = type(
+ "Transport",
+ (),
+ {"_process": type("Process", (), {"pid": 4321})()},
+ )()
+
+ async def connect(self) -> None:
+ return None
+
+ async def disconnect(self) -> None:
+ self.disconnects += 1
+
+ async def fake_reap(*args, **kwargs):
+ captured["reap_calls"] += 1
+ return 0
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+ monkeypatch.setattr(session_handler_module, "reap_duplicate_claude_resume_processes", fake_reap)
+ monkeypatch.setattr(session_handler_module.time, "monotonic", lambda: 1000.0)
+
+ controller = _Controller(tmp_path)
+ handler = SessionHandler(controller)
+ context = MessageContext(user_id="U123", channel_id="C123")
+ superseded = _run_session(handler, context)
+ composite_key = f"slack_C123:{tmp_path}"
+ setattr(superseded, "_vibe_native_session_id", "native-session-1")
+
+ # A newer turn registered its own client under the same key.
+ replacement = _StubClaudeSDKClient(None)
+ setattr(replacement, "_vibe_native_session_id", "native-session-1")
+ controller.claude_sessions[composite_key] = replacement
+
+ asyncio.run(handler.cleanup_session(composite_key, expected_client=superseded))
+
+ assert replacement.disconnects == 0
+ assert superseded.disconnects == 0
+ assert captured["reap_calls"] == 0
+ assert controller.claude_sessions[composite_key] is replacement
+
+
+def test_cleanup_records_no_teardown_intent_for_an_empty_key(monkeypatch, tmp_path: Path) -> None:
+ """No generation retired means nothing to explain later.
+
+ A marker left on an already-empty key opens a 120s window in which the NEXT
+ client's genuine ``-9`` — dying inside ``connect()``, before registration
+ can clear the record — is suppressed as a service teardown.
+ """
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module.time, "monotonic", lambda: 1000.0)
+
+ controller = _Controller(tmp_path)
+ handler = SessionHandler(controller)
+ composite_key = f"slack_C123:{tmp_path}"
+
+ asyncio.run(handler.cleanup_session(composite_key))
+
+ assert composite_key not in handler.claude_intentional_teardowns
+
+
+def test_tracking_a_create_retires_the_previous_teardown_record(monkeypatch, tmp_path: Path) -> None:
+ """The marker must not outlive the start of the replacement's creation.
+
+ A new generation that exits ``-9`` inside ``connect()`` never registers, so
+ its failure is reported with ``client=None``. Clearing only at registration
+ would leave the previous teardown's key-level marker standing to classify
+ that genuine crash as our own cleanup and swallow the user-facing error.
+ """
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module.time, "monotonic", lambda: 1000.0)
+
+ controller = _Controller(tmp_path)
+ handler = SessionHandler(controller)
+ composite_key = f"slack_C123:{tmp_path}"
+ handler.claude_intentional_teardowns[composite_key] = 1000.0
+
+ async def scenario() -> bool:
+ handler._track_claude_session_create(composite_key)
+ # No client was ever handed back, so the caller has none to pass.
+ return handler.claude_teardown_is_intentional(
+ composite_key, RuntimeError("Claude Code process exited with exit code: -9")
+ )
+
+ assert asyncio.run(scenario()) is False
+ assert composite_key not in handler.claude_intentional_teardowns
diff --git a/tests/test_claude_process_reaper.py b/tests/test_claude_process_reaper.py
index 560a17148..def8f2cc5 100644
--- a/tests/test_claude_process_reaper.py
+++ b/tests/test_claude_process_reaper.py
@@ -168,6 +168,119 @@ def test_reap_duplicate_claude_resume_processes_reaps_scoped_orphan_without_keep
assert all(pid != 300 for pid, _ in signals)
+def test_reap_duplicate_claude_resume_processes_spares_owned_replacement(monkeypatch):
+ """A live client resuming the same native id must survive keep_pid=None.
+
+ Regression for the idle-eviction race: force cleanup passes keep_pid=None,
+ so without exclude_pids the reaper kills the healthy replacement client
+ (and its helpers) that took over the session during the slow disconnect.
+ """
+ service_pid = os.getpid()
+ table = "\n".join(
+ [
+ f"{service_pid} 1 python service_main.py",
+ f"100 {service_pid} /usr/local/bin/claude --resume sess-1 --model opus",
+ f"400 {service_pid} /usr/local/bin/claude --resume sess-1 --model opus",
+ "401 400 node helper.js",
+ ]
+ )
+ signals = []
+ alive = {100, 400, 401}
+
+ def fake_kill(pid, sig):
+ if sig == 0:
+ if pid not in alive:
+ raise ProcessLookupError
+ return
+ signals.append((pid, sig))
+ alive.discard(pid)
+
+ monkeypatch.setattr(claude_process_reaper, "_run_ps", lambda: table)
+ monkeypatch.setattr(claude_process_reaper.os, "kill", fake_kill)
+
+ reaped = asyncio.run(
+ claude_process_reaper.reap_duplicate_claude_resume_processes(
+ "sess-1",
+ keep_pid=None,
+ exclude_pids={400},
+ logger=logging.getLogger("test.claude_reaper"),
+ )
+ )
+
+ assert reaped == 1
+ assert (100, signal.SIGTERM) in signals
+ assert all(pid not in (400, 401) for pid, _ in signals)
+
+
+def test_reap_duplicate_claude_resume_processes_skips_when_all_matches_owned(monkeypatch):
+ service_pid = os.getpid()
+ table = "\n".join(
+ [
+ f"{service_pid} 1 python service_main.py",
+ f"400 {service_pid} /usr/local/bin/claude --resume sess-1 --model opus",
+ ]
+ )
+ signals = []
+ monkeypatch.setattr(claude_process_reaper, "_run_ps", lambda: table)
+ monkeypatch.setattr(claude_process_reaper.os, "kill", lambda pid, sig: signals.append((pid, sig)))
+
+ reaped = asyncio.run(
+ claude_process_reaper.reap_duplicate_claude_resume_processes(
+ "sess-1",
+ keep_pid=None,
+ exclude_pids={400},
+ logger=logging.getLogger("test.claude_reaper"),
+ )
+ )
+
+ assert reaped == 0
+ assert signals == []
+
+
+def test_reap_duplicate_claude_resume_processes_counts_owned_matches_in_the_guard(monkeypatch):
+ """A departed keep_pid must not hide an orphan behind an owned replacement.
+
+ Receiver-side cleanup keeps a non-null keep_pid, but that process can be
+ gone from the table by the time the scan runs. With an owned replacement
+ and an orphan both resuming the session, filtering the replacement out
+ before the duplicate guard leaves one scoped match and spares the orphan.
+ """
+ service_pid = os.getpid()
+ table = "\n".join(
+ [
+ f"{service_pid} 1 python service_main.py",
+ f"100 {service_pid} /usr/local/bin/claude --resume sess-1 --model opus",
+ f"400 {service_pid} /usr/local/bin/claude --resume sess-1 --model opus",
+ ]
+ )
+ signals = []
+ alive = {100, 400}
+
+ def fake_kill(pid, sig):
+ if sig == 0:
+ if pid not in alive:
+ raise ProcessLookupError
+ return
+ signals.append((pid, sig))
+ alive.discard(pid)
+
+ monkeypatch.setattr(claude_process_reaper, "_run_ps", lambda: table)
+ monkeypatch.setattr(claude_process_reaper.os, "kill", fake_kill)
+
+ reaped = asyncio.run(
+ claude_process_reaper.reap_duplicate_claude_resume_processes(
+ "sess-1",
+ keep_pid=999,
+ exclude_pids={400},
+ logger=logging.getLogger("test.claude_reaper"),
+ )
+ )
+
+ assert reaped == 1
+ assert (100, signal.SIGTERM) in signals
+ assert all(pid != 400 for pid, _ in signals)
+
+
def test_reap_duplicate_claude_resume_processes_ignores_unrelated_unique_match(monkeypatch):
service_pid = os.getpid()
monkeypatch.setattr(
diff --git a/tests/test_session_handler_base_id.py b/tests/test_session_handler_base_id.py
index 3bc0767e7..fe4f5f9d7 100644
--- a/tests/test_session_handler_base_id.py
+++ b/tests/test_session_handler_base_id.py
@@ -418,7 +418,7 @@ def test_claude_terminated_process_cleans_up_and_reports_signal_diagnostic() ->
)
cleanup_calls = []
- async def _cleanup_session(key: str, *, current_receiver_task=None) -> None:
+ async def _cleanup_session(key: str, *, current_receiver_task=None, expected_client=None) -> None:
cleanup_calls.append((key, current_receiver_task))
handler.cleanup_session = _cleanup_session
@@ -446,3 +446,234 @@ def test_claude_terminated_process_cleans_up_and_reports_signal_diagnostic() ->
)
assert "Claude process terminated: SIGABRT (signal 6)" in diagnostic
assert "Claude stderr tail:\nfatal: Claude CLI aborted\ntransport closed" in diagnostic
+
+
+def test_service_initiated_teardown_signal_is_not_reported_as_session_error() -> None:
+ """A SIGKILL the service issued itself must not read as a backend crash.
+
+ Cleanup escalates SIGTERM to SIGKILL, so the SDK surfaces ``exit code -9``
+ for a process Avibe terminated deliberately. Without this containment the
+ failure falls through to the generic branch and the user is told the
+ session failed for an unknown reason.
+ """
+ controller = _Controller(platform="slack", dm_threads=False)
+ controller.im_client = _FakeIM()
+ handler = SessionHandler(controller)
+ 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)
+
+ handler.cleanup_session = _cleanup_session
+ handler._mark_claude_teardown_intentional(composite_key, None)
+ context = MessageContext(user_id="U123", channel_id="C123", platform="slack")
+
+ asyncio.run(
+ handler.handle_session_error(
+ composite_key,
+ context,
+ RuntimeError("Command failed with exit code -9"),
+ )
+ )
+
+ assert cleanup_calls == [composite_key]
+ assert controller.im_client.sent_messages == []
+
+
+def test_teardown_intent_does_not_suppress_errors_from_the_next_generation() -> None:
+ controller = _Controller(platform="slack", dm_threads=False)
+ controller.im_client = _FakeIM()
+ handler = SessionHandler(controller)
+ composite_key = "slack_C123:/tmp/workdir"
+
+ async def _cleanup_session(key: str, *, current_receiver_task=None, expected_client=None) -> None:
+ return None
+
+ handler.cleanup_session = _cleanup_session
+ handler._mark_claude_teardown_intentional(composite_key, None)
+ # A replacement client took the key, so the previous teardown says nothing
+ # about this failure.
+ handler._clear_claude_teardown_intent(composite_key)
+ context = MessageContext(user_id="U123", channel_id="C123", platform="slack")
+
+ asyncio.run(
+ handler.handle_session_error(
+ composite_key,
+ context,
+ RuntimeError("Command failed with exit code -9"),
+ )
+ )
+
+ assert len(controller.im_client.sent_messages) == 1
+ _, message = controller.im_client.sent_messages[0]
+ assert "Command failed with exit code -9" in message
+
+
+def test_unrelated_error_during_teardown_window_is_still_reported() -> None:
+ controller = _Controller(platform="slack", dm_threads=False)
+ controller.im_client = _FakeIM()
+ handler = SessionHandler(controller)
+ composite_key = "slack_C123:/tmp/workdir"
+
+ async def _cleanup_session(key: str, *, current_receiver_task=None, expected_client=None) -> None:
+ return None
+
+ handler.cleanup_session = _cleanup_session
+ handler._mark_claude_teardown_intentional(composite_key, None)
+ context = MessageContext(user_id="U123", channel_id="C123", platform="slack")
+
+ asyncio.run(
+ handler.handle_session_error(
+ composite_key,
+ context,
+ RuntimeError("Command failed with exit code 1"),
+ )
+ )
+
+ assert len(controller.im_client.sent_messages) == 1
+
+
+def test_client_teardown_marker_suppresses_signal_error_without_key_record() -> None:
+ """A client the service marked for teardown is authoritative on its own.
+
+ The per-key record is dropped when a replacement client registers, but the
+ marked client object still identifies exactly which generation was killed
+ deliberately.
+ """
+ controller = _Controller(platform="slack", dm_threads=False)
+ controller.im_client = _FakeIM()
+ handler = SessionHandler(controller)
+ composite_key = "slack_C123:/tmp/workdir"
+ client = SimpleNamespace(
+ _transport=SimpleNamespace(_process=SimpleNamespace(returncode=-9)),
+ _vibe_intentional_teardown=True,
+ )
+ controller.claude_sessions[composite_key] = client
+
+ async def _cleanup_session(key: str, *, current_receiver_task=None, expected_client=None) -> None:
+ return None
+
+ handler.cleanup_session = _cleanup_session
+ handler._clear_claude_teardown_intent(composite_key)
+ context = MessageContext(user_id="U123", channel_id="C123", platform="slack")
+
+ asyncio.run(
+ handler.handle_session_error(
+ composite_key,
+ context,
+ RuntimeError("Command failed with exit code -9"),
+ )
+ )
+
+ assert controller.im_client.sent_messages == []
+
+
+def test_teardown_containment_matches_colon_delimited_exit_code() -> None:
+ """The SDK reports write failures as ``(exit code: -9)``.
+
+ Once cleanup has popped the client there is no returncode to read, so the
+ message text is the only signal and both SDK spellings must match.
+ """
+ controller = _Controller(platform="slack", dm_threads=False)
+ controller.im_client = _FakeIM()
+ handler = SessionHandler(controller)
+ composite_key = "slack_C123:/tmp/workdir"
+
+ async def _cleanup_session(key: str, *, current_receiver_task=None, expected_client=None) -> None:
+ return None
+
+ handler.cleanup_session = _cleanup_session
+ handler._mark_claude_teardown_intentional(composite_key, None)
+ context = MessageContext(user_id="U123", channel_id="C123", platform="slack")
+
+ contained = asyncio.run(
+ handler.handle_session_error(
+ composite_key,
+ context,
+ RuntimeError("Cannot write to terminated process (exit code: -9)"),
+ )
+ )
+
+ assert contained is True
+ assert controller.im_client.sent_messages == []
+
+
+def test_reported_session_errors_are_not_marked_contained() -> None:
+ controller = _Controller(platform="slack", dm_threads=False)
+ controller.im_client = _FakeIM()
+ handler = SessionHandler(controller)
+ context = MessageContext(user_id="U123", channel_id="C123", platform="slack")
+
+ contained = asyncio.run(
+ handler.handle_session_error(
+ "slack_C123:/tmp/workdir",
+ context,
+ RuntimeError("boom"),
+ )
+ )
+
+ assert contained is False
+ assert len(controller.im_client.sent_messages) == 1
+
+
+def test_old_generation_teardown_is_contained_after_a_replacement_registers() -> None:
+ """The caller's own client decides, not whatever now holds the key.
+
+ A query from the torn-down generation can reach the handler after a
+ replacement has registered and cleared the key record. The old client was
+ already popped from ``claude_sessions``, so re-reading the map here would
+ classify the delayed ``-9`` against the healthy replacement and report a
+ deliberate teardown as a genuine backend failure.
+ """
+ controller = _Controller(platform="slack", dm_threads=False)
+ controller.im_client = _FakeIM()
+ handler = SessionHandler(controller)
+ composite_key = "slack_C123:/tmp/workdir"
+ torn_down = SimpleNamespace(
+ _transport=SimpleNamespace(_process=SimpleNamespace(returncode=-9)),
+ _vibe_intentional_teardown=True,
+ )
+ replacement = SimpleNamespace(
+ _transport=SimpleNamespace(_process=SimpleNamespace(returncode=None)),
+ )
+ controller.claude_sessions[composite_key] = replacement
+
+ async def _cleanup_session(key: str, *, current_receiver_task=None, expected_client=None) -> None:
+ return None
+
+ handler.cleanup_session = _cleanup_session
+ handler._clear_claude_teardown_intent(composite_key)
+ context = MessageContext(user_id="U123", channel_id="C123", platform="slack")
+
+ contained = asyncio.run(
+ handler.handle_session_error(
+ composite_key,
+ context,
+ RuntimeError("Command failed with exit code -9"),
+ client=torn_down,
+ )
+ )
+
+ assert contained is True
+ assert controller.im_client.sent_messages == []
+
+
+def test_claude_teardown_is_intentional_probes_the_callers_client() -> None:
+ """The public probe answers before any backend-health evidence is recorded."""
+ controller = _Controller(platform="slack", dm_threads=False)
+ controller.im_client = _FakeIM()
+ handler = SessionHandler(controller)
+ composite_key = "slack_C123:/tmp/workdir"
+ torn_down = SimpleNamespace(
+ _transport=SimpleNamespace(_process=SimpleNamespace(returncode=-9)),
+ _vibe_intentional_teardown=True,
+ )
+ healthy = SimpleNamespace(_transport=SimpleNamespace(_process=SimpleNamespace(returncode=None)))
+ controller.claude_sessions[composite_key] = healthy
+ error = RuntimeError("Command failed with exit code -9")
+
+ assert handler.claude_teardown_is_intentional(composite_key, error, client=torn_down) is True
+ assert handler.claude_teardown_is_intentional(composite_key, error, client=healthy) is False
+ # No client named and nothing marked: an ordinary failure, not a teardown.
+ assert handler.claude_teardown_is_intentional(composite_key, error) is False
diff --git a/tests/test_vault_cli.py b/tests/test_vault_cli.py
index c23b9b098..9dfe65e71 100644
--- a/tests/test_vault_cli.py
+++ b/tests/test_vault_cli.py
@@ -114,8 +114,14 @@ def _set_protected_grant(name: str, *, session_id: str | None = None, purpose: s
return _grant_from_request(conn, req, session_id=session_id)
+APPROVAL_POLL_TIMEOUT = 30.0
+
+
def _approve_next_pending_access_request(*, session_id: str | None = None, purpose: str = "run") -> dict:
- deadline = time.monotonic() + 2
+ # Generous: the loop returns as soon as the request appears, so the only
+ # thing this bounds is how long a genuinely broken run hangs. A tight
+ # budget raced the CLI's own approval wait and flaked on loaded runners.
+ deadline = time.monotonic() + APPROVAL_POLL_TIMEOUT
while time.monotonic() < deadline:
with cli._open_vault_engine().begin() as conn:
requests = []
@@ -1051,9 +1057,9 @@ def test_run_waits_for_protected_approval_then_delivers(tmp_path, capfd, monkeyp
monkeypatch.setattr(api, "avault_deliver_run", Mock())
code = cli.cmd_vault_run(
- _ns(env=["PROTECTED_KEY"], command_argv=["python3", "-c", "pass"], session_id="ses_cli", approval_wait=2)
+ _ns(env=["PROTECTED_KEY"], command_argv=["python3", "-c", "pass"], session_id="ses_cli", approval_wait=APPROVAL_POLL_TIMEOUT)
)
- approver.join(timeout=2)
+ approver.join(timeout=APPROVAL_POLL_TIMEOUT)
captured = capfd.readouterr()
assert code == 0
diff --git a/tests/test_vault_fetch.py b/tests/test_vault_fetch.py
index bb5f7a9db..42d4c5043 100644
--- a/tests/test_vault_fetch.py
+++ b/tests/test_vault_fetch.py
@@ -102,8 +102,14 @@ def _set_protected_grant(name: str, *, allow_host: list[str], session_id: str |
return _grant_from_request(conn, req, session_id=session_id)
+APPROVAL_POLL_TIMEOUT = 30.0
+
+
def _approve_next_pending_access_request(*, session_id: str | None = None) -> dict:
- deadline = time.monotonic() + 2
+ # Generous: the loop returns as soon as the request appears, so the only
+ # thing this bounds is how long a genuinely broken run hangs. A tight
+ # budget raced the CLI's own approval wait and flaked on loaded runners.
+ deadline = time.monotonic() + APPROVAL_POLL_TIMEOUT
while time.monotonic() < deadline:
with cli._open_vault_engine().begin() as conn:
requests = []
@@ -258,9 +264,9 @@ def test_fetch_waits_for_protected_approval_then_delivers(capfd, monkeypatch):
monkeypatch.setattr(api, "avault_deliver_fetch", Mock())
code = cli.cmd_vault_fetch(
- _ns(auth="GH_PAT", url="https://api.github.com/repos/o/r", session_id="ses_cli", approval_wait=2)
+ _ns(auth="GH_PAT", url="https://api.github.com/repos/o/r", session_id="ses_cli", approval_wait=APPROVAL_POLL_TIMEOUT)
)
- approver.join(timeout=2)
+ approver.join(timeout=APPROVAL_POLL_TIMEOUT)
captured = capfd.readouterr()
assert code == 0