test_runtime_bootstrap.py 16.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
from __future__ import annotations

from pathlib import Path
from types import SimpleNamespace

from apps.web_api.bootstrap import runtime as runtime_bootstrap
from apps.web_api.runtime.engine_registry import EngineRuntimeRegistry, build_default_engine_catalog
from apps.web_api.runtime.forum_runtime import build_forum_runtime
from apps.web_api.runtime.process_manager import ProcessManager
from apps.web_api.runtime.process_registry import ProcessRuntimeRegistry
from apps.web_api.runtime.search_dispatch import build_search_dispatch_runtime
from apps.web_api.runtime.status_service import RuntimeStatusService
from apps.web_api.runtime import system_state as system_state_module
from apps.web_api.runtime.system_state import SystemStateRegistry
from apps.web_api.runtime.task_runtime_store import TaskRuntimeStore
from services.application.analysis import AnalysisRunQueryService
from services.shared.events import TaskLifecycleStage, TaskLifecycleStatus
from services.shared.timeline import InMemoryTaskTimelineStore, create_task_timeline_tracker

class FakeSocketIO:
    def __init__(self) -> None:
        self.emitted: list[tuple[str, dict]] = []
        self.stop_calls = 0

    def emit(self, event: str, payload: dict) -> None:
        self.emitted.append((event, payload))

    def stop(self) -> None:
        self.stop_calls += 1


def _build_process_registry() -> ProcessRuntimeRegistry:
    return ProcessRuntimeRegistry(
        {
            "insight": {"process": None, "port": 18501, "status": "stopped", "output": []},
            "media": {"process": None, "port": 18502, "status": "stopped", "output": []},
            "query": {"process": None, "port": 18503, "status": "stopped", "output": []},
            "forum": {"process": None, "port": None, "status": "stopped", "output": []},
        }
    )


def test_build_runtime_services_exposes_injected_forum_runtime(monkeypatch):
    monkeypatch.setattr(runtime_bootstrap, "ensure_runtime_dirs", lambda: None)

    socketio = FakeSocketIO()
    process_registry = _build_process_registry()
    engine_registry = EngineRuntimeRegistry(build_default_engine_catalog())
    forum_runtime = build_forum_runtime(process_registry=process_registry)
    process_manager = ProcessManager(
        process_registry=process_registry,
        streamlit_scripts=engine_registry.streamlit_scripts(),
    )

    services = runtime_bootstrap.build_runtime_services(
        socketio,
        log_dir=Path("runtime-logs"),
        engine_registry=engine_registry,
        forum_runtime=forum_runtime,
        process_registry=process_registry,
        process_manager=process_manager,
        system_state_registry=SystemStateRegistry(),
        task_runtime_store=TaskRuntimeStore(),
        research_task_store=object(),
    )

    assert services.engine_registry is engine_registry
    assert services.forum_runtime is forum_runtime
    assert services.process_manager is process_manager
    assert services.system_lifecycle._dependencies.start_forum_engine.__self__ is forum_runtime
    assert services.system_lifecycle._dependencies.stop_forum_engine.__self__ is forum_runtime


def test_build_runtime_services_configures_research_route_services(monkeypatch):
    monkeypatch.setattr(runtime_bootstrap, "ensure_runtime_dirs", lambda: None)

    socketio = FakeSocketIO()
    captured: list[dict[str, object]] = []
    report_query_service = object()
    monkeypatch.setattr(runtime_bootstrap, "_resolve_report_query_service", lambda: report_query_service)
    monkeypatch.setattr(
        runtime_bootstrap,
        "configure_research_route_services",
        lambda **kwargs: captured.append(kwargs),
    )

    runtime_bootstrap.build_runtime_services(
        socketio,
        log_dir=Path("runtime-logs"),
        research_task_store=object(),
    )

    assert len(captured) == 1
    assert isinstance(captured[0]["analysis_query_service"], AnalysisRunQueryService)
    assert captured[0]["report_query_service"] is report_query_service


