Coverage for app / lifespan.py: 15%
72 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1# app/lifespan.py
2import logging
3from contextlib import asynccontextmanager
4from fastapi import FastAPI
6from app.db.postgres.engine import engine, SessionLocal
7from app.common.settings import AppEnv, get_settings
8from app.util import neo4j_client
10logger = logging.getLogger(__name__)
12settings = get_settings()
14LOCAL_SCENARIO = "test1"
17@asynccontextmanager
18async def lifespan(app: FastAPI):
19 # 🔹 Startup
20 try:
21 logger.info("Checking DB connection...")
22 with engine.connect():
23 pass # Force connection check
25 # Run migrations in-process (advisory-locked) — the prod image's CMD runs
26 # uvicorn directly, bypassing entrypoint.sh, so the entrypoint can't.
27 if settings.RUN_MIGRATIONS:
28 logger.info("Running migrations...")
29 from app.migrations import run_migrations
31 run_migrations()
33 # CHAINR Bot's rows, so every user has an agent to talk to from the
34 # start. Database-only and idempotent; indexing its guide needs svc-ai
35 # and is left to the ``chainr_bot_sync`` job. Never fatal: a replica
36 # that starts before migrations land serves everything else, and the
37 # job provisions the bot on its first run.
38 try:
39 from app.services.system_resources import ensure_system_resources
41 db = SessionLocal()
42 try:
43 ensure_system_resources(db)
44 finally:
45 db.close()
46 except Exception:
47 logger.exception("Could not provision CHAINR Bot at startup")
49 # Organisation roles and their permissions, as code defines them.
50 # Migration 81 created the role rows; this keeps what each allows in
51 # step with ``app/services/membership.py``. Never fatal: permission
52 # checks read the code, not these rows.
53 try:
54 from app.services.membership import ensure_roles
56 db = SessionLocal()
57 try:
58 ensure_roles(db)
59 finally:
60 db.close()
61 except Exception:
62 logger.exception("Could not reconcile organisation roles at startup")
64 try:
65 neo4j_client.ensure_index()
66 logger.info("Neo4j entity index verified")
67 except Exception:
68 logger.warning(
69 "Neo4j unavailable at startup — graph knowledge bases will fail"
70 )
72 if settings.APP_ENV == AppEnv.LOCAL:
73 from app.router.dev.scenario_loader.router import (
74 ScenarioLoadResult,
75 _list_scenarios,
76 execute_scenario_load,
77 )
79 if LOCAL_SCENARIO in _list_scenarios():
80 logger.info(
81 "LOCAL env — auto-loading scenario '%s' (Additive)", LOCAL_SCENARIO
82 )
83 db = SessionLocal()
84 try:
85 result: ScenarioLoadResult = await execute_scenario_load(
86 LOCAL_SCENARIO, "Additive", db
87 )
88 if result.success:
89 logger.info(
90 "Scenario '%s' loaded: %s", LOCAL_SCENARIO, result.message
91 )
92 else:
93 logger.warning(
94 "Scenario '%s' load failed: %s",
95 LOCAL_SCENARIO,
96 result.message,
97 )
98 finally:
99 db.close()
100 else:
101 logger.warning(
102 "LOCAL env — scenario '%s' not found, skipping auto-load",
103 LOCAL_SCENARIO,
104 )
106 # Started after migrations, so a job cannot query a table the running
107 # image expects and the database does not yet have. Only one replica
108 # actually schedules — leadership is a Postgres advisory lock — and a
109 # replica that does not win still serves requests normally, with
110 # refresh-on-view and purge-on-read as the fallback they have always
111 # been.
112 if settings.SCHEDULER_ENABLED:
113 from app.services.scheduler.runner import Scheduler, set_scheduler
115 scheduler = Scheduler(tick_seconds=settings.SCHEDULER_TICK_SECONDS)
116 set_scheduler(scheduler)
117 await scheduler.start()
118 else:
119 logger.info("Scheduler disabled; dashboards refresh on view")
121 logger.info("App ready")
123 yield
124 except Exception as e:
125 logger.exception("Startup failed.")
126 raise e
127 finally:
128 # 🔹 Shutdown
129 from app.services.scheduler.runner import get_scheduler, set_scheduler
131 # Before the scheduler stands down: the benchmark worker starts no
132 # further run and stops the one in flight at its next cell, so no new
133 # leader finds this process's run still going.
134 from app.services.evaluation import benchmark
136 benchmark.stop()
138 scheduler = get_scheduler()
139 if scheduler is not None:
140 # Stands down as leader explicitly so another replica can pick the
141 # work up immediately rather than after this connection times out.
142 await scheduler.stop()
143 set_scheduler(None)
145 engine.dispose()
146 neo4j_client.close()