Skip to content

Add Phase 0 startup diagnostics for #224 - #539

Open
rohantiwari9573 wants to merge 2 commits into
CraftOS-dev:devfrom
rohantiwari9573:fix/issue-224-startup-diagnostics
Open

rohantiwari9573 wants to merge 2 commits into
CraftOS-dev:devfrom
rohantiwari9573:fix/issue-224-startup-diagnostics

Conversation

@rohantiwari9573

@rohantiwari9573 rohantiwari9573 commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Implements Phase 0 startup diagnostics for #224 and fixes two trigger-loop logging failures that could silently terminate session processing.

Changes

1. Trigger-loop logging reliability

  • Replaced unsafe exc_info=True usage in the affected error paths with safely rendered traceback details.
  • Fixed failures caused by exception messages containing braces.
  • Added regression tests for turn-failure and stop-finalization paths.
  • Ensured failed triggers follow the existing NACK and retry/dead-letter flow instead of silently terminating the session loop.

2. Startup diagnostics

  • Added Python runtime and compatibility-shim information at startup.
  • Added boot sequence start, completion and failure diagnostics.
  • Added session-loop cancellation and unexpected-exit logging.
  • Added construction-failure diagnostics without exposing local variable values or credentials.

Testing

Validated on Python 3.10.11 and Python 3.14.3:

  • 139 tests passed, 8 skipped on each version.
  • New diagnostic tests passed, including repeated runs.
  • Related trigger, session and MCP suites passed.
  • Ruff repository-wide checks passed.
  • Mypy results unchanged from baseline.
  • Compilation and git diff --check passed.

Scope

Limited to Phase 0 startup diagnostics and the directly related trigger-loop logging regression fix. No Phase 1 configuration architecture work is included.

This PR is part of #224; do not automatically close the issue on merge.

rohantiwari9573 and others added 2 commits November 21, 2026 18:48
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 CraftOS-dev#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 <noreply@anthropic.com>
Signed-off-by: Rohan <rohantiwari166@gmail.com>
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 <noreply@anthropic.com>
Signed-off-by: Rohan <rohantiwari166@gmail.com>
@rohantiwari9573
rohantiwari9573 force-pushed the fix/issue-224-startup-diagnostics branch from 20cef36 to 52b8225 Compare November 21, 2026 13:18
@rohantiwari9573
rohantiwari9573 marked this pull request as ready for review November 21, 2026 13:42

@ahmad-ajmal ahmad-ajmal left a comment

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.

Thanks for this. The diagnosis in the first commit is spot on. I reproduced it on loguru 0.7.3: logger.error(f"... {e}", exc_info=True) raises KeyError inside the handler when e contains braces. Also worth knowing: exc_info=True never produced a traceback under loguru. It just ends up in record["extra"], so these error lines never had tracebacks before this PR.

Two small things I'd like fixed before merge (inline):

  1. The loop-exit log goes to the wrong session's log file.
  2. The runtime line reports only one of the two asyncio shims, and finds it by function name.

Bigger-picture points. Happy to take these as follow-ups rather than block this PR:

1. The same bug is in 26 other places. exc_info= is still passed to loguru in 26 calls across 9 files:

  • app/agent_base.py ×9
  • browser_adapter.py ×7
  • ui_controller.py ×3
  • action/manager.py ×2
  • one each in router.py, llm/interface.py, vlm/interface.py, profile_bundle.py and task_attribution.py

They fail the same way. For example, "Error handling incoming message: {e}" in agent_base.py crashes its own handler when the error contains braces, and the incoming message is dropped. Two changes would close this for good:

  • A mechanical sweep to logger.opt(exception=e).error(...), or just dropping the keyword.
  • A small test that fails when exc_info= appears in a loguru module.

action_framework/loader.py and hooks/usage.py use stdlib logging, where exc_info is correct, so leave those two.

2. The secret-leak risk comes from diagnose=True. You're right to avoid logger.exception() here, but the helper only protects the new call sites. There are already 19 logger.exception(...) calls that write local variable values into the log files today. Turning diagnose off on the file sinks (app/logger.py, agent_core/utils/logger.py) would fix this everywhere. Then this PR could use loguru's normal logger.opt(exception=e) and drop format_exception_details. That's a maintainer decision, because we'd lose variable values in tracebacks, so no change is needed here. I'm just flagging that the helper isn't the root fix.

3. The loop can still die; it just dies loudly now. self._service.claim(t) (app/triggers/runtime.py L583) runs outside the turn's try, so an error in claim() still kills the loop. test_a_crashed_loop_restarts_on_the_next_trigger shows the result:

  • The trigger it picked up is stuck until restart.
  • The loop only comes back when another trigger arrives for that session.

Catching errors around each loop iteration would make silent consumer death impossible: log the error and continue, and re-raise only CancelledError. That beats fixing it one log call at a time.

Comment thread app/triggers/runtime.py
Comment on lines +494 to +503
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)}"
)

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.

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

return info


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

Comment on lines +53 to +60
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

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

Comment thread app/main.py


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: …"

Comment thread app/agent_base.py
# 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.

assert "[BOOT] Boot sequence finished" not in text


# ───────────────────────── Session (trigger consumer) loop ──────────────────

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.

Test organisation: the tests in this section are regression tests for SessionRuntimeManager, not startup diagnostics. Could they move next to the existing runtime tests in tests/test_session_clear.py, or into a new tests/test_session_runtime.py? Someone touching runtime.py is more likely to find them there.

)


def test_main_logs_runtime_once_and_construction_failure_without_secrets(tmp_path):

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.

Test cost: this test imports the whole app.main in a subprocess (dependency preflight, chromadb, etc.) with a 300 s timeout. It's by far the slowest test in the file, and mostly re-checks what the unit tests already cover. Given the import side effects you mention, I'd lean towards dropping it: the runtime line is covered above, and the construction-failure branch is 5 lines.

# ───────────────────────── Runtime summary ──────────────────────────────────


def test_runtime_summary_reports_the_effective_python_version():

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.

Low-value tests (this one and test_runtime_summary_contains_no_environment_paths_or_identity at L112):

  • This test checks the exact set of keys, so adding a field (like the current_task shim from the describe_runtime comment) breaks it for no real reason. Checking the keys we care about would be enough.
  • The L112 test checks that a function that never reads env vars or paths doesn't output them. I'd drop it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants