From 8f873296a18650501d32f9da096ee2eae5d38456 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Mon, 27 Jul 2026 22:31:04 +0200 Subject: [PATCH] fix(emails): stop duplicate expiry warnings and fix the button that 404s MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two bugs in the "your N clips will be deleted tomorrow" email. The button pointed at {frontend_url}/dashboard, a route that has never existed: the app is a single-page app routed entirely through the hash, and #app is what opens it. Until today /dashboard fell through to the SPA fallback and quietly showed the marketing landing, so the link looked like it worked. Now that unknown paths return a real 404 it fails visibly. Both this and the clips-ready email now link to /#app; the clips-ready one was passing the bare frontend URL, which showed the landing page to anyone whose browser had not already set the skip-landing flag. The duplicate send is worse. De-duplication was `_warned_video_ids`, a set in process memory, and the warning window is a full day while the sweep runs every six hours. Any API restart inside that window re-armed the warning for everyone already told. That is exactly what happened today: the 06:00 warning went out, three deploys restarted the API (frontend and API share this repo, so the SEO pushes redeployed both), the container came up at 12:36, and the sweeper's first run six hours later at 18:36 mailed the same clips again. Warnings are now recorded in clip_expiry_warnings, keyed by clip id, written before the send. A new table rather than a column because the schema bootstrap is create_all, which creates missing tables but never ALTERs one — same reason SignupAttribution is its own table. The FK cascades from user_videos, so rows disappear when purge_free_expired deletes the clip and no cleanup pass is needed. Recording before sending is deliberate: a duplicate email is the failure being fixed, while a warning row for a mail that then failed to send costs that user one notice. No backfill. Clips already warned about have no row yet, so the current cohort gets one more warning after this deploys and none after that. Backfilling the window would also silence the first warning for anyone who entered it since the last sweep, and a missed deletion notice costs the user their clips, while a duplicate only costs them an email. Verified against a real Postgres: create_all builds the table, the primary key rejects a second row for the same clip, the cascade removes warnings when the clip is deleted, and warn_free_expiring sends exactly one email across two sweeps plus a module reload standing in for a restart (which is what used to produce the second email). --- app.py | 5 ++++- cloud/emails.py | 7 ++++++- cloud/models.py | 26 ++++++++++++++++++++++++++ cloud/videos.py | 28 +++++++++++++++++++--------- 4 files changed, 55 insertions(+), 11 deletions(-) diff --git a/app.py b/app.py index 9b2737c..641b868 100644 --- a/app.py +++ b/app.py @@ -858,8 +858,11 @@ async def _notify_clips_ready(job_id): if not user or not user.email: return title = clips[0].get('video_title_for_youtube_short') or clips[0].get('title') or "Your video" + # #app opens the app itself. The bare frontend URL showed the marketing + # landing to anyone whose browser had not already set the skip flag, + # which is the wrong page for someone clicking "View my clips". await send_clips_ready_email(user.email, title, len(clips), - _cloud_config.settings.frontend_url) + f"{_cloud_config.settings.frontend_url}/#app") except Exception as e: print(f"⚠️ Clips-ready email error for {job_id}: {e}") diff --git a/cloud/emails.py b/cloud/emails.py index 99fca08..3d4cd08 100644 --- a/cloud/emails.py +++ b/cloud/emails.py @@ -86,7 +86,12 @@ async def send_clips_expiring_email(email: str, clip_count: int): visible instead of deleting silently. Doubles as re-engagement for users who clipped once and went quiet. """ - dash = f"{settings.frontend_url}/dashboard" + # The app has no /dashboard route and never has: it is a single-page app + # routed entirely through the hash, and #app is what opens it (see + # dashboard/src/main.jsx). /dashboard used to land on the SPA fallback, so + # the button quietly showed the marketing page; now that unknown paths + # return a real 404 it fails visibly. + dash = f"{settings.frontend_url}/#app" n = clip_count clips = f"{n} clip" + ("s" if n != 1 else "") html = f""" diff --git a/cloud/models.py b/cloud/models.py index bde3bd9..bedc1b1 100644 --- a/cloud/models.py +++ b/cloud/models.py @@ -138,6 +138,32 @@ class UserVideo(Base): created_at = Column(DateTime(timezone=True), server_default=func.now()) +class ClipExpiryWarning(Base): + """One row per clip already covered by an expiry-warning email. + + De-duplication for ``videos.warn_free_expiring`` used to be a process-local + set, which meant every API restart re-armed the warning for clips that had + already been warned about. The warning window is a full day and the sweep + runs every six hours, so any deploy inside that window sent the same user a + second "your clips will be deleted tomorrow" email. Persisting the state + fixes that: a restart no longer forgets who has been told. + + Its own table rather than a column on ``user_videos`` because the schema + bootstrap is ``create_all`` (see cloud/database.py), which creates missing + tables but never ALTERs an existing one — see [SignupAttribution] above for + the same reasoning. The CASCADE means rows disappear on their own when + ``purge_free_expired`` deletes the clip they refer to, so this never needs + its own cleanup pass. + """ + __tablename__ = "clip_expiry_warnings" + video_id = Column(UUID(as_uuid=True), + ForeignKey("user_videos.id", ondelete="CASCADE"), + primary_key=True) + user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), + nullable=False, index=True) + warned_at = Column(DateTime(timezone=True), server_default=func.now()) + + class Project(Base): """One re-openable project per completed job. diff --git a/cloud/videos.py b/cloud/videos.py index f28e2eb..0e27775 100644 --- a/cloud/videos.py +++ b/cloud/videos.py @@ -11,7 +11,7 @@ from sqlalchemy import select, delete from .config import settings, VIDEO_RETENTION_GRACE_DAYS, FREE_CLIP_RETENTION_DAYS from . import database, storage, metering -from .models import UserVideo, Subscription, Project, User +from .models import UserVideo, Subscription, Project, User, ClipExpiryWarning from .auth import get_current_user_required router = APIRouter() @@ -333,18 +333,17 @@ async def purge_free_expired(): print(f"⚠️ Free retention purge failed for {user_id}: {e}") -# Video ids already covered by an expiry-warning email, so the 6-hourly sweep -# doesn't re-mail the same user four times during the warning window. Process -# memory only: after a restart the worst case is one duplicate warning. -_warned_video_ids: set = set() - - async def warn_free_expiring(): """Email free users whose clips enter their LAST day before deletion. The 7-day free retention is the plan's strongest honest upgrade lever, but silently deleting clips converts nobody — the user never learns they were at risk. One email on day 6 turns the real deadline into a visible one. + + "Already warned" is recorded in clip_expiry_warnings rather than in memory. + The warning window is a full day and this sweep runs every six hours, so a + process-local set meant any deploy inside that window re-mailed everyone who + had already been told. """ from datetime import datetime, timezone from .emails import send_clips_expiring_email @@ -357,10 +356,11 @@ async def warn_free_expiring(): select(UserVideo).where(UserVideo.created_at < warn_cutoff, UserVideo.created_at >= doomed_after) )).scalars()) + already = set((await s.execute(select(ClipExpiryWarning.video_id))).scalars()) by_user = {} for v in expiring: - if v.id in _warned_video_ids: + if v.id in already: continue by_user.setdefault(v.user_id, []).append(v) @@ -371,9 +371,19 @@ async def warn_free_expiring(): user = await s.get(User, user_id) if not user or not user.email: continue + # Record the warning BEFORE sending. A duplicate email is the failure we + # are fixing; a warning row for a mail that then failed to send only + # costs that user one notice, which is the cheaper way to be wrong. + try: + async with database.session() as s: + async with s.begin(): + for v in vids: + s.add(ClipExpiryWarning(video_id=v.id, user_id=user_id)) + except Exception as e: + print(f"⚠️ Could not record expiry warning for {user_id}: {e}") + continue try: await send_clips_expiring_email(user.email, len(vids)) - _warned_video_ids.update(v.id for v in vids) print(f"⏳ Expiry warning sent: {len(vids)} clip(s), user {user_id}") except Exception as e: print(f"⚠️ Expiry warning failed for {user_id}: {e}")