def test_configure_research_route_services_injects_analysis_query_service(monkeypatch):
    import backend.research_routes as research_routes

    injected_service = AnalysisRunQueryService()
    injected_report_service = object()
    monkeypatch.setattr(research_routes, "_RESEARCH_ANALYSIS_APP_SERVICE", None, raising=False)
    monkeypatch.setattr(research_routes, "_DEFAULT_RESEARCH_ANALYSIS_APP_SERVICE", None, raising=False)
    monkeypatch.setattr(research_routes, "_REPORT_APP_SERVICE", None, raising=False)
    monkeypatch.setattr(research_routes, "_RESEARCH_TASK_VIEW_APP_SERVICE", None, raising=False)

    runtime_bootstrap.configure_research_route_services(
        analysis_query_service=injected_service,
        report_query_service=injected_report_service,
    )

    assert research_routes._get_research_analysis_app_service() is injected_service
    assert research_routes._get_analysis_run_query_service() is injected_service
    assert research_routes._get_report_app_service() is injected_report_service
    assert research_routes._get_research_task_view_app_service() is not None


def test_configure_research_route_services_wires_task_view_report_builder_to_typed_query(monkeypatch):
    import backend.research_routes as research_routes

    injected_service = AnalysisRunQueryService()

    class _FakeReportQueryService:
        def __init__(self) -> None:
            self.typed_calls: list[dict[str, object]] = []
            self.payload_calls: list[dict[str, object]] = []

        def get_task_report_resource_dto(self, **kwargs):
            self.typed_calls.append(kwargs)
            return SimpleNamespace(
                to_response_payload=lambda: {
                    "task_id": kwargs["research_task_id"],
                    "report": {"report_job_id": kwargs["report_job_id"], "status": "completed"},
                }
            )

        def build_task_report_resource_payload(self, **kwargs):
            self.payload_calls.append(kwargs)
            return {"task_id": kwargs["research_task_id"], "report": {"status": "legacy"}}

    injected_report_service = _FakeReportQueryService()
    task = SimpleNamespace(id="task-1", report_job_id="report-1", status="reporting")
    monkeypatch.setattr(research_routes, "_RESEARCH_ANALYSIS_APP_SERVICE", None, raising=False)
    monkeypatch.setattr(research_routes, "_DEFAULT_RESEARCH_ANALYSIS_APP_SERVICE", None, raising=False)
    monkeypatch.setattr(research_routes, "_REPORT_APP_SERVICE", None, raising=False)
    monkeypatch.setattr(research_routes, "_RESEARCH_TASK_VIEW_APP_SERVICE", None, raising=False)
    monkeypatch.setattr(research_routes.RESEARCH_TASK_APP_SERVICE, "get_task_dto", lambda task_id: task)

    runtime_bootstrap.configure_research_route_services(
        analysis_query_service=injected_service,
        report_query_service=injected_report_service,
    )

    payload = research_routes._get_research_task_view_app_service().build_task_report_resource_payload("task-1")

    assert payload == {
        "task_id": "task-1",
        "report": {"report_job_id": "report-1", "status": "completed"},
    }
    assert injected_report_service.typed_calls == [
        {
            "research_task_id": "task-1",
            "report_job_id": "report-1",
            "task": task,
        }
    ]
    assert injected_report_service.payload_calls == []


