Clear stale sync_log 'running' entries on startup

After a container restart any in-progress jobs leave orphaned 'running' rows
with no completed_at. Added startup cleanup to mark them failed, so the UI
doesn't show a permanently stuck status.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
jtricerolph 2026-07-05 10:12:19 +00:00
parent 1612468122
commit 0e43841783

View file

@ -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