Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions app/agent_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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"}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: passing the phase dict into _boot_sequence works, but it's a workaround to share a mutable value. step()/mark() could set self._boot_phase and boot() could read it, which drops the extra parameter. Splitting out _boot_sequence to avoid re-indenting the body makes sense to me.

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.
Expand All @@ -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()
Expand All @@ -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)
Expand Down Expand Up @@ -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()
Expand Down
42 changes: 29 additions & 13 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -237,6 +239,10 @@ def _initial_settings() -> tuple:


async def main_async() -> None:
# Once per process, before anything can fail: the Python version and

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: "before anything can fail" isn't quite accurate. This module's top-level imports (runtime preflight, agent_core, AgentBase, SSL shims) all run before main_async. It is the right spot for the #224 case, which failed later during MCP startup, and it has to come after manager.py is imported to see the shim state. Maybe: "Once per process, as soon as the shim state is known: …"

# asyncio shim state are what an environment mismatch needs (#224).
log_runtime_info(logger)

# Parse command-line arguments
cli_args = _parse_cli_args()

Expand Down Expand Up @@ -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
Expand Down
65 changes: 65 additions & 0 deletions app/startup_diagnostics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# -*- coding: utf-8 -*-
"""
app.startup_diagnostics

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. 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"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Must fix. Two things:

  • manager.py installs two patches: the wait_for replacement, and the redirect of asyncio.current_task to _py_current_task (the one that fixed aiohttp and asyncio.timeout). Only the first is reported here, but the second is the one most likely to matter when debugging a 3.14 issue.
  • Matching on the name "_compat_wait_for" ties this module to a private function name in another package. If that function is renamed, this line silently says "inactive".

Suggestion: have manager.py record what it installed, e.g. WAIT_FOR_SHIM_INSTALLED and CURRENT_TASK_SHIM_INSTALLED flags set where each patch is applied. Read them here with sys.modules.get("agent_core.core.impl.action.manager") so this module stays import-free. A direct check also works for the second patch: asyncio.current_task is getattr(asyncio.tasks, "_py_current_task", None).

# 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

Comment on lines +53 to +60

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: no caller uses the log is None fallback (the only caller passes logger), and format_runtime_summary is only used here and in tests. These could collapse into a single log_runtime_info(log).


def format_exception_details(exc: BaseException) -> str:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cleanup: inside an except block, this does the same as traceback.format_exc(), which the codebase already uses in about 10 places. The only call site that really needs the explicit-exception form is _log_loop_exit. Also, now that app/triggers/runtime.py imports it, it isn't really a "startup" helper anymore. If we keep a helper, app/logger.py feels like the natural home. If diagnose gets turned off (summary point 2), this can go away in favour of logger.opt(exception=e).

"""Full traceback text for ``exc``, without local variable values."""
lines = traceback.format_exception(type(exc), exc, exc.__traceback__)
return "".join(lines).rstrip()
40 changes: 35 additions & 5 deletions app/triggers/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -27,6 +28,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:
Expand Down Expand Up @@ -472,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)}"
)
Comment on lines +494 to +503

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Must fix. This callback runs in the context of whoever called _ensure_loop, not the loop's own context, so the contextualize(session=...) inside _consume doesn't apply. If session A's turn dispatches into session B and B's loop crashes, "Loop for session B exited unexpectedly" goes into A's session.log. I confirmed this with a small loguru repro. Binding the session fixes it, because values set with bind() override contextualize():

Suggested change
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)}"
)
log = logger.bind(session=session_id) if hasattr(logger, "bind") else logger
if task.cancelled():
log.info(f"[SessionRuntime] Loop cancelled for session {session_id}")
return
exc = task.exception()
if exc is not None:
log.error(
f"[SessionRuntime] Loop for session {session_id} exited "
f"unexpectedly: {type(exc).__name__}: {exc}\n"
f"{format_exception_details(exc)}"
)

The hasattr guard is there because of the stdlib logging fallback at the top of this module.


async def _run_turn(self, session_id: str, trig: Trigger) -> None:
signal = self._stops.get(session_id)
Expand Down Expand Up @@ -602,10 +627,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)
Expand All @@ -615,9 +641,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:
Expand Down
Loading