From 8b91c75b320c483882c0320904810319a9e30561 Mon Sep 17 00:00:00 2001 From: Bill Date: Sun, 2 Nov 2025 15:36:12 -0500 Subject: [PATCH] fix: add module-level database initialization for uvicorn reliability Add database initialization at module load time to ensure it runs regardless of how uvicorn handles the lifespan context manager. Issue: The lifespan function wasn't being triggered consistently when uvicorn loads the app module, causing "no such table: jobs" errors. Solution: Initialize database when the module is imported (after app creation), providing a reliable fallback that works in all deployment scenarios. This provides defense-in-depth: 1. Lifespan function (ideal path) 2. Module-level initialization (fallback/guarantee) Both paths check deployment mode and call the appropriate init function. --- api/main.py | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/api/main.py b/api/main.py index ae225b0..f4f73d5 100644 --- a/api/main.py +++ b/api/main.py @@ -522,11 +522,27 @@ def create_app( # Create default app instance app = create_app() +# Ensure database is initialized when module is loaded +# This handles cases where lifespan might not be triggered properly +logger.info("🔧 Module-level database initialization check...") +from tools.deployment_config import is_dev_mode, get_db_path +from api.database import initialize_dev_database, initialize_database + +_db_path = app.state.db_path +if is_dev_mode(): + logger.info(" 🔧 DEV mode - initializing dev database at module load") + _dev_db_path = get_db_path(_db_path) + initialize_dev_database(_dev_db_path) +else: + logger.info(" 🏭 PROD mode - ensuring database exists at module load") + initialize_database(_db_path) +logger.info("✅ Module-level database initialization complete") + if __name__ == "__main__": import uvicorn - # Note: Database initialization happens in startup_event() - # DEV mode warning will be displayed there as well + # Note: Database initialization happens in lifespan AND at module load + # for maximum reliability uvicorn.run(app, host="0.0.0.0", port=8080)