Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(api): migrate lifecycle hooks to lifespan

Haozhe Wuf7ab8a011110
diff --git a/agent/api_server.py b/agent/api_server.py
index 84bb0cb1f..d080972c9 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -9,8 +9,9 @@ infrastructure lives in ``src.api.{security,models,helpers,state}``.
from __future__ import annotations
import logging
+from contextlib import asynccontextmanager
from pathlib import Path
-from typing import Any, Dict
+from typing import Any, AsyncIterator, Dict
from fastapi import FastAPI, HTTPException, Request, status # noqa: F401
from fastapi.responses import FileResponse # noqa: F401
@@ -113,37 +114,6 @@ from src.api.state import ( # noqa: F401, E402
console = Console()
logger = logging.getLogger(__name__)
-# ============================================================================
-# FastAPI Application
-# ============================================================================
-
-app = FastAPI(
- title="Vibe-Trading API",
- description="Vibe-Trading API: natural-language finance research, backtesting, and swarm workflows",
- version=APP_VERSION,
- docs_url="/docs",
- redoc_url="/redoc"
-)
-
-app.add_middleware(
- CORSMiddleware,
- allow_origins=_CORS_ORIGINS,
- allow_credentials=True,
- allow_methods=["*"],
- allow_headers=["*"],
-)
-
-# Middleware functions are defined in src.api.security / src.api.helpers, so
-# the @app.middleware("http") decorator cannot be used here — register them
-# programmatically instead.
-app.middleware("http")(_reject_untrusted_loopback_host)
-app.middleware("http")(_spa_html_deep_link_fallback)
-app.middleware("http")(_apply_security_headers)
-
-# ============================================================================
-# Lifecycle hooks
-# ============================================================================
-
from src.api.channels_routes import ( # noqa: E402
_start_channel_runtime,
_stop_channel_runtime,
@@ -154,7 +124,6 @@ from src.api.scheduled_routes import ( # noqa: E402
)
[email protected]_event("startup")
async def _run_startup_preflight() -> None:
"""Run preflight checks on server startup."""
from src.preflight import run_preflight
@@ -173,16 +142,46 @@ async def _run_startup_preflight() -> None:
await _start_channel_runtime()
[email protected]_event("shutdown")
async def _stop_scheduled_research_on_shutdown() -> None:
"""Stop the scheduled research executor on server shutdown."""
- await _stop_channel_runtime()
- await _stop_scheduled_research_executor()
+ try:
+ await _stop_channel_runtime()
+ finally:
+ await _stop_scheduled_research_executor()
+
+
+@asynccontextmanager
+async def _lifespan(_: FastAPI) -> AsyncIterator[None]:
+ """Run API startup and guaranteed reverse-order shutdown."""
+ try:
+ await _run_startup_preflight()
+ yield
+ finally:
+ await _stop_scheduled_research_on_shutdown()
+
+
+app = FastAPI(
+ title="Vibe-Trading API",
+ description="Vibe-Trading API: natural-language finance research, backtesting, and swarm workflows",
+ version=APP_VERSION,
+ docs_url="/docs",
+ redoc_url="/redoc",
+ lifespan=_lifespan,
+)
+
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=_CORS_ORIGINS,
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+app.middleware("http")(_reject_untrusted_loopback_host)
+app.middleware("http")(_spa_html_deep_link_fallback)
+app.middleware("http")(_apply_security_headers)
-# ============================================================================
# Route registration + re-exports
-# ============================================================================
# --- Runs ---
from src.api.runs_routes import register_runs_routes # noqa: E402
diff --git a/agent/tests/test_state_migration_wiring.py b/agent/tests/test_state_migration_wiring.py
index d1be6623f..27cee81ac 100644
--- a/agent/tests/test_state_migration_wiring.py
+++ b/agent/tests/test_state_migration_wiring.py
@@ -70,3 +70,102 @@ def test_api_startup_runs_migration(
asyncio.run(api_server._run_startup_preflight())
assert record_migration
+
+
+def test_api_lifespan_preserves_startup_and_shutdown_order(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import asyncio
+
+ import api_server
+
+ events: list[str] = []
+
+ monkeypatch.setattr(
+ migrate,
+ "migrate_legacy_state",
+ lambda: events.append("migration"),
+ )
+ monkeypatch.setattr(
+ "src.preflight.run_preflight",
+ lambda console: events.append("preflight"),
+ )
+ monkeypatch.setattr(
+ api_server,
+ "_start_scheduled_research_executor",
+ lambda: events.append("scheduler-start"),
+ )
+
+ async def start_channels() -> None:
+ events.append("channels-start")
+
+ async def stop_channels() -> None:
+ events.append("channels-stop")
+
+ async def stop_scheduler() -> None:
+ events.append("scheduler-stop")
+
+ monkeypatch.setattr(api_server, "_start_channel_runtime", start_channels)
+ monkeypatch.setattr(api_server, "_stop_channel_runtime", stop_channels)
+ monkeypatch.setattr(api_server, "_stop_scheduled_research_executor", stop_scheduler)
+ monkeypatch.setattr(
+ "src.config.accessor.get_env_config",
+ lambda: type(
+ "Cfg",
+ (),
+ {
+ "agent_tuning": type(
+ "Tuning", (), {"vibe_trading_channels_auto_start": True}
+ )()
+ },
+ )(),
+ )
+
+ async def scenario() -> None:
+ async with api_server._lifespan(api_server.app):
+ events.append("serving")
+
+ asyncio.run(scenario())
+
+ assert events == [
+ "migration",
+ "preflight",
+ "scheduler-start",
+ "channels-start",
+ "serving",
+ "channels-stop",
+ "scheduler-stop",
+ ]
+
+
+def test_api_lifespan_stops_scheduler_when_channel_shutdown_fails(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import asyncio
+
+ import api_server
+
+ events: list[str] = []
+
+ async def startup() -> None:
+ events.append("startup")
+
+ async def stop_channels() -> None:
+ events.append("channels-stop")
+ raise RuntimeError("channel shutdown failed")
+
+ async def stop_scheduler() -> None:
+ events.append("scheduler-stop")
+
+ monkeypatch.setattr(api_server, "_run_startup_preflight", startup)
+ monkeypatch.setattr(api_server, "_stop_channel_runtime", stop_channels)
+ monkeypatch.setattr(api_server, "_stop_scheduled_research_executor", stop_scheduler)
+
+ async def scenario() -> None:
+ async with api_server._lifespan(api_server.app):
+ events.append("serving")
+
+ with pytest.raises(RuntimeError, match="channel shutdown failed"):
+ asyncio.run(scenario())
+
+ assert events == ["startup", "serving", "channels-stop", "scheduler-stop"]