1) 数据装配流式+列裁剪:Repository 新增 stream_range_many_columns(只 SELECT 所需列、SQL 侧转 REAL、yield_per 分批),引擎按 required_columns 取数 (LocalEngine 仅 close+因子字段),消除 ORM/Decimal 全量物化; 2) 研究 Job 独立子进程执行(job.mode=subprocess):python -m app.cli.run_job 在子进程内设 RLIMIT_AS 上限,OOM 归档 failed 而非拖垮 API worker; 子进程异常退出由父进程补记 failed;并发上限 2; 3) 服务启动清理:残留 queued/running Job 标记 failed(防永久 running)。 实测同款全市场回测:uvicorn worker RSS 稳定 ~220MB,任务峰值内存由 4.1GB+ 降至 ~470MB,24s 完成并归档(此前 43s 未完成即 OOM)。 新增/更新测试 96 passed,ruff 干净。
66 lines
2.0 KiB
Python
66 lines
2.0 KiB
Python
"""FastAPI 应用入口。
|
|
|
|
启动:cd backend && uv run uvicorn app.main:app --reload
|
|
|
|
启动时(lifespan)清理上次进程异常退出遗留的 queued/running Job →
|
|
failed,防止「进程被杀后 Job 永久 running」(AGENT.md §20 状态机闭环)。
|
|
测试可用环境变量 QLIB_SKIP_STALE_JOB_CLEANUP=1 关闭(不触碰开发库)。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
from app.api.router import api_router
|
|
from app.core.config import get_settings
|
|
|
|
logger = logging.getLogger("uvicorn.error")
|
|
|
|
settings = get_settings()
|
|
|
|
|
|
def _cleanup_stale_jobs() -> None:
|
|
"""把上次进程异常退出遗留的 queued/running Job 标记 failed。"""
|
|
if os.environ.get("QLIB_SKIP_STALE_JOB_CLEANUP") == "1":
|
|
return
|
|
try:
|
|
from app.application.services.job_executor import mark_stale_jobs_failed
|
|
|
|
n = mark_stale_jobs_failed(reason="服务重启:上次未完成任务被中断")
|
|
if n:
|
|
logger.info("启动清理:%d 个遗留 Job 已标记 failed", n)
|
|
except Exception: # noqa: BLE001 —— 启动清理失败不阻断服务
|
|
logger.exception("启动清理残留 Job 失败")
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(_app: FastAPI):
|
|
_cleanup_stale_jobs()
|
|
yield
|
|
|
|
|
|
app = FastAPI(
|
|
title=settings.app_name,
|
|
version=settings.app_version,
|
|
description="A股个人量化研究平台 API(研究引擎 / Tushare 数据源)",
|
|
lifespan=lifespan,
|
|
)
|
|
|
|
# 开发期 CORS:允许任意来源(个人本地平台,无 Cookie 凭据,allow_credentials=False)。
|
|
# 前端默认走 Next 同源代理(见 frontend/web/next.config.ts rewrites),直连 API 也放行;
|
|
# 上线部署前请收紧为明确白名单。
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"],
|
|
allow_credentials=False,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
app.include_router(api_router, prefix=settings.api_prefix)
|