Compare commits

..
2 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 5.5 25888ca003 fix: Stripe made-for-you emails + bulk_submit job creation off the event loop (v0.282.2) (#1212)
## Summary
Two event-loop stalls from the 2026-10-22 #alerts triage. Each froze
every request on the instance.

- **22s stall, 11 requests (15:57 UTC).** `stripe_webhook` (async) →
`_handle_made_for_you_order` sent the customer order-confirmation email
through sync Postmark, with retries and SMTP fallback, on the loop. It
was the NOMAD-1800 order. The confirmation, the admin notification and
`_prepare_theme_for_job` (GCS) now run via `asyncio.to_thread`.
- **26s stall, 9 requests (15:30 UTC).** `bulk_submit` (async) ran the
credit check, default-theme lookup and one sync `create_job` +
`update_job` per song on the loop (an album batch). That block is now a
sync helper run via `asyncio.to_thread`. Behaviour is unchanged: the
same `HTTPException`s propagate from the thread.

## Guard (`test_no_blocking_async_routes.py`)
- `BLOCKING_CALLS` now includes `send_made_for_you_order_confirmation`
and `send_made_for_you_admin_notification`.
- New `test_no_known_blocking_calls_in_awaited_route_helpers` also scans
`_handle_made_for_you_order`. It is an awaited helper, not a decorated
route, so the route-only scan missed it, including its
`_prepare_theme_for_job`, which was already on the denylist.
- New `test_bulk_submit_creates_jobs_off_the_loop`.
- Both new tests fail on `origin/main` (checked against the old files)
and pass here.

Out of scope: sync `create_job`/`update_job` still runs directly in
about 20 other async routes (audio_search, file_upload, jobs.retry_job,
…). Each call is usually fast. It's worth a broader sweep if the
watchdog keeps catching them.

## Testing
- `make test` backend: 6607 passed, 8 failed. All 8 are in
`test_emulator_integration.py`, because another session's Firestore
emulator holds :8080 locally (same as noted on #1210). CI's emulator job
is authoritative.
- Targeted: bulk submit, made-for-you, Stripe webhook and the blocking
guard: 114 passed.
- The local CodeRabbit CLI failed with "Invalid token", so the bot
review stays on.

Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1562858789785309195
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1562858791446388862

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_016F41fLoBotUw2wUjGCuAok

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Improvements**
* Bulk song submissions and made-for-you order processing are less
likely to delay other activity while work is underway.
* Existing credit checks and handling of jobs created before credits run
out remain unchanged.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:55:36 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 bc8b033cb5 chore(cloudflare): app-link fingerprint for kjbox.cc (applied) (#1215)
Sets Pulumi config `kjboxcc_android_sha256_fingerprints` to the Android
debug keystore SHA-256 used by the Nomad Karaoke app builds (release key
gets added in Phase 6). Already applied (`pulumi up`: worker content
only). Google Digital Asset Links check: linked=true for kjbox.cc,
www.kjbox.cc and sing.nomadkaraoke.com.

Config-only change; CodeRabbit not needed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_013Bkasn6trBadg1Zb39vSVR

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:31:09 -04:00
7 changed files with 248 additions and 88 deletions

No files matched your search

+100 -76
View File
@@ -9,6 +9,7 @@ Submission (POST /bulk/submit) and progress (GET /bulk/{batch_id}) live here too
(added in later phases).
"""
import asyncio
import logging
import uuid
from typing import Literal, Optional
@@ -22,6 +23,9 @@ from backend.services.auth_service import AuthResult
logger = logging.getLogger(__name__)
# Strong refs to shielded tasks so they aren't garbage-collected if the request is cancelled.
_BACKGROUND_TASKS: set = set()
router = APIRouter(prefix="/bulk", tags=["bulk"])
MAX_BULK_SONGS = 100
@@ -304,92 +308,112 @@ async def bulk_submit(
user_email = auth_result.user_email
is_admin = bool(auth_result.is_admin)
# Upfront credit gate (1 credit/song minimum). Admins bypass.
if not is_admin and user_email:
from backend.services.user_service import get_user_service
locale = get_full_locale_from_request(request)
available = get_user_service().check_credits(user_email)
if available < n:
raise HTTPException(
status_code=402,
detail={
"error": "insufficient_credits",
"message": "You don't have enough credits for this batch.",
"credits_available": available,
"credits_required": n,
# Everything up to dispatch is sync Firestore/GCS work (credit check, default
# theme, one create_job + update_job per song). Run it off the event loop: a
# 2026-10-22 album batch stalled the loop 26s and 9 other requests with it.
def _create_batch_jobs() -> tuple[str, list[str]]:
# Upfront credit gate (1 credit/song minimum). Admins bypass.
if not is_admin and user_email:
from backend.services.user_service import get_user_service
available = get_user_service().check_credits(user_email)
if available < n:
raise HTTPException(
status_code=402,
detail={
"error": "insufficient_credits",
"message": "You don't have enough credits for this batch.",
"credits_available": available,
"credits_required": n,
},
)
settings = get_settings()
theme_service = get_theme_service()
theme_id = theme_service.get_default_theme_id()
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(theme_id, None, None)
batch_id = uuid.uuid4().hex[:12]
bulk_settings = body.settings.model_dump()
job_manager = JobManager()
job_ids: list[str] = []
for song in body.songs:
display_artist = (song.display_artist or song.artist).strip()
display_title = (song.display_title or song.title).strip()
request_metadata = {
"created_from": "bulk",
"batch_id": batch_id,
"user_email": user_email,
}
job_create = JobCreate(
artist=display_artist,
title=display_title,
theme_id=theme_id,
enable_cdg=resolved_cdg,
enable_txt=resolved_txt,
user_email=user_email,
audio_search_artist=song.artist.strip(),
audio_search_title=song.title.strip(),
auto_download=False,
is_private=body.settings.is_private,
review_mode=body.settings.review_mode,
backing_preference=body.settings.backing_preference,
translation_language=body.settings.translation_language,
brand_prefix=settings.default_brand_prefix,
enable_youtube_upload=settings.default_enable_youtube_upload,
youtube_description=settings.default_youtube_description,
discord_webhook_url=settings.default_discord_webhook_url,
dropbox_path=settings.default_dropbox_path,
gdrive_folder_id=settings.default_gdrive_folder_id,
request_metadata=request_metadata,
locale=locale,
)
try:
job = job_manager.create_job(job_create, is_admin=is_admin)
except InsufficientCreditsError:
# Ran out mid-batch (e.g. concurrent spend after the gate). Stop here;
# already-created jobs are valid and will proceed.
logger.warning("[batch:%s] ran out of credits after %d/%d jobs", batch_id, len(job_ids), n)
break
job_manager.update_job(
job.job_id,
{
"state_data.batch_id": batch_id,
"state_data.bulk_settings": bulk_settings,
"state_data.bulk_pending_search": True,
},
)
settings = get_settings()
theme_service = get_theme_service()
theme_id = theme_service.get_default_theme_id()
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(theme_id, None, None)
batch_id = uuid.uuid4().hex[:12]
bulk_settings = body.settings.model_dump()
job_manager = JobManager()
job_ids: list[str] = []
for song in body.songs:
display_artist = (song.display_artist or song.artist).strip()
display_title = (song.display_title or song.title).strip()
request_metadata = {
"created_from": "bulk",
"batch_id": batch_id,
"user_email": user_email,
}
job_create = JobCreate(
artist=display_artist,
title=display_title,
theme_id=theme_id,
enable_cdg=resolved_cdg,
enable_txt=resolved_txt,
user_email=user_email,
audio_search_artist=song.artist.strip(),
audio_search_title=song.title.strip(),
auto_download=False,
is_private=body.settings.is_private,
review_mode=body.settings.review_mode,
backing_preference=body.settings.backing_preference,
translation_language=body.settings.translation_language,
brand_prefix=settings.default_brand_prefix,
enable_youtube_upload=settings.default_enable_youtube_upload,
youtube_description=settings.default_youtube_description,
discord_webhook_url=settings.default_discord_webhook_url,
dropbox_path=settings.default_dropbox_path,
gdrive_folder_id=settings.default_gdrive_folder_id,
request_metadata=request_metadata,
locale=get_full_locale_from_request(request),
)
try:
job = job_manager.create_job(job_create, is_admin=is_admin)
except InsufficientCreditsError:
# Ran out mid-batch (e.g. concurrent spend after the gate). Stop here;
# already-created jobs are valid and will proceed.
logger.warning("[batch:%s] ran out of credits after %d/%d jobs", batch_id, len(job_ids), n)
break
job_manager.update_job(
job.job_id,
{
"state_data.batch_id": batch_id,
"state_data.bulk_settings": bulk_settings,
"state_data.bulk_pending_search": True,
},
)
job_ids.append(job.job_id)
if not job_ids:
raise HTTPException(status_code=402, detail="No jobs could be created")
job_ids.append(job.job_id)
return batch_id, job_ids
# Dispatch the batch search worker. Retry once on transient failure. If it
# still fails the jobs exist (and are charged) but won't process, so surface
# an explicit error with the batch_id — and tell the user NOT to resubmit
# (that would create+charge a second batch); the batch can be re-dispatched.
worker_service = get_worker_service()
triggered = await worker_service.trigger_bulk_search_worker(batch_id)
if not triggered:
async def _create_and_dispatch() -> tuple[str, list[str], bool]:
batch_id, job_ids = await asyncio.to_thread(_create_batch_jobs)
if not job_ids:
return batch_id, job_ids, False
triggered = await worker_service.trigger_bulk_search_worker(batch_id)
if not triggered:
triggered = await worker_service.trigger_bulk_search_worker(batch_id)
return batch_id, job_ids, triggered
# Shielded: if the request is cancelled (client disconnect) mid-way, the jobs
# being created and charged in the thread still get dispatched.
task = asyncio.create_task(_create_and_dispatch())
_BACKGROUND_TASKS.add(task)
task.add_done_callback(_BACKGROUND_TASKS.discard)
batch_id, job_ids, triggered = await asyncio.shield(task)
if not job_ids:
raise HTTPException(status_code=402, detail="No jobs could be created")
if not triggered:
logger.critical(
"[batch:%s] created %d jobs but FAILED to dispatch bulk-search worker",
+19 -11
View File
@@ -8,6 +8,7 @@ Handles:
- Stripe checkout and webhooks
- Admin user management
"""
import asyncio
import hashlib
import html
import logging
@@ -1304,10 +1305,21 @@ async def _handle_made_for_you_order(
logger.info(f"Created made-for-you job {job_id} for {_mask_email(customer_email)} (owned by {_mask_email(ADMIN_EMAIL)})")
# Mark the session processed straight after creating the job, before any await:
# if this task is cancelled at an await below, Stripe's retry must find the
# session already handled rather than create a second job for the same order.
# Note: Using internal method since this isn't a credit transaction
user_service._mark_stripe_session_processed(
stripe_session_id=session_id,
email=customer_email,
amount=0 # No credits, just tracking the session
)
# Prepare theme style assets for the job (same as audio_search endpoint)
if effective_theme_id:
try:
style_params_path, theme_style_assets, youtube_desc = _prepare_theme_for_job(
style_params_path, theme_style_assets, youtube_desc = await asyncio.to_thread(
_prepare_theme_for_job,
job_id, effective_theme_id, None # No color overrides for made-for-you
)
theme_update = {
@@ -1321,14 +1333,6 @@ async def _handle_made_for_you_order(
except Exception as e:
logger.warning(f"Failed to prepare theme for made-for-you job {job_id}: {e}")
# Mark session as processed for idempotency
# Note: Using internal method since this isn't a credit transaction
user_service._mark_stripe_session_processed(
stripe_session_id=session_id,
email=customer_email,
amount=0 # No credits, just tracking the session
)
# Initialize search_results for later use in email notification
search_results = None
@@ -1341,7 +1345,10 @@ async def _handle_made_for_you_order(
try:
# Providers return False (not an exception) when the send is rejected, so
# check the result rather than assuming success.
confirmation_ok = bool(email_service.send_made_for_you_order_confirmation(
# Off the event loop: a slow Postmark send (retries + SMTP fallback)
# stalled every request on the instance for 22s on 2026-10-22.
confirmation_ok = bool(await asyncio.to_thread(
email_service.send_made_for_you_order_confirmation,
to_email=customer_email,
artist=artist,
title=title,
@@ -1507,7 +1514,8 @@ async def _handle_made_for_you_order(
email=ADMIN_EMAIL,
expiry_hours=24,
)
admin_notified = bool(email_service.send_made_for_you_admin_notification(
admin_notified = bool(await asyncio.to_thread(
email_service.send_made_for_you_admin_notification,
to_email=ADMIN_EMAIL,
customer_email=customer_email,
artist=artist,
+45
View File
@@ -148,3 +148,48 @@ def test_partial_failure_returns_created_jobs(client, monkeypatch):
})
assert resp.status_code == 200
assert resp.json()["total"] == 2
@pytest.mark.asyncio
async def test_cancelled_request_still_dispatches_created_batch(monkeypatch):
"""A client disconnect mid-creation must not strand created (and charged) jobs:
the create+dispatch step is shielded, so dispatch still runs after cancellation."""
import asyncio
import threading
import backend.api.routes.bulk as bulk
from starlette.requests import Request
_patch_user_service(monkeypatch, credits=10)
jm = _patch_job_manager(monkeypatch)
started, release = threading.Event(), threading.Event()
inner_create = jm.create_job.side_effect
def _slow_create(job_create, is_admin=False):
started.set()
release.wait(5)
return inner_create(job_create, is_admin=is_admin)
jm.create_job.side_effect = _slow_create
dispatched = []
async def _trigger(batch_id):
dispatched.append(batch_id)
return True
worker = MagicMock()
worker.trigger_bulk_search_worker = _trigger
monkeypatch.setattr("backend.services.worker_service.get_worker_service", lambda: worker)
request = Request({"type": "http", "method": "POST", "path": "/api/bulk/submit", "headers": []})
body = bulk.BulkSubmitRequest(songs=[{"artist": "A", "title": "B"}], settings={})
route = asyncio.create_task(bulk.bulk_submit(request, body, _auth()()))
await asyncio.to_thread(started.wait, 5)
route.cancel()
release.set()
with pytest.raises(asyncio.CancelledError):
await route
for _ in range(100): # let the shielded task finish
if dispatched:
break
await asyncio.sleep(0.01)
assert len(dispatched) == 1
+37
View File
@@ -1026,6 +1026,43 @@ class TestHandleMadeForYouOrder:
assert job_create_arg.made_for_you is True, \
"Job must be created with made_for_you=True for made-for-you orders"
@pytest.mark.asyncio
async def test_session_marked_processed_before_theme_prep(
self, mock_job_manager, mock_email_service, mock_user_service,
mock_theme_service, order_metadata
):
"""The session must be marked processed before the first await after create_job.
If the webhook task is cancelled while theme prep runs, Stripe's retry then finds
the session handled instead of creating a second job for the same order."""
from backend.api.routes.users import _handle_made_for_you_order
marked_before_theme = []
def _prepare(*args, **kwargs):
marked_before_theme.append(mock_user_service._mark_stripe_session_processed.called)
return ("style.json", {}, None)
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
patch('backend.services.worker_service.get_worker_service'), \
patch('backend.services.audio_search_service.get_audio_search_service') as mock_get_audio, \
patch('backend.services.storage_service.StorageService'), \
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
patch('backend.api.routes.users._prepare_theme_for_job', side_effect=_prepare):
from backend.services.audio_search_service import NoResultsError
mock_audio_service = MagicMock()
mock_audio_service.search.side_effect = NoResultsError("No results")
mock_get_audio.return_value = mock_audio_service
await _handle_made_for_you_order(
session_id="sess_123",
metadata=order_metadata,
user_service=mock_user_service,
email_service=mock_email_service,
)
assert marked_before_theme == [True]
mock_user_service._mark_stripe_session_processed.assert_called_once()
@pytest.mark.asyncio
async def test_job_owned_by_admin_during_processing(
self, mock_job_manager, mock_email_service, mock_user_service,
@@ -223,6 +223,10 @@ BLOCKING_CALLS = {
"get_metadata_from_gcs",
"upload_file",
"download_file",
# 2026-10-22 watchdog culprits: the Stripe webhook's made-for-you order emails
# (Postmark retries + SMTP fallback, 22s, 11 requests).
"send_made_for_you_order_confirmation",
"send_made_for_you_admin_notification",
}
_BLOCKING_MODULE_CALLS = {("requests", "get"), ("requests", "post"), ("requests", "put"),
("requests", "delete"), ("requests", "request"), ("time", "sleep")}
@@ -328,3 +332,43 @@ async def fixed(request):
assert find_blocking_calls_in_async_routes(src) == []
hits = find_blocking_calls_in_async_routes(src, routes_only=False)
assert [h.split(" line")[0] for h in hits] == ["require_auth: validate_token_full()"]
# Async helpers that a route awaits run on the loop too, but they aren't decorated so the
# route-only scan above skips them.
AWAITED_ROUTE_HELPERS = {
BACKEND / "api" / "routes" / "users.py": {"_handle_made_for_you_order"},
}
def test_no_known_blocking_calls_in_awaited_route_helpers():
offenders = []
for path, helpers in AWAITED_ROUTE_HELPERS.items():
for hit in find_blocking_calls_in_async_routes(path.read_text(), routes_only=False):
if hit.split(":")[0] in helpers:
offenders.append(f"{path.relative_to(BACKEND.parent)}::{hit}")
assert not offenders, (
"These async route helpers call known-blocking functions on the event loop. "
"Use `await asyncio.to_thread(fn, ...)`:\n " + "\n ".join(sorted(offenders))
)
def test_bulk_submit_creates_jobs_off_the_loop():
"""bulk_submit's per-song create_job/update_job loop stalled the loop 26s
(2026-10-22, an album batch). It must stay inside the to_thread helper."""
import ast
tree = ast.parse((BACKEND / "api" / "routes" / "bulk.py").read_text())
route = next(n for n in ast.walk(tree)
if isinstance(n, ast.AsyncFunctionDef) and n.name == "bulk_submit")
direct = []
stack = list(route.body)
while stack:
node = stack.pop()
if isinstance(node, (ast.FunctionDef, ast.Lambda, ast.ClassDef)):
continue
if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
and node.func.attr in {"create_job", "update_job", "check_credits", "get_default_theme_id"}):
direct.append(f"{node.func.attr}() line {node.lineno}")
stack.extend(ast.iter_child_nodes(node))
assert not direct, f"bulk_submit calls sync Firestore/GCS on the loop: {direct}"
@@ -5,3 +5,5 @@ config:
nomad-cloudflare:googleOauthClientSecret:
secure: AAABAF/ZOcl4fY4R+829/6axVvqqq5QeZou0BtO5BkszNcDUwMc1CEnkVlDMdUX9O3SXI2EfWGcdhx9S50uMHbxnZw==
nomad-cloudflare:googleOauthClientId: 718638054799-lqgmpmaauc23mc7mu822pspvq0s1tla3.apps.googleusercontent.com
nomad-cloudflare:kjboxcc_android_sha256_fingerprints:
- FA:C6:17:45:DC:09:03:78:6F:B9:ED:E6:2A:96:2B:39:9F:73:48:F0:BB:6F:89:9B:83:32:66:75:91:03:3B:9C
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.282.1"
version = "0.282.2"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"