def test_build_runtime_services_cleanup_handler_marks_injected_system_state(monkeypatch):
    monkeypatch.setattr(runtime_bootstrap, "ensure_runtime_dirs", lambda: None)

    socketio = FakeSocketIO()
    process_registry = _build_process_registry()
    engine_registry = EngineRuntimeRegistry(build_default_engine_catalog())
    forum_runtime = build_forum_runtime(process_registry=process_registry)
    process_manager = ProcessManager(
        process_registry=process_registry,
        streamlit_scripts=engine_registry.streamlit_scripts(),
    )
    injected_system_state = SystemStateRegistry()
    injected_system_state.set_state(started=True, starting=True)
    system_state_module.SYSTEM_STATE_REGISTRY.set_state(started=True, starting=True)

    cleanup_calls: list[object] = []
    cleanup_port_marker = object()

    def cleanup_processes(*, cleanup):
        cleanup_calls.append(cleanup)
        assert cleanup is cleanup_port_marker
        injected_system_state.set_state(started=False, starting=False)

    monkeypatch.setattr(process_manager, "cleanup_processes", cleanup_processes)
    monkeypatch.setattr(
        runtime_bootstrap,
        "build_process_cleanup_port",
        lambda **kwargs: cleanup_port_marker,
    )

    services = runtime_bootstrap.build_runtime_services(
        socketio,
        log_dir=Path("runtime-logs"),
        engine_registry=engine_registry,
        forum_runtime=forum_runtime,
        process_registry=process_registry,
        process_manager=process_manager,
        system_state_registry=injected_system_state,
        task_runtime_store=TaskRuntimeStore(),
        research_task_store=object(),
    )

    services.cleanup_handler()

    assert cleanup_calls == [cleanup_port_marker]
    assert injected_system_state.snapshot() == {
        "started": False,
        "starting": False,
        "shutdown_requested": False,
    }
    assert system_state_module.SYSTEM_STATE_REGISTRY.snapshot()["started"] is True
    assert system_state_module.SYSTEM_STATE_REGISTRY.snapshot()["starting"] is True
    system_state_module.SYSTEM_STATE_REGISTRY.set_state(started=False, starting=False)


def test_build_http_route_dependencies_use_runtime_forum_object_methods():
    process_registry = _build_process_registry()
    forum_runtime = build_forum_runtime(process_registry=process_registry)
    process_manager = ProcessManager(process_registry=process_registry)
    system_state_registry = SystemStateRegistry()
    runtime_status_service = RuntimeStatusService(
        process_registry=process_registry,
        system_state_registry=system_state_registry,
        refresh_process_status=process_manager.check_app_status,
    )
    runtime_services = runtime_bootstrap.RuntimeServices(
        log_dir=Path("runtime-logs"),
        engine_registry=EngineRuntimeRegistry(build_default_engine_catalog()),
        forum_runtime=forum_runtime,
        process_registry=process_registry,
        process_manager=process_manager,
        system_state_registry=system_state_registry,
        task_runtime_store=TaskRuntimeStore(),
        runtime_status_service=runtime_status_service,
        task_timeline_tracker=create_task_timeline_tracker(
            timeline_store=InMemoryTaskTimelineStore(),
            source="tests.runtime_bootstrap",
        ),
        research_task_service=object(),
        analysis_service=object(),
        search_dispatch_runtime=build_search_dispatch_runtime(
            analysis_service=SimpleNamespace(),
        ),
        system_lifecycle=object(),
        cleanup_handler=lambda: None,
    )

    submit_search_request = lambda **_: ({"success": True}, 200)

    deps = runtime_bootstrap.build_http_route_dependencies(
        runtime_services=runtime_services,
        frontend_dev_server_url=lambda: None,
        socketio=FakeSocketIO(),
        submit_search_request=submit_search_request,
    )

    assert deps.start_forum_engine.__self__ is forum_runtime
    assert deps.stop_forum_engine.__self__ is forum_runtime
    assert deps.get_forum_output.__self__ is forum_runtime
    assert deps.get_forum_log_payload.__self__ is forum_runtime
    assert deps.get_forum_log_history.__self__ is forum_runtime
    assert deps.get_process_status.__self__ is runtime_status_service
    assert deps.get_system_status.__self__ is runtime_status_service
    assert deps.submit_search_request is submit_search_request


