Spaces:
Sleeping
Sleeping
Claude Code Claude Opus 4.6 commited on
Commit ·
63e51e7
1
Parent(s): 78dea99
Claude Code: Fix Cain - spawn brain_minimal.py worker process on startup
Browse filesThe worker process was never started, causing health check to report
"starting" forever. Added lifespan context manager to spawn worker
subprocess on startup and terminate gracefully on shutdown.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
app.py
CHANGED
|
@@ -1,6 +1,9 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import logging
|
| 3 |
import traceback
|
|
|
|
|
|
|
| 4 |
from fastapi import FastAPI, Request
|
| 5 |
from starlette.middleware.base import BaseHTTPMiddleware
|
| 6 |
from datetime import datetime
|
|
@@ -10,6 +13,7 @@ from typing import Optional
|
|
| 10 |
from fastapi.responses import PlainTextResponse
|
| 11 |
from fastapi.exceptions import RequestValidationError
|
| 12 |
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
| 13 |
|
| 14 |
# Ensure logs directory exists
|
| 15 |
os.makedirs("logs", exist_ok=True)
|
|
@@ -27,7 +31,44 @@ logger = logging.getLogger(__name__)
|
|
| 27 |
|
| 28 |
STARTUP_MODE = os.environ.get("STARTUP_MODE", "minimal")
|
| 29 |
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
|
| 33 |
class LoggingMiddleware(BaseHTTPMiddleware):
|
|
|
|
| 1 |
import os
|
| 2 |
+
import sys
|
| 3 |
import logging
|
| 4 |
import traceback
|
| 5 |
+
import subprocess
|
| 6 |
+
import signal
|
| 7 |
from fastapi import FastAPI, Request
|
| 8 |
from starlette.middleware.base import BaseHTTPMiddleware
|
| 9 |
from datetime import datetime
|
|
|
|
| 13 |
from fastapi.responses import PlainTextResponse
|
| 14 |
from fastapi.exceptions import RequestValidationError
|
| 15 |
from starlette.exceptions import HTTPException as StarletteHTTPException
|
| 16 |
+
from contextlib import asynccontextmanager
|
| 17 |
|
| 18 |
# Ensure logs directory exists
|
| 19 |
os.makedirs("logs", exist_ok=True)
|
|
|
|
| 31 |
|
| 32 |
STARTUP_MODE = os.environ.get("STARTUP_MODE", "minimal")
|
| 33 |
|
| 34 |
+
# Global worker process handle
|
| 35 |
+
_worker_process = None
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@asynccontextmanager
|
| 39 |
+
async def lifespan(app: FastAPI):
|
| 40 |
+
"""Manage worker process lifecycle."""
|
| 41 |
+
global _worker_process
|
| 42 |
+
logger.info("[LIFESPAN] Starting up - spawning brain_minimal.py worker process...")
|
| 43 |
+
try:
|
| 44 |
+
# Spawn brain_minimal.py as subprocess
|
| 45 |
+
_worker_process = subprocess.Popen(
|
| 46 |
+
[sys.executable, "/app/brain_minimal.py"],
|
| 47 |
+
stdout=subprocess.PIPE,
|
| 48 |
+
stderr=subprocess.PIPE,
|
| 49 |
+
cwd="/app"
|
| 50 |
+
)
|
| 51 |
+
logger.info(f"[LIFESPAN] Worker process spawned with PID: {_worker_process.pid}")
|
| 52 |
+
except Exception as e:
|
| 53 |
+
logger.error(f"[LIFESPAN] Failed to spawn worker: {e}")
|
| 54 |
+
|
| 55 |
+
yield # Application runs here
|
| 56 |
+
|
| 57 |
+
# Shutdown: terminate worker gracefully
|
| 58 |
+
logger.info("[LIFESPAN] Shutting down - terminating worker process...")
|
| 59 |
+
if _worker_process:
|
| 60 |
+
try:
|
| 61 |
+
_worker_process.send_signal(signal.SIGTERM)
|
| 62 |
+
_worker_process.wait(timeout=5)
|
| 63 |
+
logger.info("[LIFESPAN] Worker terminated gracefully")
|
| 64 |
+
except subprocess.TimeoutExpired:
|
| 65 |
+
logger.warning("[LIFESPAN] Worker did not terminate gracefully, killing...")
|
| 66 |
+
_worker_process.kill()
|
| 67 |
+
_worker_process.wait()
|
| 68 |
+
logger.info("[LIFESPAN] Worker killed")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
app = FastAPI(lifespan=lifespan)
|
| 72 |
|
| 73 |
|
| 74 |
class LoggingMiddleware(BaseHTTPMiddleware):
|