{"record":{"id":"e3e83dee4b9209ab","repo":"ZhuLinsen/daily_stock_analysis","slug":"fastapi-server-failed-to-start-host-port-st","errorCode":null,"errorMessage":"FastAPI server failed to start: {host}:{port}; {startup_error[0]}","messagePattern":"FastAPI server failed to start: (.+?):(.+?); (.+?)","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"critical","filePath":"main.py","lineNumber":1256,"sourceCode":"        if isinstance(install_signal_handlers, bool):\n            uvicorn_server.install_signal_handlers = False\n\n    startup_error: list[BaseException] = []\n\n    def run_server():\n        try:\n            uvicorn_server.run()\n        except Exception as exc:  # noqa: BLE001 - surface startup issues to caller promptly\n            startup_error.append(exc)\n\n    thread = threading.Thread(target=run_server, daemon=True)\n    thread.start()\n\n    timeout_seconds = 3.0\n    wait_deadline = time.time() + timeout_seconds\n    while time.time() < wait_deadline:\n        if startup_error:\n            raise RuntimeError(\n                f\"FastAPI server failed to start: {host}:{port}; {startup_error[0]}\"\n            )\n        if uvicorn_server.started:\n            logger.info(f\"FastAPI 服务已启动: http://{host}:{port}\")\n            return\n        if not thread.is_alive():\n            break\n        time.sleep(0.05)\n\n    if startup_error:\n        raise RuntimeError(f\"FastAPI server failed to start: {host}:{port}; {startup_error[0]}\")\n    if uvicorn_server.started:\n        logger.info(f\"FastAPI 服务已启动: http://{host}:{port}\")\n        return\n    if not thread.is_alive():\n        raise RuntimeError(f\"FastAPI 服务器启动后立即退出: {host}:{port}\")\n\n    raise RuntimeError(f\"FastAPI 服务在 {timeout_seconds:.1f}s 内未完成启动: {host}:{port}\")","sourceCodeStart":1238,"sourceCodeEnd":1274,"githubUrl":"https://github.com/ZhuLinsen/daily_stock_analysis/blob/5159bd72e8373d215492dff122acc9d389e219c9/main.py#L1238-L1274","documentation":"uvicorn runs in a helper thread; any exception thrown during its startup (app import failure, bind error, config error) is captured into startup_error and re-raised on the main thread as RuntimeError. This is the in-loop check that fires as soon as the failure is observed. The appended exception (startup_error[0]) is the real cause.","triggerScenarios":"The ASGI app import inside the server thread failing (syntax error, missing dependency, circular import in server.py/api), uvicorn failing to bind despite the earlier probe (race with another process grabbing the port), or invalid uvicorn kwargs derived from config (e.g. malformed log_level).","commonSituations":"Editing server.py or api/ modules introducing an import-time error, then running --serve; a port race where another container grabs the port between probe and run; missing optional dependency only imported at app import time.","solutions":["Read the tail of the message after the semicolon — it carries the original exception; fix that first (import error, missing module, etc.).","Reproduce the import directly: python -c \"import server\" to surface the traceback without the thread wrapper.","If it is a bind race, free the port or change ports and retry.","Run python -m py_compile on files you changed (per repo AGENTS.md backend gate) before starting the server."],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":"import subprocess, sys\n\n# fail fast: the ASGI app must import cleanly before threading obscures tracebacks\nsubprocess.run([sys.executable, \"-c\", \"import server\"], check=True)","typeGuard":null,"tryCatchPattern":"try:\n    run_fastapi(host, port, config)\nexcept RuntimeError as e:\n    cause = e.__cause__ or e\n    logger.exception(\"uvicorn startup failed: %s\", cause)\n    # fix the underlying import/config error, then restart — do not blind-retry","preventionTips":["Run python -c 'import server' as a preflight in dev/CI before --serve.","Keep app import side-effect free; push work into lifespan handlers.","Compile-check edited modules (python -m py_compile) before starting the server."],"tags":["server","startup","uvicorn","thread"],"backgroundTag":null,"analyzedSha":"5159bd72e8373d215492dff122acc9d389e219c9","analyzedAt":"2026-08-15T01:59:36.292Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}