def test_build_http_route_search_request_submitter_delegates_to_runtime_builder(monkeypatch):
    process_registry = _build_process_registry()
    forum_runtime = build_forum_runtime(process_registry=process_registry)
    process_manager = ProcessManager(process_registry=process_registry)
    captured: dict[str, object] = {}
    submitter = lambda **_: ({"success": True, "accepted": True}, 200)
    analysis_service = SimpleNamespace()
    system_state_registry = SystemStateRegistry()
    runtime_services = runtime_bootstrap.RuntimeServices(
        log_dir=Path("runtime-logs"),
        engine_registry=EngineRuntimeRegistry(build_default_engine_catalog()),
        forum_runtime=forum_runtime,
        process_registry=process_registry,
        process_manager=process_manager,
        system_state_registry=system_state_registry,
        task_runtime_store=TaskRuntimeStore(),
        runtime_status_service=RuntimeStatusService(
            process_registry=process_registry,
            system_state_registry=system_state_registry,
            refresh_process_status=process_manager.check_app_status,
        ),
        task_timeline_tracker=create_task_timeline_tracker(
            timeline_store=InMemoryTaskTimelineStore(),
            source="tests.runtime_bootstrap",
        ),
        research_task_service=object(),
        analysis_service=analysis_service,
        search_dispatch_runtime=build_search_dispatch_runtime(
            analysis_service=analysis_service,
        ),
        system_lifecycle=object(),
        cleanup_handler=lambda: None,
    )

    search_hooks = SimpleNamespace(
        resolve_search_query=lambda **_: ("task-1", "museum"),
        dispatch_search_request=lambda **_: {"success": True},
    )

    def fake_build_search_request_submitter(**kwargs):
        captured.update(kwargs)
        return submitter

    monkeypatch.setattr(
        runtime_bootstrap,
        "build_search_request_submitter",
        fake_build_search_request_submitter,
    )

    result = runtime_bootstrap.build_http_route_search_request_submitter(
        runtime_services=runtime_services,
        search_hooks=search_hooks,
    )

    assert result is submitter
    assert captured["analysis_service"] is analysis_service
    assert captured["research_task_service"] is runtime_services.research_task_service
    assert captured["process_registry"] is process_registry
    assert captured["resolve_search_query"](payload={"q": "museum"}, research_task_service=None) == (
        "task-1",
        "museum",
    )
    assert captured["dispatch_search_request"](query="museum") == {"success": True}
    assert callable(captured["check_app_status"])
    assert captured["log_dir"] == Path("runtime-logs")
    assert captured["write_log"] is runtime_bootstrap.write_log_to_file


def test_build_runtime_services_delegates_lifecycle_defaults_directly(monkeypatch):
    monkeypatch.setattr(runtime_bootstrap, "ensure_runtime_dirs", lambda: None)

    socketio = FakeSocketIO()
    process_registry = _build_process_registry()
    engine_registry = EngineRuntimeRegistry(build_default_engine_catalog())
    forum_runtime = build_forum_runtime(process_registry=process_registry)
    process_manager = ProcessManager(
        process_registry=process_registry,
        streamlit_scripts=engine_registry.streamlit_scripts(),
    )
    lifecycle_dependencies = object()
    captured: dict[str, object] = {}

    def fake_build_default_system_lifecycle_dependencies(**kwargs):
        captured.update(kwargs)
        return lifecycle_dependencies

    monkeypatch.setattr(
        runtime_bootstrap,
        "build_default_system_lifecycle_dependencies",
        fake_build_default_system_lifecycle_dependencies,
    )

    services = runtime_bootstrap.build_runtime_services(
        socketio,
        log_dir=Path("runtime-logs"),
        engine_registry=engine_registry,
        forum_runtime=forum_runtime,
        process_registry=process_registry,
        process_manager=process_manager,
        system_state_registry=SystemStateRegistry(),
        task_runtime_store=TaskRuntimeStore(),
        research_task_store=object(),
    )

    assert captured == {
        "process_manager": process_manager,
        "forum_runtime": forum_runtime,
        "process_registry": process_registry,
        "engine_registry": engine_registry,
    }
    assert services.system_lifecycle._dependencies is lifecycle_dependencies


def test_build_runtime_services_wires_default_task_timeline_tracker(monkeypatch):
    monkeypatch.setattr(runtime_bootstrap, "ensure_runtime_dirs", lambda: None)

    services = runtime_bootstrap.build_runtime_services(
        FakeSocketIO(),
        log_dir=Path("runtime-logs"),
        research_task_store=object(),
    )

    assert services.task_timeline_tracker is services.research_task_service.timeline_tracker
    entry = services.task_timeline_tracker.record(
        task_id="task-1",
        stage=TaskLifecycleStage.CREATED,
        status=TaskLifecycleStatus.PENDING,
        action="bootstrap check",
        source="tests.runtime_bootstrap",
    )
    assert entry.task_id == "task-1"