"""Tests for the server-log buffer, handler, and application lifecycle.""" from __future__ import annotations import asyncio import logging import subprocess import sys import textwrap import time import uuid from pathlib import Path import pytest from core import runlog as runlog_module from core.hub import Hub, UiSession from core.runlog import RunLog from core.storage import Storage def test_server_log_lifecycle_attaches_once_and_cleans_up(tmp_path): # Isolate global loggers and the application's storage from the live-server # session fixture used by the WebSocket integration tests. script = textwrap.dedent(""" import asyncio import logging import os import sqlite3 import sys os.environ["DB_PATH"] = sys.argv[1] import main async def check_lifecycle(): names = ("", "uvicorn", "uvicorn.error", "uvicorn.access") original_handlers = {name: list(logging.getLogger(name).handlers) for name in names} await main.startup() try: assert getattr(main, "log_queue", None) is not None, "startup must create the log queue" assert main.log_loop is asyncio.get_running_loop() task = main.log_broadcast_task assert task is not None and not task.done() main.attach_server_log_handler() for name in names: assert logging.getLogger(name).handlers.count(main.server_log_handler) == 1 entries = main.runlog.entries() assert any( entry["logger"] == "main" and entry["level"] == "INFO" and entry["message"].endswith(main.DB_PATH) for entry in entries ), "startup message must be captured" await asyncio.sleep(0) finally: await main.shutdown() assert task.cancelled() assert main.log_queue is None assert main.log_loop is None assert main.log_broadcast_task is None assert main.server_log_handler._publish is None assert main.hub._watchdog_task is None for name in names: assert logging.getLogger(name).handlers == original_handlers[name] before = main.runlog.entries() logging.getLogger("main").warning("after shutdown") assert main.runlog.entries() == before main.enqueue_server_log({"ts": 0, "level": "INFO", "logger": "late", "message": "late"}) try: main.storage.list_devices() except sqlite3.ProgrammingError: pass else: raise AssertionError("shutdown must close storage") asyncio.run(check_lifecycle()) """) result = subprocess.run( [sys.executable, "-c", script, str(tmp_path / "lifecycle.db")], cwd=Path(__file__).resolve().parents[1], capture_output=True, text=True, timeout=10, ) assert result.returncode == 0, result.stdout + result.stderr def run_app_check(tmp_path, body): """Keep process-global app resources separate from the live-server fixture.""" script = "import asyncio, json, logging, os, sys\n" script += 'os.environ["DB_PATH"] = sys.argv[1]\nimport main\n' script += textwrap.dedent(body) result = subprocess.run( [sys.executable, "-c", script, str(tmp_path / "app-check.db")], cwd=Path(__file__).resolve().parents[1], capture_output=True, text=True, timeout=15, ) assert result.returncode == 0, result.stdout + result.stderr def test_log_broadcast_suppresses_debug_transport_feedback_only(tmp_path): run_app_check(tmp_path, """ async def check(): await main.startup() entered, release = asyncio.Event(), asyncio.Event() sent = [] transport = logging.getLogger("uvicorn.error") transport.setLevel(logging.DEBUG) class Transport: async def send_text(self, raw): message = json.loads(raw) sent.append(message) if len(sent) == 1: entered.set() await release.wait() # Simulate DEBUG websocket frame diagnostics, including # callbacks and child tasks inheriting the send context. if len(sent) <= 4: transport.debug("outgoing frame %s", raw) asyncio.get_running_loop().call_soon( transport.debug, "deferred frame %s", raw ) async def child(): transport.debug("child frame %s", raw) await asyncio.create_task(child()) try: # Let the thread-safe enqueue callback run, then drain startup. await asyncio.sleep(0) await asyncio.wait_for(main.log_queue.join(), 1) main.hub.register_ui(main.UiSession(Transport(), "debug")) transport.debug("original record") await asyncio.wait_for(entered.wait(), 1) # An unrelated task must still be captured while send is paused. transport.debug("independent record") release.set() await asyncio.wait_for(main.log_queue.join(), 1) messages = [entry["message"] for entry in main.runlog.entries() if entry["logger"] == "uvicorn.error"] assert messages == ["original record", "independent record"], messages assert [event["payload"]["message"] for event in sent] == messages assert all(event["action"] == "event.log" for event in sent) finally: release.set() await main.shutdown() asyncio.run(check()) """) def test_log_queue_overflow_drops_oldest_without_callback_errors(tmp_path): run_app_check(tmp_path, """ async def check(): await main.startup() loop = asyncio.get_running_loop() errors = [] loop.set_exception_handler(lambda loop, context: errors.append(context)) try: main.log_broadcast_task.cancel() await asyncio.gather(main.log_broadcast_task, return_exceptions=True) queue = main.log_queue while not queue.empty(): queue.get_nowait() queue.task_done() entries = [dict(ts=i, level="INFO", logger="burst", message=str(i)) for i in range(510)] # Exercise the thread-safe enqueue path with the consumer paused. await asyncio.to_thread(lambda: [main.enqueue_server_log(e) for e in entries]) await asyncio.sleep(0) assert queue.qsize() == 500, queue.qsize() assert queue.maxsize == 500 pending = [] while not queue.empty(): pending.append(queue.get_nowait()) queue.task_done() assert pending == entries[-500:] await asyncio.wait_for(queue.join(), 1) assert errors == [], errors finally: await main.shutdown() loop.set_exception_handler(None) asyncio.run(check()) """) @pytest.mark.asyncio async def test_hub_broadcast_delivers_concurrently_without_timeout(tmp_path): storage = Storage(str(tmp_path / "hub.db")) hub = Hub(storage) release, delivered = asyncio.Event(), asyncio.Event() class Stalled: async def send_text(self, raw): await release.wait() class Healthy: async def send_text(self, raw): delivered.set() hub.register_ui(UiSession(Stalled(), "stalled")) hub.register_ui(UiSession(Healthy(), "healthy")) task = asyncio.create_task(hub.broadcast_to_ui({"action": "test"})) try: await asyncio.wait_for(delivered.wait(), 1) assert not task.done(), "default delivery must still await unfinished sessions" release.set() await asyncio.wait_for(task, 1) assert set(hub._ui_sessions) == {"stalled", "healthy"} finally: release.set() task.cancel() await asyncio.gather(task, return_exceptions=True) await hub.shutdown() storage.close() @pytest.mark.asyncio async def test_hub_broadcast_timeout_removes_stalled_and_failed_sessions(tmp_path): storage = Storage(str(tmp_path / "hub.db")) hub = Hub(storage) cancelled = asyncio.Event() received = [] class Stalled: async def send_text(self, raw): try: await asyncio.Event().wait() finally: cancelled.set() class Failed: async def send_text(self, raw): raise RuntimeError("disconnected") class Healthy: async def send_text(self, raw): received.append(raw) for sid, ws in [("stalled", Stalled()), ("failed", Failed()), ("healthy", Healthy())]: hub.register_ui(UiSession(ws, sid)) try: await asyncio.wait_for(hub.broadcast_to_ui({"action": "first"}, timeout=0.05), 1) assert cancelled.is_set() assert set(hub._ui_sessions) == {"healthy"} await hub.broadcast_to_ui({"action": "second"}, timeout=0.05) assert len(received) == 2 finally: await hub.shutdown() storage.close() def test_log_worker_times_out_stalled_client_and_keeps_delivering(tmp_path): run_app_check(tmp_path, """ async def check(): main.LOG_BROADCAST_TIMEOUT = 0.05 await main.startup() sent = [] completed, cancelled = asyncio.Event(), asyncio.Event() class Stalled: async def send_text(self, raw): try: await asyncio.Event().wait() finally: cancelled.set() class Healthy: async def send_text(self, raw): sent.append(json.loads(raw)) if len(sent) == 2: completed.set() try: await asyncio.sleep(0) await asyncio.wait_for(main.log_queue.join(), 1) main.hub.register_ui(main.UiSession(Stalled(), "stalled")) main.hub.register_ui(main.UiSession(Healthy(), "healthy")) logging.getLogger("worker.test").warning("first") logging.getLogger("worker.test").warning("second") await asyncio.wait_for(completed.wait(), 1) assert cancelled.is_set() assert set(main.hub._ui_sessions) == {"healthy"} assert [event["payload"]["message"] for event in sent] == ["first", "second"] assert not main.log_broadcast_task.done() finally: await main.shutdown() asyncio.run(check()) """) def test_repeated_active_startup_preserves_resources_and_shutdown_stops_all_tasks(tmp_path): run_app_check(tmp_path, """ async def check(): before = asyncio.all_tasks() try: await main.startup() worker = main.log_broadcast_task watchdog = main.hub._watchdog_task queue, loop = main.log_queue, main.log_loop startup_entries = main.runlog.entries() await main.startup() assert main.log_broadcast_task is worker, "startup replaced the active log worker" assert main.hub._watchdog_task is watchdog, "startup replaced the active watchdog" assert main.log_queue is queue assert main.log_loop is loop assert main.runlog.entries() == startup_entries for name in main.LOGGERS_TO_CAPTURE: assert logging.getLogger(name).handlers.count(main.server_log_handler) == 1 assert asyncio.all_tasks() - before == {worker, watchdog} await main.shutdown() assert worker.cancelled() and watchdog.cancelled() assert not asyncio.all_tasks() - before, "shutdown leaked background tasks" await main.shutdown() # Repeated shutdown is harmless. finally: await main.shutdown() leaked = asyncio.all_tasks() - before for task in leaked: task.cancel() await asyncio.gather(*leaked, return_exceptions=True) asyncio.run(check()) """) def test_startup_after_full_shutdown_rejects_closed_storage(tmp_path): run_app_check(tmp_path, """ async def check(): await main.startup() await main.shutdown() try: try: await main.startup() except RuntimeError as exc: assert "storage" in str(exc).lower() and "closed" in str(exc).lower() else: raise AssertionError("startup accepted a restart with closed storage") assert main.log_broadcast_task is None assert main.hub._watchdog_task is None assert main.log_queue is None and main.log_loop is None for name in main.LOGGERS_TO_CAPTURE: assert main.server_log_handler not in logging.getLogger(name).handlers finally: await main.shutdown() asyncio.run(check()) """) @pytest.mark.asyncio async def test_hub_start_watchdog_is_idempotent_and_restartable_after_stop(tmp_path): storage = Storage(str(tmp_path / "watchdog.db")) hub = Hub(storage) tasks = set() try: hub.start_watchdog() first = hub._watchdog_task tasks.add(first) hub.start_watchdog() tasks.add(hub._watchdog_task) assert hub._watchdog_task is first, "start_watchdog replaced the active task" await hub.stop_watchdog() assert first.cancelled() assert hub._watchdog_task is None hub.start_watchdog() tasks.add(hub._watchdog_task) assert hub._watchdog_task is not first and not hub._watchdog_task.done() await hub.shutdown() assert all(task.cancelled() for task in tasks) finally: await hub.shutdown() for task in tasks: task.cancel() await asyncio.gather(*tasks, return_exceptions=True) storage.close() def isolated_logger(*handlers: logging.Handler) -> logging.Logger: logger = logging.Logger(f"cp-agent-test-{uuid.uuid4().hex}", logging.DEBUG) logger.handlers = list(handlers) logger.propagate = False return logger def test_runlog_keeps_latest_server_records(): runlog = RunLog(maxlen=2) runlog.add("INFO", "test.one", "first", 1.0) second = runlog.add("WARNING", "test.two", "second", 2.0) third = runlog.add("ERROR", "test.three", "third", 3.0) assert runlog.entries() == [ {"ts": 2.0, "level": "WARNING", "logger": "test.two", "message": "second"}, {"ts": 3.0, "level": "ERROR", "logger": "test.three", "message": "third"}, ] assert runlog.entries()[0] is second assert runlog.entries()[1] is third def test_runlog_defaults_timestamp_but_preserves_zero(): runlog = RunLog() before = time.time() entry = runlog.add("INFO", "test.clock", "now") after = time.time() assert before <= entry["ts"] <= after assert runlog.add("INFO", "test.clock", "epoch", 0.0)["ts"] == 0.0 def test_server_log_handler_formats_message_and_traceback(): runlog = RunLog() published = [] records = [] handler = runlog_module.ServerLogHandler(runlog, published.append) logger = isolated_logger(handler) def remember_record(record): records.append(record) return True logger.addFilter(remember_record) logger.info("server started on %s", 60030) try: raise ValueError("broken") except ValueError: logger.exception("request %s failed", "abc") entries = runlog.entries() assert len(entries) == 2 assert entries[0] == { "ts": records[0].created, "level": "INFO", "logger": logger.name, "message": "server started on 60030", } assert set(entries[1]) == {"ts", "level", "logger", "message"} assert entries[1]["ts"] == records[1].created assert entries[1]["logger"] == logger.name assert entries[1]["level"] == "ERROR" assert "request abc failed\nTraceback (most recent call last):" in entries[1]["message"] assert 'raise ValueError("broken")' in entries[1]["message"] assert "ValueError: broken" in entries[1]["message"] assert published == entries assert all(sent is stored for sent, stored in zip(published, entries)) def test_server_log_handler_can_enable_and_disable_publishing(): runlog = RunLog() published = [] handler = runlog_module.ServerLogHandler(runlog) logger = isolated_logger(handler) logger.debug("buffer only") handler.set_publish(published.append) logger.warning("publish this") handler.set_publish(None) logger.error("buffer only again") entries = runlog.entries() assert [entry["message"] for entry in entries] == [ "buffer only", "publish this", "buffer only again", ] assert published == [entries[1]] assert published[0] is entries[1] @pytest.mark.parametrize("same_handler", [False, True]) @pytest.mark.parametrize("publish_fails", [False, True]) def test_server_log_handler_ignores_publisher_reentry(same_handler, publish_fails): runlog = RunLog(maxlen=1) published = [] def publish(entry): published.append(entry) # Bound recursion on the broken implementation while still evicting # the original entry if nested records are incorrectly captured. if len(published) < 3: nested_logger.info("publisher diagnostic") if publish_fails: raise RuntimeError("publisher unavailable") handler = runlog_module.ServerLogHandler(runlog, publish) nested_handler = handler if same_handler else runlog_module.ServerLogHandler(runlog, publish) nested_logger = isolated_logger(nested_handler) logger = isolated_logger(handler) logger.info("original message") entries = runlog.entries() assert [entry["message"] for entry in entries] == ["original message"] assert published == entries assert published[0] is entries[0] logger.info("later ordinary message") assert [entry["message"] for entry in published] == [ "original message", "later ordinary message", ] assert runlog.entries() == [published[1]] def test_server_log_handler_avoids_cross_thread_publisher_deadlock(): # A subprocess also bounds logging.shutdown(), which otherwise waits forever # for handler locks held by deadlocked threads, even if they are daemons. script = textwrap.dedent(""" import logging import threading from core.runlog import RunLog, ServerLogHandler barrier = threading.Barrier(2, timeout=2) buffers = [RunLog(), RunLog()] published = [[], []] completed = [False, False] errors = [] loggers = [logging.Logger("first"), logging.Logger("second")] def publisher(index): def publish(entry): published[index].append(entry) try: # Both threads must hold their original handler lock before # either callback tries to log through the other handler. barrier.wait() loggers[1 - index].info("nested diagnostic") completed[index] = True except Exception as exc: # emit() contains callback exceptions, so surface them here. errors.append(repr(exc)) return publish for index, logger in enumerate(loggers): logger.propagate = False logger.addHandler(ServerLogHandler(buffers[index], publisher(index))) threads = [ threading.Thread( target=logger.info, args=(f"original {index}",), daemon=True, ) for index, logger in enumerate(loggers) ] for thread in threads: thread.start() for thread in threads: thread.join(timeout=3) assert all(not thread.is_alive() for thread in threads), "logging threads deadlocked" assert errors == [], errors assert completed == [True, True] for index, buffer in enumerate(buffers): entries = buffer.entries() assert [entry["message"] for entry in entries] == [f"original {index}"] assert published[index] == entries assert published[index][0] is entries[0] """) try: result = subprocess.run( [sys.executable, "-c", script], cwd=Path(__file__).resolve().parents[1], capture_output=True, text=True, timeout=10, ) except subprocess.TimeoutExpired as exc: pytest.fail(f"Cross-handler logging subprocess timed out: {exc.stderr!r}") assert result.returncode == 0, result.stdout + result.stderr @pytest.mark.parametrize("failure", ["format", "buffer"]) def test_server_log_handler_allows_downstream_capture_after_failure(failure): class FailingFormatter(logging.Formatter): def format(self, record): raise RuntimeError("formatter unavailable") class FailingRunLog(RunLog): def add(self, *args, **kwargs): raise RuntimeError("buffer unavailable") runlog = RunLog() published = [] first_buffer = FailingRunLog() if failure == "buffer" else runlog first_handler = runlog_module.ServerLogHandler(first_buffer, published.append) if failure == "format": first_handler.setFormatter(FailingFormatter()) downstream_handler = runlog_module.ServerLogHandler(runlog, published.append) logger = isolated_logger(first_handler, downstream_handler) logger.info("original %s", "message") entries = runlog.entries() assert [entry["message"] for entry in entries] == ["original message"] assert published == entries assert published[0] is entries[0] @pytest.mark.parametrize("failure", ["format", "buffer", "publish"]) def test_server_log_handler_contains_failures_without_logging(failure, caplog, capsys): class FailingRunLog(RunLog): def add(self, *args, **kwargs): raise RuntimeError("buffer unavailable") def failing_publish(entry): raise RuntimeError("publisher unavailable") runlog = FailingRunLog() if failure == "buffer" else RunLog() publish = failing_publish if failure == "publish" else None handler = runlog_module.ServerLogHandler(runlog, publish) logger = isolated_logger(handler) records = [] def remember_record(record): records.append(record) return True logger.addFilter(remember_record) caplog.set_level(logging.DEBUG) if failure == "format": logger.info("invalid integer: %d", "not an integer") else: logger.info("original message") assert len(runlog.entries()) == (1 if failure == "publish" else 0) expected_message = "invalid integer: %d" if failure == "format" else "original message" assert [record.msg for record in records] == [expected_message] assert caplog.records == [] assert capsys.readouterr() == ("", "") if failure != "buffer": handler.set_publish(None) logger.info("still working") assert runlog.entries()[-1]["message"] == "still working" assert [record.msg for record in records] == [expected_message, "still working"] @pytest.mark.parametrize("same_handler", [False, True]) def test_server_log_handler_captures_propagated_record_only_once(same_handler): runlog = RunLog() published = [] handler = runlog_module.ServerLogHandler(runlog, published.append) parent_handler = handler if same_handler else runlog_module.ServerLogHandler(runlog, published.append) parent = isolated_logger(parent_handler) logger = isolated_logger(handler) logger.parent = parent logger.propagate = True logger.warning("repeated message") logger.warning("repeated message") entries = runlog.entries() assert len(entries) == 2 assert [entry["message"] for entry in entries] == ["repeated message"] * 2 assert published == entries assert all(sent is stored for sent, stored in zip(published, entries))