Repository navigation
Add Phase 0 startup diagnostics for #224 #539
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: dev
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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, |
||
| # 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 | ||
|
|
||
| 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" | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Must fix. Two things:
Suggestion: have |
||
| # 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
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: no caller uses the |
||
|
|
||
| def format_exception_details(exc: BaseException) -> str: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Cleanup: inside an |
||
| """Full traceback text for ``exc``, without local variable values.""" | ||
| lines = traceback.format_exception(type(exc), exc, exc.__traceback__) | ||
| return "".join(lines).rstrip() | ||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -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 | ||||||||||||||||||||||||||||||||||||||||||||
|
|
@@ -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: | ||||||||||||||||||||||||||||||||||||||||||||
|
|
@@ -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
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Must fix. This callback runs in the context of whoever called
Suggested change
The |
||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||
| async def _run_turn(self, session_id: str, trig: Trigger) -> None: | ||||||||||||||||||||||||||||||||||||||||||||
| signal = self._stops.get(session_id) | ||||||||||||||||||||||||||||||||||||||||||||
|
|
@@ -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) | ||||||||||||||||||||||||||||||||||||||||||||
|
|
@@ -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: | ||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Optional: passing the
phasedict into_boot_sequenceworks, but it's a workaround to share a mutable value.step()/mark()could setself._boot_phaseandboot()could read it, which drops the extra parameter. Splitting out_boot_sequenceto avoid re-indenting the body makes sense to me.