|
8 | 8 | import asyncio |
9 | 9 | import logging |
10 | 10 | import os |
11 | | -from typing import cast |
| 11 | +import threading |
| 12 | +from typing import Any, cast |
12 | 13 |
|
13 | 14 | from fastapi import FastAPI, HTTPException, Request, status |
14 | 15 | from starlette.concurrency import run_in_threadpool |
|
29 | 30 | ) |
30 | 31 | logger = logging.getLogger(__name__) |
31 | 32 |
|
| 33 | +_VALID_BENCHMARK_SOURCES = {"postgresql", "model_catalog"} |
| 34 | + |
| 35 | + |
| 36 | +def _get_benchmark_source_type() -> str: |
| 37 | + """Get configured benchmark source type.""" |
| 38 | + source = os.getenv("NEURALNAV_BENCHMARK_SOURCE", "postgresql").strip().lower() |
| 39 | + if source not in _VALID_BENCHMARK_SOURCES: |
| 40 | + logger.warning( |
| 41 | + "Unknown NEURALNAV_BENCHMARK_SOURCE='%s'; defaulting to 'postgresql'", |
| 42 | + source, |
| 43 | + ) |
| 44 | + return "postgresql" |
| 45 | + return source |
| 46 | + |
| 47 | + |
| 48 | +def _sync_model_catalog_async( |
| 49 | + client: Any, |
| 50 | + database_url: str, |
| 51 | + model_catalog: ModelCatalog, |
| 52 | + quality_scorer: Any, |
| 53 | +) -> threading.Thread: |
| 54 | + """Run Model Catalog sync in a background thread. |
| 55 | +
|
| 56 | + The app starts serving immediately (health probes, etc.) |
| 57 | + while catalog data syncs in the background. |
| 58 | + """ |
| 59 | + |
| 60 | + def _sync() -> None: |
| 61 | + try: |
| 62 | + import psycopg2 |
| 63 | + |
| 64 | + from neuralnav.knowledge_base.model_catalog_sync import sync_model_catalog |
| 65 | + |
| 66 | + logger.info("Background sync: loading Model Catalog data into PostgreSQL...") |
| 67 | + conn = psycopg2.connect(database_url) |
| 68 | + try: |
| 69 | + result = sync_model_catalog( |
| 70 | + client=client, |
| 71 | + conn=conn, |
| 72 | + model_catalog=model_catalog, |
| 73 | + quality_scorer=quality_scorer, |
| 74 | + ) |
| 75 | + if result.errors: |
| 76 | + logger.warning( |
| 77 | + "Model Catalog sync completed with %d errors", len(result.errors) |
| 78 | + ) |
| 79 | + else: |
| 80 | + logger.info("Background sync: Model Catalog data ready") |
| 81 | + finally: |
| 82 | + conn.close() |
| 83 | + except Exception: |
| 84 | + logger.exception("Background Model Catalog sync failed") |
| 85 | + |
| 86 | + thread = threading.Thread(target=_sync, name="model-catalog-sync", daemon=True) |
| 87 | + thread.start() |
| 88 | + return thread |
| 89 | + |
32 | 90 |
|
33 | 91 | # --------------------------------------------------------------------------- |
34 | 92 | # Lifespan: initialize all singletons on app.state |
|
37 | 95 |
|
38 | 96 | def init_app_state(app: FastAPI) -> None: |
39 | 97 | """Initialize all singletons on app.state during lifespan startup.""" |
| 98 | + source_type = _get_benchmark_source_type() |
| 99 | + |
| 100 | + # Always create the same components — single code path |
40 | 101 | app.state.model_catalog = ModelCatalog() |
41 | 102 | app.state.slo_repo = SLOTemplateRepository() |
42 | 103 | app.state.deployment_generator = DeploymentGenerator(simulator_mode=False) |
43 | 104 | app.state.yaml_validator = YAMLValidator() |
44 | 105 | app.state.cluster_managers = {} # dict[str, KubernetesClusterManager] |
45 | | - app.state.workflow = RecommendationWorkflow() |
| 106 | + |
| 107 | + if source_type == "model_catalog": |
| 108 | + from neuralnav.knowledge_base.model_catalog_client import ModelCatalogClient |
| 109 | + from neuralnav.recommendation.config_finder import ConfigFinder |
| 110 | + from neuralnav.recommendation.quality.usecase_scorer import UseCaseQualityScorer |
| 111 | + |
| 112 | + client = ModelCatalogClient() |
| 113 | + app.state.model_catalog_client = client |
| 114 | + quality_scorer = UseCaseQualityScorer() |
| 115 | + |
| 116 | + # Wire shared instances so sync updates propagate to recommendations |
| 117 | + config_finder = ConfigFinder(catalog=app.state.model_catalog, quality_scorer=quality_scorer) |
| 118 | + app.state.workflow = RecommendationWorkflow(config_finder=config_finder) |
| 119 | + |
| 120 | + database_url = os.getenv( |
| 121 | + "DATABASE_URL", |
| 122 | + "postgresql://postgres:neuralnav@localhost:5432/neuralnav", |
| 123 | + ) |
| 124 | + |
| 125 | + logger.info("Using Model Catalog as benchmark source (syncing to PostgreSQL)") |
| 126 | + app.state.model_catalog_sync_thread = _sync_model_catalog_async( |
| 127 | + client, database_url, app.state.model_catalog, quality_scorer |
| 128 | + ) |
| 129 | + else: |
| 130 | + app.state.model_catalog_client = None |
| 131 | + app.state.model_catalog_sync_thread = None |
| 132 | + app.state.workflow = RecommendationWorkflow() |
| 133 | + logger.info("Using PostgreSQL as benchmark source") |
46 | 134 |
|
47 | 135 |
|
48 | 136 | # --------------------------------------------------------------------------- |
|
0 commit comments