diff --git a/backend/main.py b/backend/main.py index 5fa9015..64674a9 100644 --- a/backend/main.py +++ b/backend/main.py @@ -61,6 +61,29 @@ async def lifespan(app: FastAPI): except Exception as e: logging.getLogger(__name__).warning(f"Stale batch cleanup failed: {e}") + # Startup: mark any sync_log entries stuck as 'running' as failed + # (these are orphaned by container restarts mid-job) + try: + import psycopg2 + from database import DATABASE_URL + conn = psycopg2.connect(DATABASE_URL) + try: + conn.autocommit = True + with conn.cursor() as cur: + cur.execute(""" + UPDATE sync_log + SET status = 'failed', + completed_at = NOW(), + error_message = 'Interrupted by container restart' + WHERE status = 'running' AND completed_at IS NULL + """) + if cur.rowcount: + logging.getLogger(__name__).info(f"Cleared {cur.rowcount} stale sync_log entries") + finally: + conn.close() + except Exception as e: + logging.getLogger(__name__).warning(f"Stale sync_log cleanup failed: {e}") + # Ensure ai_insights table exists try: from database import SyncSessionLocal