From 16566115b81f86c9f2596b08edee7c278b3baaa4 Mon Sep 17 00:00:00 2001 From: Rohan Date: Sat, 21 Nov 2026 17:53:27 +0530 Subject: [PATCH 1/2] #224: keep session loop alive when a turn error has braces The session loop's turn-failure and stop-finalize handlers logged with loguru as logger.error(f"... {e}", exc_info=True). loguru does not accept exc_info; any keyword argument makes it str.format() the already interpolated message, so an error text containing braces (a dict repr, JSON) raised KeyError inside the except block. The loop task died before the rows were nacked, nothing was logged, and stop()/remove_session() later swallowed the exception -- the silent consumer failure #224 names. Log without keyword arguments and append the traceback rendered by the standard library. That keeps the frames and exception text but never local variable values, which the app's diagnose=True sinks would print (the turn's frames can hold an API key). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Rohan --- app/startup_diagnostics.py | 23 ++++ app/triggers/runtime.py | 14 ++- tests/test_startup_diagnostics.py | 200 ++++++++++++++++++++++++++++++ 3 files changed, 233 insertions(+), 4 deletions(-) create mode 100644 app/startup_diagnostics.py create mode 100644 tests/test_startup_diagnostics.py diff --git a/app/startup_diagnostics.py b/app/startup_diagnostics.py new file mode 100644 index 00000000..fe935bfe --- /dev/null +++ b/app/startup_diagnostics.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +""" +app.startup_diagnostics + +Small, dependency-free helpers for diagnostics (issue #224, Phase 0). + +Secret hygiene: the app's loguru sinks use ``diagnose=True``, which prints +the values of local variables in a logged traceback. Passing an exception to +loguru (``logger.exception`` / ``opt(exception=...)``) from a frame that +holds an API key would therefore write the key into the log. These helpers +render tracebacks with the standard library instead, which shows code lines +only, never variable values. +""" + +from __future__ import annotations + +import traceback + + +def format_exception_details(exc: BaseException) -> str: + """Full traceback text for ``exc``, without local variable values.""" + lines = traceback.format_exception(type(exc), exc, exc.__traceback__) + return "".join(lines).rstrip() diff --git a/app/triggers/runtime.py b/app/triggers/runtime.py index 7b505fa7..fcb6d371 100644 --- a/app/triggers/runtime.py +++ b/app/triggers/runtime.py @@ -27,6 +27,7 @@ ) from agent_core.core.session import MAIN_SESSION_ID from agent_core.core.state.session import StateSession +from app.startup_diagnostics import format_exception_details from app.triggers.sources import TriggerSource if TYPE_CHECKING: @@ -602,10 +603,11 @@ async def _consume(self, session_id: str, queue: SessionTriggerQueue) -> None: if self._on_stopped: await self._on_stopped(session_id) except Exception as e: + # No logger kwargs: loguru would str.format() the + # message and raise on braces in the error text. logger.error( f"[SessionRuntime] Stop finalize failed for " - f"{session_id}: {e}", - exc_info=True, + f"{session_id}: {e}\n{format_exception_details(e)}" ) finally: self._stops.pop(session_id, None) @@ -615,9 +617,13 @@ async def _consume(self, session_id: str, queue: SessionTriggerQueue) -> None: # rehydration reclaims them (at-least-once delivery). raise except Exception as e: + # No logger kwargs: with any kwarg loguru str.format()s the + # message, so an error text containing braces (a dict + # repr, JSON) raised inside this handler and killed the + # loop before the rows were nacked. logger.error( - f"[SessionRuntime] Turn failed for {session_id}: {e}", - exc_info=True, + f"[SessionRuntime] Turn failed for {session_id}: {e}\n" + f"{format_exception_details(e)}" ) if self._service: for t in group: diff --git a/tests/test_startup_diagnostics.py b/tests/test_startup_diagnostics.py new file mode 100644 index 00000000..a09195b0 --- /dev/null +++ b/tests/test_startup_diagnostics.py @@ -0,0 +1,200 @@ +"""Session loop failure logging (issue #224, Phase 0). + +Covers the three Phase 0 items: the runtime summary logged once at startup, +boot success/failure brackets, and the session (trigger consumer) loop's +exits — including the regression where a turn error containing braces +crashed loguru inside the failure handler and killed the loop silently. + +No test sleeps for timing: loops are driven by events, and every wait has a +generous hang guard only. +""" + +from __future__ import annotations + +import asyncio +import time + +import pytest +from loguru import logger + +from agent_core.core.trigger import Trigger +from app.startup_diagnostics import format_exception_details +from app.triggers.runtime import SessionRuntimeManager + +SECRET = "sk-test-SENTINEL-0123456789" +HANG_GUARD_S = 10 + + +@pytest.fixture +def log_lines(): + """Capture loguru output synchronously (no enqueue) as plain text. + + diagnose/backtrace are on, as in the app's own sinks, so a test proves + that nothing reaching the log can expand local variable values. + """ + lines: list[str] = [] + sink = logger.add( + lambda m: lines.append(str(m)), + level="DEBUG", + format="{level}|{message}\n{exception}", + backtrace=True, + diagnose=True, + ) + try: + yield lines + finally: + logger.remove(sink) + + +def _joined(lines: list[str]) -> str: + return "\n".join(lines) + + +def _fail_holding_a_secret(): + api_key = SECRET # noqa: F841 — a local the traceback must not reveal + raise RuntimeError("provider rejected the request") + + +def test_exception_details_include_the_traceback_but_no_local_values(log_lines): + with pytest.raises(RuntimeError) as excinfo: + _fail_holding_a_secret() + text = format_exception_details(excinfo.value) + assert "Traceback (most recent call last)" in text + assert "_fail_holding_a_secret" in text + assert "RuntimeError: provider rejected the request" in text + assert SECRET not in text + + # Logged through a diagnose=True sink, as the app does: still no secret. + logger.error(f"failed: {text}") + assert SECRET not in _joined(log_lines) + + +class _Service: + """Minimal TriggerService stand-in recording settlement.""" + + def __init__(self, fail_claim: bool = False): + self.fail_claim = fail_claim + self.acked: list[str] = [] + self.nacked: list[tuple[str, str]] = [] + + def claim(self, trig): + if self.fail_claim: + raise RuntimeError("store unavailable") + + async def ack(self, trig): + self.acked.append(trig.next_action_description) + + async def nack(self, trig, error): + self.nacked.append((trig.next_action_description, error)) + + def on_evicted(self, *args): + pass + + +def _trigger(desc: str, session_id: str = "s1") -> Trigger: + return Trigger(time.time(), 1, desc, session_id=session_id, source="test") + + +def test_turn_error_with_braces_is_logged_nacked_and_the_loop_survives(log_lines): + """Regression: `exc_info=True` made loguru str.format() the message, so + an error text containing braces raised KeyError inside the handler — the + loop died, the rows were never nacked, and nothing was logged.""" + + async def scenario(): + done = asyncio.Event() + bad_started = asyncio.Event() + ran: list[str] = [] + + async def react(trig): + ran.append(trig.next_action_description) + if trig.next_action_description == "bad": + bad_started.set() + raise RuntimeError("bad {'id': 1}") + done.set() + + runtime = SessionRuntimeManager(react) + service = _Service() + runtime.bind_service(service) + await runtime.start() + await runtime.dispatch(_trigger("bad")) + # Dispatch the second trigger only once the first is claimed, so the + # two are not aggregated into one turn. + await asyncio.wait_for(bad_started.wait(), HANG_GUARD_S) + await runtime.dispatch(_trigger("good")) + await asyncio.wait_for(done.wait(), HANG_GUARD_S) + loop_alive = not runtime._loops["s1"].done() + await runtime.stop() + return ran, service, loop_alive + + ran, service, loop_alive = asyncio.run(scenario()) + assert ran == ["bad", "good"] + assert loop_alive + assert [desc for desc, _ in service.nacked] == ["bad"] + assert service.acked == ["good"] + + failed = [line for line in log_lines if "Turn failed for s1" in line] + assert len(failed) == 1 + assert "bad {'id': 1}" in failed[0] + assert "Traceback (most recent call last)" in failed[0] + assert "exited unexpectedly" not in _joined(log_lines) + + +def test_stop_finalizer_error_with_braces_is_logged_and_the_loop_survives( + log_lines, +): + """Regression: the force-stop path's finalize-failure log had the same + `exc_info=True` + f-string bug. A finalizer error containing braces + raised KeyError inside the handler and killed the session loop, so the + next trigger for that session never ran.""" + + async def scenario(): + in_turn = asyncio.Event() + after_ran = asyncio.Event() + ran: list[str] = [] + + async def react(trig): + ran.append(trig.next_action_description) + if trig.next_action_description == "after": + after_ran.set() + return + in_turn.set() + await asyncio.Event().wait() # runs until the stop cancels it + + async def failing_finalizer(session_id): + api_key = SECRET # noqa: F841 — must not reach the log + raise RuntimeError("finalize {'k': 1}") + + runtime = SessionRuntimeManager(react) + service = _Service() + runtime.bind_service(service) + runtime.set_stop_finalizer(failing_finalizer) + await runtime.start() + await runtime.dispatch(_trigger("long")) + await asyncio.wait_for(in_turn.wait(), HANG_GUARD_S) + + # Returns once the stop has fully settled (finalizer included). + stopped = await asyncio.wait_for(runtime.request_stop("s1"), HANG_GUARD_S) + loop_alive_after_stop = not runtime._loops["s1"].done() + + await runtime.dispatch(_trigger("after")) + await asyncio.wait_for(after_ran.wait(), HANG_GUARD_S) + await runtime.stop() + return stopped, loop_alive_after_stop, ran, service + + stopped, loop_alive, ran, service = asyncio.run(scenario()) + assert stopped is True + assert loop_alive + assert ran == ["long", "after"] + # A user stop acks the stopped turn's rows; the next turn acks normally. + assert service.acked == ["long", "after"] + assert service.nacked == [] + + text = _joined(log_lines) + failed = [line for line in log_lines if "Stop finalize failed for s1" in line] + assert len(failed) == 1 + assert failed[0].startswith("ERROR|") + assert "finalize {'k': 1}" in failed[0] + assert "Traceback (most recent call last)" in failed[0] + assert "failing_finalizer" in failed[0] + assert "exited unexpectedly" not in text + assert SECRET not in text From 52b82255c47e7ef1150157eaef658545864d2088 Mon Sep 17 00:00:00 2001 From: Rohan Date: Sat, 21 Nov 2026 17:53:46 +0530 Subject: [PATCH 2/2] #224: log runtime info, boot phases and session loop exits Phase 0 diagnostics: an environment mismatch (Python 3.14 vs nest_asyncio) broke startup with no clear signal in the logs. - Log one runtime line at startup: Python version and implementation, OS, architecture, and whether the asyncio wait_for shim and nest_asyncio are active. No env vars, paths, user or host names. - Bracket boot(): log start, finish with elapsed time, or the phase an escaping exception came from, then re-raise. Components keep their own success/failure logs; nothing is duplicated. - Log AgentBase construction failures, which reached stderr only. - Log session loops that end by cancellation or an unexpected exception; stop()/remove_session() swallow those when they await the task. A normal exit already logs "Loop ended". Tracebacks use the stdlib renderer so diagnose=True sinks never print local values such as the API key held by main_async. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Rohan --- app/agent_base.py | 29 +++ app/main.py | 42 ++-- app/startup_diagnostics.py | 46 ++++- app/triggers/runtime.py | 26 ++- tests/test_startup_diagnostics.py | 316 +++++++++++++++++++++++++++++- 5 files changed, 441 insertions(+), 18 deletions(-) diff --git a/app/agent_base.py b/app/agent_base.py index e7ef9fb6..9e0fd7e0 100644 --- a/app/agent_base.py +++ b/app/agent_base.py @@ -85,6 +85,7 @@ from app.video_gen_interface import VideoGenInterface from app.database_interface import DatabaseInterface from app.logger import logger +from app.startup_diagnostics import format_exception_details from agent_core import ( MemoryManager, MemoryFileWatcher, @@ -4319,8 +4320,33 @@ async def boot(self, *, verbose: bool = True) -> None: (the same format ``app/main.py`` shows on app launch). Tests pass False to keep output clean. """ + # Each component logs its own result; this brackets the whole + # sequence so a log shows whether boot finished, and names the phase + # an escaping exception came from. The exception still propagates. + phase = {"name": "Initializing agent"} + started = time.monotonic() + logger.info("[BOOT] Boot sequence started") + try: + await self._boot_sequence(verbose=verbose, phase=phase) + except Exception as e: + logger.error( + f"[BOOT] Boot failed during '{phase['name']}' after " + f"{time.monotonic() - started:.2f}s: {type(e).__name__}: {e}\n" + f"{format_exception_details(e)}" + ) + raise + logger.info( + f"[BOOT] Boot sequence finished in {time.monotonic() - started:.2f}s" + ) + + async def _boot_sequence(self, *, verbose: bool, phase: dict) -> None: + """The steps of ``boot()``; ``phase['name']`` tracks the current one.""" + + def mark(name: str) -> None: + phase["name"] = name def step(step_num: int, total: int, message: str) -> None: + mark(message) if not verbose: return # Aligned with run.py's own steps 1-2, ending in a checkmark. @@ -4347,6 +4373,7 @@ def step(step_num: int, total: int, message: str) -> None: self.session_manager.restore_skill_instructions() # Start usage reporter background flush + mark("Starting background services") from app.usage import get_usage_reporter self._usage_reporter = get_usage_reporter() @@ -4365,6 +4392,7 @@ def step(step_num: int, total: int, message: str) -> None: # Process unprocessed events into memory at startup (if enabled) if PROCESS_MEMORY_AT_STARTUP: + mark("Processing memory") await self._process_memory_at_startup() # Initialize and start the scheduler (handles memory processing and other periodic tasks) @@ -4403,6 +4431,7 @@ def _on_dead_letter(trig, _error: str) -> None: # Rehydrate unfinished durable triggers from the previous run into # the per-session queues, then start the session loops. + mark("Starting session runtime") requeued = 0 try: requeued = await self.trigger_service.rehydrate() diff --git a/app/main.py b/app/main.py index d18718ee..7bac7910 100644 --- a/app/main.py +++ b/app/main.py @@ -171,6 +171,8 @@ def _safe_load_windows_store_certs(self, storename, purpose): get_image_gen_model, ) from app.agent_base import AgentBase +from app.logger import logger +from app.startup_diagnostics import format_exception_details, log_runtime_info def _parse_cli_args() -> dict: @@ -237,6 +239,10 @@ def _initial_settings() -> tuple: async def main_async() -> None: + # Once per process, before anything can fail: the Python version and + # asyncio shim state are what an environment mismatch needs (#224). + log_runtime_info(logger) + # Parse command-line arguments cli_args = _parse_cli_args() @@ -267,19 +273,29 @@ async def main_async() -> None: # Use deferred initialization if no valid API key is configured yet. # This lets the interface start so first-time users can configure settings. - agent = AgentBase( - data_dir="app/data", - chroma_path="./chroma_db", - llm_provider=provider, - llm_api_key=api_key, - llm_base_url=base_url, - llm_model=model, - vlm_provider=vlm_prov, - vlm_model=vlm_mod, - image_gen_provider=img_prov, - image_gen_model=img_mod, - deferred_init=not has_valid_key, - ) + try: + agent = AgentBase( + data_dir="app/data", + chroma_path="./chroma_db", + llm_provider=provider, + llm_api_key=api_key, + llm_base_url=base_url, + llm_model=model, + vlm_provider=vlm_prov, + vlm_model=vlm_mod, + image_gen_provider=img_prov, + image_gen_model=img_mod, + deferred_init=not has_valid_key, + ) + except Exception as e: + # The traceback otherwise reaches stderr only, never the log files. + # Rendered without locals: this frame holds the API key, and the + # loguru sinks' diagnose=True would print it. + logger.error( + f"[STARTUP] Agent construction failed: {type(e).__name__}: {e}\n" + f"{format_exception_details(e)}" + ) + raise # Initialize onboarding manager with agent reference from app.onboarding import onboarding_manager diff --git a/app/startup_diagnostics.py b/app/startup_diagnostics.py index fe935bfe..c50bad17 100644 --- a/app/startup_diagnostics.py +++ b/app/startup_diagnostics.py @@ -2,19 +2,61 @@ """ app.startup_diagnostics -Small, dependency-free helpers for diagnostics (issue #224, Phase 0). +Small, dependency-free helpers for startup and lifecycle diagnostics +(issue #224, Phase 0): the runtime summary logged once at startup, and the +traceback text used when a component or a session loop fails. Secret hygiene: the app's loguru sinks use ``diagnose=True``, which prints the values of local variables in a logged traceback. Passing an exception to loguru (``logger.exception`` / ``opt(exception=...)``) from a frame that holds an API key would therefore write the key into the log. These helpers render tracebacks with the standard library instead, which shows code lines -only, never variable values. +only, never variable values. The runtime summary reads no environment +variables, paths, user names or host names. """ from __future__ import annotations +import asyncio +import platform +import sys import traceback +from typing import Dict + + +def describe_runtime() -> Dict[str, str]: + """Return the facts needed to diagnose an environment mismatch. + + Read-only: it inspects state that is already set and never imports, + installs or applies anything. + """ + # Installed by agent_core/core/impl/action/manager.py on 3.11+. + shim_active = getattr(asyncio.wait_for, "__name__", "") == "_compat_wait_for" + # Set on the asyncio module by nest_asyncio.apply(). + nest_applied = bool(getattr(asyncio, "_nest_patched", False)) + return { + "python": platform.python_version(), + "implementation": platform.python_implementation(), + "os": f"{platform.system()} {platform.release()}".strip(), + "arch": platform.machine() or "unknown", + "frozen": "yes" if getattr(sys, "frozen", False) else "no", + "wait_for_shim": "active" if shim_active else "inactive", + "nest_asyncio": "applied" if nest_applied else "not applied", + } + + +def format_runtime_summary(info: Dict[str, str]) -> str: + """Render ``describe_runtime()`` as one log line.""" + return "[STARTUP] Runtime: " + ", ".join(f"{k}={v}" for k, v in info.items()) + + +def log_runtime_info(log=None) -> Dict[str, str]: + """Log the runtime summary once and return it.""" + if log is None: + from app.logger import logger as log + info = describe_runtime() + log.info(format_runtime_summary(info)) + return info def format_exception_details(exc: BaseException) -> str: diff --git a/app/triggers/runtime.py b/app/triggers/runtime.py index fcb6d371..b016e977 100644 --- a/app/triggers/runtime.py +++ b/app/triggers/runtime.py @@ -16,6 +16,7 @@ from __future__ import annotations import asyncio +import functools import logging from contextlib import nullcontext from typing import Awaitable, Callable, Dict, Optional, TYPE_CHECKING @@ -473,10 +474,33 @@ def _ensure_loop(self, session_id: str) -> None: if existing is not None and not existing.done(): return queue = self._ensure_queue(session_id) - self._loops[session_id] = asyncio.create_task( + task = asyncio.create_task( self._consume(session_id, queue), name=f"session-loop-{session_id}", ) + task.add_done_callback(functools.partial(self._log_loop_exit, session_id)) + self._loops[session_id] = task + + @staticmethod + def _log_loop_exit(session_id: str, task: asyncio.Task) -> None: + """Record why a session loop stopped. + + A normal exit already logs "Loop ended" from ``_consume``. The other + two exits used to leave no trace: a cancelled loop, and a loop killed + by an exception (which ``stop()``/``remove_session()`` swallow when + they await the task). The task outcome is only read here, so this + changes no behaviour. + """ + if task.cancelled(): + logger.info(f"[SessionRuntime] Loop cancelled for session {session_id}") + return + exc = task.exception() + if exc is not None: + logger.error( + f"[SessionRuntime] Loop for session {session_id} exited " + f"unexpectedly: {type(exc).__name__}: {exc}\n" + f"{format_exception_details(exc)}" + ) async def _run_turn(self, session_id: str, trig: Trigger) -> None: signal = self._stops.get(session_id) diff --git a/tests/test_startup_diagnostics.py b/tests/test_startup_diagnostics.py index a09195b0..aa0c7f58 100644 --- a/tests/test_startup_diagnostics.py +++ b/tests/test_startup_diagnostics.py @@ -1,4 +1,4 @@ -"""Session loop failure logging (issue #224, Phase 0). +"""Startup and lifecycle diagnostics (issue #224, Phase 0). Covers the three Phase 0 items: the runtime summary logged once at startup, boot success/failure brackets, and the session (trigger consumer) loop's @@ -12,15 +12,28 @@ from __future__ import annotations import asyncio +import os +import platform +import subprocess +import sys +import textwrap import time +from pathlib import Path +from types import SimpleNamespace import pytest from loguru import logger from agent_core.core.trigger import Trigger -from app.startup_diagnostics import format_exception_details +from app.startup_diagnostics import ( + describe_runtime, + format_exception_details, + format_runtime_summary, + log_runtime_info, +) from app.triggers.runtime import SessionRuntimeManager +PROJECT_ROOT = Path(__file__).resolve().parents[1] SECRET = "sk-test-SENTINEL-0123456789" HANG_GUARD_S = 10 @@ -50,6 +63,67 @@ def _joined(lines: list[str]) -> str: return "\n".join(lines) +# ───────────────────────── Runtime summary ────────────────────────────────── + + +def test_runtime_summary_reports_the_effective_python_version(): + info = describe_runtime() + assert info["python"] == platform.python_version() + assert info["implementation"] == platform.python_implementation() + assert set(info) == { + "python", + "implementation", + "os", + "arch", + "frozen", + "wait_for_shim", + "nest_asyncio", + } + + +def test_runtime_info_is_logged_once_as_one_line(log_lines): + log_runtime_info(logger) + startup = [line for line in log_lines if "[STARTUP] Runtime:" in line] + assert len(startup) == 1 + assert f"python={platform.python_version()}" in startup[0] + assert startup[0].startswith("INFO|") + + +def test_runtime_summary_reflects_shim_and_nest_asyncio_state(monkeypatch): + async def _compat_wait_for(fut, timeout): # same name the shim uses + return await fut + + monkeypatch.setattr(asyncio, "wait_for", _compat_wait_for) + monkeypatch.setattr(asyncio, "_nest_patched", True, raising=False) + info = describe_runtime() + assert info["wait_for_shim"] == "active" + assert info["nest_asyncio"] == "applied" + + async def wait_for(fut, timeout): + return await fut + + monkeypatch.setattr(asyncio, "wait_for", wait_for) + monkeypatch.delattr(asyncio, "_nest_patched", raising=False) + info = describe_runtime() + assert info["wait_for_shim"] == "inactive" + assert info["nest_asyncio"] == "not applied" + + +def test_runtime_summary_contains_no_environment_paths_or_identity(monkeypatch): + monkeypatch.setenv("CRAFTBOT_TEST_SECRET", SECRET) + summary = format_runtime_summary(describe_runtime()) + assert SECRET not in summary + assert sys.executable not in summary + assert sys.prefix not in summary + assert str(Path.home()) not in summary + node = platform.node() + if node: + assert node not in summary + + +# ───────────────────────── Exception rendering ────────────────────────────── + + def _fail_holding_a_secret(): api_key = SECRET # noqa: F841 — a local the traceback must not reveal raise RuntimeError("provider rejected the request") @@ -69,6 +143,81 @@ def test_exception_details_include_the_traceback_but_no_local_values(log_lines): assert SECRET not in _joined(log_lines) +# ───────────────────────── Boot brackets ──────────────────────────────────── + + +def _boot_stub(sequence): + from app.agent_base import AgentBase + + stub = SimpleNamespace(_boot_sequence=sequence) + return lambda **kw: AgentBase.boot(stub, **kw) + + +def test_boot_logs_start_and_finish_on_success(log_lines): + calls = [] + + async def sequence(*, verbose, phase): + calls.append(verbose) + + asyncio.run(_boot_stub(sequence)(verbose=False)) + text = _joined(log_lines) + assert calls == [False] + assert "[BOOT] Boot sequence started" in text + assert "[BOOT] Boot sequence finished in" in text + assert "[BOOT] Boot failed" not in text + + +def test_boot_failure_names_the_failing_component_and_propagates(log_lines): + """Runs the real _boot_sequence (only the components are stubbed), so its + step markers must feed the phase boot() reports. The component raises + from a frame holding a secret, with braces in its message.""" + from unittest.mock import AsyncMock + + from app.agent_base import AgentBase + + error = RuntimeError("mcp config unreadable {'path': 1}") + + async def failing_mcp(): + api_key = SECRET # noqa: F841 — must not reach the log + raise error + + stub = SimpleNamespace( + _initialize_config_watcher=AsyncMock(), + _initialize_mcp=AsyncMock(side_effect=failing_mcp), + ) + stub._boot_sequence = lambda **kw: AgentBase._boot_sequence(stub, **kw) + + with pytest.raises(RuntimeError) as excinfo: + asyncio.run(AgentBase.boot(stub, verbose=False)) + assert excinfo.value is error + stub._initialize_config_watcher.assert_awaited_once() + + text = _joined(log_lines) + failed = [line for line in log_lines if "[BOOT] Boot failed" in line] + assert len(failed) == 1 + assert failed[0].startswith("ERROR|") + assert "during 'Connecting to MCP servers'" in failed[0] + assert "RuntimeError: mcp config unreadable {'path': 1}" in failed[0] + assert "Traceback (most recent call last)" in failed[0] + assert "failing_mcp" in failed[0] + assert "[BOOT] Boot sequence finished" not in text + assert SECRET not in text + + +def test_boot_cancellation_propagates_without_a_failure_log(log_lines): + async def sequence(*, verbose, phase): + raise asyncio.CancelledError + + with pytest.raises(asyncio.CancelledError): + asyncio.run(_boot_stub(sequence)(verbose=False)) + text = _joined(log_lines) + assert "[BOOT] Boot failed" not in text + assert "[BOOT] Boot sequence finished" not in text + + +# ───────────────────────── Session (trigger consumer) loop ────────────────── + + class _Service: """Minimal TriggerService stand-in recording settlement.""" @@ -95,6 +244,13 @@ def _trigger(desc: str, session_id: str = "s1") -> Trigger: return Trigger(time.time(), 1, desc, session_id=session_id, source="test") +async def _settle_loop(task: asyncio.Task) -> None: + """Wait for a loop task to finish, then let its done-callbacks run.""" + await asyncio.wait({task}, timeout=HANG_GUARD_S) + assert task.done(), "session loop did not finish" + await asyncio.sleep(0) + + def test_turn_error_with_braces_is_logged_nacked_and_the_loop_survives(log_lines): """Regression: `exc_info=True` made loguru str.format() the message, so an error text containing braces raised KeyError inside the handler — the @@ -198,3 +354,159 @@ async def failing_finalizer(session_id): assert "failing_finalizer" in failed[0] assert "exited unexpectedly" not in text assert SECRET not in text + + +def test_normal_shutdown_logs_cancellation_and_no_crash(log_lines): + async def scenario(): + done = asyncio.Event() + + async def react(trig): + done.set() + + runtime = SessionRuntimeManager(react) + runtime.bind_service(_Service()) + await runtime.start() + await runtime.dispatch(_trigger("work")) + await asyncio.wait_for(done.wait(), HANG_GUARD_S) + task = runtime._loops["s1"] + await runtime.stop() + await asyncio.sleep(0) + return task + + task = asyncio.run(scenario()) + assert task.cancelled() + text = _joined(log_lines) + assert "[SessionRuntime] Loop started for session s1" in text + assert text.count("[SessionRuntime] Loop cancelled for session s1") == 1 + assert "exited unexpectedly" not in text + assert "[SessionRuntime] Stopped" in text + + +def test_removing_a_session_logs_its_loop_cancellation(log_lines): + async def scenario(): + done = asyncio.Event() + + async def react(trig): + done.set() + + runtime = SessionRuntimeManager(react) + await runtime.start() + await runtime.dispatch(_trigger("work", session_id="s2")) + await asyncio.wait_for(done.wait(), HANG_GUARD_S) + await runtime.remove_session("s2") + await asyncio.sleep(0) + await runtime.stop() + + asyncio.run(scenario()) + assert "[SessionRuntime] Loop cancelled for session s2" in _joined(log_lines) + + +def test_an_unexpected_loop_exception_is_logged_and_still_propagates(log_lines): + """claim() runs outside the turn's try: an error there ends the loop. It + used to vanish (stop() swallows it); it must now be logged, and the task + must still carry the original exception.""" + + async def scenario(): + async def react(trig): # never reached + raise AssertionError("turn should not run") + + runtime = SessionRuntimeManager(react) + runtime.bind_service(_Service(fail_claim=True)) + await runtime.start() + await runtime.dispatch(_trigger("work")) + task = runtime._loops["s1"] + await _settle_loop(task) + await runtime.stop() + return task + + task = asyncio.run(scenario()) + assert not task.cancelled() + assert isinstance(task.exception(), RuntimeError) + crashed = [line for line in log_lines if "exited unexpectedly" in line] + assert len(crashed) == 1 + assert crashed[0].startswith("ERROR|") + assert "Loop for session s1" in crashed[0] + assert "RuntimeError: store unavailable" in crashed[0] + assert "Traceback (most recent call last)" in crashed[0] + + +def test_a_crashed_loop_restarts_on_the_next_trigger(log_lines): + """Behaviour is unchanged by the logging: a dead loop is replaced on the + next dispatch, as before.""" + + async def scenario(): + done = asyncio.Event() + service = _Service(fail_claim=True) + + async def react(trig): + done.set() + + runtime = SessionRuntimeManager(react) + runtime.bind_service(service) + await runtime.start() + await runtime.dispatch(_trigger("first")) + await _settle_loop(runtime._loops["s1"]) + service.fail_claim = False + await runtime.dispatch(_trigger("second")) + await asyncio.wait_for(done.wait(), HANG_GUARD_S) + await runtime.stop() + return service + + service = asyncio.run(scenario()) + assert service.acked == ["second"] + + +# ───────────────────────── Entry point (subprocess) ───────────────────────── + +_MAIN_SCRIPT = textwrap.dedent( + """ + import asyncio, sys + import app.main as m + from loguru import logger + + logger.add(sys.stdout, level="DEBUG", format="{level}|{message}", + backtrace=True, diagnose=True) + + SECRET = sys.argv[1] + m._initial_settings = lambda: ( + "openai", SECRET, None, None, None, None, None, None, True + ) + m._parse_cli_args = lambda: {} + + class Boom(Exception): + pass + + def failing_agent(**kwargs): + raise Boom("constructor failed") + + m.AgentBase = failing_agent + try: + asyncio.run(m.main_async()) + except Boom: + print("PROPAGATED Boom") + """ +) + + +def test_main_logs_runtime_once_and_construction_failure_without_secrets(tmp_path): + """Run the real entry module in a child process: importing app.main has + process-wide side effects (warning filters, SSL shims) that must not leak + into this test session.""" + env = dict(os.environ, CRAFTBOT_HOME=str(tmp_path), PYTHONIOENCODING="utf-8") + result = subprocess.run( + [sys.executable, "-c", _MAIN_SCRIPT, SECRET], + cwd=PROJECT_ROOT, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=300, + ) + out = result.stdout + result.stderr + assert "PROPAGATED Boom" in result.stdout, out[-3000:] + assert result.stdout.count("[STARTUP] Runtime:") == 1 + assert f"python={platform.python_version()}" in result.stdout + assert "[STARTUP] Agent construction failed: Boom: constructor failed" in out + assert "Traceback (most recent call last)" in result.stdout + assert SECRET not in out