From 3e699d61b67463542382747593eb968851cf309a Mon Sep 17 00:00:00 2001 From: Mattias Thall Date: Tue, 26 May 2026 22:52:30 +0200 Subject: [PATCH] Fix popular task failing silently when table doesn't exist MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The outer try had no except — any exception (e.g. table missing) killed the whole background task with no error visible to the user. Now: - CREATE TABLE IF NOT EXISTS inline so the task works even if the startup migration hasn't run (no server restart required) - Wrap DELETE in its own try/except - Catch and print outer exceptions so failures appear in server logs Co-Authored-By: Claude Sonnet 4.6 --- backend/routers/channels.py | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/backend/routers/channels.py b/backend/routers/channels.py index 4d82547..18a837c 100644 --- a/backend/routers/channels.py +++ b/backend/routers/channels.py @@ -719,11 +719,28 @@ def _fetch_popular_task(channel_id: int, youtube_channel_id: str): # Phase 1: store with basic info and write popular ranks immediately db = SessionLocal() try: + # Ensure table exists regardless of whether startup migration ran + db.execute(text(""" + CREATE TABLE IF NOT EXISTS channel_popular_videos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + channel_id INTEGER NOT NULL REFERENCES channels(id) ON DELETE CASCADE, + video_id INTEGER NOT NULL REFERENCES videos(id) ON DELETE CASCADE, + rank INTEGER NOT NULL, + fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE(channel_id, video_id) + ) + """)) + db.commit() + channel = db.query(Channel).filter_by(id=channel_id).first() if not channel: return - db.execute(text("DELETE FROM channel_popular_videos WHERE channel_id = :cid"), {"cid": channel_id}) - db.commit() + + try: + db.execute(text("DELETE FROM channel_popular_videos WHERE channel_id = :cid"), {"cid": channel_id}) + db.commit() + except Exception: + db.rollback() for rank, entry in enumerate(entries, start=1): yt_id = entry["id"] @@ -754,6 +771,9 @@ def _fetch_popular_task(channel_id: int, youtube_channel_id: str): db.commit() except Exception: db.rollback() + except Exception as e: + print(f"[popular] task error: {e}", flush=True) + db.rollback() finally: db.close()