Compare commits

...
40 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.8 1b7b106c21 fix(lyrics): sanitize invalid word timings to prevent overlapping screens (#804)
## Summary
- Fixes overlapping rendered lyrics on job `17f7c313` ("Atmosphere -
Scalp") — two full screens of lyrics displayed on the same 4 vertical
slots for 7-12s.
- **Distinct root cause** from the earlier libass-wrap overlap (PR
#794), which is why it recurred. This one is a genuine same-Y /
same-time overlap caused by invalid word timestamps.

## Root cause
The transcription left the 4 leading words of a segment ("A whiskey and
a") with invalid timestamps (`start=0.0`, `end=-0.005`) while the
segment itself correctly started at 15.18s.
`SegmentResizer._create_segment_from_words` derives a split line's
`start_time` from `words[0].start_time`, so the split line `"A whiskey
and a beer,"` inherited `start_time=0.0`. A `LyricsScreen` sorts by
`min(line.segment.start_time)`, so the screen jumped ahead of the INTRO
section screen; the INTRO then wiped the active-line bookkeeping and the
next screen faded in (post-instrumental) over the still-displayed
previous screen.

## Changes
- Add `SegmentResizer._sanitize_segment_timings`, run at the top of
`resize_segments` (covers all output paths via `generator.py`).
- Clamps **only invalid** word timings into the segment's `[start, end]`
window and keeps them non-decreasing; valid words are left untouched so
the karaoke highlight sweep is preserved.
- New regression tests in
`tests/unit/lyrics_transcriber/output/test_segment_resizer_timing.py`.
- Bump version `0.176.1` → `0.176.2`.

## Testing
- [x] New timing regression tests + prior line-length regression tests
pass
- [x] Full `lyrics_transcriber` unit suite: 110 passed
- [x] End-to-end against job `17f7c313`: **4 same-Y overlaps before → 0
after**

## Review
- [x] Local CodeRabbit review completed (0 findings)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 19:24:43 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 bce87a37fb feat(ui): advertise multi-site URL support on create-from-URL input (#803)
## Summary

Phase 3 of the flacfetch-sole-downloader work. Now that **all** URLs
route through flacfetch and any yt-dlp-supported site works (Facebook,
SoundCloud, TikTok, Vimeo, …), tell users so on the create-from-URL
input.

## Changes (`frontend/components/job/steps/AudioSourceStep.tsx`)

- Broaden the button label **"YouTube URL" → "Paste a link"**.
- Add a hint under the URL field: *"Works with YouTube, Facebook,
SoundCloud, TikTok, Vimeo and hundreds of other sites."* with a link to
the yt-dlp [supported-sites
list](https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md).
- Wire the URL section to i18n (`useTranslations('jobFlow')`) —
previously hardcoded — and add 4 new `jobFlow` keys (`pasteUrlButton`,
`useThisUrl`, `urlSupportedSitesHint`, `urlSupportedSitesLink`).
- Translated to **all 33 locales** via `translate.py` (key parity
verified; CI i18n validation will confirm).

## Testing

- i18n key parity verified across all 33 locale files (0 missing).
- Existing `AudioSourceStep.test.tsx` uses the global `next-intl` mock
that returns real en.json strings, and asserts none of the changed
literals — unaffected.
- Frontend `next build`/jest/E2E run in CI (node_modules isn't installed
in this worktree).

Depends on the already-shipped backend change (#802) that makes
non-YouTube URLs actually work.

Plan:
`nomadkaraoke/docs/archive/2026-06-08-flacfetch-sole-downloader-plan.md`

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 15:51:02 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 11b3d30618 feat(downloads): route all URLs through flacfetch; remove Cloud Run yt-dlp (#802)
## Summary

Phase 2 of making **flacfetch the sole audio downloader** — no yt-dlp
ever runs on Cloud Run. Fixes the original Facebook-URL job failure and
removes a class of legacy silent-fallback behaviour.

**Root cause of the reported bug** (job `34e60208`,
`facebook.com/share/v/...`): non-YouTube URLs were downloaded by local
yt-dlp *inside the Cloud Run container*, which succeeded but then died
in `convert_to_wav` (ffmpeg given both `-y` and `-n`), surfacing as a
generic `Failed to download audio file`. Rather than patch the flags,
this removes the path entirely.

## Changes

- **`youtube_download_service.py`** — `download()` now handles **any**
yt-dlp-supported URL: YouTube via the existing video-id path; everything
else (Facebook, SoundCloud, TikTok, Vimeo, …) via flacfetch's generic
`URL` source (`download_by_id(source_name="URL", download_url=url)`).
**Deleted `_download_local`** (local yt-dlp fallback); with no flacfetch
configured it now **hard-fails with a clear error** instead of silently
falling back.
- **`file_upload.create_job_from_url`** — downloads audio up front via
the service for **all** URLs (not just YouTube), then
`start_job_processing`. Removed the non-YouTube branch that triggered
the GPU worker to download locally, and the now-dead
`_trigger_audio_worker_only`. (Keeps GPU idle until audio is in GCS.)
- **`audio_worker.py`** — deleted `download_from_url` (the buggy local
path) and `download_audio`'s URL-download fallback + the dead
`_trigger_lyrics_worker_after_url_download`. The worker now only
consumes a pre-downloaded GCS file; a URL job arriving without one fails
clearly.
- **Docs** — added
`docs/archive/2026-06-08-fallback-logic-audit-prompt.md` (a prompt for a
future session to audit all legacy "fallback" logic).

Net **−331 lines**.

## Testing

- Updated/replaced tests for the removed fallbacks; added tests for
generic-URL routing (`source_name="URL"`) and the no-flacfetch
hard-fail. Affected suites green (410 passed across the touched files);
full backend collection clean.
- Depends on **flacfetch ≥ 0.21.0** (generic `URL` source) — already
shipped & deployed (flacfetch #28), and verified end-to-end: the
original Facebook URL downloads through flacfetch to GCS.

Requires no infra change. Plan:
`nomadkaraoke/docs/archive/2026-06-08-flacfetch-sole-downloader-plan.md`.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 15:15:13 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 a319bf206a feat(lyrics-review): show song artist + title in header (#801)
## Summary

The Lyrics Transcription Review header showed only the static title
"Lyrics Transcription Review". The Instrumental Review header already
displays the song (artist + title). This adds the same song display to
the lyrics review header so reviewers can see which song they're working
on at a glance.

## Changes

- `frontend/app/[locale]/app/jobs/[[...slug]]/client.tsx`: render
`artist - title` (from the existing `job` prop) next to the header
title, mirroring the Instrumental Review pattern
(`InstrumentalSelector.tsx`). Uses `[job.artist,
job.title].filter(Boolean).join(" - ")` so it degrades cleanly when a
field is missing, with `truncate` to protect the layout.
- `pyproject.toml`: version bump 0.175.1 → 0.175.2.

## Testing

- ESLint clean on the changed file.
- `tsc` reports no new errors (the 39 pre-existing errors are all in
unrelated files).
- No new user-facing strings — only renders existing `job` data — so no
i18n/translation changes (won't trip CI's locale-completeness check).
- CodeRabbit reviewed locally (1 minor finding, fixed: cleaner
artist/title join).

## Notes

Display-only, low-risk change. No existing test covers either review
header's artist/title display (the instrumental review precedent has
none either); a meaningful test would require mocking the full lyrics
data-loading lifecycle, so none was added.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 12:31:31 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 c1837c1086 fix(lyrics-review): gate audio playback until loaded + silence benign AbortError noise (#800)
## Summary
- Production error monitor flagged `AbortError: The fetching process for
the media resource was aborted...` from the lyrics-review page. Root
cause: the audio player started fetching a large file on mount but left
playback controls live before the media could play, so early clicks /
spacebar did nothing **and** the rejected `play()` promise was reported
as error noise.
- Fixes both the noise and the janky UX: playback is now gated until the
audio is fully ready, with a clear loading spinner + buffer progress
bar.

## Changes
- **AudioPlayer** is now the single source of truth for readiness:
tracks `canplaythrough` (+ fully-buffered fallback), publishes
`window.isAudioReady` and a `karaoke:audio-ready` event, and **guards
the `seekAndPlayAudio` / `toggleAudioPlayback` globals** so spacebar,
segment buttons, and the edit modal no-op until ready.
- While loading, shows a spinner + `<Progress>` bar ("Loading
audio..."); on failure shows an inline error.
- New `useAudioReady()` hook visually disables the segment play buttons
(`TranscriptionView`) and the edit-modal play button with an "Audio is
still loading..." tooltip.
- Added `.catch(() => {})` to the three bare `play()` calls and filter
benign `AbortError` in `crash-reporter` so this class of noise never
reaches the error monitor again.
- 3 new i18n strings, translated to all 33 locales (ASCII `...` to match
existing loading strings).

## Testing
- [x] Frontend unit suite green: **916 tests / 65 suites** (added
`AudioPlayer` readiness+gating, `useAudioReady`, `crash-reporter`
benign-abort cases)
- [x] Lint clean; typecheck clean on all touched files
- [ ] Manual: throttled-network check of spinner → controls transition
(recommended post-deploy)

## Review
- [x] CodeRabbit CLI review completed locally (1 finding fixed: ASCII
ellipsis; 1 pre-existing tl.json translation gap noted, out of scope)
- [x] Issues addressed

Plan doc: `docs/archive/2026-06-07-lyrics-review-audio-loading-plan.md`

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 10:45:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 7cf42c8983 feat(pricing): duration-based credit pricing + long-duration input handling (#799)
@coderabbitai ignore

## Summary

Implements **duration-based credit pricing** for karaoke jobs, replacing
the flat 1-credit/job model. Credits now scale with input audio length
(`ceil(min/10)`, hard-block >60 min), with cost confirmed before heavy
processing and reconciled against the actual measured audio. Closes out
the planned fix from the 2026-06-04 long-duration mashup incident.

- Design:
`docs/archive/2026-06-04-long-duration-input-handling-design.md`
- Plan: `docs/archive/2026-06-04-long-duration-input-handling-plan.md`

## Pricing model

`credits = max(1, ceil(minutes / 10))` — 1 credit ≤10 min, 2 ≤20 min … 6
≤60 min. Inputs over 60 min are blocked. Single source of truth in
`backend/services/pricing.py`, mirrored in `frontend/lib/pricing.ts`.

## How it works

- **`state_data.credits_charged`** is the authoritative running total.
`create_job` charges the base (URL = full N via `acknowledged_credits`;
search/upload = 1); top-ups deduct only the **delta**
(`count_as_job_creation=False`).
- **Reconciliation engine** (`duration_reconciliation.py`) runs at the
single convergence point before separation+transcription in all three
processing paths (download / post-edit / `start_job_processing`),
exactly once each. It measures the audio actually sent to AudioShake
(post-edit if trimmed):
  - actual < estimate → auto-refund the difference
- actual > estimate → pause at new **`AWAITING_DURATION_CONFIRM`**
state, user re-confirms (inline Buy Credits)
  - actual > 60 min → refund everything + cancel
- **`POST /api/jobs/{id}/confirm-duration`** (+ `POST
/api/jobs/estimate`) reuse the review-stage pause/resume.
- **Notifications**: in-browser + push, 15-min idle email, 24h reminder,
**48h auto-cancel + full refund** — via the existing idle-reminder /
stale-job machinery.
- **Admin / made-for-you jobs bypass charging entirely**
(`payment_bypassed` → reconcile short-circuits).

## Endpoints

| Method | Path | Purpose |
|---|---|---|
| `POST` | `/api/jobs/estimate` | URL duration probe →
`{duration_seconds, credits, blocked, source}` |
| `POST` | `/api/jobs/{id}/confirm-duration` | confirm cost / resume
(402 insufficient, 409 mismatch) |
| `POST` | `/api/jobs` | URL create gains optional `duration_seconds`,
`acknowledged_credits` |
| `POST` | `/api/audio-search/{id}/select` | gains optional
`acknowledged_credits` |

## Frontend

`DurationCostConfirm` modal (Radix Dialog) surfaced via a "Confirm Cost"
action on `awaiting_duration_confirm` jobs (`useDurationConfirm` hook),
per-result cost chips on audio search, `pricing` i18n namespace in all
33 locales.

## Testing

- Backend: **3358 passing** (incl. boundary tables, money-math
conservation, reconcile up/down/over-limit, confirm 402/409, idempotency
guards, stale-expiry refund, an end-to-end integration test). Frontend:
**960 passing**. i18n completeness clean.
- Reviewed locally: per-task spec + quality review, a holistic
cross-cutting review, `/test-review`, and two CodeRabbit fix cycles.

## Notable bugs caught & fixed during review

- **Multi-credit under-refund**: `_refund_credit_for_job` refunded a
flat 1 — now refunds `credits_charged` (user-cancel of a long job).
- **Admin-bypass trap**: admin jobs would pause at the confirm gate and
be charged real credits — now short-circuited.
- Over-limit double-refund (suppress `cancel_job`'s built-in 1-credit
refund); over-limit email used the wrong "48h" message;
double-confirm/double-select idempotency guards.
- Hit the summary-projection gotcha (added fields to both projection
lists + regression test).

## Known residuals / follow-ups (non-blocking)

- **URL pre-flight cost-confirm is inert** until flacfetch's
`/check-youtube` returns a `duration` key — currently falls back to a
1-credit hold + post-download reconcile (functionally correct). Separate
flacfetch change.
- Duration-confirm email **bodies** are English (URLs are
locale-prefixed; backend i18n covers en/es/de) — `# TODO(i18n)` left.
- Concurrent confirm/select **double-charge TOCTOU** is an accepted
low-probability residual (atomic claim would need a Firestore
transaction); the status-transition guard handles the realistic
double-click case.

## Deploy note

Reuses the existing Cloud Tasks idle-reminder queue and the hourly
stale-review Cloud Scheduler (status-list / action-type expansions only)
— no new infra expected, but worth confirming `pulumi up` is a no-op on
deploy.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 18:39:06 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 e806616408 fix: idempotent session revoke, error-pattern script crash, mobile header overlap (#798)
## Summary
Three independent fixes bundled together:

1. **`revoke_session` idempotency** — stops the recurring `Error
revoking session` prod error on `karaoke-backend`. Firestore
`document.update()` raises `NotFound` (404) when a session doc is
already gone (logged out / expired / cleaned up); logout against an
already-absent session now succeeds instead of erroring.
2. **`query-error-patterns.py` crash** — `last_seen`/`first_seen` are
stored as ISO-8601 strings in Firestore, but the sort key and `--hours`
filter did `float(value)`, raising `ValueError` and breaking the
`--json` path that `/prod-investigate` relies on. Added a `_to_epoch()`
helper handling datetime objects, ISO strings, and numeric epochs.
3. **Mobile header overlap** — `AppHeader` was `position: fixed` and
each consumer cleared it with a hardcoded top padding. On narrow
viewports the header wraps to 3 rows (149px on a 412px Pixel), exceeding
the 112px offset, hiding the "Create Karaoke Video" heading and the top
of the form behind it (worse across locales with longer button labels).
Switched `AppHeader` to `position: sticky` (matching the already-working
jobs-page header) so content always clears it at any height, and removed
the now-redundant magic-number offsets.

## Changes
- `backend/services/user_service.py` — catch
`google_exceptions.NotFound` in `revoke_session`, return `True`
- `backend/tests/test_revoke_session.py` — new unit tests (existing /
missing / unexpected-error paths)
- `scripts/query-error-patterns.py` — `_to_epoch()` helper for sort +
`--hours` filter
- `frontend/components/app-header.tsx` — `fixed` → `sticky`
- `frontend/app/[locale]/app/page.tsx`,
`frontend/app/[locale]/app/referrals/page.tsx` — drop hardcoded top
padding
- `pyproject.toml` — bump to 0.174.17

## Testing
- [x] Backend tests pass locally (47 passed incl. 3 new `revoke_session`
tests)
- [x] `query-error-patterns.py --json` and `--hours` verified against
live Firestore
- [x] Mobile header fix verified in Playwright at 412px (Pixel) and
1280px — overlap eliminated (title moves from 12px behind the header to
a clear gap below it)
- [x] CodeRabbit CLI review: 0 findings

## Review
- [x] Local CodeRabbit review completed
- [x] Review feedback addressed (none)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 23:24:21 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 87f36687bf fix(storage): treat missing GCS object as no-op on best-effort deletes (#797)
## Summary

Recurring production error-monitor alerts — five sibling patterns of the
form
`Error deleting file <path>: 404 DELETE ... No such object` (one each
for
`.mov`, `.mp4`, `.png`, `.jpg`, `.mkv`) — were traced to routine **admin
actions**, not a real failure.

The admin **Restart Job** (`admin.py`) and **Regenerate Screens**
(`admin.py`) endpoints
speculatively delete a *hardcoded template* of every possible output
path
(`screens/title.mov`, `screens/title.png`, `output/final_4k.mp4`,
`output/with_vocals.mkv`, …)
before re-running a job. Any given job only produces a **subset** of
those (e.g. a static
title screen has no `title.mov`; a 720p-only render has no
`final_4k.mp4`), so the absent
variants return 404.

`StorageService.delete_file()` logged those 404s at **ERROR severity
before re-raising** —
even though the callers already wrapped each call in `try/except: pass`
with a
`# File may not exist` comment. The ERROR log line is what the error
monitor ingested,
generating noise tied to every admin restart/regen.

Confirmed against the most recent occurrence: job `8e9df2c1` shows
"Admin … triggered screen regeneration" at 16:58, and the `.mov` 404 was
last logged at 17:01.

## Changes

- `StorageService.delete_file(blob_path, ignore_missing=False)`: when
`ignore_missing=True`,
a `NotFound` (404) is treated as a successful no-op — logged at `debug`,
returns `False`
(vs `True` when an object was actually deleted). Default behaviour is
**unchanged**: a
  genuine unexpected 404 still logs `ERROR` and raises.
- Wired `ignore_missing=True` into the three best-effort callers:
- admin **Restart Job** output/screen cleanup (now only reports paths
actually deleted)
  - admin **Regenerate Screens** cleanup
  - `JobManager.delete_job()` output-file cleanup
- Added unit tests: returns `True` on real delete, raises on 404 by
default, returns `False`
  (no raise) on 404 when `ignore_missing=True`.

## Testing

- `test_storage_service.py`: 19 passed (incl. 3 new)
- `test_job_manager.py` + `test_credit_enforcement.py`: 69 passed
- All admin/restart/regen suites: 218 passed, 6 skipped (emulator-only)
- CodeRabbit (uncommitted): 0 findings

## Impact

Cosmetic / operational — deletions already succeeded and jobs regen
fine; this removes the
recurring false-positive ERROR logs at the source. No behaviour change
for genuine errors.

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

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 13:35:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 676e31056e fix(review): serve preview video via signed GCS URL redirect (Cloud Run 32 MiB limit) (#796)
## Summary
The preview-video endpoint failed for long songs because the 360p
preview exceeds Cloud Run's 32 MiB response-body limit. Surfaced while
testing the recovered job `9a12cf0f` (a 32-minute mashup whose preview
is **32.4 MiB**): the modal showed *"No video with supported format and
MIME type found."*

## Root cause
`get_preview_video` downloaded the mp4 and streamed it **through Cloud
Run** via `FileResponse`. For short songs previews are a few MB, but
this preview was >32 MiB, so Cloud Run truncated the response — uvicorn
logged `206` while the client received a `500` (confirmed in LB logs).
The browser got a broken body and couldn't decode it.

## Fix
Return a **302 redirect to a signed GCS URL** (matching the existing
audio-review endpoint at `review.py:372`), so the browser fetches the
mp4 directly from GCS with byte-range support intact — Cloud Run's body
limit never applies. Also removes the now-unused
`FileResponse`/`BackgroundTask` imports.

## Testing
- [x] Backend suite: **3186 passed, 36 skipped**
- [x] New tests: `TestGetPreviewVideoRedirect` (302 → signed URL, never
proxies; 404 when missing)
- [x] Verified the deployed mp4 for `9a12cf0f` is valid (h264/aac,
480x270) — the file was always fine; only the delivery path was broken.

## Review
- [x] CodeRabbit CLI review completed locally (0 findings)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 19:55:31 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 f683af6c84 fix(lyrics): cap Firestore corrections payload + scale transcription timeout by duration (#795)
## Summary
Both production error patterns alerted on 2026-06-04 traced to a
**single oversized input** — job `9a12cf0f`, a 32-minute mashup (422
segments, 3,742 words). Two fixes, plus a follow-up design doc for the
real solution (duration-based credit pricing).

## Changes
- **Firestore doc-size (`backend/api/routes/jobs.py`):**
`submit_corrections` now persists only a lightweight summary
(`state_data.corrected_lyrics = {corrected_segment_count: N}`) instead
of the multi-MB segment arrays
(`corrected_segments`/`original_segments`/`resized_segments`, ~600KB
each) that exceeded Firestore's 1MB limit. The prior `reference_lyrics`
strip missed the real bulk. Full corrections still go to GCS
(`corrections_updated.json`), which the render worker reads. The
`complete_review` 0-segment guard reads the summary and is
backward-compatible with the legacy full-dict shape.
- **Transcription timeout (`backend/workers/lyrics_worker.py`,
`backend/config.py`):** new `compute_transcription_timeout()` scales the
outer safety-net timeout by ffprobe-measured audio duration —
`clamp(floor 1200, duration × 1.0, cap 1700)` — instead of a fixed 1200s
that flapped long tracks to `failed`.
- **Infra (`infrastructure/modules/cloud_run.py`):**
lyrics-transcription-job task timeout `1800s → 3000s` + env
`TRANSCRIPTION_TIMEOUT_CAP_SECONDS=2700` so long mashups get real
headroom. **Requires `pulumi up`.**
- **Docs:** prompt/design doc for the follow-up duration-based credit
pricing + warn/block feature
(`docs/archive/2026-06-04-long-duration-input-handling-prompt.md`); two
LESSONS-LEARNED entries.
- **Tests:** new coverage for the summary contract, guard
backward-compat, and timeout boundaries; updated obsolete
`reference_lyrics`-stripping tests; modernized 4 flaky
`asyncio.get_event_loop()` tests.

## Testing
- [x] Backend suite: **3184 passed, 36 skipped** (`pytest
backend/tests`, excluding emulator/integration)
- [x] Targeted new tests green (doc-size summary, guard, timeout
scaling)

## Review
- [x] CodeRabbit CLI review completed locally (0 findings)
- [x] Issues addressed

> Note: these are targeted fixes for the symptoms. The structural fix is
the duration-pricing feature in the linked design doc.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 19:06:45 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 70bbabc661 fix(lyrics): prevent over-long lines overlapping the slot below in rendered video (#794)
## Summary
- Fixes overlapping lyric lines in rendered karaoke videos (preview and
final 4K).
- Root cause: `SegmentResizer` could emit a line longer than
`max_line_length`, which **libass word-wraps onto a second physical row
at render time**, colliding with the lyric line in the slot below (two
lines drawn on top of each other).
- This lives in the shared `lyrics_transcriber` package, so it fixes the
overlap for **all jobs**, not just the one reported.

## Root cause
In `_create_segments_from_lines`, word objects are re-assigned to the
splitter's lines via fragile substring matching. A `;` break was
positioned *before* the semicolon, so the line ended with `around` while
the word token was `around;`; the match failed and every remaining word
fell into an **unbounded catch-all** that joined them into one over-long
line. Space-dash-space (` - `) breaks orphaned the dash the same way.

## Changes
- `;` break now splits **after** the semicolon, keeping it attached to
its word token (also reads better).
- The catch-all now **greedily packs leftover words into ≤
`max_line_length` lines** instead of one unbounded segment — a length
guarantee that holds regardless of which punctuation desyncs
word-to-line matching.
- Added regression tests (`test_segment_resizer_line_length.py`):
semicolon case, dash case, single-long-word edge case, word-order
preservation.

## Testing
- [x] New regression tests pass; full backend unit suite green (the only
failures are pre-existing `audio-separator`-not-installed env errors,
unrelated to this change).
- [x] Verified against job `5c631108` + all 22 saved review sessions:
over-length output lines → **0**, no word loss/reorder.
- [x] Re-rendered the 4K overlap moment locally — confirmed the
collision is gone.

## Review
- [x] Local CodeRabbit CLI review completed; 1 minor finding addressed.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 18:33:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 fe8430d990 fix(admin): allow regen-screens from in_review state + surface errors via toast (#793)
## Summary
- Fixes a 400 when regenerating title/end screens for a job the user has
opened in the review UI (`in_review` state).
- Fixes the root cause behind "click Regenerate Screens → modal just
closes, no error": `<Toaster />` was never mounted, so **all** `toast()`
calls (success and error) silently no-op'd.

## Changes
- **Backend:** add `in_review` to `REGENERATE_SCREENS_ALLOWED_STATES` in
`backend/api/routes/admin.py`. The sibling `/restart` endpoint already
allows `in_review`; this restores parity. Updated `docs/API.md`.
- **Frontend:** mount the shadcn `<Toaster />` (same `@/hooks/use-toast`
store) in the root `app/layout.tsx` so admin toasts render app-wide.
- **Frontend:** give the regen-screens handlers specific, human-readable
failure titles/messages (admin dashboard + compact `AdminJobActions`
toolbar).
- Version bump `0.174.12` → `0.174.13`.

## Testing
- [x] Backend: `tests/unit/test_regenerate_screens.py` — allow-list
membership, `in_review` → 200, invalid state → 400, missing job → 404 (4
pass).
- [x] Frontend: `AdminJobActions.test.tsx` — error-toast path now
covered (5 pass).
- [x] CodeRabbit CLI review: 0 findings.
- [x] Typecheck: no new errors from these changes (pre-existing errors
unrelated).

## Review
- [x] CodeRabbit CLI review completed locally
- [x] Issues addressed

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-03 12:31:19 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 eb1cc7b94f fix(encoding,ci): silence self-healing warmup 503 alert + robust E2E result check (#790)
## Summary
Two unrelated production alert-noise fixes, prompted by two false-alarm
Discord alerts on 2026-05-24:

- **Encoding worker 503 → WARNING.** A primary-VM warmup hitting `503
SERVICE_UNAVAILABLE` (or capacity exhaustion) is self-healing — the
encoding flow's `ensure_any_running()` falls back to an alternate-zone
worker and the job completes (verified live on job `a40f3024`). It no
longer logs at ERROR, so it stays below the error monitor's
`severity>=ERROR` filter and stops paging Discord for a non-incident.
- **E2E daily test result check.** Both stages now derive pass/fail from
Playwright's real exit code instead of grepping the log for `"failed"`.
The old check matched the word "failed" inside a benign retry warning
(`goto attempt 1/3 failed`) and reported failure on a run where the job
completed and Playwright printed `1 passed`.

## Changes
- `backend/api/routes/encoding_worker.py` — catch
`EncodingWorkerStartError` in `/warmup` and log at WARNING with a clear
fallback message; genuine unexpected errors still log at ERROR.
- `.github/workflows/e2e-daily.yml` — capture `${PIPESTATUS[0]}` (the
pipe to `tee` was masking Playwright's exit code as 0) and gate the
result on it, for both Stage 1 and Stage 2.
- `backend/tests/test_encoding_worker_routes.py` — 3 regression tests:
503 start failure → WARNING, capacity error → WARNING, unexpected error
→ still ERROR.
- `docs/TROUBLESHOOTING.md` — note that a WARNING-level warmup 503 is
benign/self-healing.
- `pyproject.toml` — bump 0.174.11 → 0.174.12.

## Testing
- [x] `pytest backend/tests/test_encoding_worker_routes.py
backend/tests/test_encoding_worker_manager.py` — 46 passed
- [x] YAML validated
- [x] CodeRabbit CLI review — 0 findings

## Review
- [x] Local CodeRabbit review completed
- [x] Issues addressed

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 17:17:06 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 ce21560803 fix(runner-images): bump actions/runner 2.332.0 → 2.334.0 (deprecated, broke ephemeral CI) (#791)
## Summary
GitHub deprecated **actions/runner v2.332.0** and now returns **HTTP
403** on the broker poll (`"Runner version v2.332.0 is deprecated and
cannot receive messages"`). Ephemeral/JIT runners run with
`disableUpdate`, so they **cannot self-update** — each dispatched VM
registered, got rejected, exited, and self-halted, leaving CI jobs
**queued indefinitely** plus zombie `offline` runner registrations.

Nothing in our code changed; this is GitHub-side deprecation enforcement
that hit after the May 17 image build. Root-caused from a failed VM's
`_diag/Runner_*.log`.

## Changes
- Bump `RUNNER_VERSION` `2.332.0 → 2.334.0` (current latest) in:
- `infrastructure/scripts/runner-image-provision.sh` (ephemeral image —
the one that matters)
- `infrastructure/compute/startup_scripts/github_runner.sh` +
`github_runner_gpu.sh` (legacy)
- `infrastructure/compute/startup_scripts/__init__.py` (docstring
example)
- Document the failure mode + runbook in
`docs/EPHEMERAL-GHA-RUNNERS.md`.

## Why this broke CI
Dispatch + VM boot worked fine, so it looked like the jobs were just
"stuck queued." Ruled out (with evidence): label match, runner-group
access, Cloud NAT egress, manager env config, dirty runner dir,
fresh-image regression, JIT mint. The `_diag` log showed the 403.

## Follow-up (not in this PR)
- Rebuild cadence (`0 2 1 * *`, monthly) is too slow vs. GitHub's
deprecation pace — resolve "latest" at build time and/or alert on
deprecation 403s.
- Two secondary bugs found: #789's serial-capture can't read self-halted
(stopped) VMs; zombie offline JIT registrations make `cleanup_orphans`
treat dead VMs as "registered" until the 120-min cap.

## Testing
- [x] No remaining `2.332.0` refs in repo
- [x] CodeRabbit CLI review — 0 findings
- [ ] **Takes effect only after `build-runner-images.yml` rebuild**
(runs on GitHub-hosted runners, not blocked)

## Review
- [x] Local CodeRabbit review completed

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 16:38:43 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 748d5aefab obs(runner-manager): capture serial console before deleting unregistered VMs (#789)
## Summary

Ephemeral GPU runner VMs register with GitHub roughly **1 in 3** times.
Observed today on python-audio-separator PR #288: 3 GPU VMs dispatched,
1 ran \`core-models\`, 2 booted but never registered and were silently
deleted after 40 min.

We can't fix the underlying registration bug because we have **zero
visibility** into what's happening on the failed VMs:
- STARTUP_SCRIPT's stderr (including \`./run.sh --jitconfig\` output)
goes to the serial console only
- No Ops Agent is installed on the runner image, so journald doesn't
ship anywhere
- The script's \`EXIT\` trap shuts the VM down on any failure
- Boot disks are auto-delete → forensics impossible

This PR adds the missing observability so we can root-cause the real
bug.

## Changes

- New \`_log_serial_tail(zone, name)\` helper: fetches the last 50 KiB
of serial console output via \`instances.getSerialPortOutput()\` and
prints it. The manager's stdout already flows to Cloud Logging, so the
output becomes queryable.
- \`cleanup_orphans()\` calls \`_log_serial_tail\` **only** for the
\"unregistered past grace\" delete path (the genuinely-mysterious case).
Hung-after-registration deletes are skipped because that output is
mostly job stderr, which is already in GHA logs.
- Best-effort: a fetch error logs a warning and lets the delete proceed.
- 50 KiB cap prevents pathological logging volume if many VMs fail
simultaneously.

## Testing

- [x] All 32 unit tests pass (\`pytest
infrastructure/functions/runner_manager/test_ephemeral.py\`)
- [x] 2 new tests cover \`_log_serial_tail\` directly (truncation +
swallowing fetch errors)
- [x] 3 existing \`cleanup_orphans\` tests updated to assert serial
capture is called on registration-failure path and NOT on hung-VM path

## Review

- [x] Local CodeRabbit review pending — will run before merging
- [x] No behavioural change in the happy path (registered VMs that
successfully run jobs)

## After Merge

**Manual \`pulumi up\` required** to deploy the updated Cloud Function
(per CLAUDE.md: claude-readonly ADC blocks Pulumi's
storage.objects.create). Then wait for the next GPU integration test run
to fail → query \`gcloud logging read 'serial console for gha-gpu-'\` to
see the actual failure reason → open follow-up PR with the real fix.

## Related

- Triggered by python-audio-separator PR #288 stuck on GPU integration
tests
- Builds on memory: \`project_ephemeral_runner_phase4.md\` (PRs
#781-#783 fixed kernel-skew + Secure Boot, but registration-failure
flakiness remained)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:57:29 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 771b2965c9 fix(monitoring): autoClose minimum is 30min — raise from 600s to 1800s (#788)
## Summary

Follow-up to #787. GCP Monitoring rejects \`autoClose\` values below 30
minutes — \`pulumi up\` for #787 failed with:

\`\`\`
Error 400: Field alertStrategy.autoClose had an invalid value of
"seconds: 600":
the autoclose duration should be at least 30 minutes
\`\`\`

PR #787 didn't apply atomically, so prod alert policy is still on the
old values (threshold=7200, autoClose=3600s). This PR sets autoClose to
the GCP minimum (1800s = 30min). Combined with #787's threshold bump to
9000s, the noise alert from this morning will be killed once \`pulumi
up\` lands.

## Changes

- \`auto_close\`: \`600s\` → \`1800s\` (GCP minimum)
- Added comment explaining the floor so the next agent doesn't try to
lower it

## Test plan

- [x] \`ast.parse\` clean
- [ ] \`pulumi preview\` shows in-place update to
\`runner-dispatcher-long-lived-vm-alert\` only
- [ ] \`pulumi up\` succeeds (no GCP 400)
- [ ] Cloud Console shows policy with threshold=9000, autoClose=1800s

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 14:01:42 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 689edce365 fix(monitoring): raise long-lived VM alert threshold to 2h30m (kill false positives) (#787)
## Summary

Last night's alert (`VM Alive > 2h` firing at 06:40 UTC, recovering at
~07:41 UTC) was a false positive. The cleanup pass worked correctly —
the alert policy is too tight.

## Root cause

Orphan-cleanup deletes VMs at `MAX_VM_LIFETIME_MINUTES=120` on a 15-min
scheduler tick. Worst-case lifetime = **135min**. The alert threshold
was set to exactly **120min (7200s)** with `ALIGN_MAX` over a 5-min
window and a 300s duration — so the 5-min window containing the last
pre-delete sample reports `max > 7200` for ~5min after the VM is already
gone, and `autoClose=3600s` dragged recovery out for ~1h.

### Evidence (instance `6379757481209834386` =
`gha-general-1b8a7c29c8e2`)

| Time (UTC) | Event |
|---|---|
| 04:28:53 | VM created (workflow_job.queued webhook) |
| 06:28:53 | uptime crossed 7200s (exact 2h) |
| 06:30:03 | scheduler tick fires orphan cleanup |
| 06:30:04 | function logs `gha-general-1b8a7c29c8e2: age=121.3min >
max, deleting` |
| 06:31:24 | delete operation completes (`last=True`) — **VM gone** |
| 06:40:27 | **alert fires** (9 min after VM was deleted) |
| ~07:41 | alert auto-closes |

The alert hadn't fired before because notification channels were unwired
across all policies until PR #783 merged ~12 min before this VM was born
— this was the first cleanup cycle observed via email, not the first
false positive.

## Changes

- `threshold_value`: `7200` → `9000` (150 min = worst-case 135 min + 15
min buffer)
- `auto_close`: `3600s` → `600s` (faster recovery if it ever does
legitimately fire)
- `display_name` + docs updated to `VM Alive > 2h30m`

Real cleanup-broken cases (VMs stuck at 3h+) still trigger.

## Operator action required

Per memory `feedback_claude_readonly_adc`: claude-readonly ADC can't
push Pulumi state, so this needs a manual `pulumi up --target` after
merge:

\`\`\`bash
pulumi up --target
'urn:pulumi:prod::karaoke-gen-infrastructure::gcp:monitoring/alertPolicy:AlertPolicy::runner-dispatcher-long-lived-vm-alert'
\`\`\`

Expected diff: in-place update — `displayName`,
`conditions[0].displayName`,
`conditions[0].conditionThreshold.thresholdValue` (7200 → 9000),
`alertStrategy.autoClose` (3600s → 600s), `documentation.content`.

## Test plan

- [x] `ast.parse` clean for `monitoring.py`
- [x] No tests reference the alert policy displayName/threshold (`grep
-rn "long_lived\|VM Alive" infrastructure/` only hits this file)
- [ ] `pulumi preview` shows an in-place update to
`runner-dispatcher-long-lived-vm-alert` only — no creates/deletes
- [ ] After `pulumi up`, verify policy in Cloud Console shows
threshold=9000 and autoClose=600s

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 13:56:03 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 123a15cc78 docs: correct i18n notes in CLAUDE.md to match current frontend layout (#786)
## Summary
- Fix stale path in CLAUDE.md i18n section: `frontend/src/app/[locale]/`
→ `frontend/app/[locale]/`
- Clarify that non-locale routes like
`frontend/app/app/jobs/[[...slug]]/page.tsx` are `<LocaleRedirect />`
shims, not English-only surfaces
- Note that review UIs (`/review`, `/instrumental`, `/audio-edit`) are
fully multilingual via `components/lyrics-review`,
`instrumental-review`, `audio-editor` using `useTranslations`
- Narrow the English-only claim to `/admin/*` only

## Testing
- Docs-only change; no code paths affected
- Verified the new paths exist on disk and `LocaleRedirect` is used in
the referenced shim files

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 15:03:02 +00:00
Andrew Beveridge ☄️andClaude Opus 4.7 63e36b007c fix(monitoring): wire email notification channel to all alert policies (#783)
## Summary

Followup #3 from
`docs/archive/2026-05-17-ephemeral-runner-followups-handoff.md`. Root
cause of the 2026-05-17 cutover going undetected for ~14h: the `GHA
Runner Dispatcher - Create Failures` alert had a correct log-based
metric and a correct condition — but **no notification channels were
attached to any alert policy project-wide**, so the three create-failure
events fired into the void.

Verified before this PR:

\`\`\`
$ gcloud alpha monitoring channels list --project=nomadkaraoke
(empty)
\`\`\`

## Changes

- New `create_notification_channels()` in
`infrastructure/modules/monitoring.py`: creates one email channel
(`alerts-email`, delivering to `andrew@beveridge.uk`).
- Both `create_alert_policies` and
`create_ephemeral_runner_observability` now accept a `channels` dict and
thread it into every `gcp.monitoring.AlertPolicy` via
`notification_channels=...`.
- `__main__.py` calls `create_notification_channels()` first and passes
the result through.
- `infrastructure/monitoring/README.md` rewrites the "Notification
Channels" section to point at the IaC and includes a paste-ready snippet
for adding Discord (via Discord's Slack-compatible `<webhook_url>/slack`
endpoint) as a follow-up.

Policies that now get notifications:
- `error_rate`, `queue_backlog`, `memory`, `service_unavailable`
(Karaoke Backend)
- `dispatch_failure_alert`, `long_lived_vm_alert` (GHA Runner
Dispatcher)

## Operator action required

After merge + `pulumi up`, Cloud Monitoring sends a one-time
confirmation email to `andrew@beveridge.uk`. The channel stays in
PENDING state until the link is clicked.

Verify with:

\`\`\`bash
gcloud alpha monitoring channels list --project=nomadkaraoke \\
  --format='table(displayName,type,verificationStatus,enabled)'
\`\`\`

Looking for `verificationStatus=VERIFIED`.

## Test plan

- [x] `ast.parse` clean for `monitoring.py` and `__main__.py`
- [x] Confirmed all 6 alert policies have
`notification_channels=notification_channels` attached (`grep -c
notification_channels infrastructure/modules/monitoring.py` → 11,
expected)
- [ ] `pulumi preview` shows: 1 new `NotificationChannel`, 6 in-place
`AlertPolicy` updates. No destructive ops.
- [ ] Run `pulumi up`. Verify email arrives. Click verification link.
- [ ] Force a test alert (e.g. temporarily lower a threshold) and
confirm email delivery, then revert.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 00:28:29 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 b4e7a83067 refactor(runner-manager): drop legacy fixed-pool dispatcher code (~370 lines) (#782)
## Summary

Followup #2 from
`docs/archive/2026-05-17-ephemeral-runner-followups-handoff.md`. Phase 4
(PR #780, 2026-05-18) deleted the 7 long-lived runner VMs; the
dispatcher has been running `RUNNER_MODE=ephemeral` exclusively since
then. The legacy start/stop code paths are now dead weight.

### Removed

- `infrastructure/functions/runner_manager/main.py` (~370 lines):
- `start_runners`, `_start_single_runner`, `_stop_single_runner`,
`check_and_stop_idle_runners`, `get_runner_instances`,
`update_instance_metadata`, `get_instance_metadata`,
`_get_instance_age_hours`, `check_github_for_pending_jobs`
- `RUNNER_MODE`, `RUNNER_NAMES`, `GPU_RUNNER_NAMES`,
`IDLE_TIMEOUT_HOURS` module constants + the `if RUNNER_MODE ==
'ephemeral'` branching
- The `completed`-action metadata refresh (ephemeral runners self-clean)
- `infrastructure/modules/runner_manager.py`:
  - `RUNNER_MODE` Pulumi config + validation
  - `RUNNER_NAMES` / `GPU_RUNNER_NAMES` env vars passed to the function
- `runner_names` / `gpu_runner_names` params on `create_cloud_function`
and `create_runner_manager_resources`
  - `IDLE_TIMEOUT_HOURS` env var
- `Pulumi.prod.yaml`: `karaoke-gen-infrastructure:runnerMode: ephemeral`
- `config.py`: `RunnerManagerConfig.IDLE_TIMEOUT_HOURS`
- The 35-test legacy `test_runner_manager.py` (all dead code)

### Kept

- `runner-manager-idle-check` Cloud Scheduler job and its
`?action=check_idle` query parameter — both names are now load-bearing
for backward-compat (renaming would force a Pulumi recreate without
behavioural benefit). The function routes every scheduler tick to orphan
cleanup; the resource description is updated to reflect that.

`test_ephemeral.py::TestSchedulerAuthGate` simplified: removed
`RUNNER_MODE` / `RUNNER_NAMES` env-var fixtures and rewrote
`test_scheduler_with_bearer_token_dispatches_orphan_cleanup` to verify
the tick now routes to `ephemeral.cleanup_orphans`.

## Test plan

- [x] All 26 tests in `test_ephemeral.py` pass
- [x] `python -c 'import ast; ...'` clean for every touched module
- [ ] `pulumi preview` shows: Function source bundle replace + Function
env-var diff (loses `RUNNER_MODE`, `RUNNER_NAMES`, `GPU_RUNNER_NAMES`,
`IDLE_TIMEOUT_HOURS`), Pulumi config `runnerMode` removed — no
behavioural change in prod (dispatcher is already ephemeral-only)
- [ ] After merge + `pulumi up`, watch `gcloud logging read
'resource.type=\"cloud_run_revision\" AND
resource.labels.service_name=\"github-runner-manager\" AND
textPayload:\"Dispatched ephemeral runner\"' --freshness=30m` to confirm
dispatch still works
- [ ] Watch `textPayload:\"orphan cleanup\"` to confirm the scheduler
tick still drives cleanup

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 00:28:26 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 34c36088c1 fix(runner-images): GPU NVIDIA load + Secure Boot off; runbook updated (#781)
## Summary

Followup #1 + #4 from
`docs/archive/2026-05-17-ephemeral-runner-followups-handoff.md`. Fixes
the GPU-image cutover bug that blocked python-audio-separator
integration tests, and brings the operator runbook in line with what
actually shipped.

### Root cause (validated with two GPU smoke VMs against the broken
image)

Two compounding bugs:

1. **Kernel skew**: `apt-get install cuda-drivers` pulls a newer kernel
image via the `linux-image-cloud-amd64` meta-package, but DKMS only
builds nvidia.ko against the build-VM's currently-running kernel. Fresh
ephemeral VMs boot the newer kernel (GRUB default) and find no nvidia
module for `uname -r` — `nvidia-persistenced` fails with "Failed to
query NVIDIA devices". Confirmed on `gha-runner-gpu-20260517-183755`:
image baked nvidia for `6.1.0-47`, fresh VMs boot `6.1.0-48`.
2. **Secure Boot lockdown**: `enable_secure_boot=True` puts the kernel
in `lockdown=integrity` mode and rejects unsigned modules with "Key was
rejected by service". Legacy GPU runners had no
`shielded_instance_config` (SB off by default) and weren't affected.

### Fixes

- `infrastructure/scripts/runner-image-provision.sh`: bake
`gha-gpu-modprobe.service` (GPU variant only). Runs before
`nvidia-persistenced.service` and the GCE startup script. Idempotent —
no-op when nvidia is loaded; otherwise installs matching
`linux-headers-$(uname -r)`, runs `dkms autoinstall`, and modprobes
nvidia / nvidia_uvm / nvidia_drm.
- `infrastructure/functions/runner_manager/ephemeral.py`:
`enable_secure_boot=not family.has_gpu`. Keeps Secure Boot on for
general/build.
- `docs/EPHEMERAL-GHA-RUNNERS.md`: rewrite STATUS to reflect the actual
cutover history (3 bug-fix iterations in PR #776, Phase 4 already done
in PR #780), remove the now-stale Phase-4 followups walkthrough, add 7
new lessons-learned entries.

### Verification

- Manual fix sequence on a no-SB smoke VM produced working `nvidia-smi`
(Tesla T4, driver 595.71.05, CUDA 13.2) as root and as the `runner`
user.
- An SB-on smoke VM failed with "Key was rejected by service" at
modprobe even after `dkms autoinstall`, confirming the second fix.
- Image rebuild (run
[26012660753](https://github.com/nomadkaraoke/karaoke-gen/actions/runs/26012660753))
is in flight on this branch.

End-to-end verification will be a follow-up PR in
`python-audio-separator` once the new image is `READY` and a smoke VM
from it auto-loads nvidia.

## Test plan

- [x] All 30 tests in `test_ephemeral.py` pass (4 new in
`TestSecureBootPerFamily`)
- [x] Bash syntax check on `runner-image-provision.sh`
- [ ] Smoke-test new image: fresh GPU VM with
`--no-shielded-secure-boot` from `gha-runner-gpu` family, `nvidia-smi`
works at boot
- [ ] PR in `python-audio-separator` triggers all 3 GPU integration
jobs, all green

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 00:27:45 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 86aa4923b5 chore(infra): remove sendgrid-api-key from Pulumi secrets (#784)
## Summary

Follow-up cleanup to PR #779 (SendGrid → Postmark migration). The GCP
\`sendgrid-api-key\` Secret + all its versions have been deleted via
\`pulumi up --target\`; this PR removes the corresponding entry from
\`secret_names\` so Pulumi code matches state.

Also deleted: \`SENDGRID_API_KEY\` GitHub Actions secret (both org-level
and karaoke-gen repo-level).

## Pulumi already applied
\`pulumi up --target gcp:secretmanager/secret:Secret::sendgrid-api-key\`
already run; resource is gone from Pulumi state and \`gcloud secrets
describe sendgrid-api-key\` returns NOT_FOUND.

@coderabbitai ignore

## Test plan
- [ ] CI green
- [ ] No revisions reference \`sendgrid-api-key\` (already verified —
\`SENDGRID_API_KEY\` not mounted on \`karaoke-backend-00788-xk2\`)

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 00:27:03 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 a45798bb4d fix: remove SendGrid leftovers; consolidate on Postmark (#779)
## Summary
- Fixes the failing e2e-daily notification job ([run
#25983930960](https://github.com/nomadkaraoke/karaoke-gen/actions/runs/25983930960/job/76378786060))
which still used \`smtp.sendgrid.net\` — SendGrid was cancelled ~3 weeks
ago
- Drops the \`sendgrid\` Python dep, removes \`SendGridEmailProvider\`,
simplifies provider selection in \`email_service.py\`
- Removes \`SENDGRID_API_KEY\` env bindings from Pulumi
(gdrive-validator Cloud Function + video Cloud Run Job) and from
ci.yml's Cloud Run \`--set-secrets\`
- \`sendgrid-api-key\` Secret resource intentionally kept in
\`infrastructure/modules/secrets.py\` with a "delete manually" marker so
an unrelated \`pulumi up\` doesn't destroy the live secret + versions
- Version bumped 0.174.10 → 0.174.11

## Pulumi applied
\`pulumi up --target\` already run locally with the two affected
resources (video-encoding-job + gdrive-validator-function). PR #776's
runner-manager state intentionally untouched.

@coderabbitai ignore

## Test plan
- [x] Full backend test suite (3178 tests) passes locally
- [x] CodeRabbit local review: no findings
- [x] Pulumi up applied locally (clean)
- [ ] CI green on this PR
- [ ] After merge: e2e-daily.yml notification job should pass on next
scheduled run
- [ ] Verify gdrive-validator function still emails on next post-job
trigger

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 23:40:23 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 75134249ff chore(infra): Phase 4 — remove 7 legacy github-runner VMs (~$238/mo saving) (#780)
## Summary

- Concludes the ephemeral GHA runner migration. The dispatcher Cloud
Function (`github-runner-manager`, `RUNNER_MODE=ephemeral`) has been
creating fresh single-use VMs via JIT registration since PR #776 — the
legacy long-lived `github-runner-{1,2,3}`, `github-build-runner`, and
`github-gpu-runner-{1,2,3}` VMs and their always-billed 200GB pd-ssd
boot disks are no longer needed.
- Removed the `create_github_runners(...)`, `create_build_runner(...)`,
`create_gpu_runners(...)` calls from `infrastructure/__main__.py` plus
their three `pulumi.export` lines. Kept the Cloud NAT (ephemeral VMs
still need it for outbound) and the runner manager itself.
- **Already applied in production** — 7 VMs deleted, 7 boot disks
auto-deleted, Pulumi state refreshed. CI re-running this branch will be
a Pulumi no-op for the runner resources.

## Cost saving

**$238/mo** (7 × 200GB pd-ssd at $0.17/GB/mo). Ephemeral VM boot disks
(pd-balanced, ~30 min/job, ~30 jobs/mo typical) cost a few $/mo.

## How the apply was done

Pulumi `up --target` doesn't process deletes for resources removed from
the program, and `destroy --target` insisted on tearing down the
dispatcher function too via implicit dependents. The cleanest scoped
path was:

1. `gcloud compute instances delete` for the 7 VMs (boot disks
auto-deleted via `auto_delete=True`).
2. `pulumi refresh --target ...` for each instance URN to sync state.

This avoided disturbing the in-flight `sendgrid→postmark` Pulumi drift
from PR #779 (which is the same agent's other PR — both applied targeted
Pulumi locally before merge).

## Verification

```
$ gcloud compute instances list --filter="name~'github-(runner|gpu|build)'" --project=nomadkaraoke
(empty)
$ gcloud compute disks list --filter="name~'github-(runner|gpu|build)'" --project=nomadkaraoke
(empty)
$ curl -s https://api.nomadkaraoke.com/api/health/detailed | jq .version
"0.174.11"   # the PR #776 deploy ran on an ephemeral build runner end-to-end
```

## Follow-ups (separate PRs)

- **GPU image broken** — NVIDIA kernel module fails to load on fresh
ephemeral VM boots (`nvidia-persistenced` fails, `/dev/nvidia*` absent).
Needs a systemd boot-time DKMS rebuild service. GPU CI is broken until
then; last `python-audio-separator` integration run was 2026-04-20, so
not blocking active work.
- **Dead code cleanup** — `start_runners` /
`check_and_stop_idle_runners` / `RUNNER_MODE` branching in
`infrastructure/functions/runner_manager/main.py` is now unreachable.
- **Alert notification channels** — the `GHA Runner Dispatcher - Create
Failures` policy fired during today's cutover bug but went nowhere
because no notification channels are attached project-wide. Worth wiring
up Discord/email.

## Test plan

- [x] `pytest test_ephemeral.py` — 26 passed (no logic changed in
dispatcher)
- [x] `pulumi preview` shows the runner resources are out of state (in
sync with reality)
- [x] Prod is healthy on the version that deployed via the ephemeral
build runner

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 23:06:21 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 424b908d71 fix(runner-dispatcher): omit TERMINATE for e2 families (unblocks ephemeral cutover) (#776)
## Summary

Fixes three cutover bugs that left the ephemeral runner dispatcher
silently broken since 2026-05-17T04:56Z:

1. **`on_host_maintenance="TERMINATE"` set unconditionally** — e2
machine types reject TERMINATE unless preemptible, so 100% of
general/build VM creates failed. Fix: only set TERMINATE on GPU (n1)
families where it's required because attached GPUs can't live-migrate. 3
regression tests added in `test_ephemeral.py`.
2. **GPU `disk_size_gb=150` but image is 200GB** — GCE rejects boot
disks smaller than the source image. Fix: raise GPU disk to 200GB.
3. **Runner user has no passwordless sudo** — workflow steps like `sudo
apt-get install -y google-cloud-cli-firestore-emulator`
(backend-emulator-tests) and `sudo apt-get install -y ffmpeg`
(package-*, GPU integration tests) failed with "a terminal is required
to read the password". The legacy GHA runner VMs had NOPASSWD sudo. Fix:
add `/etc/sudoers.d/runner` in the image provision script.

Fixes 1 + 2 are dispatcher code (already applied via `pulumi up --target
...:runner-manager-source ...:runner-manager-function` from this
branch). Fix 3 requires a new image build (triggered:
build-runner-images.yml on this branch).

## Why the trivial file touches

`backend/main.py` and `karaoke_gen/__init__.py` carry one-line comments
to flip the `backend` and `package` `dorny/paths-filter` outputs so this
PR exercises **all five PR-triggered self-hosted jobs** end-to-end on
ephemeral runners. Verification PR (paired):
nomadkaraoke/python-audio-separator#286.

## Test plan

- [x] `pytest test_ephemeral.py` — 26 passed locally (3 new scheduling
tests)
- [x] Pulumi applied locally (both iterations, function update verified)
- [x] First ephemeral general VM create succeeded (4 RUNNING; previously
100% failure)
- [ ] Image rebuild completes for general+build+gpu with new sudo
provision
- [ ] PR CI passes with all 5 self-hosted jobs running on the new image
- [ ] python-audio-separator#286 GPU integration tests pass on the new
GPU image
- [ ] After merge: `deploy-backend` succeeds on ephemeral build runner;
prod /api/health/detailed reports new version
- [ ] Phase 4 decommission of 7 legacy VMs+disks (separate PR, ~$220/mo
saving)

## Context

- `karaoke-gen/docs/EPHEMERAL-GHA-RUNNERS.md`
- `docs/archive/2026-05-16-ephemeral-gha-runners-plan.md` (workspace)
- Memory: `project_cost_sprint_may2026.md`

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 22:42:01 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 241ad41096 docs: GCP cost reduction sprint recap (2026-05-16/17) (#775)
## Summary

Comprehensive record of the cost-reduction sprint executed across
2026-05-16/17 covering all repos and the workspace-level billing
investigation.

Captures:
- Baseline ($840/30d gross spend, $4.7k of GFS credits at risk of
expiring unused before 2026-09-19)
- 7 cost-driver findings — secret-version sprawl on 3 OAuth secrets,
7×200GB pd-ssd boot disks on idle runner VMs, divebar-sync `set -e`
regression that broke auto-shutdown, phantom Network Intelligence Center
charges, deploy-backend's real surface, the flacfetch SSH/guest-agent
dependency, and the ADC guardrail incident
- All shipped changes across `karaoke-gen` (#764) and `flacfetch` (#26,
#27) plus the parallel ephemeral-GHA-runner work (#765-#774, runbook in
`docs/EPHEMERAL-GHA-RUNNERS.md`)
- ~$305/mo projected saving once Phase 4 lands 2026-05-24
- 7 lessons learned for future sessions

Docs-only — no code changes, no version bump.

@coderabbitai ignore

## Test plan

- [x] Markdown renders
- [x] All referenced PR numbers / file paths verified
- [x] Cross-references to existing docs (`EPHEMERAL-GHA-RUNNERS.md`,
`2026-05-16-ephemeral-gha-runners-plan.md`, March 2026 cost-reduction
docs) confirmed

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 01:12:54 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 bdc37b3b70 chore(infra): record runnerMode=ephemeral in Pulumi.prod.yaml (#774)
Syncs in-git stack config with deployed state post-cutover. No
behavioural change.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 01:02:31 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 c728b781ac docs(runner): cutover status + 1-week soak followup + lessons learned (#773)
## Summary
Updates the EPHEMERAL-GHA-RUNNERS runbook with three sections so the
operator can refer back to it during the 1-week soak and know exactly
what to do at the end:

1. **STATUS — 2026-05-17** — cutover went live at 04:56Z, current image
names, self-serve status command, serial-console tail command.
2. **Followups (1 week from cutover — 2026-05-24)** — exact verification
commands, Phase 4 decommission steps (the destructive bit that unlocks
~\$220/mo), rollback path.
3. **Iteration-cost lessons learned** — 8 hard-won gotchas from this
session covering serial-console visibility, IAP unreliability, gh-watch
rate limits, Python-from-source fragility, apt-daily race, disk-name
autoselect, Pulumi function-source generation pin, smoke-as-runner-user.

Docs-only change, no version bump.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 01:00:26 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 dd2189548d fix(runner-images): pacify apt-daily race on fresh Debian VMs (#772)
## Summary
The build-variant rebuild died at the GHA runner's
\`installdependencies.sh\` with an apt lock conflict:
\`\`\`
E: Could not get lock /var/lib/apt/lists/lock. It is held by process N
(apt-get)
'apt-get' failed with exit code '0'
Can't install dotnet core dependencies.
\`\`\`
Same code path as general (which won the race and succeeded). Just
timing relative to Debian's background \`apt-daily.service\`.

## Fix
Stop + disable + mask \`apt-daily.{service,timer}\` and
\`apt-daily-upgrade.{service,timer}\` early in the script, then wait up
to 2 min for any in-flight apt-get to release its lock. After that all
subsequent \`apt-get\` calls (including the runner's bundled installer)
have exclusive access.

## Test plan
- [x] bash -n clean
- [ ] Rebuild build variant: \`gh workflow run build-runner-images.yml
-f variants=build\`. The general rebuild from the previous run already
succeeded; only build needs retry.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 00:30:51 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 2399248c06 fix(runner-images): use pyenv for GPU variant too; drop hand-rolled Python build (#771)
## Summary
After 3 unsuccessful iterations trying to compile Python 3.13 from
source on the GPU image-build VM, switch to pyenv (which has worked
end-to-end for general/build all along).

## Failure history
| Iteration | Approach | Symptom |
|---|---|---|
| PR #765 (orig) | 3.13.0 + \`--with-ensurepip=install\` | Install-time
ensurepip crash (FileNotFoundError on _WHEEL_PKG_DIR) |
| PR #768 | 3.13.0 + \`--with-ensurepip=no\` + get-pip.py | get-pip.py
crashed on freshly-built python3.13 |
| PR #770 | 3.13.2 + \`--with-ensurepip=install\` w/o
\`--enable-optimizations\` | \`_socket\` C extension broken;
\`SystemError: error return without exception set\` from any urllib
import |

## Decision
Stop tilting at the hand-rolled-build windmill. pyenv-installed Python
3.13.0 has worked successfully for both general and build variants in
the latest runs (READY in ~5 min). The original "pyenv unreliable on
Debian 12 with CUDA installed" comment was speculation about *runtime*
conflicts — image-build VMs install CUDA but no CI job runs against CUDA
on the build VM itself, so the speculated conflict can't materialize.

Unify all three variants on pyenv. Bonus cleanup: install Poetry to
/opt/poetry on every variant (not just GPU) so the runner user can reach
it.

## Test plan
- [x] bash -n clean
- [ ] Re-trigger only the gpu variant: \`gh workflow run
build-runner-images.yml -f variants=gpu\` (general+build images already
exist and READY from the previous run).

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 23:36:29 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 659ba1ef7b fix(runner-images): image-create disk name + GPU python 3.13.2 (#770)
## Summary
Two follow-up fixes after PR #769's visibility update made it possible
to see exactly what was failing.

## What broke
1. **general/build PROVISIONED successfully** (READY marker written at
01:04 and 01:02), then the workflow's \`Create image\` step died with:
   \`\`\`
ERROR: (gcloud.compute.images.create) Invalid value for
[--source-disk-zone]:
You cannot specify [--source-disk-zone] unless you are specifying
[--source-disk].
   \`\`\`
The disk-name extraction format string returned empty. I'm using
auto-named boot disks (same as VM name), so just use \`\$VM\` directly.

2. **GPU got further than before** — phase: python 3.13 — but
\`get-pip.py | python3.13\` exited non-zero at line 197. PR #768's
workaround for the 3.13.0 install-time ensurepip bug introduced a new
failure on the bootstrap. Switch to **3.13.2** which fixes the
underlying bug, restore \`--with-ensurepip=install\`, drop the
bootstrap. Also drop \`--enable-optimizations\` (PGO runs full test
suite, can produce half-broken binaries on transient test failures).

## Plus
Wait step's failure-context dump now captures **40 lines BEFORE** the
FAILED marker (not just 5 after) so the actual error output is in the
GHA log.

## Test plan
- [x] bash + yaml syntax clean
- [ ] Re-trigger build after merge. Expected outcome: all 3 variants
build successfully end-to-end and produce images in the
\`gha-runner-{general,build,gpu}\` families.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 21:20:00 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 ce270052ff fix(runner-images): stream provisioner log to GCE serial console (eliminate SSH dependency) (#769)
## Problem
Three previous iterations of the image-build workflow failed silently.
Every diagnostic channel depended on \`gcloud compute ssh
--tunnel-through-iap\` and IAP tunneling was unreliable enough that:
- The wait step both false-positived ("Image ready" at 4 min on a 25-min
provisioner) AND false-timed-out (no output for 75 min)
- Manual SSH for debugging was equally broken — \`Connection closed by
UNKNOWN port 65535\` repeatedly

Net effect: 25–60 minute iteration loops with no actual visibility into
the provisioner's state.

## Fix
Eliminate SSH from the diagnostic path entirely:

1. **Provisioner streams to /dev/ttyS0** (GCE serial console). Readable
via \`gcloud compute instances get-serial-port-output --port=1\` with
zero SSH/IAP dependency.
2. **ERR trap + phase checkpoints.** Any non-zero exit prints \`###
runner-image-provision FAILED rc=N line=L cmd=...\` to the console. A
\`ck()\` helper marks each major phase (apt base, docker, python,
node+java, ffmpeg, poetry+gcloud, runner user, runner binary, build
pre-pull, gpu models, tool cache, cleanup, READY).
3. **Workflow wait step polls serial console.** Looks for
\`runner-image: READY:\` for success and \`runner-image-provision
FAILED\` for fast-fail. Also streams new console lines into the GHA log
on every poll so the operator sees live progress.

## Test plan
- [x] \`bash -n\` + yaml lint clean
- [ ] Re-trigger \`build-runner-images.yml\` after merge. When a variant
dies, we'll see exactly which phase failed.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 20:56:45 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 163fa95db8 fix(runner-images): bypass Python 3.13.0 install-time ensurepip crash (#768)
## Summary
Third hotfix in the runner-image series. The GPU build VM dies ~18 min
in with a Python 3.13.0 install-time crash when ensurepip runs as part
of \`make install\`.

## Root cause
\`./configure --with-ensurepip=install\` causes the Makefile to run
\`./python -E -m ensurepip --root=/\` during install, which crashes on a
missing \`_WHEEL_PKG_DIR\` path:

\`\`\`
FileNotFoundError: [Errno 2] No such file or directory
  File ".../pathlib/_local.py", line 670, in resolve
    return self.with_segments(os.path.realpath(self, strict=strict))
\`\`\`

The general/build variants use pyenv, which handles ensurepip
differently and isn't affected.

## Fix
\`--with-ensurepip=no\` + bootstrap pip from \`get-pip.py\` after \`make
install\`. Same end state, no install-time crash.

## Test plan
- [x] \`bash -n\` clean
- [ ] Re-trigger gpu build after merge

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 20:45:21 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 7f46bbc0af fix(runner-images): trust file content not IAP-tunnel ssh exit codes (#767)
## Summary
Hotfix for the build-runner-images workflow, observed failing on the
first real run after PR #766's variant-resolution fix.

## Root cause
Two related defects in the **Wait for provisioning to complete** step:

1. **False-positive readiness.** The general-image job detected `test -f
/opt/runner-image-ready` at attempt 8 (~4 min in) on a provisioner that
takes 25+ min. \`gcloud compute ssh --command='test -f ...'\` returned
exit 0 even though the remote test had nothing to test against. Most
likely an IAP-tunnel race where the SSH session closes before the remote
command completes, and the local exit code defaults to 0.

2. **Diagnostic SSH allowed to fail the step.** After "marker detected,"
a second SSH was run to `cat` the file. That one hit a real IAP error
(`destination read failed`) and `set -e` killed the step. So even if the
first marker check were trustworthy, this second hop would still flake
the build out.

## Fix
- Use `cat` instead of `test -f` for readiness check; require the output
to start with a 4-digit year (the provisioner writes an ISO-8601
timestamp). Empty stdout from a flaky SSH = "not ready, retry."
- Drop the second SSH — fold its diagnostic value into the cat above.
- Belt-and-suspenders `2>&1 || true` on the timeout-path diagnostic.

## Test plan
- [x] YAML lint clean
- [ ] Re-trigger \`build-runner-images.yml\` after merge

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 18:46:10 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 f270a88739 fix(runner-images): silent-fail when VARIANT is unresolved (#766)
## Summary
Hotfix for PR #765. The image-build workflow triggered after merge but
all three build VMs sat idle — the provisioner script's variant check
ran *before* the log redirect and silently exited when no positional arg
was passed.

## Root cause
When run as a GCE metadata startup-script (the production path), the
provisioner gets no argument. The fallback was
\`\$RUNNER_IMAGE_VARIANT\` which the workflow never set. Result: \`exit
2\` before \`exec > >(tee /var/log/...)\` — no log, no marker, no
diagnostic. The GHA workflow polled for \`/opt/runner-image-ready\` for
the full 75-minute timeout.

## Fix
1. Move the tee redirect to be the first action — every failure path now
leaves a trace in \`/var/log/runner-image-provision.log\`.
2. Resolve VARIANT from a third source: GCE instance metadata key
\`image-variant\` (which \`build-runner-images.yml\` already sets when
creating the VM). Priority: \`\$1\` → \`\$RUNNER_IMAGE_VARIANT\` →
metadata.

## Test plan
- [x] \`bash -n\` clean
- [ ] Re-trigger \`build-runner-images.yml\` after merge — expect
\`general\`/\`build\` to complete in ~25 min, \`gpu\` in ~60 min
- [ ] Smoke-test each image (script staged at
\`/tmp/smoke-test-runner-images.sh\`)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 18:27:44 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 bf5c9abdd7 feat(runners): ephemeral GHA runner dispatcher behind RUNNER_MODE flag (#765)
## Summary
- Implements Phases 1, 2, and 5 of the ephemeral GHA runner plan
([`docs/archive/2026-05-16-ephemeral-gha-runners-plan.md`](docs/archive/2026-05-16-ephemeral-gha-runners-plan.md)
at the workspace root). Target saving when fully cut over: **~\$220/mo**
(eliminates 7×200GB always-billed pd-ssd boot disks).
- **Default behaviour unchanged** — code lands with
`RUNNER_MODE=legacy`. Flipping to `ephemeral` is a Pulumi config +
targeted update, reversible in ~2 minutes.
- Operator runbook for the cutover at
[`docs/EPHEMERAL-GHA-RUNNERS.md`](docs/EPHEMERAL-GHA-RUNNERS.md)
including verification steps, rollback, and known gotchas.

## What's in this PR

**Phase 1 — image build infrastructure**
- `infrastructure/scripts/runner-image-provision.sh` — unified
provisioner with `general` / `build` / `gpu` variants (extracts the
existing `github_runner.sh` and `github_runner_gpu.sh` logic so it runs
at image-build time, not per-VM boot).
- `.github/workflows/build-runner-images.yml` — monthly cron + manual
trigger. Builds via temporary GCE VMs, snapshots to GCE image families
`gha-runner-{general,build,gpu}`, deprecates all but the newest 3 per
family.

**Phase 2 — dispatcher rewrite (behind a flag)**
- `infrastructure/functions/runner_manager/ephemeral.py` — picks image
family from job labels, mints a GitHub JIT runner config,
`compute.instances.insert` with auto-delete boot disk, falls back to
`us-east4-c` on `ZONE_RESOURCE_POOL_EXHAUSTED`. Orphan-cleanup deletes
VMs whose runner registration is gone or whose uptime exceeded 2h, and
de-registers zombie runners.
- `infrastructure/functions/runner_manager/main.py` — routes on
`RUNNER_MODE`. Legacy path untouched.
- `infrastructure/modules/runner_manager.py` — exposes `RUNNER_MODE` via
Pulumi config (`karaoke-gen-infrastructure:runnerMode`).
- 20 new unit tests in `test_ephemeral.py` (label resolution, JIT mint,
zone fallback, orphan reconciliation, zombie cleanup).

**Phase 5 — observability**
- 2 log-based metrics (`runner_dispatcher/create_failures`,
`runner_dispatcher/orphan_kills`).
- 2 alert policies: any create failure in 10 min; any ephemeral VM
uptime > 2h (orphan cleanup escape).

## Not in this PR (handed off)
- Triggering the image-build workflow for the first time (needs branch
merged first).
- `pulumi up` — `GOOGLE_APPLICATION_CREDENTIALS` points at
`claude-readonly@` per the workspace's operational guardrail; couldn't
apply from this session. Targeted apply commands are in the runbook.
Note that this repo's CI doesn't auto-apply Pulumi (see comment in
`ci.yml`).
- Phase 3 cutover (`pulumi config set runnerMode ephemeral` + test PR +
1-week soak).
- Phase 4 destructive decommission of the 7 legacy VMs (requires soak
first).

## Test plan
- [ ] `cd infrastructure/functions/runner_manager && pytest -v` — 20/20
new tests pass; 25/26 legacy tests pass (1 pre-existing failure
documented in the runbook).
- [ ] `cd infrastructure && pulumi preview --diff` — expect 4 resource
changes from this PR + 5 creates (log metrics + alerts).
- [ ] `pulumi up --target ...:runner-manager-source --target
...:runner-manager-function --target ...:runner-dispatcher-failures
--target ...:runner-dispatcher-orphan-kills --target
...:runner-dispatcher-failures-alert --target
...:runner-dispatcher-long-lived-vm-alert` — applies dispatcher +
monitoring.
- [ ] `gh workflow run build-runner-images.yml -f variants=general` —
produces first image, ~25 min.
- [ ] Smoke test launching a one-off VM from
`image-family=gha-runner-general` (runbook step).
- [ ] Repeat image build for `build` and `gpu` variants.
- [ ] Phase 3 cutover when ready (see runbook).

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 17:19:09 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 53be57fe60 fix: trim baseline GCP cost (secret retention + divebar shutdown) (#764)
## Summary

Two cost-reduction fixes bundled together:

1. **Secret version retention**
(`backend/services/credential_manager.py`): `dropbox-oauth-credentials`
had accumulated 1191 enabled versions costing ~$65/mo in replica
storage. Each refresh calls `add_secret_version` but never destroys the
prior version. Same pattern for the YouTube/GDrive secrets refreshed via
`_update_google_credentials`. Add a small
`_destroy_old_secret_versions(keep=5)` helper called after every
`add_secret_version` in this module. Errors swallowed so a prune failure
cannot break credential refresh.

2. **Divebar-sync auto-shutdown**
(`infrastructure/compute/startup_scripts/divebar_sync.sh`): VM was
running 24/7 for 45 days since 2026-03-31 — burning ~$15/mo of idle
compute. Root cause: the sync Python process crashed with a memory
error, and `set -euo pipefail` aborted the script before `shutdown -h
now` could execute. Switched to a `trap` on EXIT so shutdown runs no
matter how the script terminates. The scheduler `divebar-sync-vm-daily`
is currently **paused** — resume it after CI deploys this fix.

Estimated total savings: ~$80/mo.

The historical version backlog has already been manually cleaned:
`dropbox-oauth-credentials`, `youtube-cookies`, `spotify-oauth-token`
are all at 5 versions. This PR prevents regrowth.

@coderabbitai ignore

## Test plan

- [x] Unit tests added for `_destroy_old_secret_versions`
(destroy-beyond-keep, swallow-list-errors,
swallow-per-version-destroy-errors, no-op-when-below-keep)
- [x] Full `test_credential_manager.py` passes (31 tests)
- [x] Full backend suite passes (3187 passed, 36 skipped)
- [ ] After deploy: verify the three secrets stay at ~5 versions over
the next refresh cycle
- [ ] After deploy: resume `divebar-sync-vm-daily` scheduler and confirm
next run auto-shuts-down VM

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 16:43:21 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 e41d6a6860 Show bot-block message instead of misleading age-restriction (#763)
## Summary

Companion to flacfetch [PR
#25](https://github.com/nomadkaraoke/flacfetch/pull/25) (merged,
deployed). When flacfetch returns the new `is_bot_blocked: true` flag,
surface a clear user message explaining YouTube's bot challenge is
temporary — instead of falling through to the misleading "This YouTube
video is age-restricted" response.

## Test plan

- [x] Backend tests for affected paths: 211 pass
- [x] flacfetch 0.20.0 (with the new field) is already running on the
prod VM — verified end-to-end that `is_bot_blocked: true` is returned
for bot-challenged videos.
- [ ] CI green

## Notes

- Forward-compatible: if `is_bot_blocked` is absent (older flacfetch),
`availability.get()` returns falsy and the existing fallthrough kicks
in.
- The four pre-existing elif branches (geo / private / removed / age)
are also hardcoded English. Migrating them all to the backend `t()`
helper would be scope creep; this PR matches the existing pattern.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 16:15:06 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 64301db5d2 fix(audio-download): make worker idempotent, surface auto-retry to user (#762)
## Summary

Fixes the race condition behind job `8a9c74ff` where a single user Retry
click caused the `audio-download-job` Cloud Run Job to run 3 times,
producing a visible "Audio download failed: Invalid state transition for
job ...: downloading -> JobStatus.DOWNLOADING" error AND
double-triggering downstream L4 GPU separation + lyrics transcription
jobs.

Root cause: the user clicked Retry inside the ~75s window between Cloud
Run's failed task and its automatic task-attempt retry. Two parallel
executions raced on job state.

## Changes

**Backend**
- `audio_download_worker.py`:
- `DOWNLOAD_ALREADY_DONE_STATUSES` idempotency guard — return success
early when status is already past `DOWNLOADING_AUDIO`, instead of
re-downloading and crashing on a redundant state transition.
- `_mark_retry_pending_if_attempts_remain` writes
`state_data.cloud_run_retry_pending = { expires_at }` when
`CLOUD_RUN_TASK_ATTEMPT < CLOUD_RUN_MAX_RETRIES` (2). Final attempt
explicitly clears any stale marker.
- `_clear_retry_pending_and_error` clears the marker and `error_message`
on successful download so the dashboard stops showing a resolved
transient failure.
- `jobs.py` `/retry` endpoint returns **409** when
`cloud_run_retry_pending` is active, preventing duplicate parallel
executions.
- `job_manager.py` error-message rendering fix: f-strings now use
`.value` consistently so we don't get the misleading `downloading ->
JobStatus.DOWNLOADING` artifact.
- `cloud_run_retry_pending` added to `SUMMARY_FIELD_PATHS` and the
dashboard prune allowlist.

**Frontend**
- `isAutoRetryPending(job)` helper in `lib/job-status.ts`.
- `JobActions`: when auto-retry is pending, hide the manual Retry button
and show "Retrying automatically…" with a spinner. Falls back to Retry
once the window expires.
- `JobCard`: don't render the `error_message` banner on completed jobs
(covers legacy data where a transient failure left a stale error
string).
- New i18n keys auto-translated to all 33 locales.

**Docs**
- `LESSONS-LEARNED.md`: Cloud Run Job retry race pattern + idempotency
defenses.

## Testing

- [x] Backend unit tests pass: 3183 passed, 36 skipped (10 new tests for
this work)
- [x] Frontend Jest tests pass: 110 passed in affected suites (8 new
tests)
- [x] TDD throughout — failing test before each implementation change

Tests added cover:
- Worker idempotency across 8 post-download statuses (`DOWNLOADING`,
`AWAITING_AUDIO_EDIT`, `TRANSCRIBING`, ... `COMPLETE`)
- Retry-pending marker: written on non-final attempt, cleared on final
attempt, cleared on success
- `_is_auto_retry_pending` helper edge cases (missing / past / future /
malformed)
- Frontend: indicator shows during window, falls back to Retry after
expiry, JobCard hides stale error on complete

## Review

- [x] Local code review completed (CodeRabbit CLI auth issue →
`feature-dev:code-reviewer` agent fallback)
- [x] Should-fix finding addressed: stale marker after final attempt
blocked manual retry for ~3 min (commit `d87cd86`)
- [ ] Optional finding deferred: frontend doesn't auto-re-render at
exact expiry time (dashboard polls, self-heals)

## Infrastructure

No Pulumi changes. `audio-download-job` `max_retries=2` retained —
automatic recovery from transient Spotify timeouts still works, and the
new idempotency guard makes retries safe.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 15:02:36 -04:00
Andrew Beveridge ☄️ 37a6f12631 fix(idle-shutdown): check multi-zone fallback VMs (#758)
## Summary

The encoding-worker idle-shutdown Cloud Function only iterated
\`[primary_vm, secondary_vm]\` in the default zone — capacity-fallback
VMs in alternate zones (\`-a\`/\`-b\`) were never checked, so a fallback
started during a capacity event stayed RUNNING indefinitely after the
event resolved.

Observed 2026-05-07: \`encoding-worker-fallback-a\` in \`us-central1-a\`
ran for 13+ hours idle (~\$15 cost) before manual intervention.

## Changes

- **\`infrastructure/functions/encoding_worker_idle/main.py\`**:
- Read \`ENCODING_WORKER_FALLBACK_VMS\` env (same secret the backend
uses for capacity failover) and iterate fallbacks alongside
primary/secondary.
- Threaded \`zone\` through \`get_vm_status\` / \`get_vm_ip\` /
\`stop_vm\` so cross-zone shutdowns work.
- Keep-alive-on-recent-activity now follows \`active_override_vm\` (the
currently-routed VM during a capacity event), not always the primary.
Otherwise an active capacity-fallback would get killed while serving
real traffic.
- **\`infrastructure/modules/encoding_worker_manager.py\`** (Pulumi):
- Wire the \`encoding-worker-fallback-vms\` secret into the function via
\`secret_environment_variables\`.
- New \`gcp.secretmanager.SecretIamMember\` binding so the function's SA
can read that secret.
- **\`infrastructure/functions/encoding_worker_idle/deploy.sh\`** (new):
uploads source zip and triggers function rebuild. Was missing for this
function (other functions all have one); matches the pattern from
\`backup_to_aws/deploy.sh\` etc.
-
**\`infrastructure/functions/encoding_worker_idle/test_idle_shutdown.py\`**:
9 new tests:
  - Idle fallback gets stopped (in its own zone)
- Active-override fallback kept alive on recent activity (primary stops
instead)
  - Fallback with active jobs not stopped
  - Graceful behavior when env var missing or malformed JSON
  - 4 unit tests on the \`_parse_fallback_vms\` helper
  - All 18 tests pass.

## Already applied to prod

I ran \`pulumi up\` and \`deploy.sh\` from this branch to apply the fix.
CI's pulumi-up will be a no-op on merge.

**End-to-end verification:**
1. Started \`encoding-worker-fallback-a\` manually (RUNNING)
2. Triggered \`encoding-worker-idle-check\` scheduler
3. fallback-a went to STOPPING within ~20s ✅

Before fix: fallback-a would have stayed RUNNING (old code never checked
fallbacks).
After fix: fallback gets stopped on the next 5-min idle sweep.

## Test plan

- [x] 18 unit tests pass locally (9 existing + 9 new)
- [x] \`pulumi preview\`: 1 created (secret IAM), 1 updated (function
with secret env var), 263 unchanged
- [x] \`pulumi up\` applied successfully
- [x] \`deploy.sh\` deployed new function code
- [x] Manually verified: fallback-a started → triggered idle-check →
stopped

@coderabbitai ignore
2026-05-07 11:33:13 -04:00
211 changed files with 16333 additions and 2615 deletions

No files matched your search

+277
View File
@@ -0,0 +1,277 @@
name: Build GHA Runner Images
# Produces three custom GCE images used by the ephemeral GitHub Actions runner
# dispatcher: gha-runner-general, gha-runner-build, gha-runner-gpu.
#
# Flow per variant:
# 1. Create a temporary build VM from debian-cloud/debian-12 with
# infrastructure/scripts/runner-image-provision.sh as metadata-startup-script.
# 2. Poll for /opt/runner-image-ready via gcloud ssh (survives kernel-upgrade reboots).
# 3. Stop the VM, snapshot its boot disk to a new image in the `gha-runner-<variant>`
# image family with name gha-runner-<variant>-<timestamp>.
# 4. Delete the build VM (boot disk auto-deletes).
# 5. Deprecate older images in the family, keeping the newest 3 ACTIVE.
on:
workflow_dispatch:
inputs:
variants:
description: 'Comma-separated variants to build (general,build,gpu) or "all"'
required: false
default: 'all'
skip_prune:
description: 'Skip deprecation of old images (debugging)'
type: boolean
required: false
default: false
schedule:
# Monthly on the 1st at 02:00 UTC
- cron: '0 2 1 * *'
permissions:
contents: read
id-token: write
env:
GCP_PROJECT: nomadkaraoke
BUILD_REGION: us-central1
BUILD_ZONE: us-central1-a
BASE_IMAGE: projects/debian-cloud/global/images/family/debian-12
KEEP_IMAGES_PER_FAMILY: 3
jobs:
resolve-matrix:
name: Resolve variant matrix
runs-on: ubuntu-latest
outputs:
variants: ${{ steps.resolve.outputs.variants }}
steps:
- id: resolve
run: |
requested='${{ github.event.inputs.variants || 'all' }}'
if [[ "$requested" == "all" || -z "$requested" ]]; then
echo 'variants=["general","build","gpu"]' >> "$GITHUB_OUTPUT"
else
json="$(echo "$requested" | tr ',' '\n' | jq -R . | jq -sc .)"
echo "variants=$json" >> "$GITHUB_OUTPUT"
fi
build:
name: Build ${{ matrix.variant }} image
needs: resolve-matrix
runs-on: ubuntu-latest
timeout-minutes: 90
strategy:
fail-fast: false
matrix:
variant: ${{ fromJSON(needs.resolve-matrix.outputs.variants) }}
steps:
- uses: actions/checkout@v4
- name: Authenticate to GCP
uses: google-github-actions/auth@v2
with:
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
- name: Set up Cloud SDK
uses: google-github-actions/setup-gcloud@v2
with:
project_id: ${{ env.GCP_PROJECT }}
- name: Resolve build parameters
id: params
run: |
variant='${{ matrix.variant }}'
ts="$(date -u +%Y%m%d-%H%M%S)"
name="gha-runner-${variant}-${ts}"
family="gha-runner-${variant}"
vm="gha-image-build-${variant}-${ts}"
case "$variant" in
general|build)
machine="n2-standard-8"
disk_size="50"
accel=""
;;
gpu)
# Build with a T4 attached so DKMS module is built and validated
# against the kernel that ships in the image.
machine="n1-standard-4"
disk_size="200"
accel="--maintenance-policy=TERMINATE --accelerator=type=nvidia-tesla-t4,count=1"
;;
*)
echo "Unknown variant: $variant" >&2
exit 1
;;
esac
{
echo "name=$name"
echo "family=$family"
echo "vm=$vm"
echo "machine=$machine"
echo "disk_size=$disk_size"
echo "accel=$accel"
} >> "$GITHUB_OUTPUT"
- name: Create build VM
run: |
set -euo pipefail
gcloud compute instances create '${{ steps.params.outputs.vm }}' \
--project='${{ env.GCP_PROJECT }}' \
--zone='${{ env.BUILD_ZONE }}' \
--machine-type='${{ steps.params.outputs.machine }}' \
--image='${{ env.BASE_IMAGE }}' \
--boot-disk-size='${{ steps.params.outputs.disk_size }}GB' \
--boot-disk-type=pd-balanced \
--boot-disk-auto-delete \
--service-account="${{ secrets.GCP_SERVICE_ACCOUNT }}" \
--scopes=https://www.googleapis.com/auth/cloud-platform \
--metadata=enable-oslogin=TRUE,image-variant='${{ matrix.variant }}' \
--metadata-from-file=startup-script=infrastructure/scripts/runner-image-provision.sh \
--labels=purpose=gha-runner-image-builder,variant='${{ matrix.variant }}' \
${{ steps.params.outputs.accel }}
- name: Wait for provisioning to complete
env:
VM: ${{ steps.params.outputs.vm }}
ZONE: ${{ env.BUILD_ZONE }}
PROJECT: ${{ env.GCP_PROJECT }}
run: |
set -uo pipefail
# Read the serial console — NOT SSH — to detect completion.
#
# The provisioner script tees its full output to /dev/ttyS0 (the GCE
# serial console). `gcloud compute instances get-serial-port-output`
# returns the full console buffer with zero SSH/IAP dependency. This
# makes the wait robust against the IAP tunnel issues that previously
# caused both false-positive readiness and false-negative timeouts.
#
# The script writes one of two distinctive marker lines:
# "### runner-image: READY: ..." — successful completion
# "### runner-image-provision FAILED ..." — fatal error (with line+rc)
#
# We also stream live progress to the GHA log so the operator can
# see what's happening without leaving the run page.
deadline=$(( $(date +%s) + 75 * 60 ))
last_size=0
attempt=0
while (( $(date +%s) < deadline )); do
attempt=$((attempt+1))
console=$(gcloud compute instances get-serial-port-output "$VM" \
--zone="$ZONE" --project="$PROJECT" --port=1 2>/dev/null || true)
cur_size=${#console}
# Stream new provisioner lines (filter syslog noise).
if (( cur_size > last_size )); then
echo "$console" | tail -c +$((last_size+1)) \
| grep -E "runner-image|### |Attempt " || true
last_size=$cur_size
fi
# Success marker
if echo "$console" | grep -qE 'runner-image: READY:'; then
echo
echo "### Image ready (attempt $attempt)"
echo "$console" | grep -E 'runner-image: READY:' | tail -1
exit 0
fi
# Failure marker
if echo "$console" | grep -qE 'runner-image-provision FAILED'; then
echo
echo "### Provisioner reported FAILURE — failure block + 40 lines of preceding context:" >&2
# -B 40: include 40 lines BEFORE the marker (where the actual
# error output of the failing command lives — python tracebacks,
# apt errors, curl messages, etc).
# -A 5: include the variant/line/cmd metadata lines after the marker.
echo "$console" | grep -B 40 -A 5 'runner-image-provision FAILED' \
| tail -80 >&2
exit 1
fi
sleep 30
done
echo
echo "### Timed out waiting for READY marker after 75 minutes" >&2
echo "### Last serial console output (tail):" >&2
gcloud compute instances get-serial-port-output "$VM" \
--zone="$ZONE" --project="$PROJECT" --port=1 2>/dev/null \
| grep -E "runner-image|### " | tail -50 >&2 || true
exit 1
- name: Stop build VM
env:
VM: ${{ steps.params.outputs.vm }}
ZONE: ${{ env.BUILD_ZONE }}
PROJECT: ${{ env.GCP_PROJECT }}
run: |
set -euo pipefail
gcloud compute instances stop "$VM" --zone="$ZONE" --project="$PROJECT" --quiet
# Belt-and-suspenders wait for TERMINATED.
for _ in $(seq 1 60); do
status=$(gcloud compute instances describe "$VM" --zone="$ZONE" --project="$PROJECT" --format='value(status)')
[[ "$status" == "TERMINATED" ]] && break
sleep 5
done
- name: Create image
env:
VM: ${{ steps.params.outputs.vm }}
ZONE: ${{ env.BUILD_ZONE }}
PROJECT: ${{ env.GCP_PROJECT }}
IMAGE: ${{ steps.params.outputs.name }}
FAMILY: ${{ steps.params.outputs.family }}
run: |
set -euo pipefail
# The "Create build VM" step doesn't pass --device-name or
# --boot-disk-name, so GCE auto-names the boot disk after the
# instance. We rely on that here instead of extracting the name
# via a format expression — the previous
# `disks[0].source.scope(disks).segment(1)` selector silently
# returned empty and gcloud rejected the call with
# "You cannot specify [--source-disk-zone] unless you are
# specifying [--source-disk]".
DISK="$VM"
echo "Creating image $IMAGE in family $FAMILY from disk $DISK in $ZONE..."
gcloud compute images create "$IMAGE" \
--project="$PROJECT" \
--source-disk="$DISK" \
--source-disk-zone="$ZONE" \
--family="$FAMILY" \
--description="GHA ephemeral runner image (${{ matrix.variant }}) built ${{ github.run_id }}" \
--labels=purpose=gha-ephemeral-runner,variant=${{ matrix.variant }},built-by=gha
echo "Created $IMAGE in family $FAMILY"
- name: Delete build VM
if: always()
env:
VM: ${{ steps.params.outputs.vm }}
ZONE: ${{ env.BUILD_ZONE }}
PROJECT: ${{ env.GCP_PROJECT }}
run: |
gcloud compute instances delete "$VM" --zone="$ZONE" --project="$PROJECT" --quiet || true
- name: Deprecate old images (keep newest ${{ env.KEEP_IMAGES_PER_FAMILY }})
if: ${{ github.event.inputs.skip_prune != 'true' }}
env:
PROJECT: ${{ env.GCP_PROJECT }}
FAMILY: ${{ steps.params.outputs.family }}
KEEP: ${{ env.KEEP_IMAGES_PER_FAMILY }}
run: |
set -euo pipefail
# List ACTIVE images in this family, newest first, skip the top $KEEP.
to_deprecate=$(gcloud compute images list \
--project="$PROJECT" \
--filter="family=$FAMILY AND status=READY AND -deprecated.state:*" \
--sort-by='~creationTimestamp' \
--format='value(name)' | tail -n +$((KEEP+1)))
if [[ -z "$to_deprecate" ]]; then
echo "Nothing to deprecate."
exit 0
fi
for img in $to_deprecate; do
echo "Deprecating $img"
gcloud compute images deprecate "$img" \
--project="$PROJECT" \
--state=DEPRECATED \
--replacement="projects/$PROJECT/global/images/family/$FAMILY"
done
+12 -2
View File
@@ -652,7 +652,17 @@ jobs:
java-version: "21"
- name: Install Firestore emulator
run: sudo apt-get install -y google-cloud-cli-firestore-emulator
run: |
# Ensure Google Cloud SDK apt source is present (ephemeral runner images
# may not ship it pre-installed). Idempotent.
if ! grep -rq "packages.cloud.google.com" /etc/apt/sources.list.d/ 2>/dev/null; then
echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | \
sudo tee /etc/apt/sources.list.d/google-cloud-sdk.list
curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg | \
sudo gpg --dearmor --yes -o /usr/share/keyrings/cloud.google.gpg
fi
sudo apt-get update -y
sudo apt-get install -y google-cloud-cli-firestore-emulator
- name: Install dependencies
run: poetry install
@@ -1649,7 +1659,7 @@ jobs:
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
--vpc-egress private-ranges-only \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
- name: Update Cloud Run Jobs with new image
run: |
+19 -11
View File
@@ -83,6 +83,7 @@ jobs:
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
- name: Run Credit Purchase Test
id: run_test
working-directory: frontend
env:
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
@@ -102,16 +103,18 @@ jobs:
--reporter=list \
--timeout=600000 \
2>&1 | tee test-output-payment.log
# Capture Playwright's real exit code, not tee's (0) — the
# authoritative pass/fail signal. See Stage 2 for rationale.
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
continue-on-error: true
- name: Check test result
id: test_result
working-directory: frontend
run: |
if grep -q "CREDIT PURCHASE TEST PASSED" test-output-payment.log; then
echo "result=success" >> $GITHUB_OUTPUT
if [ "${{ steps.run_test.outputs.exit_code }}" = "0" ]; then
echo "result=success" >> "$GITHUB_OUTPUT"
else
echo "result=failure" >> $GITHUB_OUTPUT
echo "result=failure" >> "$GITHUB_OUTPUT"
fi
- name: Extract session token
@@ -209,6 +212,7 @@ jobs:
echo "token=$TOKEN" >> $GITHUB_OUTPUT
- name: Run Happy Path Test
id: run_test
working-directory: frontend
env:
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
@@ -234,16 +238,20 @@ jobs:
--reporter=list \
--timeout=3600000 \
2>&1 | tee test-output-happy-path.log
# Capture Playwright's real exit code, not tee's (0). This is the
# authoritative pass/fail signal — grepping the log for "failed" is
# fragile because benign retry warnings (e.g. "goto attempt 1/3
# failed") contain that substring and produce false alarms.
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
continue-on-error: true
- name: Check test result
id: test_result
working-directory: frontend
run: |
if grep -q "passed" test-output-happy-path.log && ! grep -q "failed" test-output-happy-path.log; then
echo "result=success" >> $GITHUB_OUTPUT
if [ "${{ steps.run_test.outputs.exit_code }}" = "0" ]; then
echo "result=success" >> "$GITHUB_OUTPUT"
else
echo "result=failure" >> $GITHUB_OUTPUT
echo "result=failure" >> "$GITHUB_OUTPUT"
fi
- name: Upload test artifacts
@@ -317,10 +325,10 @@ jobs:
if: github.event_name == 'schedule'
uses: dawidd6/action-send-mail@v3
with:
server_address: smtp.sendgrid.net
server_address: smtp.postmarkapp.com
server_port: 587
username: apikey
password: ${{ secrets.SENDGRID_API_KEY }}
username: ${{ secrets.POSTMARK_SERVER_TOKEN }}
password: ${{ secrets.POSTMARK_SERVER_TOKEN }}
subject: "E2E Daily Test ${{ needs.e2e-happy-path.result == 'success' && 'PASSED' || 'FAILED' }} - Run #${{ github.run_number }}"
to: andrew@nomadkaraoke.com
from: "Karaoke Gen CI <noreply@nomadkaraoke.com>"
+4 -2
View File
@@ -102,8 +102,10 @@ See `docs/TESTING.md` § "Ad-Hoc Production Debugging" for full details.
- All user-facing strings live in `frontend/messages/{locale}.json` (33 locales), NOT in components
- Backend strings live in `backend/translations/{locale}.json` (currently 3 locales: en, es, de)
- Components use `useTranslations('namespace')` from next-intl
- Pages are under `frontend/src/app/[locale]/` — locale-aware routing
- Admin pages (under `/admin/`, `/app/`) use DefaultIntlProvider (English-only, excluded from i18n)
- Pages are under `frontend/app/[locale]/` — locale-aware routing (customer-facing: `/`, `/app/*`, `/order/*`, `/auth/*`, `/payment/*`, `/r/*`)
- Non-locale routes at those same paths (e.g. `frontend/app/app/jobs/[[...slug]]/page.tsx`) are `<LocaleRedirect />` shims that redirect into `[locale]` — they are NOT English-only surfaces
- The `/app/jobs/#/{id}/review`, `/instrumental`, and `/audio-edit` review UIs are fully multilingual (components under `components/lyrics-review/`, `components/instrumental-review/`, `components/audio-editor/` use `useTranslations` heavily)
- Only `/admin/*` is English-only — it has no `[locale]/admin` counterpart and inherits `DefaultIntlProvider` from the root layout
- Internal links use `Link` from `@/i18n/routing` (locale-aware)
- After adding/changing English strings: `python frontend/scripts/translate.py --messages-dir frontend/messages --target all`
- Translation uses Gemini 3.1 Pro via Vertex AI with GCS cache for efficiency
+6 -5
View File
@@ -2049,6 +2049,7 @@ REGENERATE_SCREENS_ALLOWED_STATES = {
"complete",
"failed",
"awaiting_review",
"in_review", # User opened the review UI but hasn't submitted yet
"awaiting_instrumental_selection",
"instrumental_selected",
"prep_complete",
@@ -2131,7 +2132,7 @@ async def regenerate_screens(
]
for path in screen_paths:
try:
storage.delete_file(path)
storage.delete_file(path, ignore_missing=True)
except Exception:
pass # File may not exist
screens_deleted = True
@@ -2286,16 +2287,16 @@ async def restart_job(
for screen_file in ["title.mov", "title.jpg", "title.png", "end.mov", "end.jpg", "end.png"]:
try:
path = f"jobs/{job_id}/screens/{screen_file}"
storage.delete_file(path)
deleted_paths.append(path)
if storage.delete_file(path, ignore_missing=True):
deleted_paths.append(path)
except Exception:
pass
# Delete final outputs
for output_file in ["final_4k.mp4", "final_720p.mp4", "with_vocals.mkv", "preview.mp4"]:
try:
path = f"jobs/{job_id}/output/{output_file}"
storage.delete_file(path)
deleted_paths.append(path)
if storage.delete_file(path, ignore_missing=True):
deleted_paths.append(path)
except Exception:
pass
+61
View File
@@ -52,6 +52,8 @@ from backend.middleware.tenant import get_tenant_config_from_request
from backend.exceptions import InsufficientCreditsError
from backend.services.tracing import add_span_attribute
from backend.services.firestore_service import FirestoreService
from backend.services.user_service import get_user_service
from backend.services.pricing import duration_to_credits, is_blocked
from pathlib import Path
from backend.i18n import t, get_locale_from_request
@@ -228,6 +230,9 @@ class AudioSelectRequest(BaseModel):
is_private: Optional[bool] = Field(None, description="Override privacy flag (guided flow Step 3)")
display_artist: Optional[str] = Field(None, description="Override display artist name")
display_title: Optional[str] = Field(None, description="Override display title")
# Anti-mismatch guard: client may send the expected credit total it observed.
# If the server's computed target_total differs, we return 409 so the UI can refresh.
acknowledged_credits: Optional[int] = Field(None, description="Expected total credits after this selection (anti-mismatch guard)")
class AudioSelectResponse(BaseModel):
@@ -1174,6 +1179,62 @@ async def select_audio_source(
if not search_results:
raise HTTPException(status_code=400, detail="No search results cached for this job")
# -------------------------------------------------------------------------
# Duration-based pricing: charge the DELTA before triggering any download.
# -------------------------------------------------------------------------
# The selected result may carry a duration field (seconds as int).
selected_result = search_results[body.selection_index] if 0 <= body.selection_index < len(search_results) else {}
duration = selected_result.get('duration') # int seconds, or None
# Hard ceiling: reject inputs over 60 minutes immediately (before any state change).
if duration is not None and is_blocked(duration):
raise HTTPException(status_code=422, detail="Inputs over 60 minutes aren't supported")
# Idempotency guard: if a previous /select call already applied the delta charge,
# skip re-charging entirely. This makes double-click / rapid-retry safe.
# Residual race: two *truly simultaneous* requests can both read the flag as False
# and both charge before either writes it True. The atomic status transition in
# _validate_and_prepare_selection() causes the second request to fail with 400,
# so the window is tiny; any rare double-charge is recoverable via support refund.
select_charge_applied = bool((job.state_data or {}).get('select_charge_applied', False))
# Compute how many credits this job should total after selecting this result.
# If duration is unknown, keep target_total == credits_charged so owed = 0.
credits_charged = int((job.state_data or {}).get('credits_charged', 1))
target_total = duration_to_credits(duration) if duration is not None else credits_charged
owed = max(0, target_total - credits_charged)
# Anti-mismatch guard: if the client sent an expected total, verify it still matches.
if body.acknowledged_credits is not None and body.acknowledged_credits != target_total:
raise HTTPException(status_code=409, detail="Credit figure changed; please refresh")
# Deduct the owed delta (or just persist duration metadata if owed == 0).
user_email = job.user_email
if not select_charge_applied:
if owed > 0:
if not user_email:
raise HTTPException(status_code=500, detail="Job has no associated user email")
ok, _, _ = get_user_service().deduct_credits(
user_email,
job_id,
amount=owed,
reason="job_creation",
count_as_job_creation=False, # job was already counted at create_job()
)
if not ok:
raise HTTPException(status_code=402, detail="Insufficient credits")
# Persist updated credit total, duration estimate, and idempotency flag.
state_update: dict = {
"state_data.credits_charged": target_total,
"state_data.select_charge_applied": True,
}
if duration is not None:
state_update["state_data.duration_estimate_seconds"] = duration
state_update["state_data.duration_estimate_source"] = "search_metadata"
job_manager.update_job(job_id, state_update)
# -------------------------------------------------------------------------
# Validate selection and transition to DOWNLOADING_AUDIO (returns immediately)
selection_info = _validate_and_prepare_selection(
job_id=job_id,
+13
View File
@@ -10,6 +10,7 @@ import logging
from fastapi import APIRouter, Depends
from backend.api.dependencies import require_admin
from backend.services.encoding_worker_manager import EncodingWorkerManager
from backend.services.encoding_errors import EncodingWorkerStartError
logger = logging.getLogger(__name__)
@@ -46,6 +47,18 @@ async def warmup_encoding_worker(
if result["started"]:
logger.info(f"Started encoding worker VM: {result['vm_name']}")
return result
except EncodingWorkerStartError as e:
# The primary VM couldn't start (capacity exhaustion or a transient
# 503 SERVICE_UNAVAILABLE from the GCE backend). This is NOT fatal:
# the encoding flow's own warmup (ensure_any_running) falls back to
# the alternate-zone workers, so the job still completes. Log at
# WARNING so it doesn't trip the production error monitor and page us
# for self-healing capacity events.
logger.warning(
f"Primary encoding worker warmup failed ({e}); "
f"encoding will fall back to an alternate-zone worker"
)
return {"started": False, "error": str(e)}
except Exception as e:
logger.error(f"Failed to warm up encoding worker: {e}")
return {"started": False, "error": str(e)}
+47 -59
View File
@@ -10,12 +10,11 @@ Supports two upload flows:
- Client uploads files directly to GCS using signed URLs (no size limit)
- POST /api/jobs/{job_id}/uploads-complete - Validates uploads, triggers workers
"""
import asyncio
import json
import logging
import tempfile
import os
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Body, Depends
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Depends
from pathlib import Path
from typing import Optional, List, Dict, Any, Tuple
@@ -338,16 +337,6 @@ ALLOWED_IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp'}
ALLOWED_FONT_EXTENSIONS = {'.ttf', '.otf', '.woff', '.woff2'}
async def _trigger_audio_worker_only(job_id: str) -> None:
"""
Trigger only the audio worker.
Used for URL jobs where audio needs to be downloaded first.
The audio worker will trigger the lyrics worker after download completes.
"""
await worker_service.trigger_audio_worker(job_id)
def _prepare_theme_for_job(
job_id: str,
theme_id: str,
@@ -1635,6 +1624,13 @@ async def create_job_from_url(
detail = "This YouTube video is private and cannot be downloaded."
elif availability.get("is_removed"):
detail = "This YouTube video has been removed and cannot be downloaded."
elif availability.get("is_bot_blocked"):
detail = (
"We're temporarily unable to access YouTube to download this video — "
"YouTube is asking our server to verify it's not a bot. "
"Please try again in a few minutes, or use Audio Search to find this song "
"from another source."
)
elif availability.get("is_age_restricted"):
detail = "This YouTube video is age-restricted and cannot be downloaded."
else:
@@ -1777,55 +1773,47 @@ async def create_job_from_url(
if title:
logger.info(f" Title: {title}")
# For YouTube URLs, download audio NOW using YouTubeDownloadService
# This uses remote flacfetch (if configured) to avoid bot detection on Cloud Run
if _is_youtube_url(body.url):
logger.info(f"YouTube URL detected, downloading via YouTubeDownloadService")
try:
youtube_service = get_youtube_download_service()
audio_gcs_path = await youtube_service.download(
url=body.url,
job_id=job_id,
artist=artist,
title=title,
)
# Update job with the downloaded audio path
job_manager.update_job(job_id, {
'input_media_gcs_path': audio_gcs_path,
'filename': os.path.basename(audio_gcs_path),
})
logger.info(f"YouTube audio downloaded to GCS: {audio_gcs_path}")
# Use centralized start_job_processing which handles:
# 1. Validates job exists and has input_media_gcs_path
# 2. Transitions PENDING → DOWNLOADING (raises if invalid)
# 3. Triggers audio + lyrics workers in parallel
background_tasks.add_task(
job_manager.start_job_processing,
job_id,
10, # progress
"Audio downloaded, starting processing"
)
except YouTubeDownloadError as e:
logger.error(f"YouTube download failed: {e}")
job_manager.fail_job(job_id, f"YouTube download failed: {e}")
raise HTTPException(
status_code=500,
detail=t(locale, "audioSearch.youtubeDownloadError", error=str(e))
)
else:
# For non-YouTube URLs, transition to DOWNLOADING and trigger audio worker
# The audio worker will download the URL and trigger lyrics worker after
job_manager.transition_to_state(
# Download audio NOW via the flacfetch service for ALL URLs (YouTube and
# any other yt-dlp-supported site, e.g. Facebook/SoundCloud/TikTok).
# flacfetch is the sole downloader — no yt-dlp ever runs on Cloud Run.
# Downloading up front (before the GPU worker starts) also keeps the GPU
# idle until the audio is in GCS.
logger.info(f"Downloading audio from URL via flacfetch: {body.url}")
try:
download_service = get_youtube_download_service()
audio_gcs_path = await download_service.download(
url=body.url,
job_id=job_id,
new_status=JobStatus.DOWNLOADING,
progress=5,
message="Starting audio download from URL"
artist=artist,
title=title,
)
# Update job with the downloaded audio path
job_manager.update_job(job_id, {
'input_media_gcs_path': audio_gcs_path,
'filename': os.path.basename(audio_gcs_path),
})
logger.info(f"Audio downloaded to GCS: {audio_gcs_path}")
# Use centralized start_job_processing which handles:
# 1. Validates job exists and has input_media_gcs_path
# 2. Transitions PENDING → DOWNLOADING (raises if invalid)
# 3. Triggers audio + lyrics workers in parallel
background_tasks.add_task(
job_manager.start_job_processing,
job_id,
10, # progress
"Audio downloaded, starting processing"
)
except YouTubeDownloadError as e:
logger.error(f"URL download failed: {e}")
job_manager.fail_job(job_id, f"Download failed: {e}")
raise HTTPException(
status_code=500,
detail=t(locale, "audioSearch.youtubeDownloadError", error=str(e))
)
background_tasks.add_task(_trigger_audio_worker_only, job_id)
return CreateJobFromUrlResponse(
status="success",
+29 -15
View File
@@ -362,8 +362,9 @@ async def check_idle_reminder(
"""
Check if a job needs an idle reminder email.
This endpoint is called by a Cloud Tasks scheduled task 5 minutes after
a job enters AWAITING_REVIEW state.
This endpoint is called by a Cloud Tasks scheduled task after a job enters
a blocking state (AWAITING_REVIEW, AWAITING_AUDIO_EDIT, AWAITING_DURATION_CONFIRM,
or the legacy AWAITING_INSTRUMENTAL_SELECTION).
If the job is still in the blocking state and no reminder has been sent yet,
sends a reminder email to the user.
@@ -390,7 +391,11 @@ async def check_idle_reminder(
# Check if job is still in a blocking state
# Note: AWAITING_INSTRUMENTAL_SELECTION is LEGACY - kept for historical jobs only
blocking_states = [JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION]
blocking_states = [
JobStatus.AWAITING_REVIEW,
JobStatus.AWAITING_INSTRUMENTAL_SELECTION,
JobStatus.AWAITING_DURATION_CONFIRM,
]
if job.status not in [s.value for s in blocking_states]:
logger.info(f"[job:{job_id}] Job no longer in blocking state ({job.status}), skipping reminder")
add_span_event("not_blocking", {"current_status": job.status})
@@ -424,23 +429,32 @@ async def check_idle_reminder(
# Determine action type
action_type = state_data.get('blocking_action_type')
if not action_type:
action_type = "lyrics" if job.status == JobStatus.AWAITING_REVIEW.value else "instrumental"
if job.status == JobStatus.AWAITING_REVIEW.value:
action_type = "lyrics"
elif job.status == JobStatus.AWAITING_DURATION_CONFIRM.value:
action_type = "duration_confirm"
else:
action_type = "instrumental"
# Send the reminder email
try:
notification_service = get_job_notification_service()
success = await notification_service.send_action_reminder_email(
job_id=job.job_id,
user_email=job.user_email,
action_type=action_type,
user_name=None, # Could fetch from user service if needed
artist=job.artist,
title=job.title,
audio_hash=job.audio_hash,
review_token=job.review_token,
instrumental_token=job.instrumental_token,
)
if action_type == "duration_confirm":
# Duration-confirm has its own dedicated reminder method
success = await notification_service.send_duration_confirm_reminder(job)
else:
success = await notification_service.send_action_reminder_email(
job_id=job.job_id,
user_email=job.user_email,
action_type=action_type,
user_name=None, # Could fetch from user service if needed
artist=job.artist,
title=job.title,
audio_hash=job.audio_hash,
review_token=job.review_token,
instrumental_token=job.instrumental_token,
)
if success:
# Mark reminder as sent (prevents duplicate sends)
+299 -15
View File
@@ -17,7 +17,7 @@ from pathlib import Path
from typing import List, Optional, Dict, Any
from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request, UploadFile, File
from datetime import datetime
from datetime import datetime, timezone
from backend.utils.request_helpers import get_client_ip
from backend.models.job import Job, JobCreate, JobResponse, JobStatus
from backend.models.requests import (
@@ -44,7 +44,10 @@ from backend.utils.test_data import is_test_email
from backend.exceptions import InsufficientCreditsError
from backend.services.firestore_service import FirestoreService, log_to_job
from backend.models.requests import ChangeVisibilityRequest, ChangeVisibilityResponse
from pydantic import BaseModel, Field, validator
from backend.services.user_service import get_user_service
from backend.services.youtube_download_service import get_youtube_download_service
from backend.services.pricing import duration_to_credits, is_blocked
from pydantic import BaseModel, Field, HttpUrl, validator
logger = logging.getLogger(__name__)
@@ -120,6 +123,32 @@ async def create_job(
)
logger.info(f"Applying default theme: {effective_theme_id}")
# Duration-based pricing: derive credit cost from known audio duration.
# Reject inputs that are too long before any job is created.
duration_seconds = request.duration_seconds
if duration_seconds is not None and is_blocked(duration_seconds):
raise HTTPException(
status_code=422,
detail="Inputs over 60 minutes aren't supported"
)
credits = duration_to_credits(duration_seconds) if duration_seconds is not None else 1
# Anti-mismatch guard: if the client told us how many credits it expects,
# reject early if the server's computation disagrees (avoids surprise charges).
if request.acknowledged_credits is not None and request.acknowledged_credits != credits:
raise HTTPException(
status_code=409,
detail="Credit figure changed; please refresh"
)
# Build initial state_data with duration estimate for observability.
initial_state_data: Dict[str, Any] = {}
if duration_seconds is not None:
initial_state_data["duration_estimate_seconds"] = duration_seconds
initial_state_data["duration_estimate_source"] = "youtube_metadata"
else:
initial_state_data["duration_estimate_source"] = "unknown"
# Create job with all preferences
job_create = JobCreate(
url=str(request.url),
@@ -133,13 +162,18 @@ async def create_job(
webhook_url=request.webhook_url,
user_email=user_email,
is_private=request.is_private or False,
credits=credits,
)
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
# Store client IP on job for anti-abuse correlation
# Persist duration estimate fields and creation_ip in a single Firestore write.
update_payload = {
f"state_data.{k}": v for k, v in initial_state_data.items()
}
creation_ip = get_client_ip(http_request)
if creation_ip:
FirestoreService().update_job(job.job_id, {"creation_ip": creation_ip})
update_payload["creation_ip"] = creation_ip
FirestoreService().update_job(job.job_id, update_payload)
# Trace attributes for observability
add_span_attribute("job_id", job.job_id)
@@ -160,7 +194,7 @@ async def create_job(
job_id=job.job_id,
message=t(locale, "jobs.created")
)
except InsufficientCreditsError:
except (InsufficientCreditsError, HTTPException):
raise
except Exception as e:
logger.error(f"Error creating job: {e}", exc_info=True)
@@ -537,11 +571,40 @@ _SUMMARY_STATE_DATA_KEYS = {
'audio_complete', 'lyrics_complete',
'backing_vocals_analysis', 'visibility_change_in_progress',
'render_pending_capacity',
'cloud_run_retry_pending',
'credits_charged',
'pending_additional_credits',
'duration_actual_seconds',
'duration_confirm_reason',
}
_SUMMARY_FILE_URLS_KEYS = {'finals', 'videos', 'packages'}
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete', 'cancelled']
def _is_auto_retry_pending(state_data: Optional[Dict[str, Any]]) -> bool:
"""Return True if a Cloud Run Job auto-retry is currently expected.
The audio-download worker records `state_data.cloud_run_retry_pending`
with an `expires_at` when it fails and another task attempt is coming.
The /retry endpoint uses this to refuse starting a parallel execution,
and the UI uses the projected field to show a "Retrying automatically..."
indicator instead of a Retry button.
"""
pending = (state_data or {}).get('cloud_run_retry_pending')
if not isinstance(pending, dict):
return False
expires_at_str = pending.get('expires_at')
if not expires_at_str:
return False
try:
expires_at = datetime.fromisoformat(str(expires_at_str).replace('Z', '+00:00'))
except (ValueError, AttributeError):
return False
if expires_at.tzinfo is None:
expires_at = expires_at.replace(tzinfo=timezone.utc)
return expires_at > datetime.now(timezone.utc)
def _has_title_screen(file_urls: Dict[str, Any]) -> bool:
"""Return True if a title screen image (jpg or png) was generated.
@@ -1011,14 +1074,23 @@ async def submit_corrections(
)
try:
# Strip reference_lyrics from Firestore save to avoid exceeding 1MB document
# limit. reference_lyrics can be very large (e.g. Genius fetching non-lyrics
# content like screenplays). The full data is preserved in the GCS upload below.
corrections_for_firestore = {
k: v for k, v in submission.corrections.items()
if k != 'reference_lyrics'
# Persist ONLY a lightweight summary of the corrections to Firestore —
# never the full segment arrays. The complete corrections JSON
# (corrected_segments, original_segments, resized_segments, etc.) can be
# several MB for long songs (e.g. a 30+ minute mashup with hundreds of
# segments) and would blow past Firestore's 1MB per-document hard limit,
# failing the save with a 400. (An earlier fix stripped only
# reference_lyrics, but the segment arrays are the real bulk.) The full
# data is preserved in the GCS upload below (corrections_updated.json),
# which the render worker reads. The only in-Firestore consumer is the
# complete-review 0-segment guard, which just needs the segment count.
corrected_segments = submission.corrections.get('corrected_segments')
corrected_lyrics_summary = {
'corrected_segment_count': (
len(corrected_segments) if isinstance(corrected_segments, list) else 0
),
}
job_manager.update_state_data(job_id, 'corrected_lyrics', corrections_for_firestore)
job_manager.update_state_data(job_id, 'corrected_lyrics', corrected_lyrics_summary)
if submission.user_notes:
job_manager.update_state_data(job_id, 'review_notes', submission.user_notes)
@@ -1374,10 +1446,15 @@ async def complete_review(
lyrics_metadata = state_data.get('lyrics_metadata')
if lyrics_metadata is not None:
segment_count = lyrics_metadata.get('segment_count', 0)
corrected_lyrics = state_data.get('corrected_lyrics', {})
corrected_segments = corrected_lyrics.get('corrected_segments', [])
corrected_lyrics = state_data.get('corrected_lyrics') or {}
# corrected_lyrics now stores a lightweight summary
# ({'corrected_segment_count': N}). Fall back to the legacy shape (full
# dict with a corrected_segments list) for jobs saved before that change.
corrected_segment_count = corrected_lyrics.get('corrected_segment_count')
if corrected_segment_count is None:
corrected_segment_count = len(corrected_lyrics.get('corrected_segments') or [])
if segment_count == 0 and len(corrected_segments) == 0:
if segment_count == 0 and corrected_segment_count == 0:
raise HTTPException(
status_code=400,
detail=t(locale, "jobs.noLyricsDetected")
@@ -1723,6 +1800,15 @@ async def retry_job(
detail=t(locale, "jobs.notCompleted", status=job.status)
)
# Refuse if a Cloud Run Job auto-retry is already coming for this job.
# Otherwise the manual retry races with the automatic one and produces
# duplicate downloads and downstream worker triggers (see job 8a9c74ff).
if _is_auto_retry_pending(job.state_data):
raise HTTPException(
status_code=409,
detail="An automatic retry is already in progress. Please wait a few minutes."
)
try:
# Determine retry point based on what's already complete
error_details = job.error_details or {}
@@ -2513,3 +2599,201 @@ async def change_visibility(
except Exception as e:
logger.error(f"Error changing visibility for job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to change visibility: {str(e)}")
# =============================================================================
# Duration Confirmation Endpoint
# =============================================================================
class ConfirmDurationRequest(BaseModel):
"""Request body for POST /jobs/{job_id}/confirm-duration."""
acknowledged_credits: int
# Keep a set of background tasks alive to prevent GC (mirrors complete_review pattern)
_duration_confirm_tasks: set = set()
@router.post("/{job_id}/confirm-duration")
async def confirm_duration(
job_id: str,
body: ConfirmDurationRequest,
http_request: Request,
auth_result: AuthResult = Depends(require_auth),
):
"""
Confirm duration-based credit charge and resume job processing.
Called when a job is paused in AWAITING_DURATION_CONFIRM state.
The only pause reason currently used is ``reconcile``: the actual measured
duration costs more than was already charged; ``state_data.pending_additional_credits``
holds the delta owed. This applies to URL, upload, and audio-search jobs alike.
The caller must pass ``acknowledged_credits`` equal to the total credit cost
the user has agreed to pay. If the figure has changed (race condition) a 409
is returned so the frontend can refresh and re-show the dialog.
"""
locale = get_locale_from_request(http_request)
# 1. Load job — 404 if not found or not owned by this user.
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
if not _check_job_ownership(job, auth_result):
# Return 404 (not 403) to avoid leaking job existence to non-owners.
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# 2. Status guard.
if job.status != JobStatus.AWAITING_DURATION_CONFIRM:
raise HTTPException(
status_code=409,
detail=f"Job is not awaiting duration confirmation (status: {job.status})",
)
# 3. Compute owed credits and expected total.
#
# - credits_charged: total already deducted from the user's account
# - pending_additional_credits: exactly how many MORE credits are owed to clear the pause
#
# The reconcile engine is responsible for computing and storing pending_additional_credits.
# confirm_duration never needs to call duration_to_credits.
state_data = job.state_data or {}
reason = state_data.get("duration_confirm_reason", "reconcile")
credits_charged = int(state_data.get("credits_charged", 0))
owed = int(state_data.get("pending_additional_credits", 0))
expected_total = credits_charged + owed
# 4. Acknowledged-credits mismatch guard (figure may have changed; client refreshes).
if body.acknowledged_credits != expected_total:
raise HTTPException(
status_code=409,
detail=(
f"acknowledged_credits ({body.acknowledged_credits}) does not match "
f"expected total ({expected_total}). Please refresh and confirm again."
),
)
# 5. Deduct credits if any are owed.
if owed > 0:
user_email = job.user_email
if not user_email:
raise HTTPException(status_code=500, detail="Job has no associated user email")
user_svc = get_user_service()
success, _remaining, _msg = user_svc.deduct_credits(
user_email,
job_id,
amount=owed,
reason="duration_confirm",
count_as_job_creation=False, # job was already counted at create_job()
)
if not success:
raise InsufficientCreditsError(
message=f"Insufficient credits to confirm processing ({owed} credit(s) required).",
credits_available=_remaining,
credits_required=owed,
)
# Update credits_charged in state_data to reflect the new total.
job_manager.update_job(
job_id,
{
"state_data.credits_charged": credits_charged + owed,
"state_data.duration_confirmed": True,
"state_data.pending_additional_credits": 0,
},
)
else:
# owed == 0: nothing to charge, just mark confirmed.
job_manager.update_job(
job_id,
{
"state_data.duration_confirmed": True,
"state_data.pending_additional_credits": 0,
},
)
# 6. Transition job OUT of AWAITING_DURATION_CONFIRM before triggering workers.
#
# This is the idempotency guard: if a duplicate confirm POST arrives (e.g. a
# double-click) the status guard at step 2 will now 409 immediately, preventing
# a second pair of worker launches. We transition to SEPARATING_STAGE1 —
# the normal next state for both the audio and lyrics parallel tracks — which is
# a valid transition from AWAITING_DURATION_CONFIRM per STATE_TRANSITIONS.
# The audio and lyrics workers update their own track states from here on, the
# same as the normal convergence path.
job_manager.transition_to_state(
job_id,
new_status=JobStatus.SEPARATING_STAGE1,
progress=20,
message="Cost confirmed, processing",
)
# 7. Resume processing: trigger both parallel workers in background.
# Use asyncio.create_task (mirrors complete_review in review.py) so the HTTP
# response returns immediately without waiting for Cloud Run job submission.
ws = get_worker_service()
async def _trigger_workers_after_confirm():
try:
await asyncio.gather(
ws.trigger_audio_worker(job_id),
ws.trigger_lyrics_worker(job_id),
)
except Exception as exc:
logger.error(f"Job {job_id}: Failed to trigger workers after duration confirm: {exc}")
task = asyncio.create_task(_trigger_workers_after_confirm())
_duration_confirm_tasks.add(task)
task.add_done_callback(_duration_confirm_tasks.discard)
logger.info(
f"Job {job_id}: duration confirmed (reason={reason}, owed={owed}); workers triggered"
)
# 8. Return the updated job.
updated_job = job_manager.get_job(job_id)
if updated_job is None:
# Should not happen, but be safe.
return {"job_id": job_id, "status": "confirmed"}
return updated_job
# ---------------------------------------------------------------------------
# POST /jobs/estimate — URL duration probe
# ---------------------------------------------------------------------------
class EstimateRequest(BaseModel):
url: HttpUrl
@router.post("/estimate")
async def estimate_duration(
body: EstimateRequest,
auth_result: AuthResult = Depends(require_auth),
):
"""
Probe a URL to estimate its duration and compute the credit cost,
WITHOUT creating a job or downloading any audio.
Returns duration_seconds (or None if unknown), source, credits, and
whether the duration exceeds the supported ceiling (blocked).
"""
info = await get_youtube_download_service().check_availability(str(body.url))
seconds = (info or {}).get("duration")
if seconds is None:
return {
"duration_seconds": None,
"source": "unknown",
"credits": 1,
"blocked": False,
}
return {
"duration_seconds": seconds,
"source": "youtube_metadata",
"credits": duration_to_credits(seconds),
"blocked": is_blocked(seconds),
}
+41 -26
View File
@@ -22,8 +22,7 @@ from pathlib import Path
from typing import Dict, Any, List, Optional, Set, Tuple
from fastapi import APIRouter, HTTPException, Request, Depends, Form, File, UploadFile
from fastapi.responses import FileResponse, RedirectResponse, StreamingResponse
from starlette.background import BackgroundTask
from fastapi.responses import RedirectResponse
from backend.models.job import JobStatus
from backend.models.review_session import ReviewSession, ReviewSessionSummary
@@ -37,6 +36,7 @@ from backend.api.dependencies import require_auth, require_review_auth
from backend.services.auth_service import UserType
from backend.config import get_settings
from backend.i18n import t, get_locale_from_request
from backend.services.duration_reconciliation import reconcile_and_maybe_pause
from pydantic import BaseModel as _PydBaseModel
from backend.services.custom_lyrics_service import (
@@ -1125,9 +1125,19 @@ async def get_preview_video(
preview_hash: str,
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""Stream the generated preview video."""
"""Serve the generated preview video via a signed GCS URL redirect.
We redirect to a signed URL rather than proxying the bytes through Cloud
Run because Cloud Run caps response bodies at 32 MiB. Long songs (e.g. a
30+ minute mashup) produce a 360p preview larger than that, which the proxy
path truncated mid-stream — the response started as 206 but the client
received a 500, so the browser reported "no supported format". The signed
URL lets the browser fetch the mp4 directly from GCS (with byte-range
support intact), bypassing the limit entirely. Mirrors the audio-review
endpoint above.
"""
storage = StorageService()
# Check in-memory cache first
preview_gcs_path = None
if job_id in _preview_videos and preview_hash in _preview_videos[job_id]:
@@ -1137,30 +1147,14 @@ async def get_preview_video(
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
if not storage.file_exists(preview_gcs_path):
raise HTTPException(status_code=404, detail=t("en", "review.previewVideoNotFound"))
try:
# Download to temp file and stream
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp:
tmp_path = tmp.name
storage.download_file(preview_gcs_path, tmp_path)
logger.info(f"Job {job_id}: Streaming preview video {preview_hash}")
return FileResponse(
tmp_path,
media_type="video/mp4",
filename=f"preview_{preview_hash}.mp4",
headers={
"Accept-Ranges": "bytes",
"Content-Disposition": "inline",
"Cache-Control": "no-cache",
},
background=BackgroundTask(os.unlink, tmp_path),
)
signed_url = storage.generate_signed_url(preview_gcs_path, expiration_minutes=120)
logger.info(f"Job {job_id}: Redirecting to signed URL for preview video {preview_hash}")
return RedirectResponse(url=signed_url, status_code=302)
except Exception as e:
logger.error(f"Job {job_id}: Error streaming preview video: {e}", exc_info=True)
logger.error(f"Job {job_id}: Error serving preview video: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=t("en", "review.previewVideoStreamError", error=str(e)))
@@ -2182,6 +2176,27 @@ async def submit_audio_edit(
message="Audio edit complete, starting processing"
)
# Reconcile credit charge against the (possibly-edited) audio before triggering workers.
# reconcile_and_maybe_pause probes job.input_media_gcs_path — which was just updated above
# to point to the edited audio (jobs/{job_id}/input/edited.flac) if edits were applied.
if await reconcile_and_maybe_pause(job_id):
# Job paused (AWAITING_DURATION_CONFIRM) or cancelled — do not start processing.
# Reload to distinguish the two outcomes so the caller can surface the right message.
reloaded = job_manager.get_job(job_id)
if reloaded and reloaded.status in (JobStatus.CANCELLED, JobStatus.FAILED):
return {
"status": "cancelled",
"message": "Audio edit saved. Job was cancelled — audio exceeds the supported limit.",
"job_id": job_id,
"edits_applied": len(edit_stack),
}
return {
"status": "paused",
"message": "Audio edit saved. Additional credits are required to continue processing.",
"job_id": job_id,
"edits_applied": len(edit_stack),
}
# Trigger parallel workers in background so the HTTP response returns immediately.
# The worker triggers involve Cloud Run Job calls that can take 30+ seconds;
# waiting synchronously causes the browser request to time out.
+11
View File
@@ -61,6 +61,17 @@ class Settings(BaseSettings):
# use uncorrected transcription - human review will fix any issues.
agentic_correction_timeout_seconds: int = int(os.getenv("AGENTIC_CORRECTION_TIMEOUT_SECONDS", "180"))
# Lyrics transcription outer (safety-net) timeout, scaled by audio duration.
# Long inputs (e.g. 30+ minute mashups) legitimately take longer to transcribe,
# so the timeout = clamp(floor, duration * per_audio_second, cap). The cap must
# stay under the Cloud Run Job task timeout so we surface a clean RuntimeError
# before the platform hard-kills the task. The lyrics-transcription-job sets the
# task timeout to 3000s and overrides this cap to 2700s via env; the 1700s
# default here is the safe value if that env is ever unset (under an 1800s task).
transcription_timeout_floor_seconds: int = int(os.getenv("TRANSCRIPTION_TIMEOUT_FLOOR_SECONDS", "1200"))
transcription_timeout_cap_seconds: int = int(os.getenv("TRANSCRIPTION_TIMEOUT_CAP_SECONDS", "1700"))
transcription_timeout_per_audio_second: float = float(os.getenv("TRANSCRIPTION_TIMEOUT_PER_AUDIO_SECOND", "1.0"))
# AI Credit Evaluation (anti-abuse gating for free credits)
# When enabled, welcome and feedback credit grants are evaluated by Gemini
# before granting. Fail-open: if evaluation fails, credits are granted anyway.
+3
View File
@@ -1,5 +1,8 @@
"""
FastAPI application entry point for karaoke generation backend.
(Trivial comment touch to trigger backend CI on ephemeral runners after
the 2026-05-17 dispatcher e2 fix; safe to remove on next backend edit.)
"""
import logging
from contextlib import asynccontextmanager
+18 -3
View File
@@ -45,6 +45,9 @@ class JobStatus(str, Enum):
IN_AUDIO_EDIT = "in_audio_edit" # User is actively editing audio
AUDIO_EDIT_COMPLETE = "audio_edit_complete" # User submitted edited audio
# Optional: duration cost confirmation (BLOCKING) - confirm credits before heavy processing
AWAITING_DURATION_CONFIRM = "awaiting_duration_confirm" # ⚠️ WAITING FOR USER - confirm duration-based cost
# Stage 2a: Audio separation (parallel track 1)
SEPARATING_STAGE1 = "separating_stage1" # Clean instrumental separation (Modal API)
SEPARATING_STAGE2 = "separating_stage2" # Backing vocals separation (Modal API)
@@ -107,16 +110,23 @@ STATE_TRANSITIONS = {
# Audio search flow (for artist+title search mode)
JobStatus.SEARCHING_AUDIO: [JobStatus.AWAITING_AUDIO_SELECTION, JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED],
JobStatus.AWAITING_AUDIO_SELECTION: [JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
JobStatus.DOWNLOADING_AUDIO: [JobStatus.DOWNLOADING, JobStatus.FAILED],
JobStatus.DOWNLOADING_AUDIO: [JobStatus.DOWNLOADING, JobStatus.AWAITING_DURATION_CONFIRM, JobStatus.FAILED],
# DOWNLOADING allows parallel processing (audio + lyrics) and then screens when both complete
# Can also enter optional audio edit phase if requires_audio_edit flag is set
JobStatus.DOWNLOADING: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_AUDIO_EDIT, JobStatus.FAILED],
JobStatus.DOWNLOADING: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_AUDIO_EDIT, JobStatus.AWAITING_DURATION_CONFIRM, JobStatus.FAILED],
# Optional audio edit phase (trim, cut, mute, join input audio before processing)
JobStatus.AWAITING_AUDIO_EDIT: [JobStatus.IN_AUDIO_EDIT, JobStatus.AUDIO_EDIT_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
JobStatus.IN_AUDIO_EDIT: [JobStatus.AWAITING_AUDIO_EDIT, JobStatus.AUDIO_EDIT_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
JobStatus.AUDIO_EDIT_COMPLETE: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
JobStatus.AUDIO_EDIT_COMPLETE: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_DURATION_CONFIRM, JobStatus.FAILED],
# Duration cost confirmation (BLOCKING) - user confirms before heavy processing begins
JobStatus.AWAITING_DURATION_CONFIRM: [
JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING,
JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_AUDIO_EDIT,
JobStatus.FAILED, JobStatus.CANCELLED,
],
# Audio separation flow
JobStatus.SEPARATING_STAGE1: [JobStatus.SEPARATING_STAGE2, JobStatus.FAILED],
@@ -596,6 +606,11 @@ class JobCreate(BaseModel):
# Private (non-published) track mode
is_private: bool = False # Private tracks: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive
# Credit pricing: how many credits to charge for this job at creation time.
# Search and upload jobs pass the default (1) and may top up later.
# URL jobs with a known duration pass ceil(duration/600) credits.
credits: int = 1
# Request metadata (set by API endpoint from request headers)
request_metadata: Dict[str, Any] = Field(default_factory=dict)
"""
+4
View File
@@ -20,6 +20,10 @@ class URLSubmissionRequest(BaseModel):
user_email: Optional[str] = None
is_private: Optional[bool] = None # Private (non-published) track mode
# Duration-based pricing: supplied by the client from YouTube metadata
duration_seconds: Optional[float] = None # Known audio duration in seconds
acknowledged_credits: Optional[int] = None # Client's expected credit cost (anti-mismatch guard)
class UploadSubmissionRequest(BaseModel):
"""Request to submit a job from an uploaded file."""
+33 -5
View File
@@ -22,6 +22,30 @@ from backend.config import get_settings
logger = logging.getLogger(__name__)
def _destroy_old_secret_versions(client, secret_path: str, keep: int = 5) -> None:
"""Destroy ENABLED secret versions beyond the newest `keep`.
OAuth credential secrets are rewritten on every refresh, which would
otherwise accumulate hundreds of versions and cost ~$0.06/version/month
in replica storage. Only the newest version is read (`versions/latest`),
so older versions are dead weight.
"""
try:
versions = list(client.list_secret_versions(request={"parent": secret_path}))
enabled = [
v for v in versions
if v.state == v.State.ENABLED # type: ignore[attr-defined]
]
enabled.sort(key=lambda v: v.create_time, reverse=True)
for v in enabled[keep:]:
try:
client.destroy_secret_version(request={"name": v.name})
except Exception as e:
logger.warning(f"Failed to destroy {v.name}: {e}")
except Exception as e:
logger.warning(f"Failed to prune old secret versions for {secret_path}: {e}")
class CredentialStatus(str, Enum):
"""Status of OAuth credentials."""
VALID = "valid"
@@ -329,7 +353,9 @@ class CredentialManager:
parent=secret_path,
payload={"data": json.dumps(updated_data).encode("utf-8")}
)
_destroy_old_secret_versions(client, secret_path, keep=5)
logger.info(f"Updated {secret_name} with refreshed token")
return True
@@ -421,19 +447,21 @@ class CredentialManager:
"""Update stored Dropbox credentials."""
try:
from google.cloud import secretmanager
client = secretmanager.SecretManagerServiceClient()
project_id = self.settings.google_cloud_project
secret_path = f"projects/{project_id}/secrets/{self.DROPBOX_SECRET}"
client.add_secret_version(
parent=secret_path,
payload={"data": json.dumps(creds).encode("utf-8")}
)
_destroy_old_secret_versions(client, secret_path, keep=5)
logger.info("Updated Dropbox credentials with refreshed token")
return True
except Exception as e:
logger.error(f"Failed to update Dropbox credentials: {e}")
return False
+153
View File
@@ -0,0 +1,153 @@
"""Reconcile a job's credit charge against the actual audio about to be processed.
Called at the convergence point immediately before the separation+transcription
workers are triggered (post-edit if an edit occurred). The probe callable returns
the duration in seconds of `job.input_media_gcs_path` (the to-be-processed audio).
"""
import asyncio
import json
import subprocess
from dataclasses import dataclass
from typing import Callable, Optional
import logging
from backend.services.pricing import duration_to_credits, is_blocked
from backend.models.job import JobStatus
logger = logging.getLogger(__name__)
@dataclass
class ReconcileResult:
action: str # "proceed" | "pause" | "cancel"
pending_additional_credits: int = 0
actual_seconds: Optional[float] = None
def reconcile_duration(
job_id: str,
job_manager,
user_service,
probe_duration: Callable[[object], Optional[float]],
email_service=None,
) -> ReconcileResult:
job = job_manager.get_job(job_id)
actual = probe_duration(job)
state = dict(job.state_data or {})
credits_charged = int(state.get("credits_charged", 1))
# Short-circuit for admin / payment-bypassed jobs: measure duration for
# observability but do NOT pause, charge, refund, or cancel regardless of
# how long the audio turns out to be.
if state.get("payment_bypassed"):
if actual is not None:
job_manager.update_job(job_id, {"state_data.duration_actual_seconds": actual})
logger.info("Job %s: payment_bypassed=True, skipping reconcile (actual=%s s)", job_id, actual)
return ReconcileResult(action="proceed", actual_seconds=actual)
if actual is None:
logger.warning("Job %s: duration probe returned None; proceeding without reconcile", job_id)
return ReconcileResult(action="proceed", actual_seconds=None)
job_manager.update_job(job_id, {"state_data.duration_actual_seconds": actual})
if is_blocked(actual):
if credits_charged > 0:
user_service.add_credits(job.user_email, amount=credits_charged,
reason="duration_over_limit_refund", job_id=job_id)
job_manager.update_job(job_id, {"credit_refunded": True}) # suppress cancel_job's built-in 1-credit refund (we already refunded the full charge)
job_manager.cancel_job(job_id, reason="Input audio exceeds the 60-minute limit")
if email_service:
email_service.send_duration_confirm_expired(
to_email=job.user_email,
artist=getattr(job, "artist", None),
title=getattr(job, "title", None),
credits_refunded=credits_charged,
reason="over_limit",
)
return ReconcileResult(action="cancel", actual_seconds=actual)
required = duration_to_credits(actual)
delta = required - credits_charged
if delta == 0:
return ReconcileResult(action="proceed", actual_seconds=actual)
if delta < 0:
user_service.add_credits(job.user_email, amount=abs(delta),
reason="duration_refund", job_id=job_id)
job_manager.update_job(job_id, {"state_data.credits_charged": required})
return ReconcileResult(action="proceed", actual_seconds=actual)
# delta > 0 : owe more credits — pause for explicit re-confirmation.
job_manager.update_job(job_id, {
"state_data.duration_confirm_reason": "reconcile",
"state_data.pending_additional_credits": delta,
})
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_DURATION_CONFIRM,
progress=16,
message=f"This turned out longer than estimated — {delta} more credit(s) needed",
)
return ReconcileResult(action="pause", pending_additional_credits=delta, actual_seconds=actual)
# --- Pipeline wiring (impure: uses singletons + ffprobe) ---
def _ffprobe_seconds(job, storage) -> Optional[float]:
"""Header-only ffprobe of job.input_media_gcs_path via a signed URL.
Mirrors the async _get_audio_duration_ffprobe_signed helper in
backend/api/routes/jobs.py, but as a sync function suitable for use
in run_in_executor.
"""
gcs_path = getattr(job, "input_media_gcs_path", None)
if not gcs_path:
return None
try:
signed_url = storage.generate_signed_url(gcs_path, expiration_minutes=5)
result = subprocess.run(
["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", signed_url],
capture_output=True, text=True, timeout=30,
)
if result.returncode != 0:
return None
return float(json.loads(result.stdout)["format"]["duration"])
except Exception as e:
logger.warning("Job %s: ffprobe duration failed: %s", getattr(job, "id", "?"), e)
return None
async def reconcile_and_maybe_pause(job_id: str) -> bool:
"""Resolve real singletons, probe duration, run reconcile_duration, return True if blocked.
Returns True when the job has been paused (AWAITING_DURATION_CONFIRM) or cancelled,
meaning the caller must NOT trigger downstream workers.
Returns False when the job should proceed normally.
Designed for the no-edit convergence point in audio_download_worker.py.
"""
# Import at function scope to avoid circular imports.
from backend.services.job_manager import JobManager
from backend.services.user_service import get_user_service
from backend.services.storage_service import StorageService
from backend.services.email_service import get_email_service
job_manager = JobManager()
user_service = get_user_service()
storage = StorageService()
# JobManager/StorageService have no singleton accessor; instantiate directly (matches audio_download_worker).
email_service = get_email_service()
result = await asyncio.get_running_loop().run_in_executor(
None,
lambda: reconcile_duration(
job_id,
job_manager,
user_service,
lambda job: _ffprobe_seconds(job, storage),
email_service,
),
)
return result.action in ("pause", "cancel")
+291 -117
View File
@@ -2,12 +2,10 @@
Email service for sending transactional emails.
Supports multiple providers:
- Postmark (production default — better Yahoo/AOL deliverability)
- SendGrid (legacy fallback, retained during cutover)
- Postmark (production)
- Console logging (for development/testing)
Provider selection: EMAIL_PROVIDER env var (postmark|sendgrid). Defaults to
postmark when both keys are present.
Provider selection: POSTMARK_SERVER_TOKEN env var enables Postmark.
"""
import html
import logging
@@ -121,91 +119,6 @@ class PreviewEmailProvider(EmailProvider):
return self.last_html
class SendGridEmailProvider(EmailProvider):
"""
SendGrid email provider for production.
Requires SENDGRID_API_KEY environment variable.
"""
def __init__(self, api_key: str, from_email: str, from_name: str = "Nomad Karaoke"):
self.api_key = api_key
self.from_email = from_email
self.from_name = from_name
def send_email(
self,
to_email: str,
subject: str,
html_content: str,
text_content: Optional[str] = None,
cc_emails: Optional[List[str]] = None,
bcc_emails: Optional[List[str]] = None,
from_email_override: Optional[str] = None,
) -> bool:
try:
# Import here to avoid requiring sendgrid in all environments
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Email, To, Content, Cc, Bcc
sg = SendGridAPIClient(api_key=self.api_key)
# Use override sender if provided (for multi-tenant)
sender_email = from_email_override or self.from_email
message = Mail(
from_email=Email(sender_email, self.from_name),
to_emails=To(to_email),
subject=subject,
html_content=Content("text/html", html_content)
)
# Add CC recipients if provided (deduplicated and normalized)
if cc_emails:
# Normalize emails (lowercase, strip whitespace) and deduplicate
seen = set()
unique_cc_emails = []
for cc_email in cc_emails:
normalized = cc_email.strip().lower()
if normalized and normalized not in seen:
seen.add(normalized)
unique_cc_emails.append(cc_email.strip())
for cc_email in unique_cc_emails:
message.add_cc(Cc(cc_email))
# Add BCC recipients if provided (deduplicated and normalized)
if bcc_emails:
seen = set()
unique_bcc_emails = []
for bcc_email in bcc_emails:
normalized = bcc_email.strip().lower()
if normalized and normalized not in seen:
seen.add(normalized)
unique_bcc_emails.append(bcc_email.strip())
for bcc_email in unique_bcc_emails:
message.add_bcc(Bcc(bcc_email))
if text_content:
message.add_content(Content("text/plain", text_content))
response = sg.send(message)
if response.status_code >= 200 and response.status_code < 300:
cc_info = f" (CC: {', '.join(cc_emails)})" if cc_emails else ""
bcc_info = f" (BCC: {', '.join(bcc_emails)})" if bcc_emails else ""
logger.info(f"Email sent to {to_email}{cc_info}{bcc_info} via SendGrid")
return True
else:
logger.error(f"SendGrid returned status {response.status_code}")
return False
except Exception:
logger.exception("Failed to send email via SendGrid")
return False
class PostmarkEmailProvider(EmailProvider):
"""
Postmark email provider for production.
@@ -315,48 +228,25 @@ class EmailService:
self.buy_url = os.getenv("BUY_URL", self.frontend_url)
def _get_provider(self) -> EmailProvider:
"""
Get the configured email provider.
"""Get the configured email provider.
Selection rules:
- EMAIL_PROVIDER=postmark → Postmark (requires POSTMARK_SERVER_TOKEN)
- EMAIL_PROVIDER=sendgrid → SendGrid (requires SENDGRID_API_KEY)
- Unset/auto → Postmark if its token is set, else SendGrid if its key is set, else console
Postmark is used when POSTMARK_SERVER_TOKEN is set; otherwise falls
back to console logging (dev/test).
"""
provider_name = (os.getenv("EMAIL_PROVIDER") or "").strip().lower()
postmark_token = os.getenv("POSTMARK_SERVER_TOKEN")
sendgrid_api_key = os.getenv("SENDGRID_API_KEY")
from_email = os.getenv("EMAIL_FROM", "gen@nomadkaraoke.com")
from_name = os.getenv("EMAIL_FROM_NAME", "Nomad Karaoke")
if provider_name == "postmark":
if not postmark_token:
logger.error("EMAIL_PROVIDER=postmark but POSTMARK_SERVER_TOKEN is not set; falling back to console")
return ConsoleEmailProvider()
if postmark_token:
logger.info("Using Postmark email provider")
return PostmarkEmailProvider(postmark_token, from_email, from_name)
if provider_name == "sendgrid":
if not sendgrid_api_key:
logger.error("EMAIL_PROVIDER=sendgrid but SENDGRID_API_KEY is not set; falling back to console")
return ConsoleEmailProvider()
logger.info("Using SendGrid email provider")
return SendGridEmailProvider(sendgrid_api_key, from_email, from_name)
# Auto-detect: prefer Postmark when both keys are present
if postmark_token:
logger.info("Using Postmark email provider (auto-detected)")
return PostmarkEmailProvider(postmark_token, from_email, from_name)
if sendgrid_api_key:
logger.info("Using SendGrid email provider (auto-detected)")
return SendGridEmailProvider(sendgrid_api_key, from_email, from_name)
logger.warning("No email provider configured, using console logging")
return ConsoleEmailProvider()
def is_configured(self) -> bool:
"""Check if a real email provider is configured (not just console logging)."""
return isinstance(self.provider, (SendGridEmailProvider, PostmarkEmailProvider))
return isinstance(self.provider, PostmarkEmailProvider)
def send_magic_link(
self,
@@ -1230,6 +1120,148 @@ class EmailService:
text_content=text_content,
)
def send_duration_confirm_reminder(
self,
to_email: str,
job_id: Optional[str] = None,
artist: Optional[str] = None,
title: Optional[str] = None,
pending_credits: Optional[int] = None,
duration_seconds: Optional[int] = None,
confirm_url: Optional[str] = None,
locale: str = "en",
) -> bool:
"""
Send a 15-minute idle reminder email for jobs awaiting duration confirmation.
Sent when a job has been in AWAITING_DURATION_CONFIRM for 15 minutes without
the user confirming the extra cost.
Args:
to_email: User's email address
job_id: Job ID (used to build the confirm URL if not provided)
artist: Artist name for subject line
title: Song title for subject line
pending_credits: Number of additional credits required
duration_seconds: Actual duration of the song in seconds
confirm_url: Direct URL to the confirmation page
locale: User's locale (future: translated; currently English)
Returns:
True if email was sent successfully
"""
if artist and title:
subject = f"Your karaoke job needs you to confirm the cost — {artist} - {title}"
else:
subject = "Your karaoke job needs you to confirm the cost"
extra_styles = """
.alert {
background-color: #fef3c7;
border: 1px solid #fcd34d;
border-radius: 8px;
padding: 16px;
margin: 20px 0;
text-align: center;
}
.confirm-btn {
display: inline-block;
background-color: #ff7acc;
color: #ffffff !important;
text-decoration: none;
padding: 12px 24px;
border-radius: 8px;
font-weight: bold;
margin: 16px 0;
}
.cost-box {
background-color: #f0f9ff;
border: 1px solid #93c5fd;
border-radius: 8px;
padding: 16px;
margin: 20px 0;
text-align: center;
}
"""
song_name = (
f" for <strong>{html.escape(artist)} — {html.escape(title)}</strong>"
if artist and title
else ""
)
song_name_text = f" for {artist} — {title}" if artist and title else ""
# Build cost detail line (best-effort — fields may be absent for older jobs)
if pending_credits is not None and duration_seconds is not None:
duration_mins = duration_seconds // 60
duration_secs = duration_seconds % 60
duration_str = f"{duration_mins}:{duration_secs:02d}"
cost_detail_html = (
f"<p>The song{song_name} turned out to be "
f"<strong>{duration_str}</strong> long and requires "
f"<strong>{pending_credits} additional credit"
f"{'s' if pending_credits != 1 else ''}</strong> to process.</p>"
)
cost_detail_text = (
f"The song{song_name_text} turned out to be {duration_str} long and "
f"requires {pending_credits} additional credit"
f"{'s' if pending_credits != 1 else ''} to process.\n"
)
elif pending_credits is not None:
cost_detail_html = (
f"<p>Processing{song_name} requires "
f"<strong>{pending_credits} additional credit"
f"{'s' if pending_credits != 1 else ''}</strong>.</p>"
)
cost_detail_text = (
f"Processing{song_name_text} requires {pending_credits} additional credit"
f"{'s' if pending_credits != 1 else ''}.\n"
)
else:
cost_detail_html = f"<p>Your karaoke job{song_name} requires a few extra credits to continue.</p>"
cost_detail_text = f"Your karaoke job{song_name_text} requires a few extra credits to continue.\n"
# TODO(i18n): translate subject/body once duration-confirm keys are added to
# backend/translations/{locale}.json. URL already uses the locale prefix.
locale_prefix = get_locale_prefix(locale)
url_to_use = confirm_url or (
f"{self.frontend_url}{locale_prefix}/app/jobs#/{job_id}/review"
if job_id
else f"{self.frontend_url}{locale_prefix}/app"
)
content = f"""
<div class="alert">
⏰ Your job is waiting for your confirmation
</div>
{cost_detail_html}
<p>Please visit your job to review the cost and confirm whether to continue processing.</p>
<p style="text-align: center;">
<a href="{html.escape(url_to_use)}" class="confirm-btn">Confirm cost &amp; continue</a>
</p>
<p>If you have any questions, just reply to this email — we're happy to help.</p>
"""
html_content = self._build_email_html(content, extra_styles, locale=locale)
text_content = (
f"Your karaoke job is waiting for your confirmation.\n\n"
f"{cost_detail_text}\n"
f"Please visit your job to confirm: {url_to_use}\n\n"
f"If you have any questions, just reply to this email — we're happy to help."
)
return self.provider.send_email(
to_email=to_email,
subject=subject,
html_content=html_content,
text_content=text_content,
)
def send_review_expired(
self,
to_email: str,
@@ -1323,6 +1355,148 @@ class EmailService:
text_content=text_content,
)
def send_duration_confirm_expired(
self,
to_email: str,
artist: Optional[str] = None,
title: Optional[str] = None,
credits_refunded: int = 0,
locale: str = "en",
reason: str = "timeout",
) -> bool:
"""
Send duration-confirm cancellation notification email.
Two cancellation reasons are supported via the ``reason`` parameter:
- ``"timeout"`` (default): job was auto-cancelled after 48 hours in
AWAITING_DURATION_CONFIRM because the user never confirmed the extra cost.
- ``"over_limit"`` : job was immediately cancelled because the audio
duration exceeds the supported 60-minute ceiling.
Args:
to_email: User's email address
artist: Artist name for subject line
title: Song title for subject line
credits_refunded: Number of credits that were refunded
locale: User locale (reserved for future i18n; currently English)
reason: "timeout" or "over_limit" — controls the cancellation message
Returns:
True if email was sent successfully
"""
if reason == "over_limit":
if artist and title:
subject = f"Your karaoke job was cancelled — audio exceeds 60 minutes ({artist} - {title})"
else:
subject = "Your karaoke job was cancelled — audio exceeds 60 minutes"
else:
if artist and title:
subject = f"Your karaoke job was cancelled — cost not confirmed in time ({artist} - {title})"
else:
subject = "Your karaoke job was cancelled — cost not confirmed in time"
extra_styles = """
.info-box {
background-color: #f0f9ff;
border: 1px solid #93c5fd;
border-radius: 8px;
padding: 16px;
margin: 20px 0;
text-align: center;
}
.credit-badge {
display: inline-block;
background-color: #22c55e;
color: #ffffff;
padding: 4px 12px;
border-radius: 12px;
font-weight: bold;
}
.create-btn {
display: inline-block;
background-color: #ff7acc;
color: #ffffff !important;
text-decoration: none;
padding: 12px 24px;
border-radius: 8px;
font-weight: bold;
margin: 16px 0;
}
"""
song_name = f" for <strong>{html.escape(artist)} - {html.escape(title)}</strong>" if artist and title else ""
song_name_text = f" for {artist} - {title}" if artist and title else ""
credits_word = "credit" if credits_refunded == 1 else "credits"
refund_notice_html = (
f"<p>We've refunded <span class=\"credit-badge\">{credits_refunded} {credits_word}</span> "
f"to your account.</p>"
if credits_refunded > 0
else "<p>Your account has been updated.</p>"
)
refund_notice_text = (
f"We've refunded {credits_refunded} {credits_word} to your account."
if credits_refunded > 0
else "Your account has been updated."
)
if reason == "over_limit":
cancel_reason_html = (
f"Your karaoke job{song_name} was automatically cancelled because the audio "
f"exceeds the supported 60-minute limit."
)
cancel_reason_text = (
f"Your karaoke job{song_name_text} was automatically cancelled because the "
f"audio exceeds the supported 60-minute limit."
)
else:
cancel_reason_html = (
f"Your karaoke job{song_name} was automatically cancelled because the extra cost "
f"was not confirmed within 48 hours."
)
cancel_reason_text = (
f"Your karaoke job{song_name_text} was automatically cancelled because the extra "
f"cost was not confirmed within 48 hours."
)
# TODO(i18n): translate subject/body once duration-confirm keys are added to
# backend/translations/{locale}.json. URL already uses the locale prefix.
locale_prefix = get_locale_prefix(locale)
app_url = f"{self.frontend_url}{locale_prefix}/app"
content = f"""
<div class="info-box">
{cancel_reason_html}
</div>
{refund_notice_html}
<p>You can start a new job at any time — your credits are ready to use.</p>
<p style="text-align: center;">
<a href="{html.escape(app_url)}" class="create-btn">Create a new job</a>
</p>
<p>If you have any questions, just reply to this email — we're happy to help.</p>
"""
html_content = self._build_email_html(content, extra_styles, locale=locale)
text_content = (
f"{cancel_reason_text}\n\n"
f"{refund_notice_text}\n\n"
f"You can start a new job at any time: {app_url}\n\n"
f"If you have any questions, just reply to this email — we're happy to help."
)
return self.provider.send_email(
to_email=to_email,
subject=subject,
html_content=html_content,
text_content=text_content,
)
def send_youtube_upload_complete(
self,
to_email: str,
+5
View File
@@ -189,6 +189,11 @@ class FirestoreService:
'state_data.audio_complete', 'state_data.lyrics_complete',
'state_data.backing_vocals_analysis', 'state_data.visibility_change_in_progress',
'state_data.render_pending_capacity',
'state_data.cloud_run_retry_pending',
'state_data.credits_charged',
'state_data.pending_additional_credits',
'state_data.duration_actual_seconds',
'state_data.duration_confirm_reason',
'file_urls.finals', 'file_urls.videos', 'file_urls.packages',
'processing_metadata',
]
+2 -1
View File
@@ -680,7 +680,8 @@ class FlacfetchClient:
Returns:
Dict with keys: available, video_id, title, error,
is_geo_restricted, is_age_restricted, is_private, is_removed
is_geo_restricted, is_age_restricted, is_private, is_removed,
is_bot_blocked
Raises:
FlacfetchServiceError: On request failure
+81 -20
View File
@@ -17,6 +17,7 @@ from backend.config import settings
from backend.exceptions import InvalidStateTransitionError, InsufficientCreditsError
from backend.models.job import Job, JobStatus, JobCreate, STATE_TRANSITIONS
from backend.models.worker_log import WorkerLogEntry
from backend.services.duration_reconciliation import reconcile_and_maybe_pause
from backend.services.firestore_service import FirestoreService
from backend.services.storage_service import StorageService
@@ -57,15 +58,16 @@ class JobManager:
ValueError: If theme_id is not provided (all jobs require a theme)
"""
# Check credits (skip for admins)
credits_to_charge = job_create.credits
if job_create.user_email and not is_admin:
from backend.services.user_service import get_user_service
user_service = get_user_service()
if not user_service.has_credits(job_create.user_email):
credits_available = user_service.check_credits(job_create.user_email)
credits_available = user_service.check_credits(job_create.user_email)
if credits_available < credits_to_charge:
raise InsufficientCreditsError(
message="You're out of credits. Buy more to continue creating karaoke videos.",
credits_available=credits_available,
credits_required=1,
credits_required=credits_to_charge,
)
# Enforce theme requirement - all jobs must have a theme
@@ -126,17 +128,27 @@ class JobManager:
"is_admin": is_admin,
"created_from": job_create.request_metadata.get("created_from", "unknown"),
},
# Record how many credits were charged for this job (authoritative running total).
# When charging is bypassed (admin / no user_email), set credits_charged=0 and
# payment_bypassed=True so duration reconciliation short-circuits without pausing,
# charging, or refunding.
state_data=(
{"credits_charged": 0, "payment_bypassed": True}
if (is_admin or not job_create.user_email)
else {"credits_charged": credits_to_charge}
),
)
self.firestore.create_job(job)
logger.info(f"Created new job {job_id} with status PENDING")
# Deduct credit atomically (after job is persisted so we have job_id for transaction record)
# Deduct credits atomically (after job is persisted so we have job_id for transaction record)
if job_create.user_email and not is_admin:
from backend.services.user_service import get_user_service
user_service = get_user_service()
success, _remaining, deduct_msg = user_service.deduct_credit(
job_create.user_email, job_id, reason="job_creation"
success, _remaining, deduct_msg = user_service.deduct_credits(
job_create.user_email, job_id, amount=credits_to_charge, reason="job_creation",
count_as_job_creation=True,
)
if not success:
# Deduction failed (e.g., race condition) - delete the job and raise error
@@ -148,7 +160,7 @@ class JobManager:
raise InsufficientCreditsError(
message="Failed to deduct credit. Please try again.",
credits_available=0,
credits_required=1,
credits_required=credits_to_charge,
)
return job
@@ -338,7 +350,9 @@ class JobManager:
if delete_files and job and job.output_files:
for gcs_path in job.output_files.values():
try:
self.storage.delete_file(gcs_path)
# ignore_missing: a job being deleted whose recorded file is
# already gone is not an error, just skip it quietly.
self.storage.delete_file(gcs_path, ignore_missing=True)
except Exception as e:
logger.error(f"Error deleting file {gcs_path}: {e}")
@@ -395,9 +409,16 @@ class JobManager:
valid_transitions = STATE_TRANSITIONS.get(current_status, [])
if new_status not in valid_transitions:
# Normalise both sides to their string values so the message reads
# 'downloading -> downloading' rather than the misleading
# 'downloading -> JobStatus.DOWNLOADING'. The asymmetry exists
# because Job.status is deserialised with use_enum_values=True
# (plain str) while new_status is typically an enum at call time.
from_value = current_status.value if hasattr(current_status, 'value') else str(current_status)
to_value = new_status.value if hasattr(new_status, 'value') else str(new_status)
error_msg = (
f"Invalid state transition for job {job_id}: "
f"{current_status} -> {new_status}. "
f"{from_value} -> {to_value}. "
f"Valid transitions: {[s.value for s in valid_transitions]}"
)
logger.error(error_msg)
@@ -406,8 +427,8 @@ class JobManager:
raise InvalidStateTransitionError(
message=error_msg,
job_id=job_id,
from_status=current_status,
to_status=new_status.value if hasattr(new_status, 'value') else str(new_status),
from_status=from_value,
to_status=to_value,
valid_transitions=[s.value for s in valid_transitions]
)
return False
@@ -539,13 +560,15 @@ class JobManager:
self._send_push_notification(job, "complete")
# Idle reminder scheduling for blocking states
elif new_status in [JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION, JobStatus.AWAITING_AUDIO_EDIT]:
elif new_status in [JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION, JobStatus.AWAITING_AUDIO_EDIT, JobStatus.AWAITING_DURATION_CONFIRM]:
self._schedule_idle_reminder(job, new_status)
# Send push notification for blocking states
if new_status == JobStatus.AWAITING_AUDIO_EDIT:
action_type = "audio_edit"
elif new_status == JobStatus.AWAITING_REVIEW:
action_type = "lyrics"
elif new_status == JobStatus.AWAITING_DURATION_CONFIRM:
action_type = "duration_confirm"
else:
action_type = "instrumental"
self._send_push_notification(job, action_type)
@@ -625,7 +648,9 @@ class JobManager:
Schedule an idle reminder for a blocking state.
Records the timestamp when the blocking state was entered and
schedules a Cloud Tasks task for 5 minutes later.
schedules a Cloud Tasks task after a state-specific delay:
- AWAITING_DURATION_CONFIRM: 15 minutes (900s) — user needs to confirm extra cost
- All other blocking states: default delay (IDLE_REMINDER_DELAY_SECONDS)
"""
import asyncio
import threading
@@ -638,6 +663,8 @@ class JobManager:
action_type = "audio_edit"
elif new_status == JobStatus.AWAITING_REVIEW:
action_type = "lyrics"
elif new_status == JobStatus.AWAITING_DURATION_CONFIRM:
action_type = "duration_confirm"
else:
action_type = "instrumental"
@@ -653,12 +680,19 @@ class JobManager:
'state_data': {**existing_state_data, **state_data_update}
})
# Schedule the idle reminder check via worker service (5 min delay)
# Schedule the idle reminder check via worker service.
# Duration-confirm uses 15-min delay; other states use the default.
from backend.services.worker_service import get_worker_service
# Capture action_type for the closure
_action_type = action_type
async def schedule_reminder():
worker_service = get_worker_service()
await worker_service.schedule_idle_reminder(job.job_id)
if _action_type == "duration_confirm":
await worker_service.schedule_idle_reminder(job.job_id, delay_seconds=900)
else:
await worker_service.schedule_idle_reminder(job.job_id)
# Try to get existing event loop, create new one if none exists
try:
@@ -829,9 +863,12 @@ class JobManager:
def _refund_credit_for_job(self, job_id: str, job: Job, reason: str) -> bool:
"""
Refund one credit for a job if eligible.
Refund all credits charged for a job if eligible.
Skips refund if: already refunded, no user email, or admin-owned job.
Reads ``state_data.credits_charged`` (defaulting to 1 for legacy jobs
that pre-date the field) and refunds that many credits in a single
``add_credits`` call. Skips refund if: already refunded, no user
email, admin-owned job, or credits_charged == 0 (payment_bypassed).
Never raises — refund failure must not block the calling operation.
Returns:
@@ -851,14 +888,30 @@ class JobManager:
if is_admin_email(job.user_email):
return False
# Determine how many credits to refund. ``credits_charged`` is set
# at job creation (and updated on duration-confirm). Legacy jobs
# that pre-date the field are guaranteed to be 1-credit jobs, so we
# default to 1. payment_bypassed admin/no-email jobs have
# credits_charged=0 and must not be refunded.
state_data = job.state_data or {}
credits_charged = int(state_data.get("credits_charged", 1))
if credits_charged == 0:
# Admin / payment-bypassed job — nothing to refund.
logger.info(f"Job {job_id}: credits_charged=0 (payment_bypassed), skipping refund")
return False
user_service = get_user_service()
refund_ok, new_balance, refund_msg = user_service.refund_credit(
job.user_email, job_id, reason=reason
refund_ok, new_balance, refund_msg = user_service.add_credits(
job.user_email, amount=credits_charged, reason=reason, job_id=job_id
)
if refund_ok:
# Mark job as refunded to prevent double-refund
self.update_job(job_id, {'credit_refunded': True})
logger.info(f"Refunded credit for {reason} job {job_id} to {_mask_email(job.user_email)} (balance: {new_balance})")
logger.info(
f"Refunded {credits_charged} credit(s) for {reason} job {job_id} "
f"to {_mask_email(job.user_email)} (balance: {new_balance})"
)
return True
else:
logger.warning(f"Credit refund failed for job {job_id}: {refund_msg}")
@@ -1001,6 +1054,14 @@ class JobManager:
message=message
)
# Reconcile credit charge against actual audio duration before triggering workers.
# Probes input_media_gcs_path (already set by the upload handler) via ffprobe.
# Returns True when the job is paused (AWAITING_DURATION_CONFIRM) or cancelled,
# in which case we must NOT start downstream workers.
if await reconcile_and_maybe_pause(job_id):
logger.info(f"Job {job_id}: Paused for duration confirmation (or cancelled); workers not started")
return
# Check if audio separation can be skipped
# Jobs with an existing instrumental (e.g. tenant uploads) don't need
# GPU-powered audio separation — saves 5-10 minutes of processing time
@@ -317,6 +317,69 @@ class JobNotificationService:
logger.exception(f"Error sending {action_type} reminder for job {job_id}: {e}")
return False
async def send_duration_confirm_reminder(self, job) -> bool:
"""
Send a 15-minute idle reminder email for jobs awaiting duration confirmation.
Called when a job has been in AWAITING_DURATION_CONFIRM for 15 minutes and
the user has not yet confirmed the extra cost.
Args:
job: Job object with at minimum job_id, user_email, artist, title,
and state_data (may contain pending_additional_credits,
duration_actual_seconds).
Returns:
True if email was sent successfully.
"""
if not ENABLE_AUTO_EMAILS:
logger.info(f"Auto emails disabled, skipping duration-confirm reminder for job {job.job_id}")
return False
user_email = getattr(job, "user_email", None)
if not user_email:
logger.warning(f"No user email for job {job.job_id}, skipping duration-confirm reminder")
return False
try:
user_locale = self._get_user_locale(user_email)
job_id = job.job_id
artist = getattr(job, "artist", None)
title = getattr(job, "title", None)
state_data = getattr(job, "state_data", None) or {}
# Extract extra-cost details from state_data (best-effort)
pending_credits = state_data.get("pending_additional_credits")
duration_seconds = state_data.get("duration_actual_seconds")
confirm_url = (
f"{self.frontend_url}{get_locale_prefix(user_locale)}/app"
)
success = self.email_service.send_duration_confirm_reminder(
to_email=user_email,
job_id=job_id,
artist=artist,
title=title,
pending_credits=pending_credits,
duration_seconds=duration_seconds,
confirm_url=confirm_url,
locale=user_locale,
)
if success:
logger.info(
f"Sent duration_confirm reminder for job {job_id} to {_mask_email(user_email)}"
)
else:
logger.error(f"Failed to send duration_confirm reminder for job {job_id}")
return success
except Exception as e:
logger.exception(f"Error sending duration_confirm reminder for job {job.job_id}: {e}")
return False
def get_completion_message(
self,
job_id: str,
+22
View File
@@ -0,0 +1,22 @@
"""Duration-based credit pricing. Single source of truth for credit cost.
credits = max(1, ceil(duration_seconds / 600)) # 10-minute tiers
blocked = duration_seconds > 3600 # 60-minute hard ceiling
"""
from typing import Optional
import math
SECONDS_PER_CREDIT_TIER = 600 # 10 minutes per credit tier
DURATION_CREDIT_BLOCK_SECONDS = 3600 # inputs longer than 60 min are not supported
def duration_to_credits(seconds: Optional[float]) -> int:
"""Credits required to process `seconds` of audio. Minimum 1."""
if seconds is None or not math.isfinite(seconds) or seconds < 0:
return 1
return max(1, math.ceil(seconds / SECONDS_PER_CREDIT_TIER))
def is_blocked(seconds: Optional[float]) -> bool:
"""True if the input exceeds the supported duration ceiling."""
return seconds is not None and seconds > DURATION_CREDIT_BLOCK_SECONDS
@@ -247,6 +247,11 @@ class PushNotificationService:
notif_body = t(locale, "pushNotifications.reviewLyricsBody", title=title, artist=artist)
url = f"/app/jobs#/{job_id}/review"
tag = f"lyrics-{job_id}"
elif action_type == "duration_confirm":
notif_title = t(locale, "pushNotifications.confirmDurationTitle")
notif_body = t(locale, "pushNotifications.confirmDurationBody", title=title, artist=artist)
url = "/app"
tag = f"duration-confirm-{job_id}"
else: # instrumental
notif_title = t(locale, "pushNotifications.selectInstrumentalTitle")
notif_body = t(locale, "pushNotifications.selectInstrumentalBody", title=title, artist=artist)
+22 -2
View File
@@ -7,6 +7,7 @@ import json
from typing import Optional, BinaryIO, Any, Dict
from pathlib import Path
from google.cloud import storage
from google.cloud.exceptions import NotFound
from datetime import timedelta
from backend.config import settings
@@ -123,12 +124,31 @@ class StorageService:
logger.error(f"Error generating signed {method} URL for {blob_path}: {e}")
raise
def delete_file(self, blob_path: str) -> None:
"""Delete a file from GCS."""
def delete_file(self, blob_path: str, ignore_missing: bool = False) -> bool:
"""Delete a file from GCS.
Args:
blob_path: Path of the object to delete.
ignore_missing: If True, a missing object (404 NotFound) is treated as a
successful no-op and logged at debug level instead of error. Use for
best-effort deletes over a template of possible paths (e.g. job
restart/regen) where many files legitimately never existed.
Returns:
True if an object was actually deleted, False if it was already absent
(only possible when ignore_missing=True; otherwise a missing object raises).
"""
try:
blob = self.bucket.blob(blob_path)
blob.delete()
logger.info(f"Deleted gs://{settings.gcs_bucket_name}/{blob_path}")
return True
except NotFound:
if ignore_missing:
logger.debug(f"File already absent, skipping delete: {blob_path}")
return False
logger.error(f"Error deleting file {blob_path}: 404 object not found")
raise
except Exception as e:
logger.error(f"Error deleting file {blob_path}: {e}")
raise
+61 -18
View File
@@ -900,12 +900,21 @@ class UserService:
return False, None, "An error occurred during validation"
def revoke_session(self, token: str) -> bool:
"""Revoke a session (logout)."""
"""Revoke a session (logout).
Idempotent: a session document that no longer exists is already
revoked, so a missing document is treated as success rather than an
error. Firestore's ``update()`` raises NotFound when the document is
absent (e.g. already logged out, or expired/cleaned up).
"""
try:
doc_ref = self.db.collection(SESSIONS_COLLECTION).document(token)
doc_ref.update({'is_active': False})
logger.info("Session revoked")
return True
except google_exceptions.NotFound:
logger.info("Session already absent; treating revoke as success")
return True
except Exception:
logger.exception("Error revoking session")
return False
@@ -1039,27 +1048,42 @@ class UserService:
logger.exception(f"Error adding credits to {email}")
return False, 0, f"Failed to add credits: {e}"
def deduct_credit(
def deduct_credits(
self,
email: str,
job_id: str,
reason: str = "job_creation"
amount: int = 1,
reason: str = "job_creation",
count_as_job_creation: bool = True,
) -> Tuple[bool, int, str]:
"""
Deduct one credit from a user account.
Atomically deduct N credits from a user account (all-or-nothing).
Uses Firestore transaction to prevent race conditions.
Args:
email: User email address.
job_id: Job ID associated with the deduction.
amount: Number of credits to deduct (default: 1, must be > 0).
reason: Reason for the deduction (default: "job_creation").
count_as_job_creation: When True (default), increments
``total_jobs_created`` by 1. Pass False when deducting
*additional* credits for an already-existing job (e.g. the
reconcile/top-up path) so the counter is not double-counted.
Returns:
(success, remaining_credits, message)
"""
if amount <= 0:
return False, 0, "Deduction amount must be positive"
try:
email = email.lower()
doc_ref = self.db.collection(USERS_COLLECTION).document(email)
@firestore.transactional
def deduct_in_transaction(transaction):
"""Atomically check and deduct credit."""
"""Atomically check and deduct credits."""
doc = doc_ref.get(transaction=transaction)
if not doc.exists:
@@ -1068,13 +1092,13 @@ class UserService:
user_data = doc.to_dict()
current_credits = user_data.get('credits', 0)
if current_credits <= 0:
return False, 0, "Insufficient credits"
if current_credits < amount:
return False, current_credits, "Insufficient credits"
# Create transaction record
credit_txn = CreditTransaction(
id=str(uuid.uuid4()),
amount=-1,
amount=-amount,
reason=reason,
job_id=job_id,
)
@@ -1086,32 +1110,51 @@ class UserService:
transactions.append(credit_txn.model_dump(mode='json'))
# Calculate new values
new_balance = current_credits - 1
total_jobs = user_data.get('total_jobs_created', 0) + 1
new_balance = current_credits - amount
# Update atomically within transaction
transaction.update(doc_ref, {
update_payload = {
'credits': new_balance,
'credit_transactions': transactions,
'total_jobs_created': total_jobs,
'updated_at': datetime.utcnow()
})
'updated_at': datetime.utcnow(),
}
if count_as_job_creation:
update_payload['total_jobs_created'] = user_data.get('total_jobs_created', 0) + 1
return True, new_balance, f"Credit deducted. {new_balance} remaining"
# Update atomically within transaction
transaction.update(doc_ref, update_payload)
return True, new_balance, f"Deducted {amount} credit(s). {new_balance} remaining"
# Execute the transaction
fs_transaction = self.db.transaction()
success, new_balance, message = deduct_in_transaction(fs_transaction)
if success:
logger.info(f"Deducted 1 credit from {email} for job {job_id}. Remaining: {new_balance}")
logger.info(f"Deducted {amount} credit(s) from {email} for job {job_id}. Remaining: {new_balance}")
return success, new_balance, message
except Exception as e:
logger.exception(f"Error deducting credit from {email}")
logger.exception(f"Error deducting credit(s) from {email}")
return False, 0, f"Failed to deduct credit: {e}"
def deduct_credit(
self,
email: str,
job_id: str,
reason: str = "job_creation"
) -> Tuple[bool, int, str]:
"""
Deduct one credit from a user account.
Thin wrapper around deduct_credits(amount=1). Preserved for backwards
compatibility with all existing callers.
Returns:
(success, remaining_credits, message)
"""
return self.deduct_credits(email, job_id, amount=1, reason=reason)
def refund_credit(
self,
email: str,
+64 -92
View File
@@ -13,16 +13,11 @@ The flow is:
All entry points (audio search selection, direct URL submission) should use this
service for YouTube downloads to ensure consistent behavior.
"""
import asyncio
import logging
import mimetypes
import os
import re
import tempfile
from typing import Optional
from .flacfetch_client import get_flacfetch_client, FlacfetchServiceError
from .storage_service import StorageService
logger = logging.getLogger(__name__)
@@ -54,14 +49,13 @@ class YouTubeDownloadService:
def __init__(self):
self._flacfetch_client = get_flacfetch_client()
self._storage_service = StorageService()
if self._flacfetch_client:
logger.info("YouTubeDownloadService using REMOTE flacfetch (recommended)")
logger.info("YouTubeDownloadService using REMOTE flacfetch")
else:
logger.warning(
"YouTubeDownloadService using LOCAL yt_dlp - "
"downloads may fail due to YouTube bot detection on Cloud Run IPs"
"YouTubeDownloadService: remote flacfetch NOT configured "
"(FLACFETCH_API_URL) - URL downloads will fail until it is set"
)
def is_remote_enabled(self) -> bool:
@@ -121,20 +115,24 @@ class YouTubeDownloadService:
Raises:
YouTubeDownloadError: If download fails
"""
video_id = self._extract_video_id(url)
if not video_id:
raise YouTubeDownloadError(f"Could not extract video ID from URL: {url}")
logger.info(f"YouTube download: video_id={video_id}, job_id={job_id}")
if self._flacfetch_client:
return await self._download_remote(video_id, job_id, artist, title)
else:
logger.warning(
"Remote flacfetch not configured. Attempting local download, "
"but this may fail due to YouTube bot detection on Cloud Run IPs."
# flacfetch is the SOLE downloader — never run yt-dlp on Cloud Run.
# If it isn't configured, fail loudly rather than silently falling back
# to a local download (which is blocked by bot detection on Cloud Run
# IPs anyway).
if not self._flacfetch_client:
raise YouTubeDownloadError(
"Remote flacfetch is not configured (FLACFETCH_API_URL). "
"URL downloads require the flacfetch service."
)
return await self._download_local(url, job_id, artist, title)
video_id = self._extract_video_id(url)
if video_id:
logger.info(f"URL download (YouTube): video_id={video_id}, job_id={job_id}")
return await self._download_remote(video_id, job_id, artist, title)
# Any other yt-dlp-supported site (Facebook, SoundCloud, TikTok, ...).
logger.info(f"URL download (generic): url={url}, job_id={job_id}")
return await self._download_remote_url(url, job_id, artist, title)
async def download_by_id(
self,
@@ -265,7 +263,7 @@ class YouTubeDownloadService:
logger.error(f"Remote YouTube download error: {e}", exc_info=True)
raise YouTubeDownloadError(f"Remote download failed: {e}") from e
async def _download_local(
async def _download_remote_url(
self,
url: str,
job_id: str,
@@ -273,92 +271,66 @@ class YouTubeDownloadService:
title: Optional[str] = None,
) -> str:
"""
Download using local yt_dlp (fallback when remote not configured).
Download an arbitrary yt-dlp-supported URL via remote flacfetch.
Warning: This may fail on Cloud Run due to YouTube bot detection.
Used for non-YouTube sites (Facebook, SoundCloud, TikTok, Vimeo, ...).
The URL is handed to flacfetch's generic "URL" source, which downloads
on the VM and uploads to GCS.
"""
temp_dir = tempfile.mkdtemp(prefix=f"youtube_{job_id}_")
gcs_destination = f"uploads/{job_id}/audio/"
output_filename = None
if artist and title:
from karaoke_gen.utils import sanitize_filename
output_filename = f"{sanitize_filename(artist)} - {sanitize_filename(title)}"
logger.info(
f"Remote URL download: url={url}, "
f"gcs_path={gcs_destination}, filename={output_filename}"
)
try:
from karaoke_gen.file_handler import FileHandler
from karaoke_gen.utils import sanitize_filename
# Create FileHandler
file_handler = FileHandler(
logger=logger,
ffmpeg_base_command="ffmpeg -hide_banner -loglevel error -nostats -y",
create_track_subfolders=False,
dry_run=False
download_id = await self._flacfetch_client.download_by_id(
source_name="URL",
source_id=url,
download_url=url,
output_filename=output_filename,
gcs_path=gcs_destination,
)
# Build output filename
safe_artist = sanitize_filename(artist) if artist else "Unknown"
safe_title = sanitize_filename(title) if title else "Unknown"
output_filename_no_extension = os.path.join(
temp_dir, f"{safe_artist} - {safe_title}"
logger.info(f"Remote URL download started: {download_id}")
def log_progress(status):
progress = status.get("progress", 0)
logger.debug(f"Download progress: {progress:.1f}%")
final_status = await self._flacfetch_client.wait_for_download(
download_id,
timeout=300,
progress_callback=log_progress,
)
# Get cookies from environment
cookies_str = os.environ.get("YOUTUBE_COOKIES")
if cookies_str:
logger.info("Using YouTube cookies for local download")
# Download
logger.info(f"Local YouTube download: {url}")
downloaded_file = file_handler.download_video(
url=url,
output_filename_no_extension=output_filename_no_extension,
cookies_str=cookies_str
)
if not downloaded_file or not os.path.exists(downloaded_file):
gcs_path = final_status.get("gcs_path")
if not gcs_path:
raise YouTubeDownloadError(
f"Local download failed - no file returned. "
"This is likely due to YouTube bot detection on Cloud Run IPs. "
"Configure FLACFETCH_API_URL for remote downloads."
"Remote download completed but no GCS path returned"
)
logger.info(f"Downloaded video: {downloaded_file}")
if gcs_path.startswith("gs://"):
parts = gcs_path.replace("gs://", "").split("/", 1)
if len(parts) == 2:
gcs_path = parts[1]
# Convert to WAV for processing
wav_file = file_handler.convert_to_wav(
input_filename=downloaded_file,
output_filename_no_extension=output_filename_no_extension
)
if not wav_file or not os.path.exists(wav_file):
raise YouTubeDownloadError("WAV conversion failed")
logger.info(f"Converted to WAV: {wav_file}")
# Upload to GCS
filename = os.path.basename(wav_file)
gcs_path = f"uploads/{job_id}/audio/{filename}"
content_type, _ = mimetypes.guess_type(wav_file)
with open(wav_file, 'rb') as f:
self._storage_service.upload_fileobj(
f,
gcs_path,
content_type=content_type or 'audio/wav'
)
logger.info(f"Uploaded to GCS: {gcs_path}")
logger.info(f"Remote URL download complete: {gcs_path}")
return gcs_path
except FlacfetchServiceError as e:
raise YouTubeDownloadError(f"Remote download failed: {e}") from e
except YouTubeDownloadError:
raise
except Exception as e:
logger.error(f"Local YouTube download error: {e}", exc_info=True)
raise YouTubeDownloadError(f"Local download failed: {e}") from e
finally:
# Cleanup temp directory
try:
import shutil
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
except Exception as cleanup_error:
logger.warning(f"Failed to cleanup temp dir: {cleanup_error}")
logger.error(f"Remote URL download error: {e}", exc_info=True)
raise YouTubeDownloadError(f"Remote download failed: {e}") from e
# Singleton instance
@@ -0,0 +1,573 @@
"""
Tests for duration-based credit delta-charge on audio-search /select.
Covers:
- result with duration=1500s (25 min → 3 credits), credits_charged=1 → deducts 2 MORE,
credits_charged becomes 3, count_as_job_creation=False, duration_estimate_source=search_metadata
- result with duration=4000s (over 60 min) → 422, no deduction, no download
- insufficient credits for top-up → 402
- result with no duration → owed 0, no deduction, selection proceeds
- acknowledged_credits mismatch → 409
"""
from __future__ import annotations
from datetime import datetime, UTC
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from backend.models.job import Job, JobStatus
from backend.services.auth_service import UserType, AuthResult
NOW = datetime.now(UTC)
# ---------------------------------------------------------------------------
# Auth fixtures
# ---------------------------------------------------------------------------
@pytest.fixture(autouse=True)
def _ensure_auth_overrides():
"""Ensure auth dependency overrides are set for every test in this file."""
from backend.api.dependencies import require_auth, require_admin
from backend.main import app
async def mock_require_auth():
return AuthResult(
is_valid=True,
user_type=UserType.STRIPE,
remaining_uses=5,
message="Regular test user",
is_admin=False,
user_email="buyer@example.com",
)
app.dependency_overrides[require_auth] = mock_require_auth
app.dependency_overrides[require_admin] = mock_require_auth
yield
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(require_admin, None)
# ---------------------------------------------------------------------------
# Helpers: build mock jobs
# ---------------------------------------------------------------------------
def _awaiting_selection_job(
job_id: str = "sel-job-1",
credits_charged: int = 1,
user_email: str = "buyer@example.com",
search_results: list | None = None,
) -> Job:
"""A job in AWAITING_AUDIO_SELECTION with audio_search_results in state_data."""
if search_results is None:
search_results = [
{
"title": "Waterloo",
"artist": "ABBA",
"provider": "RED",
"quality": "FLAC",
"source_id": "abc123",
"target_file": "Waterloo.flac",
"url": "",
"duration": 300,
}
]
return Job(
job_id=job_id,
status=JobStatus.AWAITING_AUDIO_SELECTION,
created_at=NOW,
updated_at=NOW,
user_email=user_email,
state_data={
"credits_charged": credits_charged,
"audio_search_results": search_results,
},
)
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def mock_job_manager():
jm = MagicMock()
jm.get_job.return_value = _awaiting_selection_job()
jm.update_job.return_value = None
jm.transition_to_state.return_value = True
return jm
@pytest.fixture
def mock_user_service():
us = MagicMock()
us.deduct_credits.return_value = (True, 3, "ok")
return us
@pytest.fixture
def mock_worker_service():
ws = MagicMock()
ws.trigger_audio_download_worker = AsyncMock(return_value=True)
return ws
@pytest.fixture
def patched_app(mock_job_manager, mock_user_service, mock_worker_service):
"""Patch module-level singletons in audio_search route and yield TestClient."""
from fastapi.testclient import TestClient
from backend.main import app
with (
patch("backend.api.routes.audio_search.job_manager", mock_job_manager),
patch(
"backend.api.routes.audio_search.get_user_service",
return_value=mock_user_service,
),
patch(
"backend.api.routes.audio_search.get_worker_service",
return_value=mock_worker_service,
),
patch("backend.api.routes.audio_search.get_audio_search_service", return_value=MagicMock()),
):
yield TestClient(app), mock_job_manager, mock_user_service, mock_worker_service
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _post_select(client, job_id="sel-job-1", *, selection_index=0, **extra):
body = {"selection_index": selection_index}
body.update(extra)
return client.post(f"/api/audio-search/{job_id}/select", json=body)
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
class TestSelectPricingDeltaCharge:
"""
Duration 1500s (25 min) → ceil(1500/600) = 3 credits.
credits_charged=1 at search time → owed=2 MORE credits.
"""
def _job_1500s(self) -> Job:
return _awaiting_selection_job(
credits_charged=1,
search_results=[
{
"title": "Long Song",
"artist": "Artist",
"provider": "RED",
"quality": "FLAC",
"source_id": "abc999",
"target_file": "long.flac",
"url": "",
"duration": 1500,
}
],
)
def test_returns_200(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
resp = _post_select(client)
assert resp.status_code == 200, resp.text
def test_deducts_delta_2_credits(self, patched_app):
"""owed = duration_to_credits(1500) - credits_charged = 3 - 1 = 2."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
_post_select(client)
us.deduct_credits.assert_called_once()
args, kwargs = us.deduct_credits.call_args
amount = kwargs.get("amount", args[2] if len(args) > 2 else None)
assert amount == 2, f"Expected delta deduction of 2, got {amount}"
def test_count_as_job_creation_false(self, patched_app):
"""Job was already counted at create_job; must NOT double-count."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
_post_select(client)
us.deduct_credits.assert_called_once()
args, kwargs = us.deduct_credits.call_args
flag = kwargs.get("count_as_job_creation", args[4] if len(args) > 4 else True)
assert flag is False, "must pass count_as_job_creation=False"
def test_credits_charged_updated_to_3(self, patched_app):
"""After deduction, job_manager.update_job must store credits_charged=3."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
_post_select(client)
# Collect all update_job calls and look for credits_charged update
all_payloads: dict = {}
for call in jm.update_job.call_args_list:
args, kwargs = call
payload = args[1] if len(args) >= 2 else kwargs.get("updates", {})
if isinstance(payload, dict):
all_payloads.update(payload)
assert all_payloads.get("state_data.credits_charged") == 3, (
f"Expected state_data.credits_charged=3 in update_job payload, got: {all_payloads}"
)
def test_duration_estimate_stored(self, patched_app):
"""duration_estimate_seconds and duration_estimate_source must be persisted."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
_post_select(client)
all_payloads: dict = {}
for call in jm.update_job.call_args_list:
args, kwargs = call
payload = args[1] if len(args) >= 2 else kwargs.get("updates", {})
if isinstance(payload, dict):
all_payloads.update(payload)
assert all_payloads.get("state_data.duration_estimate_seconds") == 1500, (
f"Expected duration_estimate_seconds=1500 in update_job, got: {all_payloads}"
)
assert all_payloads.get("state_data.duration_estimate_source") == "search_metadata", (
f"Expected duration_estimate_source='search_metadata' in update_job, got: {all_payloads}"
)
def test_download_worker_triggered_after_deduction(self, patched_app):
"""Download must be triggered AFTER the credit deduction succeeds."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
_post_select(client)
ws.trigger_audio_download_worker.assert_called_once_with("sel-job-1")
class TestSelectPricingOverLimit:
"""Duration 4000s > 3600s → is_blocked=True → 422 before download."""
def _job_4000s(self) -> Job:
return _awaiting_selection_job(
credits_charged=1,
search_results=[
{
"title": "Mashup",
"artist": "DJ",
"provider": "RED",
"quality": "FLAC",
"source_id": "big999",
"target_file": "mashup.flac",
"url": "",
"duration": 4000,
}
],
)
def test_returns_422(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_4000s()
resp = _post_select(client)
assert resp.status_code == 422, resp.text
def test_no_deduction(self, patched_app):
"""Over-limit: no credits deducted."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_4000s()
_post_select(client)
us.deduct_credits.assert_not_called()
def test_no_download_triggered(self, patched_app):
"""Over-limit: download worker must NOT be triggered."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_4000s()
_post_select(client)
ws.trigger_audio_download_worker.assert_not_called()
class TestSelectPricingInsufficientCredits:
"""Top-up deduction fails → 402 Insufficient Credits."""
def _job_1500s(self) -> Job:
return _awaiting_selection_job(
credits_charged=1,
search_results=[
{
"title": "Long Song",
"artist": "Artist",
"provider": "RED",
"quality": "FLAC",
"source_id": "abc999",
"target_file": "long.flac",
"url": "",
"duration": 1500,
}
],
)
def test_returns_402_when_deduction_fails(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
us.deduct_credits.return_value = (False, 0, "Insufficient credits")
resp = _post_select(client)
assert resp.status_code == 402, resp.text
def test_no_download_on_insufficient_credits(self, patched_app):
"""If deduction fails, download worker must NOT be triggered."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
us.deduct_credits.return_value = (False, 0, "Insufficient credits")
_post_select(client)
ws.trigger_audio_download_worker.assert_not_called()
class TestSelectPricingNoDuration:
"""Result has duration=None → owed=0, no deduction, selection proceeds normally."""
def _job_no_duration(self) -> Job:
return _awaiting_selection_job(
credits_charged=1,
search_results=[
{
"title": "Unknown Length",
"artist": "Band",
"provider": "RED",
"quality": "FLAC",
"source_id": "no-dur-001",
"target_file": "unknown.flac",
"url": "",
# No 'duration' key — simulates missing duration
}
],
)
def test_returns_200(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_no_duration()
resp = _post_select(client)
assert resp.status_code == 200, resp.text
def test_no_deduction_when_no_duration(self, patched_app):
"""duration=None → owed=0 → no deduction call."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_no_duration()
_post_select(client)
us.deduct_credits.assert_not_called()
def test_download_still_triggered(self, patched_app):
"""Even without duration, the download worker must fire."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_no_duration()
_post_select(client)
ws.trigger_audio_download_worker.assert_called_once()
class TestSelectPricingAcknowledgedCreditsMismatch:
"""
acknowledged_credits sent but doesn't match server's target_total → 409.
"""
def _job_1500s(self) -> Job:
return _awaiting_selection_job(
credits_charged=1,
search_results=[
{
"title": "Long Song",
"artist": "Artist",
"provider": "RED",
"quality": "FLAC",
"source_id": "abc999",
"target_file": "long.flac",
"url": "",
"duration": 1500,
}
],
)
def test_mismatch_returns_409(self, patched_app):
"""target_total=3 (1500s), client sends acknowledged_credits=2 → 409."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
resp = _post_select(client, acknowledged_credits=2)
assert resp.status_code == 409, resp.text
def test_no_deduction_on_mismatch(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
_post_select(client, acknowledged_credits=2)
us.deduct_credits.assert_not_called()
def test_no_download_on_mismatch(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
_post_select(client, acknowledged_credits=2)
ws.trigger_audio_download_worker.assert_not_called()
def test_correct_acknowledged_credits_succeeds(self, patched_app):
"""target_total=3, acknowledged_credits=3 → 200."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
resp = _post_select(client, acknowledged_credits=3)
assert resp.status_code == 200, resp.text
class TestSelectPricingIdempotencyGuard:
"""
When select_charge_applied=True is already set in state_data, a repeated /select
call must NOT deduct any credits, regardless of what owed would compute to.
"""
def _job_already_charged(self) -> Job:
"""Job that has already had its delta charge applied (select_charge_applied=True)."""
return _awaiting_selection_job(
credits_charged=3,
search_results=[
{
"title": "Long Song",
"artist": "Artist",
"provider": "RED",
"quality": "FLAC",
"source_id": "abc999",
"target_file": "long.flac",
"url": "",
# duration=1500 → target_total=3; without guard, owed=3-3=0.
# But seed credits_charged=3 so owed is already 0 here.
# Use duration=1500 to confirm that even if recalculated it stays 0.
"duration": 1500,
}
],
)
def _job_already_charged_would_owe(self) -> Job:
"""
Job with select_charge_applied=True but credits_charged still at 1,
meaning WITHOUT the guard the code would try to charge 2 more credits.
This proves the guard short-circuits based on the flag, not the math.
"""
job = _awaiting_selection_job(
credits_charged=1,
search_results=[
{
"title": "Long Song",
"artist": "Artist",
"provider": "RED",
"quality": "FLAC",
"source_id": "abc999",
"target_file": "long.flac",
"url": "",
"duration": 1500, # would owe 2 credits without guard
}
],
)
# Inject the flag that marks the charge as already applied
job.state_data["select_charge_applied"] = True
return job
def test_reselect_does_not_double_charge(self, patched_app):
"""
Job with select_charge_applied=True and credits_charged=1, duration=1500
(owed=2 without guard) → deduct_credits must NOT be called.
"""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_already_charged_would_owe()
resp = _post_select(client)
assert resp.status_code == 200, resp.text
us.deduct_credits.assert_not_called()
def test_reselect_does_not_change_credits_charged(self, patched_app):
"""
When the guard fires, update_job must NOT include a credits_charged update.
"""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_already_charged_would_owe()
_post_select(client)
# Collect all update_job calls
all_payloads: dict = {}
for call in jm.update_job.call_args_list:
args, kwargs = call
payload = args[1] if len(args) >= 2 else kwargs.get("updates", {})
if isinstance(payload, dict):
all_payloads.update(payload)
assert "state_data.credits_charged" not in all_payloads, (
f"credits_charged must not be updated on repeat select; got: {all_payloads}"
)
def test_first_select_sets_flag(self, patched_app):
"""
A first-time /select (select_charge_applied absent) must write
select_charge_applied=True into the update_job payload.
"""
client, jm, us, ws = patched_app
# Use a job WITHOUT the flag set
jm.get_job.return_value = _awaiting_selection_job(
credits_charged=1,
search_results=[
{
"title": "Long Song",
"artist": "Artist",
"provider": "RED",
"quality": "FLAC",
"source_id": "abc999",
"target_file": "long.flac",
"url": "",
"duration": 1500,
}
],
)
resp = _post_select(client)
assert resp.status_code == 200, resp.text
all_payloads: dict = {}
for call in jm.update_job.call_args_list:
args, kwargs = call
payload = args[1] if len(args) >= 2 else kwargs.get("updates", {})
if isinstance(payload, dict):
all_payloads.update(payload)
assert all_payloads.get("state_data.select_charge_applied") is True, (
f"Expected select_charge_applied=True in update_job payload; got: {all_payloads}"
)
+498
View File
@@ -0,0 +1,498 @@
"""
Tests for POST /api/jobs/{job_id}/confirm-duration endpoint.
Covers:
- reconcile path: deduct pending_additional_credits, trigger workers
- preflight path: deduct pending_additional_credits (delta, not full cost), trigger workers
- insufficient credits → 402
- acknowledged_credits mismatch → 409
- wrong status → 409
- not found / not owner → 404
"""
from __future__ import annotations
import asyncio
from datetime import datetime, UTC
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from backend.models.job import Job, JobStatus
from backend.services.auth_service import UserType, AuthResult
NOW = datetime.now(UTC)
@pytest.fixture(autouse=True)
def _ensure_auth_overrides():
"""Ensure auth dependency overrides are set for every test in this file.
Mirrors the pattern used by test_audio_edit_routes.py — necessary because
the conftest autouse fixture can be cleared by intervening tests when running
the whole suite with -k filters.
"""
from backend.api.dependencies import require_auth, require_admin
from backend.main import app
async def mock_require_auth():
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=999,
message="Test admin token",
is_admin=True,
user_email="test@example.com",
)
app.dependency_overrides[require_auth] = mock_require_auth
app.dependency_overrides[require_admin] = mock_require_auth
yield
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(require_admin, None)
def _job(**kwargs) -> Job:
defaults = dict(
job_id="job-dur-1",
created_at=NOW,
updated_at=NOW,
user_email="owner@example.com",
)
defaults.update(kwargs)
return Job(**defaults)
def _dur_confirm_job_reconcile(
job_id="job-dur-1",
credits_charged=2,
pending_additional_credits=1,
user_email="owner@example.com",
):
"""Job in AWAITING_DURATION_CONFIRM with reason=reconcile."""
return _job(
job_id=job_id,
status=JobStatus.AWAITING_DURATION_CONFIRM,
user_email=user_email,
state_data={
"duration_confirm_reason": "reconcile",
"credits_charged": credits_charged,
"pending_additional_credits": pending_additional_credits,
},
)
def _dur_confirm_job_preflight(
job_id="job-dur-2",
credits_charged=1,
pending_additional_credits=2,
user_email="owner@example.com",
):
"""Job in AWAITING_DURATION_CONFIRM with reason=preflight.
Delta model: create_job already charged 1 credit; the upload's duration
estimate (e.g. ~25 min / 3-credit song) means 2 MORE credits are owed.
pending_additional_credits=2, credits_charged=1, expected_total=3.
"""
return _job(
job_id=job_id,
status=JobStatus.AWAITING_DURATION_CONFIRM,
user_email=user_email,
state_data={
"duration_confirm_reason": "preflight",
"credits_charged": credits_charged,
"pending_additional_credits": pending_additional_credits,
},
)
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def mock_job_manager():
jm = MagicMock()
jm.get_job.return_value = _dur_confirm_job_reconcile()
jm.update_job.return_value = None
jm.update_state_data.return_value = None
jm.transition_to_state.return_value = True
return jm
@pytest.fixture
def mock_user_service():
us = MagicMock()
# Default: successful deduction
us.deduct_credits.return_value = (True, 10, "ok")
return us
@pytest.fixture
def mock_worker_service():
ws = MagicMock()
ws.trigger_audio_worker = AsyncMock(return_value=True)
ws.trigger_lyrics_worker = AsyncMock(return_value=True)
return ws
@pytest.fixture
def patched_app(mock_job_manager, mock_user_service, mock_worker_service):
"""Patch module-level singletons and yield the TestClient."""
from fastapi.testclient import TestClient
from backend.main import app
# get_user_service and get_worker_service are called at request-time inside the
# endpoint (not at module load), so we patch them where they are looked up:
# get_user_service at the jobs module scope, get_worker_service at the module level.
with (
patch("backend.api.routes.jobs.job_manager", mock_job_manager),
patch(
"backend.api.routes.jobs.get_user_service",
return_value=mock_user_service,
),
patch(
"backend.api.routes.jobs.get_worker_service",
return_value=mock_worker_service,
),
):
yield TestClient(app), mock_job_manager, mock_user_service, mock_worker_service
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _post(client, job_id, acknowledged_credits):
return client.post(
f"/api/jobs/{job_id}/confirm-duration",
json={"acknowledged_credits": acknowledged_credits},
)
# ---------------------------------------------------------------------------
# Test classes
# ---------------------------------------------------------------------------
class TestConfirmDurationReconcile:
"""Reconcile path: credits_charged=2, pending_additional_credits=1, owed=1, expected_total=3."""
def test_returns_200_and_deducts_one_credit(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_reconcile(
credits_charged=2, pending_additional_credits=1
)
resp = _post(client, "job-dur-1", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
# Verify deduct was called with count_as_job_creation=False
us.deduct_credits.assert_called_once()
call_kwargs = us.deduct_credits.call_args
args, kwargs = call_kwargs
# Signature: deduct_credits(email, job_id, amount, reason, count_as_job_creation)
assert kwargs.get("amount", args[2] if len(args) > 2 else None) == 1
assert kwargs.get("reason", args[3] if len(args) > 3 else None) == "duration_confirm"
count_flag = kwargs.get(
"count_as_job_creation", args[4] if len(args) > 4 else True
)
assert count_flag is False, "reconcile top-up must NOT increment total_jobs_created"
def test_state_data_updated_after_confirm(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_reconcile(
credits_charged=2, pending_additional_credits=1
)
resp = _post(client, "job-dur-1", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
# update_job must have been called to persist state changes
jm.update_job.assert_called()
def test_returns_job_in_response(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_reconcile()
resp = _post(client, "job-dur-1", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
body = resp.json()
assert "job_id" in body
def test_insufficient_credits_returns_402(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_reconcile(
credits_charged=2, pending_additional_credits=1
)
us.deduct_credits.return_value = (False, 0, "Insufficient credits")
resp = _post(client, "job-dur-1", acknowledged_credits=3)
assert resp.status_code == 402, resp.text
def test_acknowledged_mismatch_returns_409(self, patched_app):
"""Client sends acknowledged_credits=99, expected is 3 → 409."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_reconcile(
credits_charged=2, pending_additional_credits=1
)
resp = _post(client, "job-dur-1", acknowledged_credits=99)
assert resp.status_code == 409, resp.text
# No credits should be deducted
us.deduct_credits.assert_not_called()
def test_workers_triggered_on_success(self, patched_app):
"""Verify that create_task was called (worker trigger fired)."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_reconcile()
with patch("backend.api.routes.jobs.asyncio.create_task") as mock_ct:
mock_ct.return_value = MagicMock()
resp = _post(client, "job-dur-1", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
mock_ct.assert_called_once()
def test_workers_not_triggered_on_credit_failure(self, patched_app):
"""If deduction fails, workers must NOT be triggered."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_reconcile()
us.deduct_credits.return_value = (False, 0, "Insufficient credits")
with patch("backend.api.routes.jobs.asyncio.create_task") as mock_ct:
resp = _post(client, "job-dur-1", acknowledged_credits=3)
assert resp.status_code == 402
mock_ct.assert_not_called()
class TestConfirmDurationPreflight:
"""Preflight path (delta model): credits_charged=1, pending_additional_credits=2, owed=2, expected_total=3.
create_job charged 1 credit at upload time; the pause-creating site computed
pending_additional_credits=2 as the delta for a ~25-min (3-credit) song.
confirm_duration deducts ONLY the delta (2), bringing credits_charged to 3.
"""
def test_preflight_returns_200(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_preflight(
credits_charged=1, pending_additional_credits=2
)
resp = _post(client, "job-dur-2", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
def test_preflight_deducts_delta_only(self, patched_app):
"""Delta model: only deduct pending_additional_credits (2), not the full cost (3)."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_preflight(
credits_charged=1, pending_additional_credits=2
)
resp = _post(client, "job-dur-2", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
us.deduct_credits.assert_called_once()
call_args, call_kwargs = us.deduct_credits.call_args
amount = call_kwargs.get("amount", call_args[2] if len(call_args) > 2 else None)
assert amount == 2, (
"preflight must deduct the delta (pending_additional_credits=2), "
"not the full cost — create_job already charged 1 credit"
)
def test_preflight_count_as_job_creation_false(self, patched_app):
"""Preflight uses count_as_job_creation=False (job was already counted at creation)."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_preflight(
credits_charged=1, pending_additional_credits=2
)
resp = _post(client, "job-dur-2", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
call_args, call_kwargs = us.deduct_credits.call_args
count_flag = call_kwargs.get(
"count_as_job_creation",
call_args[4] if len(call_args) > 4 else True,
)
assert count_flag is False, (
"preflight: job already counted at create_job() credit deduction; "
"do not double-count total_jobs_created"
)
def test_preflight_credits_charged_becomes_total(self, patched_app):
"""After confirm, credits_charged should be updated to credits_charged + owed = 3."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_preflight(
credits_charged=1, pending_additional_credits=2
)
resp = _post(client, "job-dur-2", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
jm.update_job.assert_called()
update_call_args = jm.update_job.call_args
update_dict = update_call_args[0][1] if update_call_args[0] else update_call_args[1]
assert update_dict.get("state_data.credits_charged") == 3, (
"credits_charged must be updated to 1 (prior) + 2 (owed) = 3"
)
def test_preflight_insufficient_credits_returns_402(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_preflight(
credits_charged=1, pending_additional_credits=2
)
us.deduct_credits.return_value = (False, 1, "Insufficient credits")
resp = _post(client, "job-dur-2", acknowledged_credits=3)
assert resp.status_code == 402, resp.text
def test_preflight_mismatch_returns_409(self, patched_app):
"""acknowledged_credits=5 but expected 3 (1+2) → 409."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_preflight(
credits_charged=1, pending_additional_credits=2
)
resp = _post(client, "job-dur-2", acknowledged_credits=5)
assert resp.status_code == 409, resp.text
def test_preflight_workers_triggered(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_preflight(
credits_charged=1, pending_additional_credits=2
)
with patch("backend.api.routes.jobs.asyncio.create_task") as mock_ct:
mock_ct.return_value = MagicMock()
resp = _post(client, "job-dur-2", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
mock_ct.assert_called_once()
class TestConfirmDurationIdempotency:
"""Duplicate-confirm and owed=0 paths."""
def test_duplicate_confirm_is_rejected(self, patched_app):
"""A second confirm POST must 409 because the job is no longer AWAITING_DURATION_CONFIRM.
After a successful confirm the endpoint calls transition_to_state →
SEPARATING_STAGE1. The mock default returns True from transition_to_state;
what matters is that the endpoint *issued* the transition so that a
subsequent request (now seeing a different status) would be rejected.
We verify this by asserting that transition_to_state was called with
new_status=SEPARATING_STAGE1 on the first confirm — the status guard at
step 2 would reject a second request once the real Firestore document
reflects the new status.
"""
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_reconcile(
credits_charged=2, pending_additional_credits=1
)
resp = _post(client, "job-dur-1", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
# Verify the endpoint transitioned the job out of AWAITING_DURATION_CONFIRM
# so a duplicate confirm would hit the status guard (409).
jm.transition_to_state.assert_called_once()
call_kwargs = jm.transition_to_state.call_args[1]
assert call_kwargs.get("new_status") == JobStatus.SEPARATING_STAGE1, (
"confirm_duration must transition to SEPARATING_STAGE1 before triggering "
"workers so a duplicate POST is rejected by the status guard"
)
def test_owed_zero_path(self, patched_app):
"""Job with pending_additional_credits=0: 200, deduct_credits NOT called,
duration_confirmed set, workers triggered, status transitioned out."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _job(
job_id="job-zero",
status=JobStatus.AWAITING_DURATION_CONFIRM,
user_email="owner@example.com",
state_data={
"duration_confirm_reason": "reconcile",
"credits_charged": 3,
"pending_additional_credits": 0,
},
)
with patch("backend.api.routes.jobs.asyncio.create_task") as mock_ct:
mock_ct.return_value = MagicMock()
resp = _post(client, "job-zero", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
# No credits should be deducted when owed == 0
us.deduct_credits.assert_not_called()
# State must still be persisted and workers triggered
jm.update_job.assert_called()
mock_ct.assert_called_once()
# Job must still be transitioned out of the pause state
jm.transition_to_state.assert_called_once()
call_kwargs = jm.transition_to_state.call_args[1]
assert call_kwargs.get("new_status") == JobStatus.SEPARATING_STAGE1
class TestConfirmDurationErrorCases:
"""Status guard, not-found, and not-owner cases."""
def test_wrong_status_returns_409(self, patched_app):
"""Job not in AWAITING_DURATION_CONFIRM → 409."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _job(
job_id="done-job",
status=JobStatus.COMPLETE,
user_email="owner@example.com",
state_data={},
)
resp = _post(client, "done-job", acknowledged_credits=1)
assert resp.status_code == 409, resp.text
def test_job_not_found_returns_404(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = None
resp = _post(client, "nonexistent", acknowledged_credits=1)
assert resp.status_code == 404, resp.text
def test_not_owner_returns_404(self, patched_app):
"""Job owned by different user (non-admin) should 404 to avoid leaking job existence."""
client, jm, us, ws = patched_app
# The conftest mock_auth_dependency sets user_email="test@example.com" and is_admin=True.
# To test the non-owner path we need to override auth to return a non-admin user.
from backend.api.dependencies import require_auth
from backend.main import app
async def non_owner_auth():
return AuthResult(
is_valid=True,
user_type=UserType.STRIPE,
remaining_uses=5,
message="regular user",
is_admin=False,
user_email="other@example.com", # different from owner@example.com
)
jm.get_job.return_value = _dur_confirm_job_reconcile(user_email="owner@example.com")
app.dependency_overrides[require_auth] = non_owner_auth
try:
resp = _post(client, "job-dur-1", acknowledged_credits=3)
finally:
app.dependency_overrides.pop(require_auth, None)
assert resp.status_code == 404, resp.text
+132
View File
@@ -0,0 +1,132 @@
"""
Tests for POST /api/jobs/estimate — URL duration probe.
Covers:
- duration 905s → 200, duration_seconds=905, credits=2, blocked=False
- duration 4000s → blocked=True
- probe failure (duration None) → duration_seconds=None, source="unknown", credits=1, blocked=False
`check_availability` is patched at its import location in backend.api.routes.jobs.
"""
from __future__ import annotations
from unittest.mock import AsyncMock, patch
import pytest
from fastapi.testclient import TestClient
@pytest.fixture(autouse=True)
def _ensure_auth_overrides():
"""Ensure auth dependency overrides are set for every test in this file."""
from backend.api.dependencies import require_auth, require_admin
from backend.main import app
from backend.services.auth_service import UserType, AuthResult
async def mock_require_auth():
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=999,
message="Test admin token",
is_admin=True,
user_email="test@example.com",
)
app.dependency_overrides[require_auth] = mock_require_auth
app.dependency_overrides[require_admin] = mock_require_auth
yield
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(require_admin, None)
@pytest.fixture
def client():
from backend.main import app
return TestClient(app)
@pytest.fixture
def auth_headers():
return {
"Authorization": "Bearer test-admin-token",
"Content-Type": "application/json",
}
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
def test_estimate_returns_credits(client, auth_headers):
"""905s of audio → 2 credits (ceil(905/600)=2), not blocked."""
mock_svc = AsyncMock()
mock_svc.check_availability = AsyncMock(
return_value={"available": True, "duration": 905}
)
with patch(
"backend.api.routes.jobs.get_youtube_download_service",
return_value=mock_svc,
):
resp = client.post(
"/api/jobs/estimate",
json={"url": "https://youtu.be/x"},
headers=auth_headers,
)
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["duration_seconds"] == 905
assert body["credits"] == 2
assert body["blocked"] is False
assert body["source"] == "youtube_metadata"
def test_estimate_blocks_over_60min(client, auth_headers):
"""4000s (>3600s) → blocked=True."""
mock_svc = AsyncMock()
mock_svc.check_availability = AsyncMock(
return_value={"available": True, "duration": 4000}
)
with patch(
"backend.api.routes.jobs.get_youtube_download_service",
return_value=mock_svc,
):
resp = client.post(
"/api/jobs/estimate",
json={"url": "https://youtu.be/x"},
headers=auth_headers,
)
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["blocked"] is True
assert body["duration_seconds"] == 4000
def test_estimate_probe_failure_returns_unknown(client, auth_headers):
"""When probe returns None duration → unknown source, 1 credit hold, not blocked."""
mock_svc = AsyncMock()
mock_svc.check_availability = AsyncMock(
return_value={"available": True, "duration": None}
)
with patch(
"backend.api.routes.jobs.get_youtube_download_service",
return_value=mock_svc,
):
resp = client.post(
"/api/jobs/estimate",
json={"url": "https://youtu.be/x"},
headers=auth_headers,
)
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["duration_seconds"] is None
assert body["source"] == "unknown"
assert body["credits"] == 1
assert body["blocked"] is False
@@ -0,0 +1,340 @@
"""
Tests for the idle reminder mechanism for AWAITING_DURATION_CONFIRM state.
Covers:
- POST /api/internal/jobs/{job_id}/check-idle-reminder sends email when job is in
AWAITING_DURATION_CONFIRM and action_type == "duration_confirm"
- No email sent when job has already left AWAITING_DURATION_CONFIRM
- _schedule_idle_reminder schedules a 900s reminder with action_type="duration_confirm"
when a job enters AWAITING_DURATION_CONFIRM
"""
import os
import pytest
from datetime import datetime, UTC
from unittest.mock import MagicMock, AsyncMock, patch, Mock
# Ensure env vars are set before any backend imports
os.environ.setdefault('ADMIN_TOKENS', 'test-admin-token')
os.environ.setdefault('GOOGLE_CLOUD_PROJECT', 'test-project')
from backend.models.job import Job, JobStatus
from backend.services.job_manager import JobManager
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_job(
status: JobStatus = JobStatus.AWAITING_DURATION_CONFIRM,
state_data: dict | None = None,
user_email: str = "user@example.com",
job_id: str = "job-dur-001",
made_for_you: bool = False,
) -> Job:
"""Create a minimal Job for testing."""
return Job(
job_id=job_id,
status=status,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
user_email=user_email,
artist="Test Artist",
title="Test Song",
state_data=state_data or {
"blocking_action_type": "duration_confirm",
"blocking_state_entered_at": "2026-06-04T10:00:00",
"reminder_sent": False,
"pending_additional_credits": 3,
"duration_actual_seconds": 1200,
},
made_for_you=made_for_you,
)
def _make_client():
"""Create a FastAPI TestClient with GCP mocks applied."""
from fastapi.testclient import TestClient
mock_creds = MagicMock()
mock_creds.universe_domain = "googleapis.com"
with patch("google.auth.default", return_value=(mock_creds, "test-project")), \
patch("backend.services.firestore_service.firestore"), \
patch("backend.services.storage_service.storage"):
from backend.main import app
return TestClient(app)
# ---------------------------------------------------------------------------
# Check-idle-reminder endpoint tests
# ---------------------------------------------------------------------------
class TestCheckIdleReminderDurationConfirm:
"""Tests for the check-idle-reminder endpoint handling duration_confirm jobs."""
AUTH = {"Authorization": "Bearer test-admin-token"}
def test_sends_duration_confirm_email_when_job_awaiting(self):
"""
When a job is AWAITING_DURATION_CONFIRM with action_type=duration_confirm,
POST check-idle-reminder should call send_duration_confirm_reminder once
and set reminder_sent=True.
"""
job = _make_job()
mock_job_manager = MagicMock()
mock_job_manager.get_job.return_value = job
mock_notification_service = MagicMock()
mock_notification_service.send_duration_confirm_reminder = AsyncMock(return_value=True)
client = _make_client()
with patch("backend.api.routes.internal.JobManager", return_value=mock_job_manager), \
patch(
"backend.services.job_notification_service.get_job_notification_service",
return_value=mock_notification_service,
):
response = client.post(
"/api/internal/jobs/job-dur-001/check-idle-reminder",
headers=self.AUTH,
)
assert response.status_code == 200
data = response.json()
assert data["status"] == "sent"
# Email method was called exactly once
mock_notification_service.send_duration_confirm_reminder.assert_called_once()
# reminder_sent flag was written back
update_calls = mock_job_manager.firestore.update_job.call_args_list
assert any(
call_args[0][1].get("state_data", {}).get("reminder_sent") is True
for call_args in update_calls
)
def test_no_email_when_job_no_longer_awaiting_duration_confirm(self):
"""
If the job has moved out of AWAITING_DURATION_CONFIRM (e.g. user confirmed),
the endpoint should return 'skipped' and NOT send any email.
"""
# Job is now PROCESSING (user already confirmed)
job = _make_job(status=JobStatus.PROCESSING)
mock_job_manager = MagicMock()
mock_job_manager.get_job.return_value = job
mock_notification_service = MagicMock()
mock_notification_service.send_duration_confirm_reminder = AsyncMock(return_value=True)
client = _make_client()
with patch("backend.api.routes.internal.JobManager", return_value=mock_job_manager), \
patch(
"backend.services.job_notification_service.get_job_notification_service",
return_value=mock_notification_service,
):
response = client.post(
"/api/internal/jobs/job-dur-001/check-idle-reminder",
headers=self.AUTH,
)
assert response.status_code == 200
data = response.json()
assert data["status"] == "skipped"
# No email sent
mock_notification_service.send_duration_confirm_reminder.assert_not_called()
def test_no_email_when_reminder_already_sent(self):
"""
If reminder_sent is already True, the endpoint should return 'already_sent'
without calling send_duration_confirm_reminder.
"""
job = _make_job(
state_data={
"blocking_action_type": "duration_confirm",
"blocking_state_entered_at": "2026-06-04T10:00:00",
"reminder_sent": True, # Already sent
}
)
mock_job_manager = MagicMock()
mock_job_manager.get_job.return_value = job
mock_notification_service = MagicMock()
mock_notification_service.send_duration_confirm_reminder = AsyncMock(return_value=True)
client = _make_client()
with patch("backend.api.routes.internal.JobManager", return_value=mock_job_manager), \
patch(
"backend.services.job_notification_service.get_job_notification_service",
return_value=mock_notification_service,
):
response = client.post(
"/api/internal/jobs/job-dur-001/check-idle-reminder",
headers=self.AUTH,
)
assert response.status_code == 200
data = response.json()
assert data["status"] == "already_sent"
mock_notification_service.send_duration_confirm_reminder.assert_not_called()
def test_no_email_when_made_for_you(self):
"""Made-for-you jobs should be skipped even in AWAITING_DURATION_CONFIRM."""
job = _make_job(made_for_you=True)
mock_job_manager = MagicMock()
mock_job_manager.get_job.return_value = job
mock_notification_service = MagicMock()
mock_notification_service.send_duration_confirm_reminder = AsyncMock(return_value=True)
client = _make_client()
with patch("backend.api.routes.internal.JobManager", return_value=mock_job_manager), \
patch(
"backend.services.job_notification_service.get_job_notification_service",
return_value=mock_notification_service,
):
response = client.post(
"/api/internal/jobs/job-dur-001/check-idle-reminder",
headers=self.AUTH,
)
assert response.status_code == 200
data = response.json()
assert data["status"] == "skipped"
mock_notification_service.send_duration_confirm_reminder.assert_not_called()
# ---------------------------------------------------------------------------
# _schedule_idle_reminder unit test
# ---------------------------------------------------------------------------
class TestScheduleIdleReminderDurationConfirm:
"""Tests for _schedule_idle_reminder when entering AWAITING_DURATION_CONFIRM."""
def test_schedules_reminder_with_900s_delay_for_duration_confirm(self):
"""
Entering AWAITING_DURATION_CONFIRM must schedule a reminder with
action_type='duration_confirm' and delay_seconds=900 (15 min).
"""
manager = JobManager()
manager.firestore = Mock()
mock_job = Mock(spec=Job)
mock_job.job_id = "job-dur-002"
mock_job.user_email = "user@example.com"
mock_job.state_data = {"pending_additional_credits": 2}
captured_calls = []
async def fake_schedule_reminder(job_id, delay_seconds=None):
captured_calls.append({"job_id": job_id, "delay_seconds": delay_seconds})
return True
with patch("backend.services.worker_service.get_worker_service") as mock_get_service:
mock_service = Mock()
mock_service.schedule_idle_reminder = AsyncMock(
side_effect=fake_schedule_reminder
)
mock_get_service.return_value = mock_service
manager._schedule_idle_reminder(mock_job, JobStatus.AWAITING_DURATION_CONFIRM)
# Verify state_data update contains action_type and reminder_sent
update_call = manager.firestore.update_job.call_args
assert update_call is not None
updated_data = update_call[0][1]
state_data = updated_data.get("state_data", {})
assert state_data.get("blocking_action_type") == "duration_confirm"
assert state_data.get("reminder_sent") is False
assert "blocking_state_entered_at" in state_data
def test_schedules_900s_delay_not_default_delay(self):
"""
Verify that the 900s delay is passed explicitly (not the 2-min default),
so other action types are unaffected.
"""
from backend.services import worker_service as ws_module
manager = JobManager()
manager.firestore = Mock()
mock_job = Mock(spec=Job)
mock_job.job_id = "job-dur-003"
mock_job.user_email = "user@example.com"
mock_job.state_data = {}
mock_schedule = AsyncMock(return_value=True)
with patch("backend.services.worker_service.get_worker_service") as mock_get_service:
mock_service = Mock()
mock_service.schedule_idle_reminder = mock_schedule
mock_get_service.return_value = mock_service
manager._schedule_idle_reminder(mock_job, JobStatus.AWAITING_DURATION_CONFIRM)
# Give the daemon thread a moment to run
import time
time.sleep(0.2)
if mock_schedule.called:
call_kwargs = mock_schedule.call_args
# Should pass delay_seconds=900 explicitly
delay = (
call_kwargs.kwargs.get("delay_seconds")
if call_kwargs.kwargs
else (call_kwargs.args[1] if len(call_kwargs.args) > 1 else None)
)
assert delay == 900, (
f"Expected delay_seconds=900 for duration_confirm, got {delay}. "
f"The 2-min default ({ws_module.IDLE_REMINDER_DELAY_SECONDS}s) must NOT be used."
)
def test_does_not_affect_lyrics_reminder_delay(self):
"""
Entering AWAITING_REVIEW must NOT pass 900s (it should use the default delay).
This ensures duration_confirm's explicit delay doesn't bleed into other types.
"""
from backend.services import worker_service as ws_module
manager = JobManager()
manager.firestore = Mock()
mock_job = Mock(spec=Job)
mock_job.job_id = "job-lyrics"
mock_job.user_email = "user@example.com"
mock_job.state_data = {}
mock_schedule = AsyncMock(return_value=True)
with patch("backend.services.worker_service.get_worker_service") as mock_get_service:
mock_service = Mock()
mock_service.schedule_idle_reminder = mock_schedule
mock_get_service.return_value = mock_service
manager._schedule_idle_reminder(mock_job, JobStatus.AWAITING_REVIEW)
import time
time.sleep(0.2)
if mock_schedule.called:
call_kwargs = mock_schedule.call_args
delay = (
call_kwargs.kwargs.get("delay_seconds")
if call_kwargs.kwargs
else (call_kwargs.args[1] if len(call_kwargs.args) > 1 else None)
)
# Lyrics uses default (no explicit override) — delay should be
# IDLE_REMINDER_DELAY_SECONDS or None (meaning default is used)
assert delay != 900, (
f"AWAITING_REVIEW must not use the 900s duration_confirm delay, got {delay}"
)
+209
View File
@@ -0,0 +1,209 @@
"""
Tests for duration reconciliation wired into start_job_processing (Task 12).
Covers:
- start_job_processing pauses when reconcile_and_maybe_pause returns True
→ workers are NOT triggered
- start_job_processing proceeds when reconcile_and_maybe_pause returns False
→ both workers ARE triggered
- reconcile is called AFTER input_media_gcs_path is set (upload's exact file)
- reconcile is bypassed for existing_instrumental jobs (they only trigger lyrics worker)
— reconcile is still called but the no-instrumental-present path is covered
"""
from __future__ import annotations
import asyncio
from datetime import datetime, UTC
from unittest.mock import AsyncMock, MagicMock, Mock, patch, call
import pytest
import sys
# Prevent real Firestore/GCS imports from being resolved at module load.
sys.modules.setdefault("google.cloud.firestore", MagicMock())
sys.modules.setdefault("google.cloud.storage", MagicMock())
from backend.models.job import Job, JobStatus
from backend.exceptions import InvalidStateTransitionError
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
NOW = datetime.now(UTC)
def _pending_job(
job_id="upload-job-1",
gcs_path="uploads/upload-job-1/audio/song.flac",
existing_instrumental=None,
):
return Job(
job_id=job_id,
status=JobStatus.PENDING,
created_at=NOW,
updated_at=NOW,
input_media_gcs_path=gcs_path,
existing_instrumental_gcs_path=existing_instrumental,
state_data={"credits_charged": 1},
)
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture()
def mock_firestore():
with patch("backend.services.job_manager.FirestoreService") as cls:
svc = Mock()
# get_job returns a PENDING job with input_media_gcs_path set
svc.get_job.return_value = _pending_job()
cls.return_value = svc
yield svc
@pytest.fixture()
def job_manager(mock_firestore):
from backend.services.job_manager import JobManager
return JobManager()
@pytest.fixture()
def mock_worker_service():
ws = Mock()
ws.trigger_audio_worker = AsyncMock(return_value=True)
ws.trigger_lyrics_worker = AsyncMock(return_value=True)
return ws
# ---------------------------------------------------------------------------
# Tests: reconcile wired into start_job_processing
# ---------------------------------------------------------------------------
class TestStartJobProcessingReconcile:
"""Duration reconciliation is invoked from start_job_processing."""
@pytest.mark.asyncio
async def test_reconcile_called_before_workers(self, job_manager, mock_firestore, mock_worker_service):
"""reconcile_and_maybe_pause is called before triggering workers."""
mock_reconcile = AsyncMock(return_value=False)
with (
patch("backend.services.worker_service.get_worker_service", return_value=mock_worker_service),
patch("backend.services.job_manager.reconcile_and_maybe_pause", mock_reconcile, create=True),
):
await job_manager.start_job_processing("upload-job-1")
mock_reconcile.assert_awaited_once_with("upload-job-1")
@pytest.mark.asyncio
async def test_workers_not_triggered_when_reconcile_pauses(
self, job_manager, mock_firestore, mock_worker_service
):
"""When reconcile_and_maybe_pause returns True, no workers must be started."""
mock_reconcile = AsyncMock(return_value=True)
with (
patch("backend.services.worker_service.get_worker_service", return_value=mock_worker_service),
patch("backend.services.job_manager.reconcile_and_maybe_pause", mock_reconcile, create=True),
):
await job_manager.start_job_processing("upload-job-1")
mock_worker_service.trigger_audio_worker.assert_not_called()
mock_worker_service.trigger_lyrics_worker.assert_not_called()
@pytest.mark.asyncio
async def test_both_workers_triggered_when_reconcile_proceeds(
self, job_manager, mock_firestore, mock_worker_service
):
"""When reconcile_and_maybe_pause returns False, both workers ARE triggered."""
mock_reconcile = AsyncMock(return_value=False)
with (
patch("backend.services.worker_service.get_worker_service", return_value=mock_worker_service),
patch("backend.services.job_manager.reconcile_and_maybe_pause", mock_reconcile, create=True),
):
await job_manager.start_job_processing("upload-job-1")
mock_worker_service.trigger_audio_worker.assert_awaited_once_with("upload-job-1")
mock_worker_service.trigger_lyrics_worker.assert_awaited_once_with("upload-job-1")
@pytest.mark.asyncio
async def test_reconcile_is_called_after_transition_to_downloading(
self, job_manager, mock_firestore, mock_worker_service
):
"""Reconcile must run AFTER the job has transitioned to DOWNLOADING.
input_media_gcs_path is already set by the upload handler before
start_job_processing is called; the job is transitioned to DOWNLOADING
first, then reconcile probes it. This test confirms the ordering by
checking that transition_to_state is called before reconcile.
"""
call_log: list[str] = []
orig_transition = job_manager.transition_to_state
def tracking_transition(*a, **kw):
call_log.append("transition")
return orig_transition(*a, **kw)
async def tracking_reconcile(job_id):
call_log.append("reconcile")
return False
with (
patch("backend.services.worker_service.get_worker_service", return_value=mock_worker_service),
patch("backend.services.job_manager.reconcile_and_maybe_pause", side_effect=tracking_reconcile, create=True),
patch.object(job_manager, "transition_to_state", side_effect=tracking_transition),
):
await job_manager.start_job_processing("upload-job-1")
assert call_log.index("transition") < call_log.index("reconcile"), (
"transition_to_state must precede reconcile_and_maybe_pause; "
f"got order: {call_log}"
)
@pytest.mark.asyncio
async def test_existing_instrumental_job_reconcile_then_lyrics_only(
self, job_manager, mock_firestore, mock_worker_service
):
"""Jobs with existing_instrumental_gcs_path: reconcile is still called,
then only lyrics worker is triggered (audio separation is skipped)."""
mock_firestore.get_job.return_value = _pending_job(
existing_instrumental="uploads/upload-job-1/audio/existing_instrumental.mp3"
)
mock_reconcile = AsyncMock(return_value=False)
with (
patch("backend.services.worker_service.get_worker_service", return_value=mock_worker_service),
patch("backend.services.job_manager.reconcile_and_maybe_pause", mock_reconcile, create=True),
):
await job_manager.start_job_processing("upload-job-1")
# Reconcile must still be called
mock_reconcile.assert_awaited_once_with("upload-job-1")
# Audio worker must NOT be called (separation skipped)
mock_worker_service.trigger_audio_worker.assert_not_called()
# Lyrics worker IS called
mock_worker_service.trigger_lyrics_worker.assert_awaited_once_with("upload-job-1")
@pytest.mark.asyncio
async def test_existing_instrumental_paused_by_reconcile(
self, job_manager, mock_firestore, mock_worker_service
):
"""When reconcile returns True for existing-instrumental job,
even the lyrics worker is NOT triggered."""
mock_firestore.get_job.return_value = _pending_job(
existing_instrumental="uploads/upload-job-1/audio/existing_instrumental.mp3"
)
mock_reconcile = AsyncMock(return_value=True)
with (
patch("backend.services.worker_service.get_worker_service", return_value=mock_worker_service),
patch("backend.services.job_manager.reconcile_and_maybe_pause", mock_reconcile, create=True),
):
await job_manager.start_job_processing("upload-job-1")
mock_worker_service.trigger_audio_worker.assert_not_called()
mock_worker_service.trigger_lyrics_worker.assert_not_called()
@@ -0,0 +1,450 @@
"""
Tests for duration-based credit pricing on URL job creation.
Covers:
- URL create with duration_seconds → charges N credits, stores credits_charged
- duration_seconds over 60 min → 422 (blocked)
- acknowledged_credits mismatch → 409
- default path (no duration_seconds) still charges 1 credit
"""
from __future__ import annotations
import asyncio
from datetime import datetime, UTC
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from backend.models.job import Job, JobStatus
from backend.services.auth_service import UserType, AuthResult
NOW = datetime.now(UTC)
# ---------------------------------------------------------------------------
# Auth fixtures
# ---------------------------------------------------------------------------
@pytest.fixture(autouse=True)
def _ensure_auth_overrides():
"""Ensure auth dependency overrides are set for every test in this file."""
from backend.api.dependencies import require_auth, require_admin
from backend.main import app
async def mock_require_auth():
return AuthResult(
is_valid=True,
user_type=UserType.STRIPE,
remaining_uses=5,
message="Regular test user",
is_admin=False,
user_email="buyer@example.com",
)
app.dependency_overrides[require_auth] = mock_require_auth
app.dependency_overrides[require_admin] = mock_require_auth
yield
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(require_admin, None)
# ---------------------------------------------------------------------------
# Helper: build a minimal Job returned by mock job_manager.create_job
# ---------------------------------------------------------------------------
def _pending_job(job_id="url-job-1", credits_charged=1, user_email="buyer@example.com") -> Job:
return Job(
job_id=job_id,
status=JobStatus.PENDING,
created_at=NOW,
updated_at=NOW,
user_email=user_email,
state_data={"credits_charged": credits_charged},
)
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def mock_job_manager():
jm = MagicMock()
# Default: returns a 1-credit job; individual tests override as needed
jm.create_job.return_value = _pending_job(credits_charged=1)
return jm
@pytest.fixture
def mock_worker_service():
ws = MagicMock()
ws.trigger_audio_worker = AsyncMock(return_value=True)
ws.trigger_lyrics_worker = AsyncMock(return_value=True)
return ws
@pytest.fixture
def mock_theme_service():
ts = MagicMock()
ts.get_default_theme_id.return_value = "nomad"
return ts
@pytest.fixture
def mock_user_service():
us = MagicMock()
us.check_credits.return_value = 10
us.has_credits.return_value = True
return us
@pytest.fixture
def patched_app(mock_job_manager, mock_worker_service, mock_theme_service, mock_user_service):
"""Patch module-level singletons and yield the TestClient."""
from fastapi.testclient import TestClient
from backend.main import app
with (
patch("backend.api.routes.jobs.job_manager", mock_job_manager),
patch("backend.api.routes.jobs.worker_service", mock_worker_service),
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service),
patch("backend.api.routes.jobs.get_user_service", return_value=mock_user_service),
patch("backend.services.firestore_service.FirestoreService.update_job"),
):
yield TestClient(app), mock_job_manager, mock_worker_service, mock_theme_service, mock_user_service
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _post_url_job(client, *, url="https://youtube.com/watch?v=abc", **extra):
body = {"url": url}
body.update(extra)
return client.post("/api/jobs", json=body)
# ---------------------------------------------------------------------------
# Tests: duration-based pricing on URL create
# ---------------------------------------------------------------------------
class TestURLCreatePricing:
"""Duration-based credit pricing on POST /api/jobs."""
def test_905s_with_acknowledged_2_charges_2_credits(self, patched_app):
"""
905 seconds → ceil(905/600) = 2 credits.
User sends acknowledged_credits=2, has ≥2 credits.
Expect: 200, JobCreate called with credits=2,
returned state_data.credits_charged == 2.
"""
client, jm, ws, ts, us = patched_app
# create_job returns a job with credits_charged=2
jm.create_job.return_value = _pending_job(credits_charged=2)
resp = _post_url_job(client, duration_seconds=905, acknowledged_credits=2)
assert resp.status_code == 200, resp.text
# Verify create_job was called with credits=2
jm.create_job.assert_called_once()
call_kwargs = jm.create_job.call_args
job_create_arg = call_kwargs[0][0] if call_kwargs[0] else call_kwargs[1].get("job_create")
assert job_create_arg.credits == 2, (
f"Expected credits=2 in JobCreate, got {job_create_arg.credits}"
)
def test_905s_credits_charged_stored(self, patched_app):
"""state_data.credits_charged on the returned job should equal 2."""
client, jm, ws, ts, us = patched_app
jm.create_job.return_value = _pending_job(credits_charged=2)
resp = _post_url_job(client, duration_seconds=905, acknowledged_credits=2)
assert resp.status_code == 200, resp.text
# The route returns a JobResponse (job_id, status, message) but we can
# confirm the job_manager was called correctly (credits_charged lives in Job.state_data
# which is set by create_job implementation).
body = resp.json()
assert "job_id" in body
def test_4000s_blocked_returns_422(self, patched_app):
"""
4000 seconds > 3600 → is_blocked() = True → 422 before job is created.
"""
client, jm, ws, ts, us = patched_app
resp = _post_url_job(client, duration_seconds=4000)
assert resp.status_code == 422, resp.text
# Job must NOT be created
jm.create_job.assert_not_called()
def test_3600s_exactly_is_blocked_returns_422(self, patched_app):
"""
3600 seconds is NOT blocked (> not >=), should succeed.
Actually: is_blocked checks > 3600, so exactly 3600 is NOT blocked.
"""
from backend.services.pricing import is_blocked
assert not is_blocked(3600), "3600s should not be blocked (ceiling is >3600)"
client, jm, ws, ts, us = patched_app
jm.create_job.return_value = _pending_job(credits_charged=6)
resp = _post_url_job(client, duration_seconds=3600, acknowledged_credits=6)
# 3600s = ceil(3600/600) = 6 credits, not blocked → success
assert resp.status_code == 200, resp.text
def test_3601s_blocked_returns_422(self, patched_app):
"""3601 seconds > 3600 → blocked."""
client, jm, ws, ts, us = patched_app
resp = _post_url_job(client, duration_seconds=3601)
assert resp.status_code == 422, resp.text
jm.create_job.assert_not_called()
def test_acknowledged_credits_mismatch_returns_409(self, patched_app):
"""
duration_seconds=905 → credits=2, but acknowledged_credits=1 → 409.
"""
client, jm, ws, ts, us = patched_app
resp = _post_url_job(client, duration_seconds=905, acknowledged_credits=1)
assert resp.status_code == 409, resp.text
# Job must NOT be created when acknowledged_credits mismatches
jm.create_job.assert_not_called()
def test_no_duration_charges_1_credit(self, patched_app):
"""
When duration_seconds is not provided, fall back to credits=1 (unchanged behaviour).
"""
client, jm, ws, ts, us = patched_app
jm.create_job.return_value = _pending_job(credits_charged=1)
resp = _post_url_job(client)
assert resp.status_code == 200, resp.text
jm.create_job.assert_called_once()
call_kwargs = jm.create_job.call_args
job_create_arg = call_kwargs[0][0] if call_kwargs[0] else call_kwargs[1].get("job_create")
assert job_create_arg.credits == 1, (
f"No duration → credits should default to 1, got {job_create_arg.credits}"
)
def test_duration_estimate_stored_on_job(self, patched_app):
"""
When duration_seconds is provided, the handler must call FirestoreService.update_job
with state_data.duration_estimate_seconds and state_data.duration_estimate_source.
"""
from unittest.mock import patch as _patch
client, jm, ws, ts, us = patched_app
jm.create_job.return_value = _pending_job(credits_charged=2)
with _patch("backend.services.firestore_service.FirestoreService.update_job") as mock_update:
resp = _post_url_job(client, duration_seconds=905, acknowledged_credits=2)
assert resp.status_code == 200, resp.text
# update_job must have been called at least once
assert mock_update.called, "FirestoreService.update_job was never called"
# Collect every update_payload passed across all calls
all_payloads: dict = {}
for call in mock_update.call_args_list:
# call[0] = positional args: (job_id, payload)
payload = call[0][1] if len(call[0]) >= 2 else call[1].get("updates", {})
all_payloads.update(payload)
assert all_payloads.get("state_data.duration_estimate_seconds") == 905, (
f"Expected state_data.duration_estimate_seconds=905 in update_job payload, "
f"got: {all_payloads}"
)
assert all_payloads.get("state_data.duration_estimate_source") == "youtube_metadata", (
f"Expected state_data.duration_estimate_source='youtube_metadata' in update_job payload, "
f"got: {all_payloads}"
)
def test_no_duration_duration_estimate_source_unknown(self, patched_app):
"""Without duration_seconds, duration_estimate_source defaults to 'unknown'."""
client, jm, ws, ts, us = patched_app
jm.create_job.return_value = _pending_job(credits_charged=1)
resp = _post_url_job(client)
assert resp.status_code == 200, resp.text
# ---------------------------------------------------------------------------
# Tests: create_job generalisation (Part A) via JobManager directly
# ---------------------------------------------------------------------------
class TestJobManagerCreditsParam:
"""
Unit tests for JobManager.create_job with configurable credits.
Tests the Part A changes without going through the HTTP layer.
"""
@pytest.fixture
def mock_fs(self):
with patch("backend.services.job_manager.FirestoreService") as cls:
svc = MagicMock()
cls.return_value = svc
yield svc
@pytest.fixture
def mock_storage(self):
with patch("backend.services.job_manager.StorageService") as cls:
svc = MagicMock()
cls.return_value = svc
yield svc
@pytest.fixture
def mock_us(self):
svc = MagicMock()
with patch("backend.services.user_service.get_user_service", return_value=svc):
yield svc
def _jm(self, mock_fs, mock_storage):
from backend.services.job_manager import JobManager
return JobManager()
def test_default_credits_is_1(self, mock_fs, mock_storage, mock_us):
"""JobCreate.credits defaults to 1."""
from backend.models.job import JobCreate
jc = JobCreate(theme_id="nomad")
assert jc.credits == 1
def test_explicit_credits_stored(self, mock_fs, mock_storage, mock_us):
"""JobCreate.credits=3 is accepted."""
from backend.models.job import JobCreate
jc = JobCreate(theme_id="nomad", credits=3)
assert jc.credits == 3
def test_create_job_no_email_skips_credit_check(self, mock_fs, mock_storage, mock_us):
"""Jobs with no user_email skip credit gate (unchanged behaviour)."""
from backend.services.job_manager import JobManager
from backend.models.job import JobCreate
jm = JobManager()
job = jm.create_job(JobCreate(theme_id="nomad"), is_admin=False)
assert job is not None
mock_us.has_credits.assert_not_called()
mock_us.deduct_credits.assert_not_called()
def test_admin_bypasses_credit_check(self, mock_fs, mock_storage, mock_us):
"""Admin bypass unchanged for any credits value."""
from backend.services.job_manager import JobManager
from backend.models.job import JobCreate
jm = JobManager()
job = jm.create_job(
JobCreate(theme_id="nomad", user_email="admin@test.com", credits=5),
is_admin=True,
)
assert job is not None
mock_us.has_credits.assert_not_called()
mock_us.deduct_credits.assert_not_called()
def test_has_credits_gate_uses_credits_param(self, mock_fs, mock_storage, mock_us):
"""has_credits gate should check the user has >= credits, not just >= 1."""
from backend.services.job_manager import JobManager
from backend.models.job import JobCreate
from backend.exceptions import InsufficientCreditsError
mock_us.has_credits.return_value = False
mock_us.check_credits.return_value = 1 # only 1 credit, need 3
jm = JobManager()
with pytest.raises(InsufficientCreditsError) as exc_info:
jm.create_job(
JobCreate(theme_id="nomad", user_email="user@test.com", credits=3),
is_admin=False,
)
# credits_required should match what we asked for
assert exc_info.value.credits_required == 3
def test_deduct_credits_called_with_n(self, mock_fs, mock_storage, mock_us):
"""deduct_credits is called with amount=credits (not always 1)."""
from backend.services.job_manager import JobManager
from backend.models.job import JobCreate
mock_us.has_credits.return_value = True
mock_us.check_credits.return_value = 5
mock_us.deduct_credits.return_value = (True, 3, "Deducted 2. 3 remaining")
jm = JobManager()
jm.create_job(
JobCreate(theme_id="nomad", user_email="user@test.com", credits=2),
is_admin=False,
)
mock_us.deduct_credits.assert_called_once()
call_args, call_kwargs = mock_us.deduct_credits.call_args
amount = call_kwargs.get("amount", call_args[2] if len(call_args) > 2 else None)
assert amount == 2, f"Expected deduct_credits(amount=2), got amount={amount}"
def test_deduct_credits_default_is_1(self, mock_fs, mock_storage, mock_us):
"""Default path (credits=1) still deducts exactly 1 credit."""
from backend.services.job_manager import JobManager
from backend.models.job import JobCreate
mock_us.has_credits.return_value = True
mock_us.check_credits.return_value = 5
mock_us.deduct_credits.return_value = (True, 4, "Deducted 1. 4 remaining")
jm = JobManager()
jm.create_job(
JobCreate(theme_id="nomad", user_email="user@test.com"),
is_admin=False,
)
mock_us.deduct_credits.assert_called_once()
call_args, call_kwargs = mock_us.deduct_credits.call_args
amount = call_kwargs.get("amount", call_args[2] if len(call_args) > 2 else None)
assert amount == 1, f"Default path must deduct 1 credit, got amount={amount}"
def test_credits_charged_in_state_data(self, mock_fs, mock_storage, mock_us):
"""state_data.credits_charged should equal credits on the created job."""
from backend.services.job_manager import JobManager
from backend.models.job import JobCreate
mock_us.has_credits.return_value = True
mock_us.check_credits.return_value = 10
mock_us.deduct_credits.return_value = (True, 7, "Deducted 3. 7 remaining")
jm = JobManager()
job = jm.create_job(
JobCreate(theme_id="nomad", user_email="user@test.com", credits=3),
is_admin=False,
)
assert job.state_data.get("credits_charged") == 3, (
f"state_data.credits_charged should be 3, got {job.state_data}"
)
def test_rollback_on_deduction_failure(self, mock_fs, mock_storage, mock_us):
"""If deduct_credits fails, job is deleted and InsufficientCreditsError raised."""
from backend.services.job_manager import JobManager
from backend.models.job import JobCreate
from backend.exceptions import InsufficientCreditsError
mock_us.has_credits.return_value = True
mock_us.check_credits.return_value = 5
mock_us.deduct_credits.return_value = (False, 0, "Race condition")
jm = JobManager()
with pytest.raises(InsufficientCreditsError):
jm.create_job(
JobCreate(theme_id="nomad", user_email="user@test.com", credits=2),
is_admin=False,
)
mock_fs.create_job.assert_called_once()
mock_fs.delete_job.assert_called_once()
@@ -0,0 +1,617 @@
"""
Integration tests for the duration-pricing reconcile flow.
Tests the end-to-end path through:
1. reconcile_duration (engine) pausing a job at AWAITING_DURATION_CONFIRM
2. POST /api/jobs/{id}/confirm-duration resuming the job and deducting credits
Money-critical: the delta-deduction math (started at 2 credits, ended at 4,
EXACTLY 2 deducted on confirm — not 4, not the full cost again) is the primary
invariant under test.
Also includes a companion DOWN-reconcile assertion (refund path, no pause).
Harness notes
-------------
- Follows the mocking pattern from backend/tests/integration/test_state_machine_flow.py
and test_youtube_flow.py: no Firestore emulator, mocked collaborators.
- The confirm-duration endpoint is exercised via FastAPI's TestClient.
- Worker triggers are patched so no real Cloud Run jobs fire.
"""
import pytest
from datetime import datetime, UTC
from unittest.mock import MagicMock, AsyncMock, Mock, patch, call
# Mock google.cloud.firestore before any module that imports it is loaded.
import sys
sys.modules.setdefault('google.cloud.firestore', MagicMock())
sys.modules.setdefault('google.cloud.storage', MagicMock())
from backend.models.job import Job, JobStatus
from backend.services.duration_reconciliation import reconcile_duration, ReconcileResult
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_job(
job_id: str = "dur-test-001",
status: JobStatus = JobStatus.DOWNLOADING,
credits_charged: int = 2,
user_email: str = "user@example.com",
input_media_gcs_path: str = "gs://bucket/jobs/dur-test-001/audio.flac",
extra_state_data: dict = None,
) -> Job:
"""Build a Job instance with the given fields."""
state_data = {"credits_charged": credits_charged}
if extra_state_data:
state_data.update(extra_state_data)
return Job(
job_id=job_id,
artist="Test Artist",
title="Test Song",
status=status,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
input_media_gcs_path=input_media_gcs_path,
state_data=state_data,
user_email=user_email,
)
def _make_mock_job_manager(job: Job) -> MagicMock:
"""Return a JobManager mock whose get_job always returns `job`."""
mgr = MagicMock()
mgr.get_job.return_value = job
mgr.update_job.return_value = None
mgr.transition_to_state.return_value = True
return mgr
def _make_mock_user_service() -> MagicMock:
"""Return a UserService mock with sensible defaults."""
svc = MagicMock()
# deduct_credits returns (success, remaining, message)
svc.deduct_credits.return_value = (True, 8, "2 credits deducted")
# add_credits returns (success, new_balance, message)
svc.add_credits.return_value = (True, 10, "Credits added")
return svc
# ---------------------------------------------------------------------------
# Part A.1 — Reconcile-UP path (engine only)
# ---------------------------------------------------------------------------
class TestReconcileUpEngine:
"""
Engine-level: reconcile_duration produces the correct pause result when
actual duration (2100 s) exceeds what was charged (2 credits at ~15 min).
"""
def test_reconcile_up_pauses_job_at_awaiting_duration_confirm(self):
"""
Given: credits_charged=2, actual=2100 s → required=4, delta=2
Expect: action="pause", pending_additional_credits=2,
job transitioned to AWAITING_DURATION_CONFIRM,
state_data updated with reason="reconcile" and delta=2.
"""
job_id = "dur-test-up-001"
job = _make_job(job_id=job_id, credits_charged=2)
mgr = _make_mock_job_manager(job)
svc = _make_mock_user_service()
result = reconcile_duration(
job_id=job_id,
job_manager=mgr,
user_service=svc,
probe_duration=lambda _job: 2100.0, # ~35 min → 4 credits
)
assert result.action == "pause"
assert result.pending_additional_credits == 2
assert result.actual_seconds == 2100.0
# transition_to_state called with AWAITING_DURATION_CONFIRM
mgr.transition_to_state.assert_called_once()
transition_call = mgr.transition_to_state.call_args
# Engine calls with keyword args: transition_to_state(job_id=..., new_status=..., ...)
new_status = (
transition_call.kwargs.get("new_status")
or (transition_call.args[1] if len(transition_call.args) >= 2 else None)
)
assert new_status == JobStatus.AWAITING_DURATION_CONFIRM, (
f"Expected AWAITING_DURATION_CONFIRM, got {new_status}"
)
# update_job called with duration_confirm_reason and delta
update_calls_flat = {}
for c in mgr.update_job.call_args_list:
if c.args and len(c.args) >= 2 and isinstance(c.args[1], dict):
update_calls_flat.update(c.args[1])
elif c.kwargs.get("updates"):
update_calls_flat.update(c.kwargs["updates"])
assert update_calls_flat.get("state_data.duration_confirm_reason") == "reconcile"
assert update_calls_flat.get("state_data.pending_additional_credits") == 2
# No credits deducted by the engine (deduction happens at confirm time)
svc.deduct_credits.assert_not_called()
def test_reconcile_up_does_not_trigger_workers(self):
"""Engine must NOT trigger workers when pausing — workers are triggered by confirm."""
job_id = "dur-test-up-002"
job = _make_job(job_id=job_id, credits_charged=2)
mgr = _make_mock_job_manager(job)
svc = _make_mock_user_service()
# No worker_service attribute on job_manager — engine should not call it
assert not hasattr(mgr, "trigger_audio_worker") or True # safe to check
reconcile_duration(
job_id=job_id,
job_manager=mgr,
user_service=svc,
probe_duration=lambda _job: 2100.0,
)
# Verify no worker-like calls were made on job_manager
called_methods = [str(c) for c in mgr.mock_calls]
assert not any("trigger" in m for m in called_methods), (
f"Engine should not trigger workers; calls: {called_methods}"
)
# ---------------------------------------------------------------------------
# Part A.2 — Reconcile-DOWN path (engine + user_service.add_credits)
# ---------------------------------------------------------------------------
class TestReconcileDownEngine:
"""
Engine-level: when actual duration (600 s) is less than what was charged
(4 credits), the engine auto-refunds the delta and returns action="proceed".
"""
def test_reconcile_down_refunds_delta_and_proceeds(self):
"""
Given: credits_charged=4, actual=600 s → required=1, delta=-3
Expect: action="proceed", add_credits called with amount=3,
reason="duration_refund", credits_charged updated to 1.
No pause. No transition to AWAITING_DURATION_CONFIRM.
"""
job_id = "dur-test-down-001"
job = _make_job(job_id=job_id, credits_charged=4)
mgr = _make_mock_job_manager(job)
svc = _make_mock_user_service()
result = reconcile_duration(
job_id=job_id,
job_manager=mgr,
user_service=svc,
probe_duration=lambda _job: 600.0, # 10 min → 1 credit
)
assert result.action == "proceed"
assert result.actual_seconds == 600.0
# add_credits called with correct amount and reason
svc.add_credits.assert_called_once_with(
job.user_email,
amount=3,
reason="duration_refund",
job_id=job_id,
)
# credits_charged updated to the new (lower) required amount
refund_update_found = any(
(c.args[1] if (c.args and len(c.args) >= 2 and isinstance(c.args[1], dict))
else c.kwargs.get("updates", {})).get("state_data.credits_charged") == 1
for c in mgr.update_job.call_args_list
)
assert refund_update_found, (
"Expected update_job to set credits_charged=1 after refund. "
f"Actual update_job calls: {mgr.update_job.call_args_list}"
)
# No pause
for c in mgr.transition_to_state.call_args_list:
status = c.args[1] if len(c.args) >= 2 else c.kwargs.get("new_status")
assert status != JobStatus.AWAITING_DURATION_CONFIRM, (
"Reconcile-DOWN must NOT pause at AWAITING_DURATION_CONFIRM"
)
# ---------------------------------------------------------------------------
# Part A.3 — Full reconcile-UP + confirm-duration end-to-end via TestClient
# ---------------------------------------------------------------------------
class TestReconcileUpEndToEnd:
"""
End-to-end: drive the reconcile engine directly (with mocked collaborators)
to produce the paused state, then call the real confirm-duration endpoint
via FastAPI TestClient and verify all credit-math invariants.
"""
@pytest.fixture
def mock_creds(self):
creds = MagicMock()
creds.universe_domain = "googleapis.com"
creds.token = "fake-token"
creds.valid = True
return creds
@pytest.fixture
def test_setup(self, mock_creds):
"""
Build a stable Job fixture that reflects the paused state produced by
reconcile_duration, then wire it into a TestClient with patched
job_manager, user_service, and worker_service.
The fixture simulates exactly the state that reconcile_duration would
write to Firestore:
- status = AWAITING_DURATION_CONFIRM
- state_data.credits_charged = 2
- state_data.pending_additional_credits = 2
- state_data.duration_confirm_reason = "reconcile"
"""
job_id = "dur-test-e2e-001"
user_email = "user@example.com"
# "Paused" job: the state reconcile_duration leaves behind
paused_job = _make_job(
job_id=job_id,
status=JobStatus.AWAITING_DURATION_CONFIRM,
credits_charged=2,
user_email=user_email,
extra_state_data={
"pending_additional_credits": 2,
"duration_confirm_reason": "reconcile",
},
)
# "Resumed" job: what get_job returns AFTER confirm (post-transition)
resumed_job = _make_job(
job_id=job_id,
status=JobStatus.SEPARATING_STAGE1,
credits_charged=4,
user_email=user_email,
extra_state_data={
"pending_additional_credits": 0,
"duration_confirm_reason": "reconcile",
"duration_confirmed": True,
},
)
mock_jm = MagicMock()
# First call returns the paused job; subsequent calls return the resumed one
mock_jm.get_job.side_effect = [paused_job, resumed_job]
mock_jm.update_job.return_value = None
mock_jm.transition_to_state.return_value = True
mock_us = MagicMock()
# User has 10 credits; deduct 2 → 8 remaining
mock_us.deduct_credits.return_value = (True, 8, "2 credits deducted")
mock_ws = MagicMock()
mock_ws.trigger_audio_worker = AsyncMock(return_value=True)
mock_ws.trigger_lyrics_worker = AsyncMock(return_value=True)
yield {
"job_id": job_id,
"user_email": user_email,
"paused_job": paused_job,
"resumed_job": resumed_job,
"mock_jm": mock_jm,
"mock_us": mock_us,
"mock_ws": mock_ws,
}
def _make_client(self, setup, mock_creds):
"""Return a TestClient with all necessary patches applied."""
from fastapi.testclient import TestClient
from backend.main import app
patches = [
patch("backend.api.routes.jobs.job_manager", setup["mock_jm"]),
patch("backend.api.routes.jobs.worker_service", setup["mock_ws"]),
patch("backend.api.routes.jobs.get_user_service", return_value=setup["mock_us"]),
patch("google.auth.default", return_value=(mock_creds, "test-project")),
]
return patches, TestClient(app)
def test_confirm_duration_returns_200_with_sufficient_credits(self, test_setup, mock_creds):
"""
POST /api/jobs/{id}/confirm-duration with acknowledged_credits=4 and a
user who has sufficient balance must return 200.
"""
setup = test_setup
patches = [
patch("backend.api.routes.jobs.job_manager", setup["mock_jm"]),
patch("backend.api.routes.jobs.worker_service", setup["mock_ws"]),
patch("backend.api.routes.jobs.get_user_service", return_value=setup["mock_us"]),
patch("google.auth.default", return_value=(mock_creds, "test-project")),
]
from fastapi.testclient import TestClient
from backend.main import app
with patches[0], patches[1], patches[2], patches[3]:
client = TestClient(app)
response = client.post(
f"/api/jobs/{setup['job_id']}/confirm-duration",
json={"acknowledged_credits": 4},
headers={"Authorization": "Bearer test-admin-token"},
)
assert response.status_code == 200, (
f"Expected 200, got {response.status_code}: {response.text}"
)
def test_confirm_duration_deducts_exactly_the_delta(self, test_setup, mock_creds):
"""
MONEY MATH: Only the delta (2 credits) must be deducted — not the full
cost (4) and not the original charge (2) again.
History: job created with credits_charged=2 (original deduction at job-create).
Reconcile found delta=2 more owed.
Confirm should deduct exactly 2 with count_as_job_creation=False.
"""
setup = test_setup
patches = [
patch("backend.api.routes.jobs.job_manager", setup["mock_jm"]),
patch("backend.api.routes.jobs.worker_service", setup["mock_ws"]),
patch("backend.api.routes.jobs.get_user_service", return_value=setup["mock_us"]),
patch("google.auth.default", return_value=(mock_creds, "test-project")),
]
from fastapi.testclient import TestClient
from backend.main import app
with patches[0], patches[1], patches[2], patches[3]:
client = TestClient(app)
client.post(
f"/api/jobs/{setup['job_id']}/confirm-duration",
json={"acknowledged_credits": 4},
headers={"Authorization": "Bearer test-admin-token"},
)
setup["mock_us"].deduct_credits.assert_called_once()
call_kwargs = setup["mock_us"].deduct_credits.call_args
# Extract positional and keyword args
args = call_kwargs.args
kwargs = call_kwargs.kwargs
# user_email is first positional arg, job_id is second
called_email = args[0] if args else kwargs.get("email", kwargs.get("user_email"))
called_job_id = args[1] if len(args) > 1 else kwargs.get("job_id")
called_amount = kwargs.get("amount", args[2] if len(args) > 2 else None)
called_reason = kwargs.get("reason", args[3] if len(args) > 3 else None)
called_count_as_creation = kwargs.get("count_as_job_creation")
assert called_email == setup["user_email"], (
f"Expected email={setup['user_email']}, got {called_email}"
)
assert called_job_id == setup["job_id"], (
f"Expected job_id={setup['job_id']}, got {called_job_id}"
)
assert called_amount == 2, (
f"MONEY BUG: Expected deduct_credits(amount=2) for the delta, "
f"but got amount={called_amount}. "
"The confirm endpoint must deduct only the delta (pending_additional_credits), "
"not the full cost or the original charge again."
)
assert called_reason == "duration_confirm", (
f"Expected reason='duration_confirm', got {called_reason}"
)
assert called_count_as_creation is False, (
"count_as_job_creation must be False for a delta top-up "
f"(job was already counted at create_job). Got: {called_count_as_creation}"
)
def test_confirm_duration_updates_credits_charged_to_total(self, test_setup, mock_creds):
"""
After confirm, state_data.credits_charged must be updated to 4
(2 original + 2 delta), not left at 2.
"""
setup = test_setup
patches = [
patch("backend.api.routes.jobs.job_manager", setup["mock_jm"]),
patch("backend.api.routes.jobs.worker_service", setup["mock_ws"]),
patch("backend.api.routes.jobs.get_user_service", return_value=setup["mock_us"]),
patch("google.auth.default", return_value=(mock_creds, "test-project")),
]
from fastapi.testclient import TestClient
from backend.main import app
with patches[0], patches[1], patches[2], patches[3]:
client = TestClient(app)
client.post(
f"/api/jobs/{setup['job_id']}/confirm-duration",
json={"acknowledged_credits": 4},
headers={"Authorization": "Bearer test-admin-token"},
)
# Collect all update_job calls and check credits_charged was set to 4
all_updates = {}
for c in setup["mock_jm"].update_job.call_args_list:
updates_arg = c.args[1] if (c.args and len(c.args) >= 2) else c.kwargs.get("updates", {})
if isinstance(updates_arg, dict):
all_updates.update(updates_arg)
assert all_updates.get("state_data.credits_charged") == 4, (
f"Expected credits_charged=4 in update_job call. "
f"Actual updates written: {all_updates}"
)
assert all_updates.get("state_data.pending_additional_credits") == 0, (
"Expected pending_additional_credits=0 after confirm"
)
def test_confirm_duration_transitions_to_separating_stage1(self, test_setup, mock_creds):
"""
The job must be transitioned OUT of AWAITING_DURATION_CONFIRM to
SEPARATING_STAGE1 before workers are triggered.
"""
setup = test_setup
patches = [
patch("backend.api.routes.jobs.job_manager", setup["mock_jm"]),
patch("backend.api.routes.jobs.worker_service", setup["mock_ws"]),
patch("backend.api.routes.jobs.get_user_service", return_value=setup["mock_us"]),
patch("google.auth.default", return_value=(mock_creds, "test-project")),
]
from fastapi.testclient import TestClient
from backend.main import app
with patches[0], patches[1], patches[2], patches[3]:
client = TestClient(app)
client.post(
f"/api/jobs/{setup['job_id']}/confirm-duration",
json={"acknowledged_credits": 4},
headers={"Authorization": "Bearer test-admin-token"},
)
setup["mock_jm"].transition_to_state.assert_called()
call_args = setup["mock_jm"].transition_to_state.call_args
new_status = (
call_args.args[1]
if (call_args.args and len(call_args.args) >= 2)
else call_args.kwargs.get("new_status")
)
assert new_status == JobStatus.SEPARATING_STAGE1, (
f"Expected transition to SEPARATING_STAGE1, got {new_status}"
)
def test_confirm_duration_wrong_acknowledged_credits_returns_409(self, test_setup, mock_creds):
"""
If acknowledged_credits does not match expected_total (credits_charged + owed),
the endpoint must return 409 (stale client; frontend should refresh).
"""
setup = test_setup
# Reset side_effect so get_job always returns paused_job for this test
setup["mock_jm"].get_job.side_effect = None
setup["mock_jm"].get_job.return_value = setup["paused_job"]
patches = [
patch("backend.api.routes.jobs.job_manager", setup["mock_jm"]),
patch("backend.api.routes.jobs.worker_service", setup["mock_ws"]),
patch("backend.api.routes.jobs.get_user_service", return_value=setup["mock_us"]),
patch("google.auth.default", return_value=(mock_creds, "test-project")),
]
from fastapi.testclient import TestClient
from backend.main import app
with patches[0], patches[1], patches[2], patches[3]:
client = TestClient(app)
response = client.post(
f"/api/jobs/{setup['job_id']}/confirm-duration",
json={"acknowledged_credits": 3}, # wrong — expected 4
headers={"Authorization": "Bearer test-admin-token"},
)
assert response.status_code == 409, (
f"Expected 409 for mismatched acknowledged_credits, got {response.status_code}: {response.text}"
)
# No deduction must happen on a 409
setup["mock_us"].deduct_credits.assert_not_called()
def test_confirm_duration_insufficient_credits_returns_402(self, test_setup, mock_creds):
"""
If deduct_credits fails (user is broke), the endpoint must return 402.
No state changes should persist (no transition, job stays paused).
"""
setup = test_setup
setup["mock_jm"].get_job.side_effect = None
setup["mock_jm"].get_job.return_value = setup["paused_job"]
# Simulate insufficient credits
setup["mock_us"].deduct_credits.return_value = (False, 0, "Insufficient credits")
patches = [
patch("backend.api.routes.jobs.job_manager", setup["mock_jm"]),
patch("backend.api.routes.jobs.worker_service", setup["mock_ws"]),
patch("backend.api.routes.jobs.get_user_service", return_value=setup["mock_us"]),
patch("google.auth.default", return_value=(mock_creds, "test-project")),
]
from fastapi.testclient import TestClient
from backend.main import app
with patches[0], patches[1], patches[2], patches[3]:
client = TestClient(app)
response = client.post(
f"/api/jobs/{setup['job_id']}/confirm-duration",
json={"acknowledged_credits": 4},
headers={"Authorization": "Bearer test-admin-token"},
)
assert response.status_code == 402, (
f"Expected 402 for insufficient credits, got {response.status_code}: {response.text}"
)
# Job must NOT be transitioned when user can't pay
setup["mock_jm"].transition_to_state.assert_not_called()
def test_confirm_duration_full_credit_math_invariant(self, test_setup, mock_creds):
"""
FULL CREDIT MATH end-to-end invariant:
- Start: credits_charged=2 (at job creation time, original deduction=2)
- Reconcile: actual=2100s → required=4 → delta=2 (no deduction yet, just pause)
- Confirm: exactly 2 more credits deducted; credits_charged updated to 4
- Total lifetime deduction from account: 2 (at create) + 2 (at confirm) = 4
- Not 4 + anything, not 2 again — exactly the delta
"""
setup = test_setup
patches = [
patch("backend.api.routes.jobs.job_manager", setup["mock_jm"]),
patch("backend.api.routes.jobs.worker_service", setup["mock_ws"]),
patch("backend.api.routes.jobs.get_user_service", return_value=setup["mock_us"]),
patch("google.auth.default", return_value=(mock_creds, "test-project")),
]
from fastapi.testclient import TestClient
from backend.main import app
# Phase 1: simulate reconcile_duration (engine side, mocked collaborators)
engine_jm = _make_mock_job_manager(
_make_job(job_id=setup["job_id"], credits_charged=2)
)
engine_us = _make_mock_user_service()
engine_result = reconcile_duration(
job_id=setup["job_id"],
job_manager=engine_jm,
user_service=engine_us,
probe_duration=lambda _j: 2100.0,
)
# Verify engine produced the correct pause signal
assert engine_result.action == "pause"
assert engine_result.pending_additional_credits == 2
engine_us.deduct_credits.assert_not_called() # engine must NOT deduct
# Phase 2: hit the confirm endpoint
with patches[0], patches[1], patches[2], patches[3]:
client = TestClient(app)
response = client.post(
f"/api/jobs/{setup['job_id']}/confirm-duration",
json={"acknowledged_credits": 4},
headers={"Authorization": "Bearer test-admin-token"},
)
assert response.status_code == 200
# The confirm endpoint must have deducted exactly the delta
setup["mock_us"].deduct_credits.assert_called_once()
deduct_call = setup["mock_us"].deduct_credits.call_args
deducted = deduct_call.kwargs.get("amount", deduct_call.args[2] if len(deduct_call.args) > 2 else None)
assert deducted == 2, (
f"CREDIT MATH INVARIANT FAILED: deduct_credits called with amount={deducted}, "
"expected 2 (the delta only). "
"Total lifetime cost must be original_2 + delta_2 = 4, not more."
)
# credits_charged in state_data must end at 4
all_updates = {}
for c in setup["mock_jm"].update_job.call_args_list:
upd = (c.args[1] if (c.args and len(c.args) >= 2) else c.kwargs.get("updates", {}))
if isinstance(upd, dict):
all_updates.update(upd)
assert all_updates.get("state_data.credits_charged") == 4
+21 -22
View File
@@ -241,10 +241,10 @@ class TestYouTubeDownloadErrorHandling:
assert "Remote download failed" in str(exc.value)
@pytest.mark.asyncio
async def test_invalid_youtube_url_raises_clear_error(self):
async def test_download_without_flacfetch_raises_clear_error(self):
"""
When given an invalid YouTube URL (no video ID extractable),
should raise a clear error.
With no flacfetch configured, download must fail clearly (no local
yt-dlp fallback on Cloud Run).
"""
from backend.services.youtube_download_service import (
YouTubeDownloadService,
@@ -261,11 +261,11 @@ class TestYouTubeDownloadErrorHandling:
with pytest.raises(YouTubeDownloadError) as exc:
await service.download(
url="not-a-valid-youtube-url",
url="https://youtu.be/abcDEF12345",
job_id="job123",
)
assert "Could not extract video ID" in str(exc.value)
assert "flacfetch" in str(exc.value).lower()
class TestRemoteVsLocalDownload:
@@ -306,13 +306,20 @@ class TestRemoteVsLocalDownload:
assert "uploads/job_test/audio/" in result
@pytest.mark.asyncio
async def test_local_download_when_remote_not_configured(self):
async def test_non_youtube_url_uses_generic_url_source(self):
"""
When FLACFETCH_API_URL is not configured, should fall back to local.
A non-YouTube URL is routed through flacfetch's generic 'URL' source.
"""
mock_client = MagicMock()
mock_client.download_by_id = AsyncMock(return_value="download_123")
mock_client.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://bucket/uploads/job_test/audio/test.m4a",
})
with patch(
'backend.services.youtube_download_service.get_flacfetch_client',
return_value=None # No remote client
return_value=mock_client
):
from backend.services.youtube_download_service import (
YouTubeDownloadService,
@@ -321,18 +328,10 @@ class TestRemoteVsLocalDownload:
reset_youtube_download_service()
service = YouTubeDownloadService()
assert service.is_remote_enabled() is False
sc_url = "https://soundcloud.com/forss/flickermood"
result = await service.download(url=sc_url, job_id="job_test")
# Mock the local download to avoid actually calling yt_dlp
with patch.object(
service, '_download_local',
new_callable=AsyncMock,
return_value="uploads/job/audio/test.wav"
) as mock_local:
result = await service.download(
url="https://youtu.be/abcDEF12345",
job_id="job_test",
)
mock_local.assert_called_once()
assert result == "uploads/job/audio/test.wav"
call_kwargs = mock_client.download_by_id.call_args.kwargs
assert call_kwargs["source_name"] == "URL"
assert call_kwargs["download_url"] == sc_url
assert "uploads/job_test/audio/" in result
@@ -0,0 +1,260 @@
import pytest
from unittest.mock import MagicMock, call
from backend.services.duration_reconciliation import reconcile_duration, ReconcileResult
def _job(credits_charged=2, gcs="gs://b/audio.flac", email="u@test.com", payment_bypassed=False):
job = MagicMock()
job.id = "job1"
job.user_email = email
job.artist = "Test Artist"
job.title = "Test Song"
job.input_media_gcs_path = gcs
state = {"credits_charged": credits_charged}
if payment_bypassed:
state["payment_bypassed"] = True
job.state_data = state
return job
def _ctx(actual_seconds, credits_charged=2):
job_manager = MagicMock()
job_manager.get_job.return_value = _job(credits_charged=credits_charged)
user_service = MagicMock()
user_service.add_credits.return_value = (True, 99, "ok")
user_service.deduct_credits.return_value = (True, 1, "ok")
probe = MagicMock(return_value=actual_seconds)
return job_manager, user_service, probe
def test_equal_proceeds():
jm, us, probe = _ctx(actual_seconds=900, credits_charged=2) # 15min -> 2 credits
result = reconcile_duration("job1", jm, us, probe)
assert result.action == "proceed"
us.add_credits.assert_not_called()
us.deduct_credits.assert_not_called()
def test_shorter_auto_refunds_and_proceeds():
jm, us, probe = _ctx(actual_seconds=300, credits_charged=2) # 5min -> 1 credit, refund 1
result = reconcile_duration("job1", jm, us, probe)
assert result.action == "proceed"
us.add_credits.assert_called_once()
_, kwargs = us.add_credits.call_args
assert kwargs.get("amount") == 1
assert "refund" in (kwargs.get("reason", "") or "")
def test_longer_pauses_for_reconfirm():
jm, us, probe = _ctx(actual_seconds=1800, credits_charged=2) # 30min -> 3 credits, +1 owed
result = reconcile_duration("job1", jm, us, probe)
assert result.action == "pause"
assert result.pending_additional_credits == 1
jm.transition_to_state.assert_called_once()
us.deduct_credits.assert_not_called()
def test_over_limit_refunds_all_and_cancels():
jm, us, probe = _ctx(actual_seconds=4000, credits_charged=2) # >60min
# Track call order via a parent mock
parent = MagicMock()
parent.attach_mock(jm.update_job, "update_job")
parent.attach_mock(jm.cancel_job, "cancel_job")
result = reconcile_duration("job1", jm, us, probe)
assert result.action == "cancel"
# Full refund called exactly once with the right amount
us.add_credits.assert_called_once()
_, kwargs = us.add_credits.call_args
assert kwargs.get("amount") == 2 # full refund
# Suppression flag must be set BEFORE cancel_job so cancel_job's built-in
# _refund_credit_for_job guard sees credit_refunded=True and skips.
calls = parent.mock_calls
update_suppression = next(
(c for c in calls
if c[0] == "update_job" and len(c[1]) >= 2 and isinstance(c[1][1], dict) and c[1][1].get("credit_refunded") is True),
None,
)
assert update_suppression is not None, "update_job({'credit_refunded': True}) was never called"
cancel_idx = next(i for i, c in enumerate(calls) if c[0] == "cancel_job")
suppress_idx = calls.index(update_suppression)
assert suppress_idx < cancel_idx, (
"update_job(credit_refunded=True) must be called BEFORE cancel_job"
)
jm.cancel_job.assert_called_once()
def test_probe_none_proceeds_without_charge_change():
jm, us, probe = _ctx(actual_seconds=None, credits_charged=2)
result = reconcile_duration("job1", jm, us, probe)
assert result.action == "proceed"
us.add_credits.assert_not_called()
us.deduct_credits.assert_not_called()
# ---------------------------------------------------------------------------
# Bug 1 regression: payment_bypassed jobs must never pause/charge/refund/cancel
# ---------------------------------------------------------------------------
def _bypassed_job(actual_seconds, credits_charged=0):
"""Return (job_manager, user_service, probe) for a payment-bypassed job."""
job = _job(credits_charged=credits_charged, payment_bypassed=True)
job_manager = MagicMock()
job_manager.get_job.return_value = job
user_service = MagicMock()
user_service.add_credits.return_value = (True, 99, "ok")
probe = MagicMock(return_value=actual_seconds)
return job_manager, user_service, probe
def test_payment_bypassed_long_duration_proceeds_without_pause():
"""Bug 1: admin/payment-bypassed job whose duration exceeds estimate must NOT pause."""
jm, us, probe = _bypassed_job(actual_seconds=1800, credits_charged=0) # 30min -> would be +3 credits
result = reconcile_duration("job1", jm, us, probe)
assert result.action == "proceed", (
f"payment_bypassed job must proceed, got {result.action!r}"
)
jm.transition_to_state.assert_not_called()
us.add_credits.assert_not_called()
us.deduct_credits.assert_not_called()
def test_payment_bypassed_over_limit_proceeds_without_cancel():
"""Bug 1: payment-bypassed job >60min must NOT be cancelled (admin bypass)."""
jm, us, probe = _bypassed_job(actual_seconds=4000, credits_charged=0) # >60min
result = reconcile_duration("job1", jm, us, probe)
assert result.action == "proceed", (
f"payment_bypassed job >60min must proceed, got {result.action!r}"
)
jm.cancel_job.assert_not_called()
us.add_credits.assert_not_called()
def test_payment_bypassed_short_duration_proceeds_without_refund():
"""Bug 1: payment-bypassed job shorter than estimate must NOT trigger a credits refund."""
jm, us, probe = _bypassed_job(actual_seconds=300, credits_charged=0) # 5min
result = reconcile_duration("job1", jm, us, probe)
assert result.action == "proceed"
us.add_credits.assert_not_called()
# ---------------------------------------------------------------------------
# Bug 2 regression: over-limit cancellation email called with correct kwargs
# ---------------------------------------------------------------------------
def test_over_limit_sends_email_with_correct_kwargs():
"""Bug 2: over-limit cancel must call email_service with named kwargs, not positional job arg."""
jm, us, probe = _ctx(actual_seconds=4000, credits_charged=2) # >60min
email_service = MagicMock()
email_service.send_duration_confirm_expired.return_value = True
result = reconcile_duration("job1", jm, us, probe, email_service=email_service)
assert result.action == "cancel"
email_service.send_duration_confirm_expired.assert_called_once()
_, kwargs = email_service.send_duration_confirm_expired.call_args
assert kwargs.get("to_email") == "u@test.com", f"Expected to_email=u@test.com, got {kwargs}"
assert kwargs.get("credits_refunded") == 2, f"Expected credits_refunded=2, got {kwargs}"
def test_over_limit_no_email_when_email_service_is_none():
"""Bug 2: when email_service is None, no crash on over-limit path."""
jm, us, probe = _ctx(actual_seconds=4000, credits_charged=2)
# Should not raise
result = reconcile_duration("job1", jm, us, probe, email_service=None)
assert result.action == "cancel"
# ---------------------------------------------------------------------------
# Bug C regression: over-limit cancel uses reason="over_limit" (not "timeout")
# ---------------------------------------------------------------------------
def test_over_limit_sends_email_with_over_limit_reason():
"""
Bug C: over-limit immediate cancellation must send send_duration_confirm_expired
with reason='over_limit', NOT the default reason='timeout' which says
'48-hour expiry'. The user sees the wrong cancellation message otherwise.
"""
jm, us, probe = _ctx(actual_seconds=4000, credits_charged=2) # >60min
email_service = MagicMock()
email_service.send_duration_confirm_expired.return_value = True
result = reconcile_duration("job1", jm, us, probe, email_service=email_service)
assert result.action == "cancel"
email_service.send_duration_confirm_expired.assert_called_once()
_, kwargs = email_service.send_duration_confirm_expired.call_args
assert kwargs.get("reason") == "over_limit", (
f"Expected reason='over_limit' for immediate over-60-min cancellation, "
f"got reason={kwargs.get('reason')!r}. "
"The user would see a misleading '48-hour expiry' message."
)
def test_stale_48h_expiry_sends_email_with_timeout_reason():
"""
The 48h stale path (stale_review_processor) calls send_duration_confirm_expired
without a reason kwarg — which defaults to 'timeout'. This test verifies that
a 'timeout' reason (or no explicit reason) produces the correct timeout message
in send_duration_confirm_expired, guarding against accidentally using 'over_limit'.
This is a unit test of the email_service method, not the reconcile path.
"""
import sys
sys.modules.setdefault('google.cloud.firestore', MagicMock())
sys.modules.setdefault('google.cloud.storage', MagicMock())
from unittest.mock import patch, MagicMock as MM2
with patch('backend.services.email_service.EmailService._build_email_html', return_value="html"), \
patch('backend.services.email_service.EmailService.provider', create=True) as mock_provider:
from backend.services.email_service import EmailService
class _FakeProvider:
def send_email(self, **kwargs):
return True
svc = EmailService.__new__(EmailService)
svc.frontend_url = "https://gen.nomadkaraoke.com"
svc.provider = _FakeProvider()
svc._build_email_html = lambda content, styles, locale="en": content
# Default reason (timeout) — should mention 48 hours, not 60 minutes
import io, contextlib
out = io.StringIO()
# Capture text content by monkeypatching send_email
sent = {}
class _CapturingProvider:
def send_email(self, to_email, subject, html_content, text_content):
sent['subject'] = subject
sent['text'] = text_content
return True
svc.provider = _CapturingProvider()
svc.send_duration_confirm_expired(
to_email="u@test.com", artist="A", title="B", credits_refunded=2
# no reason= → default "timeout"
)
assert "48" in sent['subject'] or "48" in sent['text'] or "not confirmed" in sent['subject'], (
f"Default (timeout) email should mention 48-hour expiry. subject={sent.get('subject')!r}"
)
assert "60" not in sent['subject'], (
f"Default (timeout) email should not say '60 minutes'. subject={sent.get('subject')!r}"
)
# over_limit reason — should mention 60 minutes, not 48 hours
svc.send_duration_confirm_expired(
to_email="u@test.com", artist="A", title="B", credits_refunded=2, reason="over_limit"
)
assert "60" in sent['subject'], (
f"over_limit email subject should mention 60 minutes. subject={sent.get('subject')!r}"
)
assert "48" not in sent['subject'] and "not confirmed" not in sent['subject'], (
f"over_limit email should not say '48 hours'. subject={sent.get('subject')!r}"
)
@@ -0,0 +1,18 @@
from backend.models.job import JobStatus, STATE_TRANSITIONS
def test_awaiting_duration_confirm_exists():
assert JobStatus.AWAITING_DURATION_CONFIRM.value == "awaiting_duration_confirm"
def test_can_pause_from_download_and_edit_complete():
assert JobStatus.AWAITING_DURATION_CONFIRM in STATE_TRANSITIONS[JobStatus.DOWNLOADING]
assert JobStatus.AWAITING_DURATION_CONFIRM in STATE_TRANSITIONS[JobStatus.AUDIO_EDIT_COMPLETE]
assert JobStatus.AWAITING_DURATION_CONFIRM in STATE_TRANSITIONS[JobStatus.DOWNLOADING_AUDIO]
def test_resume_targets_processing_or_terminal():
targets = STATE_TRANSITIONS[JobStatus.AWAITING_DURATION_CONFIRM]
for t in (JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING,
JobStatus.GENERATING_SCREENS, JobStatus.FAILED, JobStatus.CANCELLED):
assert t in targets
+56
View File
@@ -0,0 +1,56 @@
import pytest
from backend.services.pricing import duration_to_credits, is_blocked, SECONDS_PER_CREDIT_TIER, DURATION_CREDIT_BLOCK_SECONDS
@pytest.mark.parametrize("seconds,expected", [
(0, 1),
(1, 1),
(599, 1),
(600, 1),
(601, 2),
(1200, 2),
(1201, 3),
(3000, 5),
(3001, 6),
(3600, 6),
])
def test_duration_to_credits_tiers(seconds, expected):
assert duration_to_credits(seconds) == expected
@pytest.mark.parametrize("seconds,blocked", [
(3600, False),
(3601, True),
(10000, True),
(0, False),
])
def test_is_blocked(seconds, blocked):
assert is_blocked(seconds) is blocked
def test_constants():
assert SECONDS_PER_CREDIT_TIER == 600
assert DURATION_CREDIT_BLOCK_SECONDS == 3600
def test_duration_to_credits_handles_none_and_negative():
assert duration_to_credits(None) == 1
assert duration_to_credits(-5) == 1
def test_duration_to_credits_handles_non_finite():
"""NaN and Inf from malformed metadata must not propagate into math.ceil."""
assert duration_to_credits(float('nan')) == 1
assert duration_to_credits(float('inf')) == 1
assert duration_to_credits(float('-inf')) == 1
def test_is_blocked_handles_none_and_negative():
assert is_blocked(None) is False
assert is_blocked(-5) is False
def test_is_blocked_non_finite():
"""NaN should not be treated as blocked; inf exceeds the limit so it is blocked."""
assert is_blocked(float('nan')) is False
assert is_blocked(float('inf')) is True
@@ -0,0 +1,315 @@
"""
Tests for UserService.deduct_credits(amount) and the deduct_credit wrapper.
Construction pattern mirrors test_credit_evaluation.py:
- patch backend.services.user_service.firestore and get_settings
- instantiate UserService() directly
- seed Firestore via mock_db
USERS_COLLECTION = "gen_users"
CreditTransaction fields: id, amount, reason, job_id, created_at
Tuple return shape: (success: bool, remaining_credits: int, message: str)
"""
import uuid
import pytest
from unittest.mock import MagicMock, patch, call
from datetime import datetime
# ---------------------------------------------------------------------------
# Helper: build a minimal Firestore document snapshot dict for a user
# ---------------------------------------------------------------------------
def _make_user_doc(credits: int, transactions: list = None):
"""Return the dict that doc.to_dict() would return for a user document."""
return {
"email": "test@example.com",
"credits": credits,
"credit_transactions": transactions or [],
"total_jobs_created": 0,
}
def _make_mock_db(user_dict):
"""
Build a mock Firestore db whose collection().document().get() returns
a snapshot whose .to_dict() yields user_dict.
"""
mock_db = MagicMock()
# Snapshot
mock_snapshot = MagicMock()
mock_snapshot.exists = True
mock_snapshot.to_dict.return_value = user_dict
# doc_ref.get(transaction=...) returns snapshot
mock_doc_ref = MagicMock()
mock_doc_ref.get.return_value = mock_snapshot
mock_collection = MagicMock()
mock_collection.document.return_value = mock_doc_ref
mock_db.collection.return_value = mock_collection
# transaction() must return an object that can be used as a Firestore transaction.
# The @firestore.transactional decorator calls the inner function with a
# google.cloud.firestore.Transaction object; here we mock so that
# deduct_in_transaction(fs_transaction) is invoked synchronously.
mock_transaction = MagicMock()
mock_db.transaction.return_value = mock_transaction
return mock_db, mock_doc_ref, mock_snapshot, mock_transaction
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def user_service_factory():
"""
Factory: given a user dict, return an instantiated UserService whose db
is wired to return that user from gen_users/<email>.
Uses the same mock pattern as test_credit_evaluation.py:
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
Patches are started immediately and stopped at test teardown so they remain
active when the test body calls service methods (important for asserting that
@firestore.transactional is called at decoration time inside deduct_credits).
"""
active_patches = []
def _factory(user_dict):
p_settings = patch('backend.services.user_service.get_settings')
p_firestore = patch('backend.services.user_service.firestore')
mock_settings = p_settings.start()
mock_firestore_module = p_firestore.start()
active_patches.extend([p_settings, p_firestore])
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db, mock_doc_ref, mock_snapshot, mock_transaction = _make_mock_db(user_dict)
mock_firestore_module.Client.return_value = mock_db
# Make @firestore.transactional a MagicMock whose side_effect is a
# pass-through (returns the inner function unchanged). This means:
# 1. The decorator still works — deduct_in_transaction is callable.
# 2. We can assert that mock_firestore_module.transactional was
# called, so removing the @firestore.transactional decorator
# from the source would break the atomicity tests.
mock_firestore_module.transactional = MagicMock(side_effect=lambda fn: fn)
from backend.services.user_service import UserService
service = UserService()
# Replace db with our wired mock (UserService.__init__ sets self.db)
service.db = mock_db
return service, mock_db, mock_doc_ref, mock_snapshot, mock_transaction, mock_firestore_module
yield _factory
# Teardown: stop all patches after each test
for p in active_patches:
p.stop()
# ---------------------------------------------------------------------------
# Tests: deduct_credits(email, job_id, amount, reason)
# ---------------------------------------------------------------------------
class TestDeductCredits:
def test_deduct_3_from_5_returns_success_remaining_2(self, user_service_factory):
"""deduct_credits(amount=3) on a user with 5 credits → success, remaining=2."""
user_dict = _make_user_doc(credits=5)
service, mock_db, mock_doc_ref, mock_snapshot, mock_transaction, mock_firestore_module = user_service_factory(user_dict)
success, remaining, message = service.deduct_credits(
"test@example.com", "job-abc", amount=3
)
assert success is True
assert remaining == 2
# transaction.update must have been called with new balance 2
mock_transaction.update.assert_called_once()
update_args = mock_transaction.update.call_args[0]
assert update_args[1]['credits'] == 2
# --- C2: verify the transactional path is actually exercised ---
# If the @firestore.transactional decorator were removed, this would fail.
mock_firestore_module.transactional.assert_called_once()
mock_db.transaction.assert_called_once()
def test_deduct_4_from_2_returns_failure_unchanged(self, user_service_factory):
"""deduct_credits(amount=4) on user with 2 credits → failure, balance unchanged at 2."""
user_dict = _make_user_doc(credits=2)
service, mock_db, mock_doc_ref, mock_snapshot, mock_transaction, mock_firestore_module = user_service_factory(user_dict)
success, remaining, message = service.deduct_credits(
"test@example.com", "job-xyz", amount=4
)
assert success is False
assert remaining == 2 # unchanged
assert "insufficient" in message.lower()
# No mutation must have happened
mock_transaction.update.assert_not_called()
def test_deduct_1_from_1_via_deduct_credits_returns_success_remaining_0(self, user_service_factory):
"""deduct_credits(amount=1) on user with 1 credit → success, remaining=0."""
user_dict = _make_user_doc(credits=1)
service, mock_db, mock_doc_ref, mock_snapshot, mock_transaction, mock_firestore_module = user_service_factory(user_dict)
success, remaining, message = service.deduct_credits(
"test@example.com", "job-001", amount=1
)
assert success is True
assert remaining == 0
mock_transaction.update.assert_called_once()
update_args = mock_transaction.update.call_args[0]
assert update_args[1]['credits'] == 0
def test_invalid_amount_zero_returns_failure(self, user_service_factory):
"""deduct_credits(amount=0) → failure, message about positive amount."""
user_dict = _make_user_doc(credits=5)
service, mock_db, mock_doc_ref, mock_snapshot, mock_transaction, mock_firestore_module = user_service_factory(user_dict)
success, remaining, message = service.deduct_credits(
"test@example.com", "job-000", amount=0
)
assert success is False
assert remaining == 0
assert "positive" in message.lower()
mock_transaction.update.assert_not_called()
def test_invalid_amount_negative_returns_failure(self, user_service_factory):
"""deduct_credits(amount=-1) → failure, message about positive amount."""
user_dict = _make_user_doc(credits=5)
service, mock_db, mock_doc_ref, mock_snapshot, mock_transaction, mock_firestore_module = user_service_factory(user_dict)
success, remaining, message = service.deduct_credits(
"test@example.com", "job-000", amount=-1
)
assert success is False
assert remaining == 0
assert "positive" in message.lower()
mock_transaction.update.assert_not_called()
def test_credit_transaction_record_has_correct_amount(self, user_service_factory):
"""CreditTransaction stored has amount=-3 for deduct_credits(amount=3)."""
user_dict = _make_user_doc(credits=10)
service, mock_db, mock_doc_ref, mock_snapshot, mock_transaction, mock_firestore_module = user_service_factory(user_dict)
service.deduct_credits("test@example.com", "job-txn", amount=3)
mock_transaction.update.assert_called_once()
update_kwargs = mock_transaction.update.call_args[0][1]
transactions = update_kwargs['credit_transactions']
assert len(transactions) == 1
assert transactions[0]['amount'] == -3
# --- I2: total_jobs_created assertions ---
def test_count_as_job_creation_true_increments_total_jobs(self, user_service_factory):
"""count_as_job_creation=True (default) increments total_jobs_created by 1."""
user_dict = _make_user_doc(credits=5)
service, mock_db, mock_doc_ref, mock_snapshot, mock_transaction, mock_firestore_module = user_service_factory(user_dict)
service.deduct_credits("test@example.com", "job-new", amount=1, count_as_job_creation=True)
update_payload = mock_transaction.update.call_args[0][1]
assert update_payload['total_jobs_created'] == 1 # was 0 → now 1
def test_count_as_job_creation_false_does_not_set_total_jobs(self, user_service_factory):
"""count_as_job_creation=False leaves total_jobs_created out of the update payload."""
user_dict = _make_user_doc(credits=5)
service, mock_db, mock_doc_ref, mock_snapshot, mock_transaction, mock_firestore_module = user_service_factory(user_dict)
service.deduct_credits("test@example.com", "job-reconcile", amount=2, count_as_job_creation=False)
update_payload = mock_transaction.update.call_args[0][1]
assert 'total_jobs_created' not in update_payload
# --- I1: user-not-found ---
def test_user_not_found_returns_failure(self, user_service_factory):
"""When the user doc does not exist, returns (False, 0, 'User not found') with no update."""
user_dict = _make_user_doc(credits=5)
service, mock_db, mock_doc_ref, mock_snapshot, mock_transaction, mock_firestore_module = user_service_factory(user_dict)
# Override snapshot to simulate a missing document
mock_snapshot.exists = False
success, remaining, message = service.deduct_credits(
"ghost@example.com", "job-ghost", amount=1
)
assert success is False
assert remaining == 0
assert "user not found" in message.lower()
mock_transaction.update.assert_not_called()
# ---------------------------------------------------------------------------
# Tests: deduct_credit wrapper (legacy single-credit deduction)
# ---------------------------------------------------------------------------
class TestDeductCreditWrapper:
def test_legacy_deduct_credit_deducts_exactly_1(self, user_service_factory):
"""deduct_credit(email, job_id) deducts exactly 1 and returns (True, n-1, message)."""
user_dict = _make_user_doc(credits=5)
service, mock_db, mock_doc_ref, mock_snapshot, mock_transaction, mock_firestore_module = user_service_factory(user_dict)
success, remaining, message = service.deduct_credit(
"test@example.com", "job-legacy"
)
assert success is True
assert remaining == 4
# Verify the transaction updated credits by exactly 1
update_args = mock_transaction.update.call_args[0]
assert update_args[1]['credits'] == 4
def test_legacy_deduct_credit_returns_same_tuple_shape(self, user_service_factory):
"""deduct_credit returns (bool, int, str) tuple — same shape as before."""
user_dict = _make_user_doc(credits=3)
service, mock_db, mock_doc_ref, mock_snapshot, mock_transaction, mock_firestore_module = user_service_factory(user_dict)
result = service.deduct_credit("test@example.com", "job-shape")
assert isinstance(result, tuple)
assert len(result) == 3
success, remaining, message = result
assert isinstance(success, bool)
assert isinstance(remaining, int)
assert isinstance(message, str)
def test_legacy_deduct_credit_uses_default_reason(self, user_service_factory):
"""deduct_credit default reason is 'job_creation', passed through to CreditTransaction."""
user_dict = _make_user_doc(credits=5)
service, mock_db, mock_doc_ref, mock_snapshot, mock_transaction, mock_firestore_module = user_service_factory(user_dict)
service.deduct_credit("test@example.com", "job-reason")
update_args = mock_transaction.update.call_args[0]
transactions = update_args[1]['credit_transactions']
assert transactions[0]['reason'] == 'job_creation'
def test_legacy_deduct_credit_insufficient_returns_failure(self, user_service_factory):
"""deduct_credit when credits=0 returns (False, 0, msg) — same as before."""
user_dict = _make_user_doc(credits=0)
service, mock_db, mock_doc_ref, mock_snapshot, mock_transaction, mock_firestore_module = user_service_factory(user_dict)
success, remaining, message = service.deduct_credit(
"test@example.com", "job-broke"
)
assert success is False
assert remaining == 0
mock_transaction.update.assert_not_called()
+1 -1
View File
@@ -319,7 +319,7 @@ class TestSubmitFeedbackEmailIntegration:
# Email service throws an exception
mock_email_svc = Mock()
mock_email_svc.send_feedback_notification.side_effect = Exception("SendGrid down")
mock_email_svc.send_feedback_notification.side_effect = Exception("Postmark down")
mock_get_email.return_value = mock_email_svc
mock_user_svc = Mock()
+357 -3
View File
@@ -4,6 +4,7 @@ Tests for the audio download worker.
Tests the standalone worker that downloads audio from various sources
(YouTube, Spotify, RED/OPS) and triggers processing workers.
"""
import os
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from datetime import datetime, UTC
@@ -102,7 +103,9 @@ class TestProcessAudioDownload:
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory:
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory, \
patch("backend.workers.audio_download_worker.reconcile_and_maybe_pause",
new_callable=AsyncMock, return_value=False):
mock_jm = MagicMock()
mock_jm.get_job.return_value = job
@@ -117,7 +120,7 @@ class TestProcessAudioDownload:
result = await process_audio_download("test-job-123")
assert result is True
mock_jm.update_job.assert_called_once_with("test-job-123", {
mock_jm.update_job.assert_any_call("test-job-123", {
'input_media_gcs_path': "uploads/test-job-123/audio/song.mp3",
'filename': "song.mp3",
})
@@ -146,6 +149,47 @@ class TestProcessAudioDownload:
mock_jm.fail_job.assert_called_once()
assert "Download timed out" in mock_jm.fail_job.call_args[0][1]
@pytest.mark.asyncio
@pytest.mark.parametrize("status", [
JobStatus.DOWNLOADING,
JobStatus.AWAITING_AUDIO_EDIT,
JobStatus.AUDIO_COMPLETE,
JobStatus.TRANSCRIBING,
JobStatus.GENERATING_SCREENS,
JobStatus.AWAITING_REVIEW,
JobStatus.RENDERING_VIDEO,
JobStatus.COMPLETE,
])
async def test_skips_when_download_already_done(self, status):
"""If status is past DOWNLOADING_AUDIO, the download must not be re-run.
This prevents Cloud Run Job retries of a successful execution from
re-downloading, double-transitioning state, and double-triggering
downstream workers (see job 8a9c74ff).
"""
job = _make_job(status=status)
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory:
mock_jm = MagicMock()
mock_jm.get_job.return_value = job
mock_jm_cls.return_value = mock_jm
mock_ws = AsyncMock()
mock_ws_factory.return_value = mock_ws
result = await process_audio_download("test-job-123")
assert result is True, f"Expected idempotent success when status={status.value}"
mock_dl.assert_not_awaited()
mock_jm.transition_to_state.assert_not_called()
mock_jm.fail_job.assert_not_called()
mock_ws.trigger_audio_worker.assert_not_awaited()
mock_ws.trigger_lyrics_worker.assert_not_awaited()
@pytest.mark.asyncio
async def test_uses_state_data_selection_when_available(self):
"""Should prefer state_data search results over job-level params."""
@@ -163,7 +207,9 @@ class TestProcessAudioDownload:
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory:
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory, \
patch("backend.workers.audio_download_worker.reconcile_and_maybe_pause",
new_callable=AsyncMock, return_value=False):
mock_jm = MagicMock()
mock_jm.get_job.return_value = job
@@ -183,6 +229,132 @@ class TestProcessAudioDownload:
assert call_kwargs['source_id'] == 'spotify123'
class TestCloudRunRetryPending:
"""Tests for the cloud_run_retry_pending signal set on fail_job.
Cloud Run Job auto-retries failed task attempts. When the worker fails
on attempt N and N < max_retries, the worker must mark the job so the
UI can show "Retrying automatically..." instead of a Retry button, and
so the /retry endpoint refuses to start a second parallel execution.
"""
@pytest.mark.asyncio
async def test_marks_retry_pending_when_attempts_remain(self):
"""Failure on attempt 0 (with attempts 1,2 still possible) marks retry pending."""
job = _make_job()
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
patch.dict(os.environ, {"CLOUD_RUN_TASK_ATTEMPT": "0"}, clear=False):
mock_jm = MagicMock()
mock_jm.get_job.return_value = job
mock_jm_cls.return_value = mock_jm
mock_dl.side_effect = DownloadError("Download timed out")
result = await process_audio_download("test-job-123")
assert result is False
# state_data.cloud_run_retry_pending should be set before fail_job
update_calls = [c for c in mock_jm.update_state_data.call_args_list
if c.args[1] == 'cloud_run_retry_pending']
assert len(update_calls) == 1, "Expected exactly one cloud_run_retry_pending update"
pending = update_calls[0].args[2]
assert pending['expected_attempt'] == 1
assert 'expires_at' in pending
mock_jm.fail_job.assert_called_once()
@pytest.mark.asyncio
async def test_clears_stale_retry_pending_on_final_attempt(self):
"""Failure on the final attempt must clear any marker left by an
earlier attempt — otherwise the UI shows "Retrying automatically..."
for the marker's full TTL after the job has actually failed
permanently, blocking the user from clicking Retry.
"""
job = _make_job()
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
patch.dict(os.environ, {"CLOUD_RUN_TASK_ATTEMPT": "2"}, clear=False):
mock_jm = MagicMock()
mock_jm.get_job.return_value = job
mock_jm_cls.return_value = mock_jm
mock_dl.side_effect = DownloadError("Download timed out")
result = await process_audio_download("test-job-123")
assert result is False
# Final attempt must NOT write a new pending dict, but MUST clear
# any stale marker (set to None).
pending_writes = [
c for c in mock_jm.update_state_data.call_args_list
if c.args[1] == 'cloud_run_retry_pending' and c.args[2] is not None
]
pending_clears = [
c for c in mock_jm.update_state_data.call_args_list
if c.args[1] == 'cloud_run_retry_pending' and c.args[2] is None
]
assert pending_writes == [], "Final attempt must not write a new pending marker"
assert len(pending_clears) == 1, (
f"Final attempt must clear stale marker; got: {mock_jm.update_state_data.call_args_list}"
)
mock_jm.fail_job.assert_called_once()
@pytest.mark.asyncio
async def test_clears_retry_pending_and_error_on_success(self):
"""Successful download clears any stale retry-pending flag and error message."""
job = _make_job(
error_message="Audio download failed: previous attempt timeout",
state_data={'cloud_run_retry_pending': {'expires_at': '2026-05-16T16:00:00Z', 'expected_attempt': 1}},
)
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory, \
patch("backend.workers.audio_download_worker.reconcile_and_maybe_pause",
new_callable=AsyncMock, return_value=False):
mock_jm = MagicMock()
mock_jm.get_job.return_value = job
mock_jm.transition_to_state.return_value = True
mock_jm_cls.return_value = mock_jm
mock_dl.return_value = ("uploads/test-job-123/audio/song.mp3", "song.mp3")
mock_ws = AsyncMock()
mock_ws_factory.return_value = mock_ws
result = await process_audio_download("test-job-123")
assert result is True
# Look at update_job calls to find the error-clearing one
error_clear_calls = [
c for c in mock_jm.update_job.call_args_list
if isinstance(c.args[1], dict)
and c.args[1].get('error_message') is None
and 'error_details' in c.args[1]
]
assert len(error_clear_calls) >= 1, (
f"Expected an update_job call clearing error_message; got: "
f"{mock_jm.update_job.call_args_list}"
)
# Look for cloud_run_retry_pending being cleared (set to None)
pending_clears = [
c for c in mock_jm.update_state_data.call_args_list
if c.args[1] == 'cloud_run_retry_pending' and c.args[2] is None
]
assert len(pending_clears) == 1, (
f"Expected cloud_run_retry_pending to be cleared; got state_data updates: "
f"{mock_jm.update_state_data.call_args_list}"
)
class TestAudioEditPreGeneration:
"""Tests for pre-generation of editor assets when requires_audio_edit is set."""
@@ -262,6 +434,188 @@ class TestAudioEditPreGeneration:
assert any(c.kwargs.get('new_status') == JobStatus.AWAITING_AUDIO_EDIT for c in calls)
class TestFfprobeSeconds:
"""Tests for the _ffprobe_seconds helper in duration_reconciliation."""
def test_ffprobe_seconds_parses_duration(self):
"""Should return float duration when ffprobe succeeds."""
from backend.services.duration_reconciliation import _ffprobe_seconds
job = MagicMock()
job.id = "job-abc"
job.input_media_gcs_path = "gs://b/a.flac"
storage = MagicMock()
storage.generate_signed_url.return_value = "https://signed"
mock_result = MagicMock()
mock_result.returncode = 0
mock_result.stdout = '{"format": {"duration": "1957.8"}}'
with patch("backend.services.duration_reconciliation.subprocess.run",
return_value=mock_result) as mock_run:
result = _ffprobe_seconds(job, storage)
assert result == 1957.8
storage.generate_signed_url.assert_called_once_with("gs://b/a.flac", expiration_minutes=5)
mock_run.assert_called_once()
args = mock_run.call_args[0][0]
assert "ffprobe" in args[0]
assert "https://signed" in args
def test_ffprobe_seconds_returns_none_on_error(self):
"""Should return None when ffprobe exits with non-zero returncode."""
from backend.services.duration_reconciliation import _ffprobe_seconds
job = MagicMock()
job.id = "job-abc"
job.input_media_gcs_path = "gs://b/a.flac"
storage = MagicMock()
storage.generate_signed_url.return_value = "https://signed"
mock_result = MagicMock()
mock_result.returncode = 1
mock_result.stderr = "No such file"
with patch("backend.services.duration_reconciliation.subprocess.run",
return_value=mock_result):
result = _ffprobe_seconds(job, storage)
assert result is None
def test_ffprobe_seconds_returns_none_when_no_gcs_path(self):
"""Should return None when job has no input_media_gcs_path."""
from backend.services.duration_reconciliation import _ffprobe_seconds
job = MagicMock()
job.id = "job-abc"
job.input_media_gcs_path = None
storage = MagicMock()
result = _ffprobe_seconds(job, storage)
assert result is None
storage.generate_signed_url.assert_not_called()
class TestReconcileAndMaybePause:
"""Tests for the reconcile_and_maybe_pause pipeline-wiring function."""
@pytest.mark.asyncio
async def test_returns_true_when_action_is_pause(self):
"""Should return True (meaning: block worker) when reconcile says pause."""
from backend.services.duration_reconciliation import (
reconcile_and_maybe_pause, ReconcileResult,
)
# JobManager/StorageService are imported at function scope inside reconcile_and_maybe_pause,
# so we patch them at their source modules. get_user_service is also at source module.
with patch("backend.services.duration_reconciliation.reconcile_duration",
return_value=ReconcileResult(action="pause", pending_additional_credits=1)), \
patch("backend.services.job_manager.JobManager"), \
patch("backend.services.user_service.get_user_service"), \
patch("backend.services.storage_service.StorageService"):
result = await reconcile_and_maybe_pause("job-xyz")
assert result is True
@pytest.mark.asyncio
async def test_returns_true_when_action_is_cancel(self):
"""Should return True (meaning: block worker) when reconcile says cancel."""
from backend.services.duration_reconciliation import (
reconcile_and_maybe_pause, ReconcileResult,
)
with patch("backend.services.duration_reconciliation.reconcile_duration",
return_value=ReconcileResult(action="cancel")), \
patch("backend.services.job_manager.JobManager"), \
patch("backend.services.user_service.get_user_service"), \
patch("backend.services.storage_service.StorageService"):
result = await reconcile_and_maybe_pause("job-xyz")
assert result is True
@pytest.mark.asyncio
async def test_returns_false_when_action_is_proceed(self):
"""Should return False (meaning: allow workers) when reconcile says proceed."""
from backend.services.duration_reconciliation import (
reconcile_and_maybe_pause, ReconcileResult,
)
with patch("backend.services.duration_reconciliation.reconcile_duration",
return_value=ReconcileResult(action="proceed")), \
patch("backend.services.job_manager.JobManager"), \
patch("backend.services.user_service.get_user_service"), \
patch("backend.services.storage_service.StorageService"):
result = await reconcile_and_maybe_pause("job-xyz")
assert result is False
class TestNoEditPathRespectsPause:
"""Tests that the no-edit path in process_audio_download respects reconcile_and_maybe_pause."""
@pytest.mark.asyncio
async def test_workers_not_triggered_when_paused(self):
"""When reconcile_and_maybe_pause returns True, trigger_audio/lyrics_worker must not be called."""
job = _make_job(source_name="YouTube", source_id="dQw4w9WgXcQ")
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory, \
patch("backend.workers.audio_download_worker.reconcile_and_maybe_pause",
new_callable=AsyncMock, return_value=True) as mock_ramp:
mock_jm = MagicMock()
mock_jm.get_job.return_value = job
mock_jm.transition_to_state.return_value = True
mock_jm_cls.return_value = mock_jm
mock_dl.return_value = ("uploads/test-job-123/audio/song.mp3", "song.mp3")
mock_ws = AsyncMock()
mock_ws_factory.return_value = mock_ws
result = await process_audio_download("test-job-123")
assert result is True
mock_ramp.assert_awaited_once_with("test-job-123")
mock_ws.trigger_audio_worker.assert_not_awaited()
mock_ws.trigger_lyrics_worker.assert_not_awaited()
@pytest.mark.asyncio
async def test_workers_triggered_when_not_paused(self):
"""When reconcile_and_maybe_pause returns False, workers proceed as normal."""
job = _make_job(source_name="YouTube", source_id="dQw4w9WgXcQ")
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory, \
patch("backend.workers.audio_download_worker.reconcile_and_maybe_pause",
new_callable=AsyncMock, return_value=False) as mock_ramp:
mock_jm = MagicMock()
mock_jm.get_job.return_value = job
mock_jm.transition_to_state.return_value = True
mock_jm_cls.return_value = mock_jm
mock_dl.return_value = ("uploads/test-job-123/audio/song.mp3", "song.mp3")
mock_ws = AsyncMock()
mock_ws_factory.return_value = mock_ws
result = await process_audio_download("test-job-123")
assert result is True
mock_ramp.assert_awaited_once_with("test-job-123")
mock_ws.trigger_audio_worker.assert_awaited_once_with("test-job-123")
mock_ws.trigger_lyrics_worker.assert_awaited_once_with("test-job-123")
class TestDownloadAudio:
"""Tests for _download_audio routing."""
+105 -2
View File
@@ -449,7 +449,12 @@ class TestSubmitAudioEdit:
mock_job_manager.get_job.return_value = audio_edit_job_with_edits
with patch(PATCH_STORAGE_SVC) as MockStorage, \
patch(PATCH_WORKER_SVC) as mock_get_ws:
patch(PATCH_WORKER_SVC) as mock_get_ws, \
patch(
"backend.api.routes.review.reconcile_and_maybe_pause",
new_callable=AsyncMock,
) as mock_reconcile:
mock_reconcile.return_value = False # proceed normally
mock_ws = AsyncMock()
mock_get_ws.return_value = mock_ws
@@ -481,7 +486,12 @@ class TestSubmitAudioEdit:
mock_job_manager.get_job.return_value = audio_edit_job
with patch(PATCH_STORAGE_SVC) as MockStorage, \
patch(PATCH_WORKER_SVC) as mock_get_ws:
patch(PATCH_WORKER_SVC) as mock_get_ws, \
patch(
"backend.api.routes.review.reconcile_and_maybe_pause",
new_callable=AsyncMock,
) as mock_reconcile:
mock_reconcile.return_value = False # proceed normally
mock_ws = AsyncMock()
mock_get_ws.return_value = mock_ws
@@ -508,6 +518,99 @@ class TestSubmitAudioEdit:
resp = test_client.post("/api/review/nonexistent/audio-edit/submit", json={})
assert resp.status_code == 404
def test_submit_paused_by_reconciliation_does_not_trigger_workers(
self, test_client, mock_job_manager, audio_edit_job_with_edits
):
"""When reconcile_and_maybe_pause returns True the workers must NOT be triggered."""
# Reloaded job is AWAITING_DURATION_CONFIRM (paused, not cancelled)
paused_job = _job(
job_id="edit-job-2",
status=JobStatus.AWAITING_DURATION_CONFIRM,
state_data={"audio_edit_stack": [{"gcs_path": "gs://b/edit.flac"}]},
)
mock_job_manager.get_job.side_effect = [audio_edit_job_with_edits, paused_job]
with patch(PATCH_STORAGE_SVC), \
patch(PATCH_WORKER_SVC) as mock_get_ws, \
patch(
"backend.api.routes.review.reconcile_and_maybe_pause",
new_callable=AsyncMock,
) as mock_reconcile:
mock_reconcile.return_value = True # paused / cancelled
mock_ws = AsyncMock()
mock_get_ws.return_value = mock_ws
resp = test_client.post("/api/review/edit-job-2/audio-edit/submit", json={})
# Must be a non-error response (pause is a normal outcome, not 4xx/5xx)
assert resp.status_code == 200
data = resp.json()
assert data["status"] == "paused"
# Workers must NOT have been triggered
mock_ws.trigger_audio_worker.assert_not_called()
mock_ws.trigger_lyrics_worker.assert_not_called()
def test_submit_over_limit_returns_cancelled_status(
self, test_client, mock_job_manager, audio_edit_job_with_edits
):
"""
Bug F: when reconcile_and_maybe_pause cancels the job (over-limit),
the response must say status='cancelled', not 'paused'.
"""
# Reloaded job is CANCELLED after over-limit reconciliation
cancelled_job = _job(
job_id="edit-job-2",
status=JobStatus.CANCELLED,
state_data={"audio_edit_stack": [{"gcs_path": "gs://b/edit.flac"}]},
)
mock_job_manager.get_job.side_effect = [audio_edit_job_with_edits, cancelled_job]
with patch(PATCH_STORAGE_SVC), \
patch(PATCH_WORKER_SVC) as mock_get_ws, \
patch(
"backend.api.routes.review.reconcile_and_maybe_pause",
new_callable=AsyncMock,
) as mock_reconcile:
mock_reconcile.return_value = True # over-limit → cancelled
mock_ws = AsyncMock()
mock_get_ws.return_value = mock_ws
resp = test_client.post("/api/review/edit-job-2/audio-edit/submit", json={})
assert resp.status_code == 200
data = resp.json()
assert data["status"] == "cancelled", (
f"Expected status='cancelled' for over-limit cancellation, got {data.get('status')!r}. "
"The frontend needs this to show the correct message to the user."
)
# Workers must NOT have been triggered
mock_ws.trigger_audio_worker.assert_not_called()
mock_ws.trigger_lyrics_worker.assert_not_called()
def test_submit_reconciliation_false_triggers_workers(
self, test_client, mock_job_manager, audio_edit_job_with_edits
):
"""When reconcile_and_maybe_pause returns False the workers ARE triggered."""
mock_job_manager.get_job.return_value = audio_edit_job_with_edits
with patch(PATCH_STORAGE_SVC), \
patch(PATCH_WORKER_SVC) as mock_get_ws, \
patch(
"backend.api.routes.review.reconcile_and_maybe_pause",
new_callable=AsyncMock,
) as mock_reconcile:
mock_reconcile.return_value = False # proceed normally
mock_ws = AsyncMock()
mock_get_ws.return_value = mock_ws
resp = test_client.post("/api/review/edit-job-2/audio-edit/submit", json={})
assert resp.status_code == 200
data = resp.json()
assert data["status"] == "success"
# --- Helper function tests ---
+4 -4
View File
@@ -100,7 +100,7 @@ class TestGetCorrectionDataReturnsUpdatedCorrections:
# Call the endpoint (synchronously for testing)
import asyncio
result = asyncio.get_event_loop().run_until_complete(
result = asyncio.run(
get_correction_data("test-job-123", ("user@test.com", "job_owner"))
)
@@ -136,7 +136,7 @@ class TestGetCorrectionDataReturnsUpdatedCorrections:
# Call the endpoint
import asyncio
result = asyncio.get_event_loop().run_until_complete(
result = asyncio.run(
get_correction_data("test-job-123", ("user@test.com", "job_owner"))
)
@@ -172,7 +172,7 @@ class TestGetCorrectionDataReturnsUpdatedCorrections:
# Call the endpoint
import asyncio
result = asyncio.get_event_loop().run_until_complete(
result = asyncio.run(
get_correction_data("test-job-123", ("user@test.com", "job_owner"))
)
@@ -214,7 +214,7 @@ class TestGetCorrectionDataReturnsUpdatedCorrections:
storage.generate_signed_url.return_value = "https://signed-url.com"
import asyncio
result = asyncio.get_event_loop().run_until_complete(
result = asyncio.run(
get_correction_data("test-job-123", ("user@test.com", "job_owner"))
)
+95 -1
View File
@@ -11,6 +11,7 @@ from backend.services.credential_manager import (
CredentialStatus,
CredentialCheckResult,
DeviceAuthInfo,
_destroy_old_secret_versions,
get_credential_manager,
)
@@ -369,9 +370,102 @@ class TestAuthRoutes:
class TestFileUploadCredentialValidation:
"""Tests for credential validation in file upload."""
def test_credential_manager_imported(self):
"""Test that credential manager is imported in file upload."""
from backend.api.routes.file_upload import get_credential_manager, CredentialStatus
assert get_credential_manager is not None
assert CredentialStatus is not None
class TestDestroyOldSecretVersions:
"""Tests for _destroy_old_secret_versions helper."""
def _make_version(self, name, state, create_time):
v = MagicMock()
v.name = name
v.state = state
v.create_time = create_time
return v
def test_destroys_versions_beyond_keep_count(self):
"""Keep newest N, destroy the rest."""
client = MagicMock()
enabled = MagicMock()
# State enum lookup on the version (v.State.ENABLED) — make .State.ENABLED a sentinel
# and match it on each version's `.state` field.
State = MagicMock()
State.ENABLED = "ENABLED"
def mk(name, ts):
v = MagicMock()
v.name = name
v.state = State.ENABLED
v.State = State # so v.state == v.State.ENABLED resolves correctly
v.create_time = ts
return v
# 7 versions, oldest → newest by create_time
versions = [mk(f"v{i}", i) for i in range(7)]
client.list_secret_versions.return_value = versions
_destroy_old_secret_versions(client, "projects/p/secrets/s", keep=3)
# Should destroy 4 oldest (v0..v3); keep v4, v5, v6
destroyed_names = [
c.kwargs["request"]["name"]
for c in client.destroy_secret_version.call_args_list
]
assert sorted(destroyed_names) == ["v0", "v1", "v2", "v3"]
def test_swallows_list_errors(self):
"""List failure must not raise — refresh path must keep working."""
client = MagicMock()
client.list_secret_versions.side_effect = RuntimeError("boom")
_destroy_old_secret_versions(client, "projects/p/secrets/s", keep=5)
client.destroy_secret_version.assert_not_called()
def test_swallows_per_version_destroy_errors(self):
"""One bad destroy doesn't abort the rest."""
client = MagicMock()
State = MagicMock()
State.ENABLED = "ENABLED"
def mk(name, ts):
v = MagicMock()
v.name = name
v.state = State.ENABLED
v.State = State
v.create_time = ts
return v
versions = [mk(f"v{i}", i) for i in range(7)]
client.list_secret_versions.return_value = versions
# First destroy fails, rest succeed
client.destroy_secret_version.side_effect = [
RuntimeError("nope"), None, None, None,
]
_destroy_old_secret_versions(client, "projects/p/secrets/s", keep=3)
# All 4 destroy calls attempted despite first failing
assert client.destroy_secret_version.call_count == 4
def test_does_nothing_when_below_keep_count(self):
"""If fewer than `keep` enabled versions exist, destroy nothing."""
client = MagicMock()
State = MagicMock()
State.ENABLED = "ENABLED"
def mk(name, ts):
v = MagicMock()
v.name = name
v.state = State.ENABLED
v.State = State
v.create_time = ts
return v
versions = [mk(f"v{i}", i) for i in range(3)]
client.list_secret_versions.return_value = versions
_destroy_old_secret_versions(client, "projects/p/secrets/s", keep=5)
client.destroy_secret_version.assert_not_called()
+168 -103
View File
@@ -60,8 +60,8 @@ class TestCreditCheckOnJobCreation:
self, job_manager, mock_firestore_service, mock_user_service
):
"""Job creation succeeds when user has credits, and credit is deducted."""
mock_user_service.has_credits.return_value = True
mock_user_service.deduct_credit.return_value = (True, 4, "Credit deducted. 4 remaining")
mock_user_service.check_credits.return_value = 5 # has enough credits
mock_user_service.deduct_credits.return_value = (True, 4, "Credit deducted. 4 remaining")
job = job_manager.create_job(
JobCreate(artist="Test", title="Song", theme_id="nomad", user_email="user@test.com"),
@@ -69,10 +69,10 @@ class TestCreditCheckOnJobCreation:
)
assert job.status == JobStatus.PENDING
mock_user_service.has_credits.assert_called_once_with("user@test.com")
mock_user_service.deduct_credit.assert_called_once()
# Verify deduct_credit was called with user email, job_id, and reason
call_args = mock_user_service.deduct_credit.call_args
mock_user_service.check_credits.assert_called_once_with("user@test.com")
mock_user_service.deduct_credits.assert_called_once()
# Verify deduct_credits was called with user email
call_args = mock_user_service.deduct_credits.call_args
assert call_args[0][0] == "user@test.com"
def test_job_creation_fails_without_credits(
@@ -103,8 +103,8 @@ class TestCreditCheckOnJobCreation:
)
assert job.status == JobStatus.PENDING
mock_user_service.has_credits.assert_not_called()
mock_user_service.deduct_credit.assert_not_called()
mock_user_service.check_credits.assert_not_called()
mock_user_service.deduct_credits.assert_not_called()
def test_job_without_user_email_skips_credit_check(
self, job_manager, mock_firestore_service, mock_user_service
@@ -116,14 +116,14 @@ class TestCreditCheckOnJobCreation:
)
assert job.status == JobStatus.PENDING
mock_user_service.has_credits.assert_not_called()
mock_user_service.check_credits.assert_not_called()
def test_deduction_failure_deletes_job_and_raises(
self, job_manager, mock_firestore_service, mock_user_service
):
"""If credit deduction fails after job creation, the job is deleted."""
mock_user_service.has_credits.return_value = True
mock_user_service.deduct_credit.return_value = (False, 0, "Insufficient credits")
mock_user_service.check_credits.return_value = 5 # passes the gate
mock_user_service.deduct_credits.return_value = (False, 0, "Race condition: insufficient credits")
with pytest.raises(InsufficientCreditsError):
job_manager.create_job(
@@ -137,50 +137,86 @@ class TestCreditCheckOnJobCreation:
class TestCreditRefundOnJobFailure:
"""Test credit refund when jobs fail."""
"""Test credit refund when jobs fail.
_refund_credit_for_job now calls user_service.add_credits directly
(rather than refund_credit) so it can refund the exact credits_charged
amount instead of a hard-coded 1.
"""
def _mock_job(self, credits_charged=1, credit_refunded=False, user_email="user@test.com"):
"""Helper: build a minimal mock Job with state_data.credits_charged."""
job = Mock(spec=Job)
job.user_email = user_email
job.credit_refunded = credit_refunded
job.state_data = {"credits_charged": credits_charged}
return job
def test_credit_refunded_on_job_failure(
self, job_manager, mock_firestore_service, mock_user_service
):
"""Credit is refunded when a non-admin job fails."""
mock_job = Mock(spec=Job)
mock_job.user_email = "user@test.com"
mock_job.credit_refunded = False
"""Credit is refunded when a non-admin job fails (1-credit legacy job)."""
mock_job = self._mock_job(credits_charged=1)
mock_firestore_service.get_job.return_value = mock_job
mock_user_service.refund_credit.return_value = (True, 1, "Refunded")
mock_user_service.add_credits.return_value = (True, 1, "Refunded")
with patch('backend.services.auth_service.is_admin_email', return_value=False):
result = job_manager.fail_job("job123", "Processing error")
assert result is True
mock_user_service.refund_credit.assert_called_once_with(
"user@test.com", "job123", reason="job_failed"
mock_user_service.add_credits.assert_called_once_with(
"user@test.com", amount=1, reason="job_failed", job_id="job123"
)
def test_multi_credit_job_refunds_full_amount_on_failure(
self, job_manager, mock_firestore_service, mock_user_service
):
"""A 4-credit long-duration job must refund 4 credits on failure, not 1."""
mock_job = self._mock_job(credits_charged=4)
mock_firestore_service.get_job.return_value = mock_job
mock_user_service.add_credits.return_value = (True, 6, "Refunded 4")
with patch('backend.services.auth_service.is_admin_email', return_value=False):
result = job_manager.fail_job("job123", "Processing error")
assert result is True
mock_user_service.add_credits.assert_called_once_with(
"user@test.com", amount=4, reason="job_failed", job_id="job123"
)
def test_payment_bypassed_job_skips_refund_on_failure(
self, job_manager, mock_firestore_service, mock_user_service
):
"""Admin / payment_bypassed jobs have credits_charged=0 — nothing to refund."""
mock_job = self._mock_job(credits_charged=0)
mock_firestore_service.get_job.return_value = mock_job
with patch('backend.services.auth_service.is_admin_email', return_value=False):
result = job_manager.fail_job("job123", "Processing error")
assert result is True
mock_user_service.add_credits.assert_not_called()
def test_credit_refund_skipped_for_admin_jobs(
self, job_manager, mock_firestore_service, mock_user_service
):
"""Credit refund is skipped for admin-owned jobs."""
mock_job = Mock(spec=Job)
mock_job.user_email = "admin@nomadkaraoke.com"
mock_job.credit_refunded = False
mock_job = self._mock_job(credits_charged=1, user_email="admin@nomadkaraoke.com")
mock_firestore_service.get_job.return_value = mock_job
with patch('backend.services.auth_service.is_admin_email', return_value=True):
result = job_manager.fail_job("job123", "Processing error")
assert result is True
mock_user_service.refund_credit.assert_not_called()
mock_user_service.add_credits.assert_not_called()
def test_refund_failure_does_not_fail_job_marking(
self, job_manager, mock_firestore_service, mock_user_service
):
"""If refund fails, the job is still marked as failed."""
mock_job = Mock(spec=Job)
mock_job.user_email = "user@test.com"
mock_job.credit_refunded = False
mock_job = self._mock_job(credits_charged=1)
mock_firestore_service.get_job.return_value = mock_job
mock_user_service.refund_credit.side_effect = Exception("Firestore error")
mock_user_service.add_credits.side_effect = Exception("Firestore error")
with patch('backend.services.auth_service.is_admin_email', return_value=False):
result = job_manager.fail_job("job123", "Processing error")
@@ -191,80 +227,124 @@ class TestCreditRefundOnJobFailure:
self, job_manager, mock_firestore_service, mock_user_service
):
"""No refund attempted when job has no user_email."""
mock_job = Mock(spec=Job)
mock_job.user_email = None
mock_job.credit_refunded = False
mock_job = self._mock_job(credits_charged=1, user_email=None)
mock_firestore_service.get_job.return_value = mock_job
result = job_manager.fail_job("job123", "Processing error")
assert result is True
mock_user_service.refund_credit.assert_not_called()
mock_user_service.add_credits.assert_not_called()
def test_no_double_refund_when_already_refunded(
self, job_manager, mock_firestore_service, mock_user_service
):
"""No refund if credit_refunded is already True."""
mock_job = Mock(spec=Job)
mock_job.user_email = "user@test.com"
mock_job.credit_refunded = True
mock_job = self._mock_job(credits_charged=1, credit_refunded=True)
mock_firestore_service.get_job.return_value = mock_job
with patch('backend.services.auth_service.is_admin_email', return_value=False):
result = job_manager.fail_job("job123", "Processing error")
assert result is True
mock_user_service.refund_credit.assert_not_called()
mock_user_service.add_credits.assert_not_called()
class TestCreditRefundOnJobCancellation:
"""Test credit refund when jobs are cancelled."""
"""Test credit refund when jobs are cancelled.
_refund_credit_for_job now calls user_service.add_credits directly
(rather than refund_credit) so it can refund the exact credits_charged
amount instead of a hard-coded 1.
"""
def _mock_job(self, credits_charged=1, credit_refunded=False,
user_email="user@test.com", status=None):
"""Helper: build a minimal mock Job with state_data.credits_charged."""
job = Mock(spec=Job)
job.user_email = user_email
job.credit_refunded = credit_refunded
job.state_data = {"credits_charged": credits_charged}
job.status = status or JobStatus.PENDING
return job
def test_credit_refunded_on_cancellation(
self, job_manager, mock_firestore_service, mock_user_service
):
"""Credit is refunded when a non-admin job is cancelled."""
mock_job = Mock(spec=Job)
mock_job.user_email = "user@test.com"
mock_job.credit_refunded = False
mock_job.status = JobStatus.PENDING
"""Credit is refunded when a non-admin job is cancelled (1-credit job)."""
mock_job = self._mock_job(credits_charged=1)
mock_firestore_service.get_job.return_value = mock_job
mock_user_service.refund_credit.return_value = (True, 1, "Refunded")
mock_user_service.add_credits.return_value = (True, 1, "Refunded")
with patch('backend.services.auth_service.is_admin_email', return_value=False):
result = job_manager.cancel_job("job123", reason="User cancelled")
assert result is True
mock_user_service.refund_credit.assert_called_once_with(
"user@test.com", "job123", reason="job_cancelled"
mock_user_service.add_credits.assert_called_once_with(
"user@test.com", amount=1, reason="job_cancelled", job_id="job123"
)
def test_multi_credit_cancel_refunds_full_amount(
self, job_manager, mock_firestore_service, mock_user_service
):
"""A 4-credit long job cancellation must refund 4 credits, not 1."""
mock_job = self._mock_job(credits_charged=4)
mock_firestore_service.get_job.return_value = mock_job
mock_user_service.add_credits.return_value = (True, 6, "Refunded 4")
with patch('backend.services.auth_service.is_admin_email', return_value=False):
result = job_manager.cancel_job("job123", reason="User cancelled")
assert result is True
mock_user_service.add_credits.assert_called_once_with(
"user@test.com", amount=4, reason="job_cancelled", job_id="job123"
)
def test_cancel_guard_prevents_double_refund_when_credit_refunded(
self, job_manager, mock_firestore_service, mock_user_service
):
"""If credit_refunded is already True, cancel must NOT refund again."""
mock_job = self._mock_job(credits_charged=4, credit_refunded=True)
mock_firestore_service.get_job.return_value = mock_job
with patch('backend.services.auth_service.is_admin_email', return_value=False):
result = job_manager.cancel_job("job123")
assert result is True
mock_user_service.add_credits.assert_not_called()
def test_payment_bypassed_cancel_refunds_nothing(
self, job_manager, mock_firestore_service, mock_user_service
):
"""Admin / payment_bypassed jobs (credits_charged=0) must not be refunded on cancel."""
mock_job = self._mock_job(credits_charged=0)
mock_firestore_service.get_job.return_value = mock_job
with patch('backend.services.auth_service.is_admin_email', return_value=False):
result = job_manager.cancel_job("job123")
assert result is True
mock_user_service.add_credits.assert_not_called()
def test_cancel_skips_refund_for_admin_jobs(
self, job_manager, mock_firestore_service, mock_user_service
):
"""Credit refund is skipped when admin cancels their own job."""
mock_job = Mock(spec=Job)
mock_job.user_email = "admin@nomadkaraoke.com"
mock_job.credit_refunded = False
mock_job.status = JobStatus.PENDING
mock_job = self._mock_job(credits_charged=1, user_email="admin@nomadkaraoke.com")
mock_firestore_service.get_job.return_value = mock_job
with patch('backend.services.auth_service.is_admin_email', return_value=True):
result = job_manager.cancel_job("job123")
assert result is True
mock_user_service.refund_credit.assert_not_called()
mock_user_service.add_credits.assert_not_called()
def test_cancel_refund_failure_does_not_block_cancellation(
self, job_manager, mock_firestore_service, mock_user_service
):
"""If refund fails, the job is still cancelled."""
mock_job = Mock(spec=Job)
mock_job.user_email = "user@test.com"
mock_job.credit_refunded = False
mock_job.status = JobStatus.PENDING
mock_job = self._mock_job(credits_charged=1)
mock_firestore_service.get_job.return_value = mock_job
mock_user_service.refund_credit.side_effect = Exception("Firestore error")
mock_user_service.add_credits.side_effect = Exception("Firestore error")
with patch('backend.services.auth_service.is_admin_email', return_value=False):
result = job_manager.cancel_job("job123")
@@ -275,109 +355,98 @@ class TestCreditRefundOnJobCancellation:
self, job_manager, mock_firestore_service, mock_user_service
):
"""Cannot cancel a job in a terminal state."""
mock_job = Mock(spec=Job)
mock_job.status = JobStatus.COMPLETE
mock_job = self._mock_job(credits_charged=1, status=JobStatus.COMPLETE)
mock_firestore_service.get_job.return_value = mock_job
result = job_manager.cancel_job("job123")
assert result is False
mock_user_service.refund_credit.assert_not_called()
mock_user_service.add_credits.assert_not_called()
class TestCreditRefundOnJobDeletion:
"""Test credit refund when jobs are deleted."""
"""Test credit refund when jobs are deleted.
_refund_credit_for_job now calls user_service.add_credits directly
(rather than refund_credit) so it can refund the exact credits_charged amount.
"""
def _mock_job(self, credits_charged=1, credit_refunded=False,
user_email="user@test.com", status=None):
job = Mock(spec=Job)
job.user_email = user_email
job.credit_refunded = credit_refunded
job.state_data = {"credits_charged": credits_charged}
job.status = status or JobStatus.PENDING
job.output_files = {}
return job
def test_credit_refunded_on_delete_pending_job(
self, job_manager, mock_firestore_service, mock_user_service
):
"""Credit is refunded when a pending job is deleted."""
mock_job = Mock(spec=Job)
mock_job.user_email = "user@test.com"
mock_job.credit_refunded = False
mock_job.status = JobStatus.PENDING
mock_job.output_files = {}
"""Credit is refunded when a pending job is deleted (1-credit job)."""
mock_job = self._mock_job(credits_charged=1)
mock_firestore_service.get_job.return_value = mock_job
mock_user_service.refund_credit.return_value = (True, 1, "Refunded")
mock_user_service.add_credits.return_value = (True, 1, "Refunded")
with patch('backend.services.auth_service.is_admin_email', return_value=False):
job_manager.delete_job("job123")
mock_user_service.refund_credit.assert_called_once_with(
"user@test.com", "job123", reason="job_deleted"
mock_user_service.add_credits.assert_called_once_with(
"user@test.com", amount=1, reason="job_deleted", job_id="job123"
)
def test_no_refund_on_delete_completed_job(
self, job_manager, mock_firestore_service, mock_user_service
):
"""No refund when deleting a completed job (user got their video)."""
mock_job = Mock(spec=Job)
mock_job.user_email = "user@test.com"
mock_job.credit_refunded = False
mock_job.status = JobStatus.COMPLETE
mock_job.output_files = {}
mock_job = self._mock_job(credits_charged=1, status=JobStatus.COMPLETE)
mock_firestore_service.get_job.return_value = mock_job
job_manager.delete_job("job123")
mock_user_service.refund_credit.assert_not_called()
mock_user_service.add_credits.assert_not_called()
def test_no_refund_on_delete_prep_complete_job(
self, job_manager, mock_firestore_service, mock_user_service
):
"""No refund when deleting a prep-complete job."""
mock_job = Mock(spec=Job)
mock_job.user_email = "user@test.com"
mock_job.credit_refunded = False
mock_job.status = JobStatus.PREP_COMPLETE
mock_job.output_files = {}
mock_job = self._mock_job(credits_charged=1, status=JobStatus.PREP_COMPLETE)
mock_firestore_service.get_job.return_value = mock_job
job_manager.delete_job("job123")
mock_user_service.refund_credit.assert_not_called()
mock_user_service.add_credits.assert_not_called()
def test_no_double_refund_on_delete_failed_job(
self, job_manager, mock_firestore_service, mock_user_service
):
"""No refund when deleting a failed job (already refunded on failure)."""
mock_job = Mock(spec=Job)
mock_job.user_email = "user@test.com"
mock_job.credit_refunded = True
mock_job.status = JobStatus.FAILED
mock_job.output_files = {}
mock_job = self._mock_job(credits_charged=1, credit_refunded=True, status=JobStatus.FAILED)
mock_firestore_service.get_job.return_value = mock_job
job_manager.delete_job("job123")
mock_user_service.refund_credit.assert_not_called()
mock_user_service.add_credits.assert_not_called()
def test_no_double_refund_on_delete_cancelled_job(
self, job_manager, mock_firestore_service, mock_user_service
):
"""No refund when deleting a cancelled job (already refunded on cancel)."""
mock_job = Mock(spec=Job)
mock_job.user_email = "user@test.com"
mock_job.credit_refunded = True
mock_job.status = JobStatus.CANCELLED
mock_job.output_files = {}
mock_job = self._mock_job(credits_charged=1, credit_refunded=True, status=JobStatus.CANCELLED)
mock_firestore_service.get_job.return_value = mock_job
job_manager.delete_job("job123")
mock_user_service.refund_credit.assert_not_called()
mock_user_service.add_credits.assert_not_called()
def test_delete_refund_failure_does_not_block_deletion(
self, job_manager, mock_firestore_service, mock_user_service
):
"""If refund fails, the job is still deleted."""
mock_job = Mock(spec=Job)
mock_job.user_email = "user@test.com"
mock_job.credit_refunded = False
mock_job.status = JobStatus.PENDING
mock_job.output_files = {}
mock_job = self._mock_job(credits_charged=1)
mock_firestore_service.get_job.return_value = mock_job
mock_user_service.refund_credit.side_effect = Exception("Firestore error")
mock_user_service.add_credits.side_effect = Exception("Firestore error")
with patch('backend.services.auth_service.is_admin_email', return_value=False):
job_manager.delete_job("job123")
@@ -389,17 +458,13 @@ class TestCreditRefundOnJobDeletion:
self, job_manager, mock_firestore_service, mock_user_service
):
"""No refund when admin deletes their own job."""
mock_job = Mock(spec=Job)
mock_job.user_email = "admin@nomadkaraoke.com"
mock_job.credit_refunded = False
mock_job.status = JobStatus.PENDING
mock_job.output_files = {}
mock_job = self._mock_job(credits_charged=1, user_email="admin@nomadkaraoke.com")
mock_firestore_service.get_job.return_value = mock_job
with patch('backend.services.auth_service.is_admin_email', return_value=True):
job_manager.delete_job("job123")
mock_user_service.refund_credit.assert_not_called()
mock_user_service.add_credits.assert_not_called()
class TestWelcomeCredits:
+23 -14
View File
@@ -343,7 +343,14 @@ class TestCreateCustomInstrumentalEndpoint:
class TestSubmitCorrectionsReferenceLyricsStripping:
"""Tests for reference_lyrics being stripped from Firestore save in submit_corrections."""
"""Tests for the corrections Firestore save in submit_corrections.
Originally this only stripped reference_lyrics, but a long mashup
(prod job 9a12cf0f) showed the segment arrays are the real bulk and still
blew past Firestore's 1MB limit. submit_corrections now persists ONLY a
lightweight summary (corrected_segment_count) to Firestore; the full
corrections (all arrays + reference_lyrics) are preserved in GCS.
"""
def _make_corrections_payload(self, extra_keys=None):
"""Build a valid corrections payload that passes CorrectionsSubmission validation.
@@ -358,16 +365,18 @@ class TestSubmitCorrectionsReferenceLyricsStripping:
data.update(extra_keys)
return data
def test_reference_lyrics_stripped_from_firestore_save(
def test_only_summary_saved_to_firestore(
self, review_job, mock_job_manager, mock_worker_service, patched_client, auth_headers
):
"""Verify reference_lyrics is excluded from Firestore state_data update."""
"""Firestore state_data must hold only the summary — no heavy arrays."""
mock_job_manager.get_job.return_value = review_job
mock_storage = MagicMock()
corrections_data = self._make_corrections_payload(extra_keys={
"corrected_segments": [{"text": "hello"}],
"corrected_segments": [{"text": "hello"}, {"text": "world"}],
"original_segments": [{"text": "hello"}, {"text": "world"}],
"resized_segments": [{"text": "hello"}, {"text": "world"}],
"reference_lyrics": {
"genius": "Very long lyrics content..." * 1000,
},
@@ -383,15 +392,14 @@ class TestSubmitCorrectionsReferenceLyricsStripping:
assert response.status_code == 200
# Check update_state_data was called with data that does NOT contain reference_lyrics
# The corrected_lyrics state_data write must be a small summary only.
state_data_call = mock_job_manager.update_state_data.call_args_list[0]
assert state_data_call[0][1] == "corrected_lyrics"
saved_data = state_data_call[0][2] # Third positional arg is the data dict
assert "reference_lyrics" not in saved_data
# Check preserved keys are still present
assert "lines" in saved_data
assert "metadata" in saved_data
assert "corrected_segments" in saved_data
for heavy in ("reference_lyrics", "lines", "corrected_segments",
"original_segments", "resized_segments"):
assert heavy not in saved_data, f"{heavy} must not be stored in Firestore"
assert saved_data["corrected_segment_count"] == 2
def test_full_corrections_saved_to_gcs(
self, review_job, mock_job_manager, mock_worker_service, patched_client, auth_headers
@@ -445,11 +453,12 @@ class TestSubmitCorrectionsReferenceLyricsStripping:
assert response.status_code == 200
# State data should have all keys (no reference_lyrics to strip)
# State data holds only the summary, even when reference_lyrics is absent.
state_data_call = mock_job_manager.update_state_data.call_args_list[0]
assert state_data_call[0][1] == "corrected_lyrics"
saved_data = state_data_call[0][2]
assert "lines" in saved_data
assert "metadata" in saved_data
assert saved_data == {"corrected_segment_count": 1}
assert "lines" not in saved_data
assert "reference_lyrics" not in saved_data
+19 -176
View File
@@ -11,7 +11,6 @@ from backend.services.email_service import (
EmailService,
EmailProvider,
ConsoleEmailProvider,
SendGridEmailProvider,
PostmarkEmailProvider,
get_email_service,
)
@@ -59,101 +58,6 @@ class TestConsoleEmailProvider:
assert result is True
class TestSendGridEmailProvider:
"""Tests for SendGrid email provider."""
def test_send_email_success(self):
"""Test successful email sending via SendGrid."""
provider = SendGridEmailProvider(
api_key="test-api-key",
from_email="from@example.com",
from_name="Test Sender",
)
mock_response = Mock()
mock_response.status_code = 202
# Patch at the sendgrid module level since it's imported inline
with patch('sendgrid.SendGridAPIClient') as mock_sg:
mock_client = Mock()
mock_client.send.return_value = mock_response
mock_sg.return_value = mock_client
result = provider.send_email(
to_email="user@example.com",
subject="Test Subject",
html_content="<p>Test</p>",
)
assert result is True
mock_client.send.assert_called_once()
def test_send_email_with_cc(self):
"""Test email sending with CC via SendGrid."""
provider = SendGridEmailProvider(
api_key="test-api-key",
from_email="from@example.com",
)
mock_response = Mock()
mock_response.status_code = 202
with patch('sendgrid.SendGridAPIClient') as mock_sg:
mock_client = Mock()
mock_client.send.return_value = mock_response
mock_sg.return_value = mock_client
result = provider.send_email(
to_email="user@example.com",
subject="Test Subject",
html_content="<p>Test</p>",
cc_emails=["cc@example.com"],
)
assert result is True
def test_send_email_failure_status(self):
"""Test email sending failure due to bad status."""
provider = SendGridEmailProvider(
api_key="test-api-key",
from_email="from@example.com",
)
mock_response = Mock()
mock_response.status_code = 400
with patch('sendgrid.SendGridAPIClient') as mock_sg:
mock_client = Mock()
mock_client.send.return_value = mock_response
mock_sg.return_value = mock_client
result = provider.send_email(
to_email="user@example.com",
subject="Test Subject",
html_content="<p>Test</p>",
)
assert result is False
def test_send_email_exception(self):
"""Test email sending exception handling."""
provider = SendGridEmailProvider(
api_key="test-api-key",
from_email="from@example.com",
)
with patch('sendgrid.SendGridAPIClient') as mock_sg:
mock_sg.return_value.send.side_effect = Exception("API error")
result = provider.send_email(
to_email="user@example.com",
subject="Test Subject",
html_content="<p>Test</p>",
)
assert result is False
class TestPostmarkEmailProvider:
"""Tests for Postmark email provider."""
@@ -272,46 +176,19 @@ class TestEmailServiceProviderSelection:
@pytest.fixture(autouse=True)
def _clear_env(self, monkeypatch):
for var in ("EMAIL_PROVIDER", "POSTMARK_SERVER_TOKEN", "SENDGRID_API_KEY"):
monkeypatch.delenv(var, raising=False)
monkeypatch.delenv("POSTMARK_SERVER_TOKEN", raising=False)
def test_explicit_postmark_uses_postmark(self, monkeypatch):
monkeypatch.setenv("EMAIL_PROVIDER", "postmark")
def test_postmark_when_token_set(self, monkeypatch):
monkeypatch.setenv("POSTMARK_SERVER_TOKEN", "pm-token")
monkeypatch.setenv("SENDGRID_API_KEY", "sg-key")
svc = EmailService()
assert isinstance(svc.provider, PostmarkEmailProvider)
assert svc.is_configured() is True
def test_explicit_sendgrid_uses_sendgrid(self, monkeypatch):
monkeypatch.setenv("EMAIL_PROVIDER", "sendgrid")
monkeypatch.setenv("POSTMARK_SERVER_TOKEN", "pm-token")
monkeypatch.setenv("SENDGRID_API_KEY", "sg-key")
svc = EmailService()
assert isinstance(svc.provider, SendGridEmailProvider)
def test_explicit_postmark_without_token_falls_back_to_console(self, monkeypatch):
monkeypatch.setenv("EMAIL_PROVIDER", "postmark")
monkeypatch.setenv("SENDGRID_API_KEY", "sg-key")
def test_console_when_no_token(self, monkeypatch):
svc = EmailService()
assert isinstance(svc.provider, ConsoleEmailProvider)
assert svc.is_configured() is False
def test_auto_prefers_postmark_when_both_keys_set(self, monkeypatch):
monkeypatch.setenv("POSTMARK_SERVER_TOKEN", "pm-token")
monkeypatch.setenv("SENDGRID_API_KEY", "sg-key")
svc = EmailService()
assert isinstance(svc.provider, PostmarkEmailProvider)
def test_auto_falls_back_to_sendgrid_when_only_sendgrid_set(self, monkeypatch):
monkeypatch.setenv("SENDGRID_API_KEY", "sg-key")
svc = EmailService()
assert isinstance(svc.provider, SendGridEmailProvider)
def test_auto_uses_console_when_no_keys(self, monkeypatch):
svc = EmailService()
assert isinstance(svc.provider, ConsoleEmailProvider)
class TestEmailServiceJobCompletion:
"""Tests for job completion email method."""
@@ -554,29 +431,27 @@ class TestEmailServiceActionReminder:
class TestEmailServiceConfiguration:
"""Tests for email service configuration."""
def test_uses_sendgrid_when_configured(self):
"""Test that SendGrid is used when API key is set."""
with patch.dict('os.environ', {'SENDGRID_API_KEY': 'test-key'}):
def test_uses_postmark_when_configured(self):
"""Test that Postmark is used when server token is set."""
with patch.dict('os.environ', {'POSTMARK_SERVER_TOKEN': 'test-token'}):
service = EmailService()
assert isinstance(service.provider, SendGridEmailProvider)
assert isinstance(service.provider, PostmarkEmailProvider)
def test_uses_console_when_not_configured(self):
"""Test that console is used when no API key."""
with patch.dict('os.environ', {}, clear=True):
# Remove SENDGRID_API_KEY if it exists
import os
original = os.environ.pop('SENDGRID_API_KEY', None)
try:
service = EmailService()
assert isinstance(service.provider, ConsoleEmailProvider)
finally:
if original:
os.environ['SENDGRID_API_KEY'] = original
"""Test that console is used when no token."""
import os
original = os.environ.pop('POSTMARK_SERVER_TOKEN', None)
try:
service = EmailService()
assert isinstance(service.provider, ConsoleEmailProvider)
finally:
if original:
os.environ['POSTMARK_SERVER_TOKEN'] = original
def test_is_configured_true_for_sendgrid(self):
"""Test is_configured returns True for SendGrid."""
def test_is_configured_true_for_postmark(self):
"""Test is_configured returns True for Postmark."""
service = EmailService()
service.provider = SendGridEmailProvider("key", "from@example.com")
service.provider = PostmarkEmailProvider("token", "from@example.com")
assert service.is_configured() is True
def test_is_configured_false_for_console(self):
@@ -620,38 +495,6 @@ class TestCCFunctionality:
# Check that CC was logged
assert "cc1@example.com" in caplog.text or "CC:" in caplog.text
def test_sendgrid_provider_adds_cc_recipients(self):
"""Test that SendGrid provider adds CC recipients to message."""
provider = SendGridEmailProvider(
api_key="test-api-key",
from_email="from@example.com",
)
mock_response = Mock()
mock_response.status_code = 202
# Patch at sendgrid module level since imports are inline
with patch('sendgrid.SendGridAPIClient') as mock_sg:
mock_client = Mock()
mock_client.send.return_value = mock_response
mock_sg.return_value = mock_client
# We need to capture the Mail object
with patch('sendgrid.helpers.mail.Mail') as mock_mail_class:
mock_mail = MagicMock()
mock_mail_class.return_value = mock_mail
provider.send_email(
to_email="user@example.com",
subject="Test",
html_content="<p>Test</p>",
cc_emails=["cc@example.com"],
)
# Verify add_cc was called
mock_mail.add_cc.assert_called()
class TestMadeForYouOrderConfirmation:
"""Tests for send_made_for_you_order_confirmation method."""
@@ -3,12 +3,18 @@ Unit tests for encoding worker lifecycle endpoints.
Tests the warmup and heartbeat API endpoints.
"""
import logging
import pytest
from unittest.mock import MagicMock
from fastapi import FastAPI
from fastapi.testclient import TestClient
from backend.api.routes.encoding_worker import router, get_worker_manager
from backend.api.dependencies import require_admin
from backend.services.encoding_errors import (
EncodingWorkerCapacityError,
EncodingWorkerStartError,
)
def get_mock_admin():
@@ -56,6 +62,75 @@ class TestWarmupEndpoint:
assert response.json()["started"] is False
assert "error" in response.json()
def test_warmup_503_start_failure_logged_as_warning(self, caplog):
"""A transient 503/start failure must NOT log at ERROR.
The encoding flow falls back to alternate-zone workers, so this is a
self-healing event. Logging it at ERROR trips the production error
monitor (severity>=ERROR) and pages us for a non-incident.
"""
self.mock_manager.ensure_primary_running.side_effect = (
EncodingWorkerStartError(
"VM encoding-worker-b start failed in us-central1-c: "
"503 — SERVICE UNAVAILABLE",
vm_name="encoding-worker-b",
zone="us-central1-c",
)
)
with caplog.at_level(logging.WARNING):
response = self.client.post("/api/internal/encoding-worker/warmup")
assert response.status_code == 200
assert response.json()["started"] is False
warmup_records = [
r for r in caplog.records if "warmup failed" in r.getMessage()
]
assert warmup_records, "expected a warmup-failure log record"
assert all(r.levelno == logging.WARNING for r in warmup_records)
# And nothing from this endpoint should be at ERROR.
assert not [
r
for r in caplog.records
if r.levelno >= logging.ERROR
and r.name == "backend.api.routes.encoding_worker"
]
def test_warmup_capacity_error_logged_as_warning(self, caplog):
"""Capacity exhaustion is also self-healing → WARNING, not ERROR."""
self.mock_manager.ensure_primary_running.side_effect = (
EncodingWorkerCapacityError(
"VM encoding-worker-b could not be started in us-central1-c: "
"ZONE_RESOURCE_POOL_EXHAUSTED",
vm_name="encoding-worker-b",
zone="us-central1-c",
code="ZONE_RESOURCE_POOL_EXHAUSTED",
)
)
with caplog.at_level(logging.WARNING):
response = self.client.post("/api/internal/encoding-worker/warmup")
assert response.status_code == 200
assert not [
r
for r in caplog.records
if r.levelno >= logging.ERROR
and r.name == "backend.api.routes.encoding_worker"
]
def test_warmup_unexpected_error_still_logged_as_error(self, caplog):
"""Genuinely unexpected failures must still surface at ERROR."""
self.mock_manager.ensure_primary_running.side_effect = RuntimeError(
"misconfigured service account"
)
with caplog.at_level(logging.WARNING):
response = self.client.post("/api/internal/encoding-worker/warmup")
assert response.status_code == 200
error_records = [
r
for r in caplog.records
if r.levelno >= logging.ERROR
and r.name == "backend.api.routes.encoding_worker"
]
assert error_records, "unexpected errors must remain at ERROR severity"
class TestHeartbeatEndpoint:
def setup_method(self):
+52 -55
View File
@@ -241,31 +241,14 @@ class TestUserEmailExtraction:
class TestUrlJobWorkerSequencing:
"""
Issue 2: YouTube URL download race condition.
URL job worker triggering.
Root cause: Both audio and lyrics workers were triggered in parallel.
For URL jobs, lyrics worker would timeout waiting for audio to download.
These tests verify that URL jobs trigger workers sequentially.
URL jobs are now downloaded by the flacfetch service in create_from_url
BEFORE any worker runs, so `input_media_gcs_path` is already set and both
workers can start in parallel (no sequential audio→lyrics handoff, no local
yt-dlp fallback in the worker).
"""
@pytest.mark.asyncio
async def test_url_job_triggers_only_audio_worker_initially(self):
"""
create-from-url must only trigger audio worker, not lyrics worker.
The audio worker will trigger lyrics after download completes.
"""
from backend.api.routes.file_upload import _trigger_audio_worker_only
with patch('backend.api.routes.file_upload.worker_service') as mock_ws:
mock_ws.trigger_audio_worker = AsyncMock()
mock_ws.trigger_lyrics_worker = AsyncMock()
await _trigger_audio_worker_only("test-job-id")
mock_ws.trigger_audio_worker.assert_called_once_with("test-job-id")
mock_ws.trigger_lyrics_worker.assert_not_called()
@pytest.mark.asyncio
async def test_parallel_worker_triggers_both_workers(self):
"""
@@ -284,39 +267,6 @@ class TestUrlJobWorkerSequencing:
mock_ws.trigger_audio_worker.assert_called_once_with("test-job-id")
mock_ws.trigger_lyrics_worker.assert_called_once_with("test-job-id")
@pytest.mark.asyncio
async def test_audio_worker_triggers_lyrics_after_url_download(self):
"""
Audio worker must trigger lyrics worker after successful URL download.
"""
from backend.workers.audio_worker import _trigger_lyrics_worker_after_url_download
# Mock at the source module where it's imported from
with patch('backend.services.worker_service.get_worker_service') as mock_get_ws:
mock_ws = Mock()
mock_ws.trigger_lyrics_worker = AsyncMock()
mock_get_ws.return_value = mock_ws
await _trigger_lyrics_worker_after_url_download("test-job-id")
mock_ws.trigger_lyrics_worker.assert_called_once_with("test-job-id")
@pytest.mark.asyncio
async def test_audio_worker_lyrics_trigger_handles_errors_gracefully(self):
"""
If lyrics worker trigger fails, audio processing should continue.
"""
from backend.workers.audio_worker import _trigger_lyrics_worker_after_url_download
# Mock at the source module where it's imported from
with patch('backend.services.worker_service.get_worker_service') as mock_get_ws:
mock_ws = Mock()
mock_ws.trigger_lyrics_worker = AsyncMock(side_effect=Exception("Network error"))
mock_get_ws.return_value = mock_ws
# Should not raise exception
await _trigger_lyrics_worker_after_url_download("test-job-id")
class TestAudioSearchCacheIndependence:
"""
@@ -504,6 +454,53 @@ class TestTranscriptionTimeout:
assert "timed out" in error_message.lower()
class TestDurationScaledTranscriptionTimeout:
"""Tests for compute_transcription_timeout.
Prod incident (job 9a12cf0f, "Van - Mashup"): a ~32-minute mashup
(1957s audio) hit the fixed 1200s transcription timeout and flapped to
'failed' on attempts where AudioShake was slow, even though a healthy run
transcribes it in ~438s. The timeout is now scaled by audio duration,
bounded by [floor, cap], where the cap stays under the Cloud Run Job task
timeout so we surface a clean RuntimeError before the platform hard-kills.
"""
def _settings(self, floor=1200, cap=1700, per_sec=1.0):
s = MagicMock()
s.transcription_timeout_floor_seconds = floor
s.transcription_timeout_cap_seconds = cap
s.transcription_timeout_per_audio_second = per_sec
return s
def test_short_song_uses_floor(self):
from backend.workers.lyrics_worker import compute_transcription_timeout
# 3-minute song -> stays at the floor.
assert compute_transcription_timeout(180, self._settings()) == 1200
def test_long_mashup_scales_up_to_cap(self):
from backend.workers.lyrics_worker import compute_transcription_timeout
# 32-minute mashup (1957s) -> scaled value capped at 1700.
assert compute_transcription_timeout(1957, self._settings()) == 1700
def test_mid_length_scales_between_floor_and_cap(self):
from backend.workers.lyrics_worker import compute_transcription_timeout
# 1500s audio, 1.0x -> 1500 (between floor 1200 and cap 1700).
assert compute_transcription_timeout(1500, self._settings()) == 1500
def test_unknown_duration_falls_back_to_floor(self):
from backend.workers.lyrics_worker import compute_transcription_timeout
assert compute_transcription_timeout(None, self._settings()) == 1200
assert compute_transcription_timeout(0, self._settings()) == 1200
assert compute_transcription_timeout(-5, self._settings()) == 1200
def test_cap_never_exceeds_cloud_run_task_timeout(self):
"""The default cap must stay safely under the 1800s Cloud Run Job task timeout."""
from backend.config import Settings
s = Settings()
assert s.transcription_timeout_cap_seconds <= 1700
assert s.transcription_timeout_floor_seconds == 1200
class TestJobOwnershipFiltering:
"""
Additional tests for job ownership and filtering.
+73 -4
View File
@@ -701,6 +701,33 @@ class TestTransitionToStateRaisesBehavior:
error = exc_info.value
assert error.job_id == "test123"
def test_invalid_transition_message_uses_consistent_status_names(
self, job_manager, mock_firestore_service
):
"""The error message must render both states using their string values.
Regression: previously rendered 'downloading -> JobStatus.DOWNLOADING'
because current_status was deserialized as str (use_enum_values=True)
while new_status remained an enum. This made debugging confusing.
"""
mock_firestore_service.get_job.return_value = Job(
job_id="test123",
status=JobStatus.DOWNLOADING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC)
)
with pytest.raises(InvalidStateTransitionError) as exc_info:
job_manager.transition_to_state("test123", JobStatus.DOWNLOADING)
message = str(exc_info.value)
assert "downloading -> downloading" in message, (
f"Expected 'downloading -> downloading' in message, got: {message}"
)
assert "JobStatus." not in message, (
f"Expected no 'JobStatus.' prefix in message, got: {message}"
)
def test_invalid_transition_returns_false_when_not_raising(self, job_manager, mock_firestore_service):
"""Test that invalid transition returns False when raise_on_invalid=False."""
mock_firestore_service.get_job.return_value = Job(
@@ -798,7 +825,8 @@ class TestStartJobProcessing:
input_media_gcs_path="gs://bucket/audio.mp3"
)
with patch('backend.services.worker_service.get_worker_service') as mock_get_worker:
with patch('backend.services.worker_service.get_worker_service') as mock_get_worker, \
patch('backend.services.job_manager.reconcile_and_maybe_pause', AsyncMock(return_value=False)):
mock_worker = Mock()
mock_worker.trigger_audio_worker = AsyncMock()
mock_worker.trigger_lyrics_worker = AsyncMock()
@@ -838,7 +866,8 @@ class TestStartJobProcessing:
# Simulate some work
call_order.append(('lyrics_end', datetime.now()))
with patch('backend.services.worker_service.get_worker_service') as mock_get_worker:
with patch('backend.services.worker_service.get_worker_service') as mock_get_worker, \
patch('backend.services.job_manager.reconcile_and_maybe_pause', AsyncMock(return_value=False)):
mock_worker = Mock()
mock_worker.trigger_audio_worker = AsyncMock(side_effect=track_audio)
mock_worker.trigger_lyrics_worker = AsyncMock(side_effect=track_lyrics)
@@ -867,7 +896,8 @@ class TestStartJobProcessing:
existing_instrumental_gcs_path="uploads/test123/audio/existing_instrumental.mp3"
)
with patch('backend.services.worker_service.get_worker_service') as mock_get_worker:
with patch('backend.services.worker_service.get_worker_service') as mock_get_worker, \
patch('backend.services.job_manager.reconcile_and_maybe_pause', AsyncMock(return_value=False)):
mock_worker = Mock()
mock_worker.trigger_audio_worker = AsyncMock()
mock_worker.trigger_lyrics_worker = AsyncMock()
@@ -906,7 +936,8 @@ class TestStartJobProcessing:
existing_instrumental_gcs_path=None # No existing instrumental
)
with patch('backend.services.worker_service.get_worker_service') as mock_get_worker:
with patch('backend.services.worker_service.get_worker_service') as mock_get_worker, \
patch('backend.services.job_manager.reconcile_and_maybe_pause', AsyncMock(return_value=False)):
mock_worker = Mock()
mock_worker.trigger_audio_worker = AsyncMock()
mock_worker.trigger_lyrics_worker = AsyncMock()
@@ -918,6 +949,44 @@ class TestStartJobProcessing:
mock_worker.trigger_audio_worker.assert_called_once_with("test123")
mock_worker.trigger_lyrics_worker.assert_called_once_with("test123")
@pytest.mark.asyncio
async def test_workers_not_triggered_when_reconcile_pauses(self, job_manager, mock_firestore_service):
"""When reconcile_and_maybe_pause returns True, start_job_processing must NOT
trigger any downstream workers.
This is the caller-callee contract gap: if the ``if await
reconcile_and_maybe_pause(job_id): return`` guard were deleted from
start_job_processing, all other tests would still pass because they all
use return_value=False. This test uses return_value=True so the deletion
would cause it to fail — proving the guard is there and effective.
"""
mock_firestore_service.get_job.return_value = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
input_media_gcs_path="gs://bucket/audio.mp3",
)
with patch("backend.services.worker_service.get_worker_service") as mock_get_worker, \
patch(
"backend.services.job_manager.reconcile_and_maybe_pause",
AsyncMock(return_value=True), # job paused/cancelled
) as mock_ramp:
mock_worker = Mock()
mock_worker.trigger_audio_worker = AsyncMock()
mock_worker.trigger_lyrics_worker = AsyncMock()
mock_get_worker.return_value = mock_worker
await job_manager.start_job_processing("test123")
# reconcile was called
mock_ramp.assert_awaited_once_with("test123")
# workers must NOT have been triggered
mock_worker.trigger_audio_worker.assert_not_called()
mock_worker.trigger_lyrics_worker.assert_not_called()
if __name__ == "__main__":
pytest.main([__file__, "-v"])
@@ -385,6 +385,77 @@ class TestGetCompletionMessage:
assert call_kwargs.get('artist') is None
class TestDurationConfirmReminderEmail:
"""Tests for send_duration_confirm_reminder CTA URL."""
@pytest.mark.asyncio
async def test_confirm_url_points_to_dashboard_not_review(self):
"""
The CTA URL in the duration-confirm reminder must point to /app (the
dashboard where the confirm banner appears), NOT to /review (which renders
an error because the job is not yet in a review state).
"""
from unittest.mock import MagicMock
service = JobNotificationService()
service.frontend_url = "https://gen.nomadkaraoke.com"
service.email_service = Mock()
service.email_service.send_duration_confirm_reminder = Mock(return_value=True)
mock_job = MagicMock()
mock_job.job_id = "job-dur-999"
mock_job.user_email = "user@example.com"
mock_job.artist = "Test Artist"
mock_job.title = "Test Song"
mock_job.state_data = {
"pending_additional_credits": 3,
"duration_actual_seconds": 1200,
}
with patch('backend.services.job_notification_service.ENABLE_AUTO_EMAILS', True), \
patch.object(service, '_get_user_locale', return_value='en'):
await service.send_duration_confirm_reminder(mock_job)
call_kwargs = service.email_service.send_duration_confirm_reminder.call_args.kwargs
confirm_url = call_kwargs.get("confirm_url")
# Must end with /app — the dashboard — NOT /review
assert confirm_url is not None, "confirm_url was not passed to email_service"
assert confirm_url.endswith("/app"), (
f"confirm_url should end with /app (dashboard), got: {confirm_url!r}"
)
assert "/review" not in confirm_url, (
f"confirm_url must NOT contain /review (wrong state), got: {confirm_url!r}"
)
assert confirm_url == "https://gen.nomadkaraoke.com/en/app"
@pytest.mark.asyncio
async def test_confirm_url_uses_user_locale_prefix(self):
"""The confirm_url should respect the user's locale (e.g. /de/app for German)."""
from unittest.mock import MagicMock
service = JobNotificationService()
service.frontend_url = "https://gen.nomadkaraoke.com"
service.email_service = Mock()
service.email_service.send_duration_confirm_reminder = Mock(return_value=True)
mock_job = MagicMock()
mock_job.job_id = "job-dur-de"
mock_job.user_email = "user@example.com"
mock_job.artist = "Test Artist"
mock_job.title = "Test Song"
mock_job.state_data = {}
with patch('backend.services.job_notification_service.ENABLE_AUTO_EMAILS', True), \
patch.object(service, '_get_user_locale', return_value='de'):
await service.send_duration_confirm_reminder(mock_job)
call_kwargs = service.email_service.send_duration_confirm_reminder.call_args.kwargs
confirm_url = call_kwargs.get("confirm_url")
assert confirm_url == "https://gen.nomadkaraoke.com/de/app"
class TestGlobalInstance:
"""Tests for global instance management."""
@@ -837,6 +837,88 @@ class TestNotificationFormatting:
assert "download" in payload["body"].lower()
class TestDurationConfirmNotification:
"""Tests for send_blocking_notification with action_type='duration_confirm'."""
@pytest.mark.asyncio
async def test_duration_confirm_notification_title_and_body(self, push_service):
"""send_blocking_notification formats duration_confirm notification correctly."""
mock_doc = Mock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"push_subscriptions": [{
"endpoint": "https://push.example.com/endpoint",
"keys": {"p256dh": "key", "auth": "auth"},
"tenant_id": None,
}]
}
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
job = {
"job_id": "test-job-dur-001",
"user_email": "test@example.com",
"artist": "Test Artist",
"title": "Test Song",
}
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
await push_service.send_blocking_notification(job, "duration_confirm")
call_args = mock_webpush.call_args
import json
payload = json.loads(call_args[1]["data"])
# Title must indicate cost confirmation, not instrumental or lyrics
assert "confirm" in payload["title"].lower() or "cost" in payload["title"].lower(), (
f"Expected cost-confirmation title, got: {payload['title']!r}"
)
# Body must mention confirmation (not instrumental selection)
assert "confirm" in payload["body"].lower(), (
f"Expected confirmation body, got: {payload['body']!r}"
)
# URL must point to dashboard (/app), NOT to /instrumental or /review
assert payload["url"] == "/app", (
f"Expected /app deeplink for duration_confirm, got: {payload['url']!r}"
)
assert "/instrumental" not in payload["url"], (
"duration_confirm must NOT deeplink to /instrumental"
)
assert "/review" not in payload["url"], (
"duration_confirm must NOT deeplink to /review"
)
@pytest.mark.asyncio
async def test_duration_confirm_does_not_affect_instrumental(self, push_service):
"""Instrumental branch still produces /instrumental URL after adding duration_confirm."""
mock_doc = Mock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"push_subscriptions": [{
"endpoint": "https://push.example.com/endpoint",
"keys": {"p256dh": "key", "auth": "auth"},
"tenant_id": None,
}]
}
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
job = {
"job_id": "test-job-dur-002",
"user_email": "test@example.com",
"artist": "Test Artist",
"title": "Test Song",
}
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
await push_service.send_blocking_notification(job, "instrumental")
call_args = mock_webpush.call_args
import json
payload = json.loads(call_args[1]["data"])
assert "/instrumental" in payload["url"], (
f"Instrumental branch must still use /instrumental URL, got: {payload['url']!r}"
)
class TestSingleton:
"""Tests for singleton pattern."""
+65
View File
@@ -0,0 +1,65 @@
"""
Tests for UserService.revoke_session idempotency.
Revoking a session that no longer exists (already logged out, expired, or
cleaned up) should be treated as success rather than logged as an error.
Firestore's document.update() raises NotFound when the document is absent.
"""
from unittest.mock import MagicMock, patch
# Mock Firestore before importing modules that use it
import sys
sys.modules.setdefault('google.cloud.firestore', MagicMock())
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
from google.api_core import exceptions as google_exceptions
class TestRevokeSession:
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_revoke_existing_session_succeeds(self, mock_fs, mock_settings):
"""A normal revoke updates is_active and returns True."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
doc_ref = mock_db.collection.return_value.document.return_value
from backend.services.user_service import UserService
service = UserService()
assert service.revoke_session("token-abc") is True
doc_ref.update.assert_called_once_with({'is_active': False})
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_revoke_missing_session_is_idempotent(self, mock_fs, mock_settings):
"""A missing session document is already revoked → return True, no error."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
doc_ref = mock_db.collection.return_value.document.return_value
doc_ref.update.side_effect = google_exceptions.NotFound(
"No document to update: sessions/deadbeef"
)
from backend.services.user_service import UserService
service = UserService()
assert service.revoke_session("missing-token") is True
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_revoke_unexpected_error_returns_false(self, mock_fs, mock_settings):
"""Genuine errors (not NotFound) are swallowed and return False."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
doc_ref = mock_db.collection.return_value.document.return_value
doc_ref.update.side_effect = google_exceptions.DeadlineExceeded("timeout")
from backend.services.user_service import UserService
service = UserService()
assert service.revoke_session("token-abc") is False
+274 -3
View File
@@ -12,20 +12,108 @@ from backend.models.job import Job, JobStatus
class TestJobsRouteHelpers:
"""Tests for helper functions in jobs.py routes."""
def test_jobs_router_structure(self):
"""Test jobs router has expected structure."""
from backend.api.routes.jobs import router
assert router is not None
# Check that common route patterns exist
route_paths = [route.path for route in router.routes]
assert any('/jobs' in p or 'jobs' in str(p) for p in route_paths)
class TestIsAutoRetryPending:
"""Tests for the _is_auto_retry_pending helper used by /retry."""
def _now(self, offset_seconds=0):
from datetime import timedelta, timezone
return (datetime.now(timezone.utc) + timedelta(seconds=offset_seconds)).isoformat()
def test_returns_false_for_missing_state_data(self):
from backend.api.routes.jobs import _is_auto_retry_pending
assert _is_auto_retry_pending(None) is False
assert _is_auto_retry_pending({}) is False
def test_returns_false_when_no_retry_pending_field(self):
from backend.api.routes.jobs import _is_auto_retry_pending
assert _is_auto_retry_pending({'other_field': 'x'}) is False
def test_returns_true_when_pending_not_expired(self):
from backend.api.routes.jobs import _is_auto_retry_pending
state_data = {'cloud_run_retry_pending': {
'expires_at': self._now(60),
'expected_attempt': 1,
}}
assert _is_auto_retry_pending(state_data) is True
def test_returns_false_when_pending_expired(self):
from backend.api.routes.jobs import _is_auto_retry_pending
state_data = {'cloud_run_retry_pending': {
'expires_at': self._now(-60),
'expected_attempt': 1,
}}
assert _is_auto_retry_pending(state_data) is False
def test_returns_false_for_malformed_expires_at(self):
from backend.api.routes.jobs import _is_auto_retry_pending
assert _is_auto_retry_pending({'cloud_run_retry_pending': {'expires_at': 'not-a-date'}}) is False
assert _is_auto_retry_pending({'cloud_run_retry_pending': {'expires_at': None}}) is False
assert _is_auto_retry_pending({'cloud_run_retry_pending': 'not-a-dict'}) is False
class TestSummaryFieldPathsIncludesRetryPending:
"""Regression: cloud_run_retry_pending must be projected so the dashboard
can render the 'Retrying automatically' state. Per MEMORY note, the
Firestore projection AND the Python prune allowlist must both include it.
"""
def test_firestore_projection_includes_retry_pending(self):
from backend.services.firestore_service import FirestoreService
assert 'state_data.cloud_run_retry_pending' in FirestoreService.SUMMARY_FIELD_PATHS
def test_summary_prune_allows_retry_pending(self):
from backend.api.routes.jobs import _SUMMARY_STATE_DATA_KEYS
assert 'cloud_run_retry_pending' in _SUMMARY_STATE_DATA_KEYS
class TestSummaryFieldPathsIncludesDurationPricing:
"""Regression: duration-pricing fields must be in both SUMMARY_FIELD_PATHS
and _SUMMARY_STATE_DATA_KEYS so the dashboard can render the
awaiting_duration_confirm modal with correct cost figures.
Per project MEMORY note: mocked-job tests won't catch a missing Firestore
projection — this class is the authoritative regression guard.
"""
_EXPECTED_STATE_DATA_FIELDS = [
'credits_charged',
'pending_additional_credits',
'duration_actual_seconds',
'duration_confirm_reason',
]
def test_firestore_projection_includes_duration_pricing_fields(self):
from backend.services.firestore_service import FirestoreService
for field in self._EXPECTED_STATE_DATA_FIELDS:
path = f'state_data.{field}'
assert path in FirestoreService.SUMMARY_FIELD_PATHS, (
f"'{path}' must be in SUMMARY_FIELD_PATHS so the dashboard "
f"can display the duration-pricing confirm modal"
)
def test_summary_prune_allows_duration_pricing_keys(self):
from backend.api.routes.jobs import _SUMMARY_STATE_DATA_KEYS
for field in self._EXPECTED_STATE_DATA_FIELDS:
assert field in _SUMMARY_STATE_DATA_KEYS, (
f"'{field}' must be in _SUMMARY_STATE_DATA_KEYS so it is not "
f"stripped before reaching the dashboard"
)
class TestJobStatusTransitions:
"""Tests for job status transition validation.
These test the Job model's state machine which is critical for
preventing invalid operations.
"""
@@ -938,3 +1026,186 @@ class TestCorrectionsDuetFlag:
s3 = CorrectionsSubmission(**base)
assert s3.is_duet is None
class TestCorrectionsFirestoreDocSize:
"""Regression tests for the Firestore 1MB doc-size limit on corrections save.
Prod incident (job 9a12cf0f, "Van - Mashup"): saving corrections for a long
song wrote ~1.8MB of segment arrays into the job document, exceeding
Firestore's 1MB/document hard limit. The fix stores only a lightweight
summary (corrected_segment_count) in state_data.corrected_lyrics; the full
corrections are preserved in GCS (corrections_updated.json).
"""
import json as _json
@pytest.fixture
def mock_job(self):
job = MagicMock(spec=Job)
job.job_id = "job-bigcorrections"
job.status = JobStatus.AWAITING_REVIEW
job.state_data = {}
return job
def _big_corrections(self, n_segments=422):
"""Build a corrections payload mimicking a long song (>1MB raw)."""
def _segment(i):
return {
"id": f"seg-{i}",
"text": "the quick brown fox jumps over the lazy dog " * 4,
"start_time": float(i),
"end_time": float(i) + 1.0,
"words": [
{"id": f"w-{i}-{j}", "text": "word", "start_time": float(j),
"end_time": float(j) + 0.2, "confidence": 0.9}
for j in range(12)
],
}
segments = [_segment(i) for i in range(n_segments)]
return {
"lines": [],
"metadata": {"source": "test"},
"corrected_segments": segments,
"original_segments": segments,
"resized_segments": segments,
"reference_lyrics": {},
}
def _call_submit_corrections(self, mock_job, corrections, mock_jm, mock_st):
import asyncio
from backend.api.routes.jobs import submit_corrections
from backend.models.requests import CorrectionsSubmission
submission = CorrectionsSubmission(corrections=corrections)
mock_jm.get_job.return_value = mock_job
mock_jm.update_state_data.return_value = None
mock_jm.transition_to_state.return_value = True
mock_st.upload_json.return_value = None
mock_request = MagicMock()
mock_request.headers = {}
async def _run():
return await submit_corrections(
job_id=mock_job.job_id,
submission=submission,
http_request=mock_request,
background_tasks=MagicMock(),
auth_result=MagicMock(user_email="t@t.com", role="job_owner", job_id=mock_job.job_id),
)
# StorageService is imported inside the endpoint, so patch it at the source module.
with patch("backend.api.routes.jobs.job_manager", mock_jm), \
patch("backend.api.routes.jobs._check_job_ownership", return_value=True), \
patch("backend.api.routes.jobs.get_locale_from_request", return_value="en"), \
patch("backend.services.storage_service.StorageService", return_value=mock_st):
return asyncio.run(_run())
def _corrected_lyrics_payload(self, mock_jm):
calls = [c for c in mock_jm.update_state_data.call_args_list
if c.args[1] == "corrected_lyrics"]
assert len(calls) == 1, "corrected_lyrics should be written exactly once"
return calls[0].args[2]
def test_corrections_save_stores_only_small_summary(self, mock_job):
"""The corrected_lyrics written to Firestore must be a small summary,
not the multi-MB segment arrays."""
mock_jm, mock_st = MagicMock(), MagicMock()
corrections = self._big_corrections(n_segments=422)
# Sanity: the raw payload is genuinely over the 1MB Firestore limit.
assert len(self._json.dumps(corrections).encode("utf-8")) > 1_048_576
result = self._call_submit_corrections(mock_job, corrections, mock_jm, mock_st)
assert result["status"] == "success"
payload = self._corrected_lyrics_payload(mock_jm)
# No heavy arrays must be present.
for heavy in ("corrected_segments", "original_segments", "resized_segments",
"reference_lyrics", "lines"):
assert heavy not in payload, f"{heavy} must not be stored in Firestore"
# Summary stays comfortably small.
assert len(self._json.dumps(payload).encode("utf-8")) < 1024
def test_corrections_summary_records_segment_count(self, mock_job):
"""The summary must record the corrected segment count for the guard."""
mock_jm, mock_st = MagicMock(), MagicMock()
corrections = self._big_corrections(n_segments=37)
self._call_submit_corrections(mock_job, corrections, mock_jm, mock_st)
payload = self._corrected_lyrics_payload(mock_jm)
assert payload["corrected_segment_count"] == 37
def test_corrections_full_payload_still_saved_to_gcs(self, mock_job):
"""The full corrections (with arrays) must still be uploaded to GCS."""
mock_jm, mock_st = MagicMock(), MagicMock()
corrections = self._big_corrections(n_segments=10)
self._call_submit_corrections(mock_job, corrections, mock_jm, mock_st)
upload_calls = mock_st.upload_json.call_args_list
assert len(upload_calls) == 1
path, data = upload_calls[0].args[0], upload_calls[0].args[1]
assert path.endswith("corrections_updated.json")
assert len(data["corrected_segments"]) == 10
class TestCompleteReviewSegmentGuard:
"""The complete-review 0-segment guard must read the corrected_lyrics summary
(new shape) and still work for legacy jobs that stored the full dict."""
def _make_job(self, segment_count, corrected_lyrics):
job = MagicMock(spec=Job)
job.job_id = "job-guard"
job.status = JobStatus.IN_REVIEW
job.state_data = {
"lyrics_metadata": {"segment_count": segment_count},
"corrected_lyrics": corrected_lyrics,
}
return job
def _call_complete_review(self, job):
import asyncio
from backend.api.routes.jobs import complete_review
mock_jm = MagicMock()
mock_jm.get_job.return_value = job
mock_request = MagicMock()
mock_request.headers = {}
async def _run():
return await complete_review(
job_id=job.job_id,
body=None,
request=mock_request,
background_tasks=MagicMock(),
auth_result=MagicMock(user_email="t@t.com", role="job_owner", job_id=job.job_id),
)
with patch("backend.api.routes.jobs.job_manager", mock_jm), \
patch("backend.api.routes.jobs._check_job_ownership", return_value=True), \
patch("backend.api.routes.jobs.get_locale_from_request", return_value="en"), \
patch("backend.api.routes.jobs.worker_service", MagicMock()):
return asyncio.run(_run())
def test_guard_blocks_when_no_segments_summary_shape(self):
"""0 transcription segments AND 0 corrected segments -> 400."""
from fastapi import HTTPException
job = self._make_job(0, {"corrected_segment_count": 0})
with pytest.raises(HTTPException) as exc:
self._call_complete_review(job)
assert exc.value.status_code == 400
def test_guard_allows_when_summary_has_segments(self):
"""0 transcription segments but corrections have segments -> allowed."""
job = self._make_job(0, {"corrected_segment_count": 5})
result = self._call_complete_review(job)
assert result["status"] == "success"
def test_guard_allows_legacy_full_dict_shape(self):
"""Legacy jobs stored full dict with corrected_segments list -> still allowed."""
job = self._make_job(0, {"corrected_segments": [{"id": "a"}, {"id": "b"}]})
result = self._call_complete_review(job)
assert result["status"] == "success"
+48
View File
@@ -1046,3 +1046,51 @@ class TestPreviewVideoDuetFlag:
asyncio.run(_run())
assert exc_info.value.status_code == 400
assert "is_duet" in exc_info.value.detail
class TestGetPreviewVideoRedirect:
"""get_preview_video must redirect to a signed GCS URL, not proxy the bytes.
Cloud Run caps response bodies at 32 MiB. A long song's 360p preview exceeds
that, so streaming it through Cloud Run (the old FileResponse path) truncated
mid-stream — the response started 206 but the client got a 500, and the
browser reported "no supported format". Serving a 302 to a signed URL lets
the browser fetch the mp4 directly from GCS, bypassing the limit.
"""
def _call(self, mock_storage, job_id="job-x", preview_hash="abc123"):
import asyncio
from backend.api.routes.review import get_preview_video, _preview_videos
_preview_videos.clear() # force the standard-path / file_exists branch
with patch("backend.api.routes.review.StorageService", return_value=mock_storage):
return asyncio.run(get_preview_video(
job_id=job_id,
preview_hash=preview_hash,
auth_info=("user@test.com", "job_owner"),
))
def test_returns_302_redirect_to_signed_url(self):
from starlette.responses import RedirectResponse
mock_storage = MagicMock()
mock_storage.file_exists.return_value = True
mock_storage.generate_signed_url.return_value = "https://signed.example/preview.mp4?sig=xyz"
resp = self._call(mock_storage)
assert isinstance(resp, RedirectResponse)
assert resp.status_code == 302
assert resp.headers["location"] == "https://signed.example/preview.mp4?sig=xyz"
# Signed URL must be generated for the preview GCS object — never proxied.
mock_storage.generate_signed_url.assert_called_once()
assert mock_storage.generate_signed_url.call_args[0][0] == "jobs/job-x/previews/abc123.mp4"
mock_storage.download_file.assert_not_called()
def test_returns_404_when_preview_missing(self):
from fastapi import HTTPException
mock_storage = MagicMock()
mock_storage.file_exists.return_value = False
with pytest.raises(HTTPException) as exc_info:
self._call(mock_storage)
assert exc_info.value.status_code == 404
mock_storage.generate_signed_url.assert_not_called()
@@ -0,0 +1,450 @@
"""
Unit tests for stale duration-confirm processor.
Tests the 24h reminder and 48h auto-cancel+refund logic for jobs stuck in
AWAITING_DURATION_CONFIRM state, within the shared stale review processor.
Money-critical: verifies the FULL credits_charged amount is refunded (not flat 1)
and that the idempotency flag prevents double-refunds.
"""
import pytest
from datetime import datetime, timedelta, timezone
from unittest.mock import Mock, MagicMock, patch, call
# Mock Google Cloud before imports
import sys
sys.modules.setdefault('google.cloud.firestore', MagicMock())
sys.modules.setdefault('google.cloud.storage', MagicMock())
from backend.models.job import JobStatus
def _make_duration_confirm_job(
job_id="dur-job-1",
hours_ago=50,
user_email="user@test.com",
artist="Test Artist",
title="Test Song",
credits_charged=3,
made_for_you=False,
tenant_id="",
expiry_reminder_sent=False,
has_blocking_state=True,
):
"""Helper to create a mock AWAITING_DURATION_CONFIRM job."""
job = Mock()
job.job_id = job_id
job.status = JobStatus.AWAITING_DURATION_CONFIRM
job.user_email = user_email
job.artist = artist
job.title = title
job.made_for_you = made_for_you
job.tenant_id = tenant_id
if has_blocking_state:
entered_at = (datetime.now(timezone.utc) - timedelta(hours=hours_ago)).isoformat()
job.state_data = {
'blocking_state_entered_at': entered_at,
'credits_charged': credits_charged,
}
if expiry_reminder_sent:
job.state_data['expiry_reminder_sent'] = True
else:
job.state_data = {}
return job
def _make_review_job(
job_id="rev-job-1",
status=JobStatus.AWAITING_REVIEW,
hours_ago=50,
user_email="user@test.com",
artist="Test Artist",
title="Test Song",
expiry_reminder_sent=False,
):
"""Helper to create a mock AWAITING_REVIEW job."""
job = Mock()
job.job_id = job_id
job.status = status
job.user_email = user_email
job.artist = artist
job.title = title
job.made_for_you = False
job.tenant_id = ""
entered_at = (datetime.now(timezone.utc) - timedelta(hours=hours_ago)).isoformat()
job.state_data = {
'blocking_state_entered_at': entered_at,
'blocking_action_type': 'lyrics',
}
if expiry_reminder_sent:
job.state_data['expiry_reminder_sent'] = True
return job
@pytest.mark.asyncio
class TestStaleDurationConfirm:
"""Tests for AWAITING_DURATION_CONFIRM jobs in the stale review processor."""
@pytest.fixture
def mock_firestore(self):
service = Mock()
service.list_jobs.return_value = []
service.update_job = Mock()
return service
@pytest.fixture
def mock_job_manager(self):
manager = Mock()
manager.cancel_job.return_value = True
return manager
@pytest.fixture
def mock_email_service(self):
service = Mock()
service.send_review_reminder.return_value = True
service.send_review_expired.return_value = True
service.send_duration_confirm_reminder.return_value = True
service.send_duration_confirm_expired.return_value = True
return service
@pytest.fixture
def mock_user_service(self):
service = Mock()
service.check_credits.return_value = 5
service.add_credits.return_value = (True, 5, "Added 3 credits")
user = Mock()
user.locale = "en"
service.get_user.return_value = user
return service
def _patch_all(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Return a context manager that patches all dependencies."""
from contextlib import contextmanager
@contextmanager
def patches():
with patch('backend.workers.stale_review_processor.FirestoreService', return_value=mock_firestore), \
patch('backend.workers.stale_review_processor.JobManager', return_value=mock_job_manager), \
patch('backend.workers.stale_review_processor.get_email_service', return_value=mock_email_service), \
patch('backend.services.user_service.get_user_service', return_value=mock_user_service):
yield
return patches()
# ------------------------------------------------------------------
# 48h expiry: full refund of credits_charged
# ------------------------------------------------------------------
async def test_48h_expires_with_full_credits_refund(
self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service
):
"""
A duration-confirm job at >=48h should be cancelled, refund ALL
credits_charged (3 in this case, not flat 1), and send
send_duration_confirm_expired.
"""
job = _make_duration_confirm_job(hours_ago=50, credits_charged=3)
# list_jobs called for: AWAITING_REVIEW, IN_REVIEW, AWAITING_DURATION_CONFIRM
mock_firestore.list_jobs.side_effect = [[], [], [job]]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["jobs_expired"] == 1
# Must call add_credits with the full amount (3), not flat 1
mock_user_service.add_credits.assert_called_once_with(
job.user_email,
amount=3,
reason="duration_confirm_expired",
job_id=job.job_id,
)
# Must cancel job with correct reason
mock_job_manager.cancel_job.assert_called_once_with(
job.job_id,
reason="Duration confirmation not completed within 48 hours",
)
# Must send the duration-confirm expired email (NOT review expired)
mock_email_service.send_duration_confirm_expired.assert_called_once()
mock_email_service.send_review_expired.assert_not_called()
async def test_48h_no_double_refund_from_cancel_job(
self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service
):
"""
cancel_job's built-in 1-credit refund must be suppressed so the user
is not refunded twice. The processor must mark credit_refunded=True on
the job (via firestore.update_job) BEFORE calling cancel_job.
"""
job = _make_duration_confirm_job(hours_ago=50, credits_charged=3)
mock_firestore.list_jobs.side_effect = [[], [], [job]]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
await process_stale_reviews()
# Collect all update_job calls
update_calls = mock_firestore.update_job.call_args_list
# One of the calls must set credit_refunded=True
credit_refunded_call = [
c for c in update_calls
if isinstance(c.args[1] if c.args else c.kwargs.get('updates', {}), dict)
and c.args[1].get('credit_refunded') is True
]
assert credit_refunded_call, (
"Expected firestore.update_job({'credit_refunded': True}) before cancel_job "
f"to prevent double-refund. Actual calls: {update_calls}"
)
async def test_48h_credits_charged_zero_skips_add_credits(
self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service
):
"""If credits_charged==0, add_credits should NOT be called (nothing to refund)."""
job = _make_duration_confirm_job(hours_ago=50, credits_charged=0)
mock_firestore.list_jobs.side_effect = [[], [], [job]]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["jobs_expired"] == 1
mock_user_service.add_credits.assert_not_called()
mock_job_manager.cancel_job.assert_called_once()
async def test_48h_sets_expiry_idempotency_flag_after_cancel(
self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service
):
"""
The expiry idempotency flag must be set AFTER a successful cancel_job.
Ordering requirement (Bug E fix): if cancel_job fails the flag must NOT be
set — otherwise the job is stuck (unflagged refund but never cancelled).
"""
job = _make_duration_confirm_job(hours_ago=50, credits_charged=2)
mock_firestore.list_jobs.side_effect = [[], [], [job]]
call_order = []
def record_cancel(*args, **kwargs):
call_order.append("cancel_job")
return True
def record_update(job_id, updates):
if isinstance(updates, dict) and updates.get('state_data.duration_confirm_expiry_processed') is True:
call_order.append("flag_set")
mock_job_manager.cancel_job.side_effect = record_cancel
mock_firestore.update_job.side_effect = record_update
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
await process_stale_reviews()
# Both events must have been recorded
assert "cancel_job" in call_order, "cancel_job was never called"
assert "flag_set" in call_order, (
"Expected update_job with state_data.duration_confirm_expiry_processed=True "
"to be called after cancel_job"
)
# Flag must come AFTER cancel
cancel_idx = call_order.index("cancel_job")
flag_idx = call_order.index("flag_set")
assert flag_idx > cancel_idx, (
f"Idempotency flag was set (pos {flag_idx}) BEFORE cancel_job (pos {cancel_idx}). "
"It must be set only after a successful cancel."
)
async def test_48h_flag_not_set_when_cancel_fails(
self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service
):
"""If cancel_job returns False, the idempotency flag must NOT be written."""
job = _make_duration_confirm_job(hours_ago=50, credits_charged=2)
mock_firestore.list_jobs.side_effect = [[], [], [job]]
mock_job_manager.cancel_job.return_value = False # cancel fails
# Reset side_effect so update_job works normally
mock_firestore.update_job.side_effect = None
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
await process_stale_reviews()
# Flag must NOT be set when cancel failed
update_calls = mock_firestore.update_job.call_args_list
expiry_flag_calls = [
c for c in update_calls
if isinstance(c.args[1] if len(c.args) > 1 else c.kwargs.get('updates', {}), dict)
and (c.args[1] if len(c.args) > 1 else c.kwargs.get('updates', {})).get(
'state_data.duration_confirm_expiry_processed'
) is True
]
assert not expiry_flag_calls, (
"Idempotency flag must NOT be written when cancel_job returns False. "
f"Actual update_job calls: {update_calls}"
)
# ------------------------------------------------------------------
# Idempotency: already-processed job is not refunded again
# ------------------------------------------------------------------
async def test_idempotency_already_processed_not_refunded_again(
self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service
):
"""A job already flagged duration_confirm_expiry_processed must not be processed again."""
job = _make_duration_confirm_job(hours_ago=50, credits_charged=3)
job.state_data['duration_confirm_expiry_processed'] = True
mock_firestore.list_jobs.side_effect = [[], [], [job]]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["jobs_expired"] == 0
mock_user_service.add_credits.assert_not_called()
mock_job_manager.cancel_job.assert_not_called()
mock_email_service.send_duration_confirm_expired.assert_not_called()
# ------------------------------------------------------------------
# 24h reminder
# ------------------------------------------------------------------
async def test_24h_sends_duration_confirm_reminder(
self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service
):
"""
A duration-confirm job at 24–48h should send send_duration_confirm_reminder,
not be cancelled, and not refund credits.
"""
job = _make_duration_confirm_job(hours_ago=30, credits_charged=2)
mock_firestore.list_jobs.side_effect = [[], [], [job]]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["reminders_sent"] == 1
assert result["jobs_expired"] == 0
mock_email_service.send_duration_confirm_reminder.assert_called_once()
call_kwargs = mock_email_service.send_duration_confirm_reminder.call_args.kwargs
assert call_kwargs["to_email"] == job.user_email
# Must NOT cancel or refund
mock_job_manager.cancel_job.assert_not_called()
mock_user_service.add_credits.assert_not_called()
mock_email_service.send_review_reminder.assert_not_called()
async def test_24h_reminder_sets_expiry_reminder_sent_flag(
self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service
):
"""The expiry_reminder_sent flag must be set after sending reminder."""
job = _make_duration_confirm_job(hours_ago=30, credits_charged=2)
mock_firestore.list_jobs.side_effect = [[], [], [job]]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
await process_stale_reviews()
update_calls = mock_firestore.update_job.call_args_list
reminder_flag_calls = [
c for c in update_calls
if isinstance(c.args[1] if c.args else c.kwargs.get('updates', {}), dict)
and c.args[1].get('state_data.expiry_reminder_sent') is True
]
assert reminder_flag_calls, (
f"Expected expiry_reminder_sent=True update. Actual calls: {update_calls}"
)
async def test_24h_reminder_skipped_if_already_sent(
self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service
):
"""If expiry_reminder_sent is already True, reminder must NOT be sent again."""
job = _make_duration_confirm_job(hours_ago=30, credits_charged=2, expiry_reminder_sent=True)
mock_firestore.list_jobs.side_effect = [[], [], [job]]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["reminders_sent"] == 0
mock_email_service.send_duration_confirm_reminder.assert_not_called()
# ------------------------------------------------------------------
# Under 24h: no action
# ------------------------------------------------------------------
async def test_under_24h_no_action(
self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service
):
"""Jobs under 24h must be left alone."""
job = _make_duration_confirm_job(hours_ago=12, credits_charged=2)
mock_firestore.list_jobs.side_effect = [[], [], [job]]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["reminders_sent"] == 0
assert result["jobs_expired"] == 0
mock_email_service.send_duration_confirm_reminder.assert_not_called()
mock_job_manager.cancel_job.assert_not_called()
mock_user_service.add_credits.assert_not_called()
# ------------------------------------------------------------------
# Regression: review-state jobs still use old path
# ------------------------------------------------------------------
async def test_regression_review_job_still_uses_review_path(
self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service
):
"""
AWAITING_REVIEW jobs must still use the existing review expiry path:
cancel_job + send_review_expired (with credits_balance), NOT
add_credits + send_duration_confirm_expired.
"""
review_job = _make_review_job(job_id="rev-1", hours_ago=50)
mock_firestore.list_jobs.side_effect = [[review_job], [], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["jobs_expired"] == 1
# Old path: cancel_job (includes 1-credit refund internally)
mock_job_manager.cancel_job.assert_called_once_with(
"rev-1", reason="Review not completed within 48 hours"
)
# Old email: send_review_expired with credits_balance
mock_email_service.send_review_expired.assert_called_once()
call_kwargs = mock_email_service.send_review_expired.call_args.kwargs
assert call_kwargs["to_email"] == review_job.user_email
assert "credits_balance" in call_kwargs
# Must NOT use duration-confirm path
mock_user_service.add_credits.assert_not_called()
mock_email_service.send_duration_confirm_expired.assert_not_called()
async def test_regression_review_job_24h_reminder_unchanged(
self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service
):
"""AWAITING_REVIEW jobs at 24-48h still use send_review_reminder (unchanged)."""
review_job = _make_review_job(job_id="rev-2", hours_ago=30)
mock_firestore.list_jobs.side_effect = [[review_job], [], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["reminders_sent"] == 1
mock_email_service.send_review_reminder.assert_called_once()
mock_email_service.send_duration_confirm_reminder.assert_not_called()
+13 -13
View File
@@ -110,7 +110,7 @@ class TestProcessStaleReviews:
async def test_expires_job_over_48h(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should expire a job that's been in review for over 48 hours."""
job = _make_job(hours_ago=50)
mock_firestore.list_jobs.side_effect = [[job], []] # awaiting_review query, in_review query
mock_firestore.list_jobs.side_effect = [[job], [], []] # awaiting_review query, in_review query
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
@@ -130,7 +130,7 @@ class TestProcessStaleReviews:
async def test_expires_job_over_48h_with_reminder_already_sent(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should expire job >48h even if reminder was already sent (no duplicate reminder)."""
job = _make_job(hours_ago=50, expiry_reminder_sent=True)
mock_firestore.list_jobs.side_effect = [[job], []]
mock_firestore.list_jobs.side_effect = [[job], [], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
@@ -145,7 +145,7 @@ class TestProcessStaleReviews:
async def test_sends_reminder_24_to_48h(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should send reminder for job in 24-48h range."""
job = _make_job(hours_ago=30)
mock_firestore.list_jobs.side_effect = [[job], []]
mock_firestore.list_jobs.side_effect = [[job], [], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
@@ -169,7 +169,7 @@ class TestProcessStaleReviews:
async def test_skips_if_expiry_reminder_already_sent(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should skip reminder if expiry_reminder_sent is already True."""
job = _make_job(hours_ago=30, expiry_reminder_sent=True)
mock_firestore.list_jobs.side_effect = [[job], []]
mock_firestore.list_jobs.side_effect = [[job], [], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
@@ -185,7 +185,7 @@ class TestProcessStaleReviews:
# reminder_sent is True (set by idle reminder system) but expiry_reminder_sent is not set
assert job.state_data['reminder_sent'] is True
assert 'expiry_reminder_sent' not in job.state_data
mock_firestore.list_jobs.side_effect = [[job], []]
mock_firestore.list_jobs.side_effect = [[job], [], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
@@ -197,7 +197,7 @@ class TestProcessStaleReviews:
async def test_no_action_under_24h(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should take no action for jobs under 24 hours old."""
job = _make_job(hours_ago=12)
mock_firestore.list_jobs.side_effect = [[job], []]
mock_firestore.list_jobs.side_effect = [[job], [], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
@@ -211,7 +211,7 @@ class TestProcessStaleReviews:
async def test_skips_made_for_you_jobs(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should skip made-for-you jobs regardless of age."""
job = _make_job(hours_ago=100, made_for_you=True)
mock_firestore.list_jobs.side_effect = [[job], []]
mock_firestore.list_jobs.side_effect = [[job], [], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
@@ -224,7 +224,7 @@ class TestProcessStaleReviews:
async def test_skips_tenant_jobs(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should skip tenant/white-label jobs regardless of age."""
job = _make_job(hours_ago=100, tenant_id="vocalstar")
mock_firestore.list_jobs.side_effect = [[job], []]
mock_firestore.list_jobs.side_effect = [[job], [], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
@@ -237,7 +237,7 @@ class TestProcessStaleReviews:
async def test_skips_job_without_blocking_state(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should skip jobs that have no blocking_state_entered_at."""
job = _make_job(hours_ago=50, has_blocking_state=False)
mock_firestore.list_jobs.side_effect = [[job], []]
mock_firestore.list_jobs.side_effect = [[job], [], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
@@ -249,7 +249,7 @@ class TestProcessStaleReviews:
async def test_expires_job_without_email(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should still expire jobs with no user_email (just skip the email)."""
job = _make_job(hours_ago=50, user_email=None)
mock_firestore.list_jobs.side_effect = [[job], []]
mock_firestore.list_jobs.side_effect = [[job], [], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
@@ -264,7 +264,7 @@ class TestProcessStaleReviews:
"""An error processing one job should not prevent processing others."""
job1 = _make_job(job_id="job-bad", hours_ago=50)
job2 = _make_job(job_id="job-good", hours_ago=50)
mock_firestore.list_jobs.side_effect = [[job1, job2], []]
mock_firestore.list_jobs.side_effect = [[job1, job2], [], []]
# First cancel raises, second succeeds
mock_job_manager.cancel_job.side_effect = [Exception("DB error"), True]
@@ -283,7 +283,7 @@ class TestProcessStaleReviews:
job_remind = _make_job(job_id="remind-1", hours_ago=30)
job_fresh = _make_job(job_id="fresh-1", hours_ago=12)
job_skip = _make_job(job_id="skip-1", hours_ago=50, made_for_you=True)
mock_firestore.list_jobs.side_effect = [[job_expire, job_remind, job_fresh, job_skip], []]
mock_firestore.list_jobs.side_effect = [[job_expire, job_remind, job_fresh, job_skip], [], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
@@ -296,7 +296,7 @@ class TestProcessStaleReviews:
async def test_handles_in_review_status(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should process jobs in IN_REVIEW status (user opened but abandoned)."""
job = _make_job(job_id="in-review-1", status=JobStatus.IN_REVIEW, hours_ago=50)
mock_firestore.list_jobs.side_effect = [[], [job]] # Empty awaiting, one in_review
mock_firestore.list_jobs.side_effect = [[], [job], []] # Empty awaiting, one in_review, empty duration_confirm
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
+46 -3
View File
@@ -221,11 +221,54 @@ class TestStorageServiceDelete:
mock_client_class.return_value = mock_client
service = StorageService()
service.delete_file("uploads/job123/file.flac")
result = service.delete_file("uploads/job123/file.flac")
mock_bucket.blob.assert_called_once_with("uploads/job123/file.flac")
mock_blob.delete.assert_called_once()
assert result is True
@patch("backend.services.storage_service.storage.Client")
@patch("backend.services.storage_service.settings")
def test_delete_file_missing_raises_by_default(self, mock_settings, mock_client_class):
"""A 404 on delete raises when ignore_missing is not set (default)."""
from google.cloud.exceptions import NotFound
mock_settings.google_cloud_project = "test-project"
mock_settings.gcs_bucket_name = "test-bucket"
mock_blob = Mock()
mock_blob.delete.side_effect = NotFound("No such object")
mock_bucket = Mock()
mock_bucket.blob.return_value = mock_blob
mock_client = Mock()
mock_client.bucket.return_value = mock_bucket
mock_client_class.return_value = mock_client
service = StorageService()
with pytest.raises(NotFound):
service.delete_file("jobs/abc/screens/title.mov")
@patch("backend.services.storage_service.storage.Client")
@patch("backend.services.storage_service.settings")
def test_delete_file_missing_ignored(self, mock_settings, mock_client_class):
"""With ignore_missing=True, a 404 is a no-op returning False (no raise)."""
from google.cloud.exceptions import NotFound
mock_settings.google_cloud_project = "test-project"
mock_settings.gcs_bucket_name = "test-bucket"
mock_blob = Mock()
mock_blob.delete.side_effect = NotFound("No such object")
mock_bucket = Mock()
mock_bucket.blob.return_value = mock_blob
mock_client = Mock()
mock_client.bucket.return_value = mock_bucket
mock_client_class.return_value = mock_client
service = StorageService()
result = service.delete_file("jobs/abc/screens/title.mov", ignore_missing=True)
assert result is False
@patch("backend.services.storage_service.storage.Client")
@patch("backend.services.storage_service.settings")
def test_delete_folder(self, mock_settings, mock_client_class):
+43 -98
View File
@@ -780,61 +780,16 @@ class TestAudioWorkerModelConfiguration:
assert call_kwargs['other_stems_models'] == []
class TestDownloadFromUrl:
"""Tests for download_from_url function - URL-based audio download."""
def test_download_from_url_function_exists(self):
"""Test that download_from_url function exists in audio_worker."""
from backend.workers.audio_worker import download_from_url
assert callable(download_from_url)
def test_download_from_url_signature(self):
"""Test that download_from_url has the expected signature."""
import inspect
from backend.workers.audio_worker import download_from_url
sig = inspect.signature(download_from_url)
params = list(sig.parameters.keys())
# Should have these parameters
assert 'url' in params
assert 'temp_dir' in params
assert 'artist' in params
assert 'title' in params
assert 'job_manager' in params
assert 'job_id' in params
def test_download_from_url_is_async(self):
"""Test that download_from_url is an async function."""
import inspect
from backend.workers.audio_worker import download_from_url
assert inspect.iscoroutinefunction(download_from_url)
@pytest.mark.asyncio
async def test_download_from_url_returns_none_for_invalid_url(self):
"""Test that download_from_url handles errors gracefully."""
from backend.workers.audio_worker import download_from_url
with tempfile.TemporaryDirectory() as temp_dir:
# This should fail gracefully (no yt-dlp in test env or invalid URL)
result = await download_from_url(
url='not-a-valid-url',
temp_dir=temp_dir,
artist='Test',
title='Test'
)
# Should return None on error (graceful failure)
assert result is None
class TestDownloadAudioWithUrl:
"""Tests for download_audio function with URL-based jobs."""
"""Tests for download_audio: it only ever consumes a pre-downloaded GCS file.
URLs are downloaded by the flacfetch service in create_job_from_url before
any worker runs — the audio worker never runs yt-dlp on Cloud Run.
"""
@pytest.fixture
def mock_job_with_url(self):
"""Create a mock job with a URL."""
"""A URL job that (incorrectly) reached the worker without a GCS path."""
return Job(
job_id="test123",
status=JobStatus.PROCESSING,
@@ -844,7 +799,7 @@ class TestDownloadAudioWithUrl:
title="Test Song",
url="https://www.youtube.com/watch?v=test123"
)
@pytest.fixture
def mock_job_manager(self, mock_job_with_url):
"""Create a mock JobManager."""
@@ -852,40 +807,34 @@ class TestDownloadAudioWithUrl:
manager.get_job.return_value = mock_job_with_url
manager.update_job.return_value = None
return manager
@pytest.fixture
def mock_storage(self):
"""Create a mock StorageService."""
storage = MagicMock()
return storage
@pytest.mark.asyncio
async def test_download_audio_from_url(self, mock_job_with_url, mock_job_manager, mock_storage):
"""Test download_audio routes to URL download when job has URL."""
with patch('backend.workers.audio_worker.download_from_url', return_value='/tmp/test.wav') as mock_download:
from backend.workers.audio_worker import download_audio
with tempfile.TemporaryDirectory() as temp_dir:
result = await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_with_url,
job_manager_instance=mock_job_manager
)
# Should have called download_from_url
mock_download.assert_called_once()
# Check positional args
args = mock_download.call_args[0]
assert args[0] == "https://www.youtube.com/watch?v=test123" # url
assert args[1] == temp_dir # temp_dir
assert args[2] == "Test Artist" # artist
assert args[3] == "Test Song" # title
async def test_download_audio_url_without_gcs_path_refuses(self, mock_job_with_url, mock_job_manager, mock_storage):
"""A URL job with no GCS file must fail (no local yt-dlp fallback)."""
from backend.workers.audio_worker import download_audio
with tempfile.TemporaryDirectory() as temp_dir:
result = await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_with_url,
job_manager_instance=mock_job_manager
)
# Refuses to download locally → returns None, never touches storage
assert result is None
mock_storage.download_file.assert_not_called()
@pytest.mark.asyncio
async def test_download_audio_from_gcs_when_no_url(self, mock_job_manager, mock_storage):
"""Test download_audio downloads from GCS when job has no URL."""
async def test_download_audio_from_gcs(self, mock_job_manager, mock_storage):
"""Test download_audio downloads from GCS when input_media_gcs_path is set."""
mock_job_no_url = Job(
job_id="test123",
status=JobStatus.PROCESSING,
@@ -895,24 +844,20 @@ class TestDownloadAudioWithUrl:
title="Test Song",
input_media_gcs_path="uploads/test123/song.flac"
)
with patch('backend.workers.audio_worker.download_from_url') as mock_url_download:
from backend.workers.audio_worker import download_audio
with tempfile.TemporaryDirectory() as temp_dir:
result = await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_no_url,
job_manager_instance=mock_job_manager
)
# Should NOT have called download_from_url
mock_url_download.assert_not_called()
# Should have called storage.download_file
mock_storage.download_file.assert_called()
from backend.workers.audio_worker import download_audio
with tempfile.TemporaryDirectory() as temp_dir:
await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_no_url,
job_manager_instance=mock_job_manager
)
# Should have downloaded the pre-existing GCS file
mock_storage.download_file.assert_called()
class TestBackingVocalsAnalysis:
+24 -26
View File
@@ -4,7 +4,6 @@ Unit tests for YouTubeDownloadService.
Tests the consolidated YouTube download service that handles all YouTube
downloads in the cloud backend.
"""
import os
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -179,43 +178,42 @@ class TestYouTubeDownloadService:
assert "Remote download failed" in str(exc.value)
# =========================================================================
# Local Fallback Tests
# Generic (non-YouTube) URL Tests
# =========================================================================
@pytest.mark.asyncio
async def test_download_falls_back_to_local_when_remote_disabled(self):
"""When remote not configured, should use local yt_dlp."""
mock_storage = MagicMock()
mock_storage.upload_fileobj = MagicMock()
mock_file_handler = MagicMock()
mock_file_handler.download_video = MagicMock(return_value="/tmp/test.webm")
mock_file_handler.convert_to_wav = MagicMock(return_value="/tmp/test.wav")
async def test_download_generic_url_uses_url_source(self):
"""Non-YouTube URLs route through flacfetch's generic 'URL' source."""
mock_client = MagicMock()
mock_client.download_by_id = AsyncMock(return_value="download_123")
mock_client.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://bucket/uploads/job123/audio/Artist - Title.m4a",
})
fb_url = "https://www.facebook.com/share/v/1EnC8Bi5Uq/"
with patch(
'backend.services.youtube_download_service.get_flacfetch_client',
return_value=None # No remote client
), patch(
'backend.services.youtube_download_service.StorageService',
return_value=mock_storage
), patch(
'backend.services.youtube_download_service.YouTubeDownloadService._download_local',
new_callable=AsyncMock,
return_value="uploads/job123/audio/test.wav"
) as mock_local:
return_value=mock_client
):
service = YouTubeDownloadService()
result = await service.download(
url="https://youtu.be/dQw4w9WgXcQ",
url=fb_url,
job_id="job123",
artist="Artist",
title="Title",
)
assert result == "uploads/job123/audio/test.wav"
mock_local.assert_called_once()
assert result == "uploads/job123/audio/Artist - Title.m4a"
call_kwargs = mock_client.download_by_id.call_args.kwargs
assert call_kwargs["source_name"] == "URL"
assert call_kwargs["download_url"] == fb_url
assert call_kwargs["source_id"] == fb_url
@pytest.mark.asyncio
async def test_download_invalid_url_raises_error(self):
"""Should raise error for URLs that can't extract video ID."""
async def test_download_raises_when_remote_not_configured(self):
"""No silent local fallback: hard-fail when flacfetch isn't configured."""
with patch(
'backend.services.youtube_download_service.get_flacfetch_client',
return_value=None
@@ -224,11 +222,11 @@ class TestYouTubeDownloadService:
with pytest.raises(YouTubeDownloadError) as exc:
await service.download(
url="https://vimeo.com/123456",
url="https://youtu.be/dQw4w9WgXcQ",
job_id="job123",
)
assert "Could not extract video ID" in str(exc.value)
assert "flacfetch" in str(exc.value).lower()
# =========================================================================
# Singleton Tests
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Select Instrumental",
"selectInstrumentalBody": "\"{title}\" by {artist} needs instrumental selection",
"videoReadyTitle": "Video Ready!",
"videoReadyBody": "Your karaoke video for \"{title}\" by {artist} is ready to download"
"videoReadyBody": "Your karaoke video for \"{title}\" by {artist} is ready to download",
"confirmDurationTitle": "Confirm job cost",
"confirmDurationBody": "\"{title}\" by {artist} needs a cost confirmation to continue"
},
"admin": {
"invalidDomainFormat": "Invalid domain format",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "تحديد المسار الموسيقي",
"selectInstrumentalBody": "\"{title}\" للفنان {artist} تحتاج إلى تحديد المسار الموسيقي",
"videoReadyTitle": "الفيديو جاهز!",
"videoReadyBody": "فيديو الكاريوكي الخاص بك لأغنية \"{title}\" للفنان {artist} جاهز للتنزيل"
"videoReadyBody": "فيديو الكاريوكي الخاص بك لأغنية \"{title}\" للفنان {artist} جاهز للتنزيل",
"confirmDurationTitle": "تأكيد تكلفة المهمة",
"confirmDurationBody": "تحتاج \"{title}\" للفنان {artist} إلى تأكيد التكلفة للمتابعة"
},
"admin": {
"invalidDomainFormat": "تنسيق النطاق غير صالح",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Selecciona la pista instrumental",
"selectInstrumentalBody": "\"{title}\" de {artist} necessita la selecció de la pista instrumental",
"videoReadyTitle": "Vídeo llest!",
"videoReadyBody": "El teu vídeo de karaoke per a \"{title}\" de {artist} està llest per descarregar"
"videoReadyBody": "El teu vídeo de karaoke per a \"{title}\" de {artist} està llest per descarregar",
"confirmDurationTitle": "Confirma el cost de la tasca",
"confirmDurationBody": "\"{title}\" de {artist} necessita una confirmació de cost per continuar"
},
"admin": {
"invalidDomainFormat": "Format de domini no vàlid",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Vyber instrumentál",
"selectInstrumentalBody": "\"{title}\" od {artist} vyžaduje výběr instrumentálu",
"videoReadyTitle": "Video je připraveno!",
"videoReadyBody": "Tvoje karaoke video pro \"{title}\" od {artist} je připraveno ke stažení"
"videoReadyBody": "Tvoje karaoke video pro \"{title}\" od {artist} je připraveno ke stažení",
"confirmDurationTitle": "Potvrď cenu úlohy",
"confirmDurationBody": "\"{title}\" od {artist} vyžaduje potvrzení ceny pro pokračování"
},
"admin": {
"invalidDomainFormat": "Neplatný formát domény",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Vælg instrumental",
"selectInstrumentalBody": "\"{title}\" af {artist} kræver valg af instrumental",
"videoReadyTitle": "Videoen er klar!",
"videoReadyBody": "Din karaokevideo til \"{title}\" af {artist} er klar til download"
"videoReadyBody": "Din karaokevideo til \"{title}\" af {artist} er klar til download",
"confirmDurationTitle": "Bekræft opgavepris",
"confirmDurationBody": "\"{title}\" af {artist} kræver en prisbekræftelse for at fortsætte"
},
"admin": {
"invalidDomainFormat": "Ugyldigt domæneformat",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Instrumental auswählen",
"selectInstrumentalBody": "\"{title}\" von {artist} benötigt eine Instrumentalauswahl",
"videoReadyTitle": "Video fertig!",
"videoReadyBody": "Dein Karaoke-Video für \"{title}\" von {artist} ist bereit zum Herunterladen"
"videoReadyBody": "Dein Karaoke-Video für \"{title}\" von {artist} ist bereit zum Herunterladen",
"confirmDurationTitle": "Auftragskosten bestätigen",
"confirmDurationBody": "\"{title}\" von {artist} benötigt eine Kostenbestätigung, um fortzufahren"
},
"admin": {
"invalidDomainFormat": "Ungültiges Domain-Format",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Επιλογή Instrumental",
"selectInstrumentalBody": "Το \"{title}\" από {artist} χρειάζεται επιλογή instrumental",
"videoReadyTitle": "Το Βίντεο Είναι Έτοιμο!",
"videoReadyBody": "Το καραόκε βίντεό σου για το \"{title}\" από {artist} είναι έτοιμο για λήψη"
"videoReadyBody": "Το καραόκε βίντεό σου για το \"{title}\" από {artist} είναι έτοιμο για λήψη",
"confirmDurationTitle": "Επιβεβαίωσε το κόστος εργασίας",
"confirmDurationBody": "Το \"{title}\" από {artist} χρειάζεται επιβεβαίωση κόστους για να συνεχίσει"
},
"admin": {
"invalidDomainFormat": "Μη έγκυρη μορφή τομέα",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Select Instrumental",
"selectInstrumentalBody": "\"{title}\" by {artist} needs instrumental selection",
"videoReadyTitle": "Video Ready!",
"videoReadyBody": "Your karaoke video for \"{title}\" by {artist} is ready to download"
"videoReadyBody": "Your karaoke video for \"{title}\" by {artist} is ready to download",
"confirmDurationTitle": "Confirm job cost",
"confirmDurationBody": "\"{title}\" by {artist} needs a cost confirmation to continue"
},
"admin": {
"invalidDomainFormat": "Invalid domain format",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Seleccionar instrumental",
"selectInstrumentalBody": "\"{title}\" de {artist} necesita selección de instrumental",
"videoReadyTitle": "¡Video listo!",
"videoReadyBody": "Tu video de karaoke para \"{title}\" de {artist} está listo para descargar"
"videoReadyBody": "Tu video de karaoke para \"{title}\" de {artist} está listo para descargar",
"confirmDurationTitle": "Confirmar costo del trabajo",
"confirmDurationBody": "\"{title}\" de {artist} necesita una confirmación de costo para continuar"
},
"admin": {
"invalidDomainFormat": "Formato de dominio inválido",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Valitse instrumentaali",
"selectInstrumentalBody": "\"{title}\" esittäjältä {artist} vaatii instrumentaalin valintaa",
"videoReadyTitle": "Video on valmis!",
"videoReadyBody": "Karaokevideosi kappaleelle \"{title}\" esittäjältä {artist} on valmis ladattavaksi"
"videoReadyBody": "Karaokevideosi kappaleelle \"{title}\" esittäjältä {artist} on valmis ladattavaksi",
"confirmDurationTitle": "Vahvista työn hinta",
"confirmDurationBody": "\"{title}\" esittäjältä {artist} vaatii hinnan vahvistuksen jatkamista varten"
},
"admin": {
"invalidDomainFormat": "Virheellinen verkkotunnuksen muoto",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Sélectionner l'instrumental",
"selectInstrumentalBody": "\"{title}\" de {artist} nécessite la sélection d'un instrumental",
"videoReadyTitle": "Vidéo prête !",
"videoReadyBody": "Ta vidéo karaoké pour \"{title}\" de {artist} est prête à être téléchargée"
"videoReadyBody": "Ta vidéo karaoké pour \"{title}\" de {artist} est prête à être téléchargée",
"confirmDurationTitle": "Confirme le coût de la tâche",
"confirmDurationBody": "\"{title}\" de {artist} nécessite une confirmation de coût pour continuer"
},
"admin": {
"invalidDomainFormat": "Format de domaine invalide",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "בחירת פלייבק",
"selectInstrumentalBody": "\"{title}\" מאת {artist} דורש בחירת פלייבק",
"videoReadyTitle": "הווידאו מוכן!",
"videoReadyBody": "סרטון הקריוקי שלכם עבור \"{title}\" מאת {artist} מוכן להורדה"
"videoReadyBody": "סרטון הקריוקי שלכם עבור \"{title}\" מאת {artist} מוכן להורדה",
"confirmDurationTitle": "אישור עלות המשימה",
"confirmDurationBody": "\"{title}\" של {artist} דורש אישור עלות כדי להמשיך"
},
"admin": {
"invalidDomainFormat": "פורמט דומיין לא חוקי",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "इंस्ट्रुमेंटल चुनो",
"selectInstrumentalBody": "{artist} के \"{title}\" के लिए इंस्ट्रुमेंटल चुनने की ज़रूरत है",
"videoReadyTitle": "वीडियो तैयार है!",
"videoReadyBody": "{artist} का तुम्हारा कराओके वीडियो \"{title}\" डाउनलोड के लिए तैयार है"
"videoReadyBody": "{artist} का तुम्हारा कराओके वीडियो \"{title}\" डाउनलोड के लिए तैयार है",
"confirmDurationTitle": "जॉब की लागत की पुष्टि करो",
"confirmDurationBody": "जारी रखने के लिए {artist} के \"{title}\" को लागत की पुष्टि की ज़रूरत है"
},
"admin": {
"invalidDomainFormat": "अमान्य डोमेन फ़ॉर्मैट",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Odaberi instrumental",
"selectInstrumentalBody": "\"{title}\" od {artist} treba odabir instrumentala",
"videoReadyTitle": "Video je spreman!",
"videoReadyBody": "Tvoj karaoke video za \"{title}\" od {artist} je spreman za preuzimanje"
"videoReadyBody": "Tvoj karaoke video za \"{title}\" od {artist} je spreman za preuzimanje",
"confirmDurationTitle": "Potvrdi trošak posla",
"confirmDurationBody": "\"{title}\" od {artist} zahtijeva potvrdu troška za nastavak"
},
"admin": {
"invalidDomainFormat": "Nevažeći format domene",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Instrumentális sáv kiválasztása",
"selectInstrumentalBody": "\"{title}\" ({artist}) instrumentális sávjának kiválasztása szükséges",
"videoReadyTitle": "A videó kész!",
"videoReadyBody": "A(z) \"{title}\" ({artist}) karaoke videód készen áll a letöltésre"
"videoReadyBody": "A(z) \"{title}\" ({artist}) karaoke videód készen áll a letöltésre",
"confirmDurationTitle": "Feladat költségének jóváhagyása",
"confirmDurationBody": "{artist} \"{title}\" című számának folytatásához jóvá kell hagynod a költségeket."
},
"admin": {
"invalidDomainFormat": "Érvénytelen domain formátum",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Pilih Instrumental",
"selectInstrumentalBody": "\"{title}\" oleh {artist} memerlukan pemilihan instrumental",
"videoReadyTitle": "Video Siap!",
"videoReadyBody": "Video karaoke Anda untuk \"{title}\" oleh {artist} siap diunduh"
"videoReadyBody": "Video karaoke Anda untuk \"{title}\" oleh {artist} siap diunduh",
"confirmDurationTitle": "Konfirmasi biaya pekerjaan",
"confirmDurationBody": "\"{title}\" oleh {artist} memerlukan konfirmasi biaya untuk melanjutkan"
},
"admin": {
"invalidDomainFormat": "Format domain tidak valid",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Seleziona la strumentale",
"selectInstrumentalBody": "\"{title}\" di {artist} richiede la selezione della strumentale",
"videoReadyTitle": "Video pronto!",
"videoReadyBody": "Il tuo video karaoke per \"{title}\" di {artist} è pronto per il download"
"videoReadyBody": "Il tuo video karaoke per \"{title}\" di {artist} è pronto per il download",
"confirmDurationTitle": "Conferma il costo del lavoro",
"confirmDurationBody": "\"{title}\" di {artist} richiede una conferma del costo per continuare"
},
"admin": {
"invalidDomainFormat": "Formato del dominio non valido",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "インストゥルメンタルの選択",
"selectInstrumentalBody": "{artist} の「{title}」のインストゥルメンタルの選択をお願いします",
"videoReadyTitle": "動画の準備ができました!",
"videoReadyBody": "{artist} の「{title}」のカラオケ動画がダウンロード可能になりました"
"videoReadyBody": "{artist} の「{title}」のカラオケ動画がダウンロード可能になりました",
"confirmDurationTitle": "料金の確認",
"confirmDurationBody": "{artist}の「{title}」の処理を続けるには、料金の確認が必要です"
},
"admin": {
"invalidDomainFormat": "無効なドメイン形式です",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "반주 선택",
"selectInstrumentalBody": "{artist}의 \"{title}\" 반주 선택이 필요합니다",
"videoReadyTitle": "비디오 준비 완료!",
"videoReadyBody": "{artist}의 \"{title}\" 노래방 비디오를 다운로드할 준비가 되었습니다"
"videoReadyBody": "{artist}의 \"{title}\" 노래방 비디오를 다운로드할 준비가 되었습니다",
"confirmDurationTitle": "작업 비용 확인",
"confirmDurationBody": "{artist}의 \"{title}\" 작업을 계속 진행하려면 비용 확인이 필요합니다"
},
"admin": {
"invalidDomainFormat": "잘못된 도메인 형식",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Pilih Instrumental",
"selectInstrumentalBody": "\"{title}\" oleh {artist} memerlukan pemilihan instrumental",
"videoReadyTitle": "Video Sedia!",
"videoReadyBody": "Video karaoke anda untuk \"{title}\" oleh {artist} sedia untuk dimuat turun"
"videoReadyBody": "Video karaoke anda untuk \"{title}\" oleh {artist} sedia untuk dimuat turun",
"confirmDurationTitle": "Sahkan kos kerja",
"confirmDurationBody": "\"{title}\" oleh {artist} memerlukan pengesahan kos untuk diteruskan"
},
"admin": {
"invalidDomainFormat": "Format domain tidak sah",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Velg instrumental",
"selectInstrumentalBody": "\"{title}\" av {artist} trenger valg av instrumental",
"videoReadyTitle": "Video klar!",
"videoReadyBody": "Karaokevideoen din for \"{title}\" av {artist} er klar for nedlasting"
"videoReadyBody": "Karaokevideoen din for \"{title}\" av {artist} er klar for nedlasting",
"confirmDurationTitle": "Bekreft jobbkostnad",
"confirmDurationBody": "\"{title}\" av {artist} trenger en kostnadsbekreftelse for å fortsette"
},
"admin": {
"invalidDomainFormat": "Ugyldig domeneformat",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Selecteer Instrumental",
"selectInstrumentalBody": "\"{title}\" van {artist} heeft een instrumental-selectie nodig",
"videoReadyTitle": "Video klaar!",
"videoReadyBody": "Je karaokevideo voor \"{title}\" van {artist} is klaar om te downloaden"
"videoReadyBody": "Je karaokevideo voor \"{title}\" van {artist} is klaar om te downloaden",
"confirmDurationTitle": "Bevestig kosten",
"confirmDurationBody": "Voor \"{title}\" van {artist} moet je de kosten bevestigen om door te gaan"
},
"admin": {
"invalidDomainFormat": "Ongeldig domeinformaat",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Wybierz podkład",
"selectInstrumentalBody": "\"{title}\" wykonawcy {artist} wymaga wyboru podkładu",
"videoReadyTitle": "Wideo gotowe!",
"videoReadyBody": "Twoje wideo karaoke dla \"{title}\" wykonawcy {artist} jest gotowe do pobrania"
"videoReadyBody": "Twoje wideo karaoke dla \"{title}\" wykonawcy {artist} jest gotowe do pobrania",
"confirmDurationTitle": "Potwierdź koszt zadania",
"confirmDurationBody": "\"{title}\" wykonawcy {artist} wymaga potwierdzenia kosztów, aby kontynuować"
},
"admin": {
"invalidDomainFormat": "Nieprawidłowy format domeny",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Selecionar Instrumental",
"selectInstrumentalBody": "\"{title}\" de {artist} precisa de seleção de instrumental",
"videoReadyTitle": "Vídeo Pronto!",
"videoReadyBody": "Seu vídeo de karaokê para \"{title}\" de {artist} está pronto para baixar"
"videoReadyBody": "Seu vídeo de karaokê para \"{title}\" de {artist} está pronto para baixar",
"confirmDurationTitle": "Confirmar custo do serviço",
"confirmDurationBody": "\"{title}\" de {artist} precisa de uma confirmação de custo para continuar"
},
"admin": {
"invalidDomainFormat": "Formato de domínio inválido",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Selectează instrumentalul",
"selectInstrumentalBody": "\"{title}\" de {artist} necesită selectarea instrumentalului",
"videoReadyTitle": "Videoclipul este gata!",
"videoReadyBody": "Videoclipul tău de karaoke pentru \"{title}\" de {artist} este gata de descărcare"
"videoReadyBody": "Videoclipul tău de karaoke pentru \"{title}\" de {artist} este gata de descărcare",
"confirmDurationTitle": "Confirmă costul lucrării",
"confirmDurationBody": "\"{title}\" de {artist} necesită o confirmare a costului pentru a continua"
},
"admin": {
"invalidDomainFormat": "Format de domeniu invalid",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Выбери инструментал",
"selectInstrumentalBody": "\"{title}\" от {artist} требует выбора инструментала",
"videoReadyTitle": "Видео готово!",
"videoReadyBody": "Твое караоке-видео для \"{title}\" от {artist} готово к скачиванию"
"videoReadyBody": "Твое караоке-видео для \"{title}\" от {artist} готово к скачиванию",
"confirmDurationTitle": "Подтверди стоимость работы",
"confirmDurationBody": "Для продолжения работы над \"{title}\" исполнителя {artist} необходимо подтвердить стоимость"
},
"admin": {
"invalidDomainFormat": "Неверный формат домена",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Vyber inštrumentál",
"selectInstrumentalBody": "\"{title}\" od {artist} vyžaduje výber inštrumentálu",
"videoReadyTitle": "Video je pripravené!",
"videoReadyBody": "Tvoje karaoke video pre \"{title}\" od {artist} je pripravené na stiahnutie"
"videoReadyBody": "Tvoje karaoke video pre \"{title}\" od {artist} je pripravené na stiahnutie",
"confirmDurationTitle": "Potvrď cenu úlohy",
"confirmDurationBody": "\"{title}\" od {artist} vyžaduje potvrdenie ceny pre pokračovanie"
},
"admin": {
"invalidDomainFormat": "Neplatný formát domény",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Välj instrumental",
"selectInstrumentalBody": "\"{title}\" av {artist} kräver att du väljer instrumental",
"videoReadyTitle": "Videon är klar!",
"videoReadyBody": "Din karaokevideo för \"{title}\" av {artist} är redo att laddas ner"
"videoReadyBody": "Din karaokevideo för \"{title}\" av {artist} är redo att laddas ner",
"confirmDurationTitle": "Bekräfta jobbkostnad",
"confirmDurationBody": "\"{title}\" av {artist} kräver att du bekräftar kostnaden för att fortsätta"
},
"admin": {
"invalidDomainFormat": "Ogiltigt domänformat",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "เลือกดนตรีบรรเลง",
"selectInstrumentalBody": "เพลง \"{title}\" โดย {artist} รอให้คุณเลือกดนตรีบรรเลง",
"videoReadyTitle": "วิดีโอพร้อมแล้ว!",
"videoReadyBody": "วิดีโอคาราโอเกะเพลง \"{title}\" โดย {artist} พร้อมให้ดาวน์โหลดแล้ว"
"videoReadyBody": "วิดีโอคาราโอเกะเพลง \"{title}\" โดย {artist} พร้อมให้ดาวน์โหลดแล้ว",
"confirmDurationTitle": "ยืนยันค่าใช้จ่ายของงาน",
"confirmDurationBody": "\"{title}\" โดย {artist} ต้องการการยืนยันค่าใช้จ่ายเพื่อดำเนินการต่อ"
},
"admin": {
"invalidDomainFormat": "รูปแบบโดเมนไม่ถูกต้อง",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Pumili ng Instrumental",
"selectInstrumentalBody": "Kailangang pumili ng instrumental para sa \"{title}\" ni {artist}",
"videoReadyTitle": "Handa na ang Video!",
"videoReadyBody": "Handa nang i-download ang iyong karaoke video para sa \"{title}\" ni {artist}"
"videoReadyBody": "Handa nang i-download ang iyong karaoke video para sa \"{title}\" ni {artist}",
"confirmDurationTitle": "Kumpirmahin ang gastos ng gawain",
"confirmDurationBody": "Kailangan ng kumpirmasyon sa gastos ng \"{title}\" ni {artist} para makapagpatuloy"
},
"admin": {
"invalidDomainFormat": "Mali ang format ng domain",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Enstrümantal Seç",
"selectInstrumentalBody": "{artist} - \"{title}\" enstrümantal seçimi gerektiriyor",
"videoReadyTitle": "Video Hazır!",
"videoReadyBody": "{artist} - \"{title}\" karaoke videon indirilmeye hazır"
"videoReadyBody": "{artist} - \"{title}\" karaoke videon indirilmeye hazır",
"confirmDurationTitle": "İş maliyetini onayla",
"confirmDurationBody": "Devam etmek için {artist} - \"{title}\" şarkısının maliyetini onaylaman gerekiyor"
},
"admin": {
"invalidDomainFormat": "Geçersiz alan adı formatı",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Вибери інструментал",
"selectInstrumentalBody": "\"{title}\" від {artist} потребує вибору інструменталу",
"videoReadyTitle": "Відео готове!",
"videoReadyBody": "Твоє караоке-відео для \"{title}\" від {artist} готове до завантаження"
"videoReadyBody": "Твоє караоке-відео для \"{title}\" від {artist} готове до завантаження",
"confirmDurationTitle": "Підтвердь вартість завдання",
"confirmDurationBody": "\"{title}\" від {artist} потребує підтвердження вартості для продовження"
},
"admin": {
"invalidDomainFormat": "Недійсний формат домену",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "Chọn nhạc nền",
"selectInstrumentalBody": "\"{title}\" của {artist} cần chọn nhạc nền",
"videoReadyTitle": "Video đã sẵn sàng!",
"videoReadyBody": "Video karaoke của bạn cho bài hát \"{title}\" của {artist} đã sẵn sàng để tải xuống"
"videoReadyBody": "Video karaoke của bạn cho bài hát \"{title}\" của {artist} đã sẵn sàng để tải xuống",
"confirmDurationTitle": "Xác nhận chi phí công việc",
"confirmDurationBody": "\"{title}\" của {artist} cần xác nhận chi phí để tiếp tục"
},
"admin": {
"invalidDomainFormat": "Định dạng tên miền không hợp lệ",
+3 -1
View File
@@ -163,7 +163,9 @@
"selectInstrumentalTitle": "选择伴奏",
"selectInstrumentalBody": "{artist} 的“{title}”需要选择伴奏",
"videoReadyTitle": "视频已就绪!",
"videoReadyBody": "您制作的卡拉OK视频({artist} - {title})已准备好下载"
"videoReadyBody": "您制作的卡拉OK视频({artist} - {title})已准备好下载",
"confirmDurationTitle": "确认任务费用",
"confirmDurationBody": "{artist} 的 \"{title}\" 需要确认费用后才能继续"
},
"admin": {
"invalidDomainFormat": "无效的域名格式",
+119
View File
@@ -22,6 +22,7 @@ import mimetypes
import os
import shutil
import tempfile
from datetime import datetime, timedelta, timezone
from backend.models.job import JobStatus
from backend.services.job_manager import JobManager
@@ -29,11 +30,105 @@ from backend.services.storage_service import StorageService
from backend.services.worker_service import get_worker_service
from backend.services.flacfetch_client import get_flacfetch_client, FlacfetchServiceError
from backend.services.audio_search_service import DownloadError
from backend.services.duration_reconciliation import reconcile_and_maybe_pause
logger = logging.getLogger(__name__)
# Must match max_retries on the audio-download-job in infrastructure/modules/cloud_run.py.
# When CLOUD_RUN_TASK_ATTEMPT < MAX_RETRIES, Cloud Run will retry on failure.
CLOUD_RUN_MAX_RETRIES = 2
# How long the "retry pending" marker is valid for after we record it.
# Generous enough to cover Cloud Run's retry delay (~75s) + provisioning (~75s)
# plus a buffer for slow starts. After this window the UI falls back to the
# normal Retry button so users aren't stuck waiting forever.
RETRY_PENDING_WINDOW = timedelta(minutes=3)
# Statuses indicating the download has already completed for this job.
# When the worker is invoked with one of these statuses, it has been re-run
# (e.g. Cloud Run Job auto-retry of a successful task) and must return
# successfully without re-downloading — re-downloading races with downstream
# workers and breaks the state machine (see job 8a9c74ff post-mortem).
DOWNLOAD_ALREADY_DONE_STATUSES = frozenset({
JobStatus.DOWNLOADING,
JobStatus.AWAITING_AUDIO_EDIT,
JobStatus.IN_AUDIO_EDIT,
JobStatus.AUDIO_EDIT_COMPLETE,
JobStatus.AUDIO_COMPLETE,
JobStatus.TRANSCRIBING,
JobStatus.CORRECTING,
JobStatus.LYRICS_COMPLETE,
JobStatus.GENERATING_SCREENS,
JobStatus.APPLYING_PADDING,
JobStatus.AWAITING_REVIEW,
JobStatus.IN_REVIEW,
JobStatus.REVIEW_COMPLETE,
JobStatus.RENDERING_VIDEO,
JobStatus.RENDER_PENDING_CAPACITY,
JobStatus.AWAITING_INSTRUMENTAL_SELECTION,
JobStatus.INSTRUMENTAL_SELECTED,
JobStatus.GENERATING_VIDEO,
JobStatus.ENCODING,
JobStatus.PACKAGING,
JobStatus.UPLOADING,
JobStatus.NOTIFYING,
JobStatus.COMPLETE,
JobStatus.PREP_COMPLETE,
JobStatus.CANCELLED,
})
def _current_task_attempt() -> int:
"""Read CLOUD_RUN_TASK_ATTEMPT env var injected by Cloud Run Jobs.
Returns 0 outside of Cloud Run Jobs (e.g. unit tests, local invocations).
"""
try:
return int(os.environ.get("CLOUD_RUN_TASK_ATTEMPT", "0"))
except ValueError:
return 0
def _mark_retry_pending_if_attempts_remain(job_manager: JobManager, job_id: str) -> None:
"""If Cloud Run will auto-retry this failed task, record that on the job.
The UI and /retry endpoint use this to avoid showing a Retry button (and
refusing manual retries) while an automatic retry is still in flight.
On the FINAL attempt (no retry coming), explicitly clear any marker left
by an earlier attempt. Otherwise the marker from attempt N persists for
its full TTL after attempt N+1 also fails — blocking the user from
clicking Retry for up to RETRY_PENDING_WINDOW after the job actually
failed permanently.
"""
attempt = _current_task_attempt()
if attempt >= CLOUD_RUN_MAX_RETRIES:
job_manager.update_state_data(job_id, 'cloud_run_retry_pending', None)
return
expires_at = datetime.now(timezone.utc) + RETRY_PENDING_WINDOW
job_manager.update_state_data(job_id, 'cloud_run_retry_pending', {
'expires_at': expires_at.isoformat(),
'expected_attempt': attempt + 1,
})
def _clear_retry_pending_and_error(job_manager: JobManager, job_id: str) -> None:
"""Clear retry-pending marker and stale error fields after a successful run.
Called once the download has succeeded so the dashboard stops displaying
a transient failure message and the retry button (where shown elsewhere)
no longer wrongly suggests action is required.
"""
job_manager.update_state_data(job_id, 'cloud_run_retry_pending', None)
job_manager.update_job(job_id, {
'error_message': None,
'error_details': {},
})
def _extract_gcs_path(filepath: str) -> str:
"""Extract relative GCS path from a full gs:// URL or path."""
bucket_prefix = "gs://karaoke-gen-storage-nomadkaraoke/"
@@ -72,6 +167,17 @@ async def process_audio_download(job_id: str) -> bool:
logger.error(f"[job:{job_id}] Job not found")
return False
# Idempotency guard: if the download is already done (status is past
# DOWNLOADING_AUDIO), return success without re-running. This handles
# Cloud Run Job auto-retries of a successful task — re-downloading
# would double-trigger downstream workers and break state transitions.
if job.status in DOWNLOAD_ALREADY_DONE_STATUSES:
logger.info(
f"[job:{job_id}] Download already complete (status={job.status}), "
f"skipping re-run"
)
return True
# Validate job is in correct state
if job.status not in (JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED):
logger.warning(
@@ -127,6 +233,10 @@ async def process_audio_download(job_id: str) -> bool:
'filename': filename,
})
# Download succeeded — clear any stale retry-pending marker and
# previous error so the UI stops showing a resolved failure.
_clear_retry_pending_and_error(job_manager, job_id)
# Transition from DOWNLOADING_AUDIO to DOWNLOADING
job_manager.transition_to_state(
job_id=job_id,
@@ -169,6 +279,13 @@ async def process_audio_download(job_id: str) -> bool:
logger.info(f"[job:{job_id}] Audio download complete, awaiting audio edit")
return True
# Reconcile credit charge against actual audio duration before processing.
# If the audio turns out longer than estimated, the job is paused for
# re-confirmation (AWAITING_DURATION_CONFIRM) or cancelled; in either case
# we must NOT trigger downstream workers.
if await reconcile_and_maybe_pause(job_id):
return True # paused for confirmation or cancelled; workers not started
# Trigger audio separation and lyrics workers
worker_service = get_worker_service()
await asyncio.gather(
@@ -181,10 +298,12 @@ async def process_audio_download(job_id: str) -> bool:
except (DownloadError, FlacfetchServiceError) as e:
logger.error(f"[job:{job_id}] Download failed: {e}")
_mark_retry_pending_if_attempts_remain(job_manager, job_id)
job_manager.fail_job(job_id, f"Audio download failed: {e}")
return False
except Exception as e:
logger.error(f"[job:{job_id}] Download failed: {e}", exc_info=True)
_mark_retry_pending_if_attempts_remain(job_manager, job_id)
job_manager.fail_job(job_id, f"Audio download failed: {e}")
return False
+21 -197
View File
@@ -21,9 +21,7 @@ import shutil
import tempfile
import time
from typing import Optional, Dict, Any
from pathlib import Path
from backend.models.job import JobStatus
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.job_health_service import validate_worker_can_run
@@ -40,29 +38,6 @@ from karaoke_gen.audio_processor import AudioProcessor
logger = logging.getLogger(__name__)
async def _trigger_lyrics_worker_after_url_download(job_id: str) -> None:
"""
Trigger lyrics worker after URL audio download completes.
For URL jobs, we use sequential triggering:
1. Audio worker downloads and uploads audio to GCS
2. Audio worker triggers lyrics worker (this function)
3. Both workers then proceed in parallel (audio separation + lyrics transcription)
This prevents the race condition where lyrics worker times out waiting for audio.
"""
from backend.services.worker_service import get_worker_service
try:
worker_service = get_worker_service()
await worker_service.trigger_lyrics_worker(job_id)
logger.info(f"Job {job_id}: Triggered lyrics worker after URL download")
except Exception as e:
# Log but don't fail - audio processing can still continue
# The job will eventually timeout if lyrics worker doesn't run
logger.error(f"Job {job_id}: Failed to trigger lyrics worker: {e}")
# Default ensemble presets — resolved by audio-separator package into models + algorithm.
# To change models, update ensemble_presets.json in audio-separator and release a new version.
DEFAULT_INSTRUMENTAL_PRESET = "instrumental_clean" # Fv7z + Resurrection, SDR ~17.5
@@ -80,126 +55,6 @@ AUDIO_WORKER_LOGGERS = [
]
async def download_from_url(url: str, temp_dir: str, artist: str, title: str, job_manager: JobManager = None, job_id: str = None) -> Optional[str]:
"""
Download audio from a URL using local yt_dlp.
IMPORTANT: This is a LEGACY FALLBACK for non-YouTube URLs only!
For YouTube URLs, use YouTubeDownloadService instead, which:
- Uses remote flacfetch when configured (avoids Cloud Run bot detection)
- Has proper error handling and GCS upload
This function uses local yt_dlp and will likely FAIL for YouTube URLs
on Cloud Run due to bot detection (YouTube blocks Cloud Run IP ranges).
Uses the FileHandler from karaoke_gen which includes:
- Anti-detection options (user agent, headers, delays)
- Cookie support for authenticated downloads
- Retry logic
If artist and/or title are not provided, attempts to extract them from
the URL metadata.
Args:
url: URL to download from (NOT recommended for YouTube - use YouTubeDownloadService)
temp_dir: Temporary directory to save to
artist: Artist name for filename (can be None for auto-detection)
title: Song title for filename (can be None for auto-detection)
job_manager: Optional JobManager to update job with detected metadata
job_id: Optional job ID to update
Returns:
Path to downloaded audio file, or None if failed
"""
try:
from karaoke_gen.file_handler import FileHandler
from karaoke_gen.utils import sanitize_filename
# Create FileHandler instance
file_handler = FileHandler(
logger=logger,
ffmpeg_base_command="ffmpeg -hide_banner -loglevel error -nostats -y",
create_track_subfolders=False,
dry_run=False
)
# Try to extract metadata if artist or title not provided
if not artist or not title:
logger.info(f"Extracting metadata from URL: {url}")
metadata = file_handler.extract_metadata_from_url(url)
if metadata:
if not artist:
artist = metadata.get('artist', 'Unknown')
logger.info(f"Auto-detected artist: {artist}")
if not title:
title = metadata.get('title', 'Unknown')
logger.info(f"Auto-detected title: {title}")
# Update job with detected metadata if job_manager provided
if job_manager and job_id:
update_data = {}
if artist:
update_data['artist'] = artist
if title:
update_data['title'] = title
if update_data:
job_manager.update_job(job_id, update_data)
logger.info(f"Updated job {job_id} with detected metadata")
else:
logger.warning("Could not extract metadata from URL, using defaults")
artist = artist or "Unknown"
title = title or "Unknown"
# Create output filename (without extension)
safe_artist = sanitize_filename(artist) if artist else "Unknown"
safe_title = sanitize_filename(title) if title else "Unknown"
output_filename_no_extension = os.path.join(temp_dir, f"{safe_artist} - {safe_title}")
# Get YouTube cookies from environment variable if available
# This helps bypass "Sign in to confirm you're not a bot" errors
cookies_str = os.environ.get("YOUTUBE_COOKIES")
if cookies_str:
logger.info("Using YouTube cookies for download authentication")
else:
logger.info("No YOUTUBE_COOKIES env var set - attempting download without cookies")
# Download using FileHandler (includes anti-detection features)
logger.info(f"Downloading from URL: {url}")
downloaded_file = file_handler.download_video(
url=url,
output_filename_no_extension=output_filename_no_extension,
cookies_str=cookies_str
)
if downloaded_file and os.path.exists(downloaded_file):
logger.info(f"Downloaded video: {downloaded_file}")
# Convert to WAV for processing
wav_file = file_handler.convert_to_wav(
input_filename=downloaded_file,
output_filename_no_extension=output_filename_no_extension
)
if wav_file and os.path.exists(wav_file):
logger.info(f"Converted to WAV: {wav_file}")
return wav_file
else:
logger.error("WAV conversion failed")
return None
else:
logger.error("Download failed - no file returned")
return None
except ImportError as e:
logger.error(f"Import error: {e}. Check karaoke_gen installation.")
return None
except Exception as e:
logger.error(f"Failed to download from URL {url}: {e}", exc_info=True)
return None
def create_audio_processor(
temp_dir: str,
model_file_dir: Optional[str] = None,
@@ -543,12 +398,16 @@ async def download_audio(
job_manager_instance: JobManager = None
) -> Optional[str]:
"""
Download or fetch audio file to local temp directory.
Handles two cases:
1. Uploaded file: Download from GCS using input_media_gcs_path
2. URL (YouTube, etc.): Download using yt-dlp or other tools
Fetch the job's audio file from GCS to a local temp directory.
All inputs are expected to already be in GCS by the time this worker runs:
- Uploaded files: at input_media_gcs_path
- URL jobs: downloaded by the flacfetch service in create_job_from_url
before any worker is triggered
This worker never downloads from a URL itself (no yt-dlp on Cloud Run); a
URL job arriving without a GCS file is treated as an upstream bug.
Args:
job_id: Job ID
temp_dir: Temporary directory to save to
@@ -594,55 +453,20 @@ async def download_audio(
logger.info(f"Job {job_id}: Downloaded audio from GCS: {input_url}")
return local_path
# Case 3: Fresh URL that needs downloading (legacy fallback)
# NOTE: YouTube URLs should be downloaded by YouTubeDownloadService in file_upload.py
# BEFORE triggering this worker. If we reach here with a YouTube URL, it means
# the download was not done upfront, which will likely fail due to bot detection.
# A URL job that reached this worker WITHOUT a pre-downloaded GCS file is
# an upstream bug: all URLs are downloaded by the flacfetch service in
# create_job_from_url before any worker runs. We never run yt-dlp on
# Cloud Run, so there is no local fallback — fail clearly instead.
if job.url:
# Check if this is a YouTube URL that should have been handled earlier
is_youtube = any(domain in job.url.lower() for domain in ['youtube.com', 'youtu.be'])
if is_youtube:
logger.warning(
f"Job {job_id}: YouTube URL reached download_audio() fallback. "
"This may fail due to bot detection. YouTube URLs should be "
"downloaded via YouTubeDownloadService before triggering workers."
)
logger.info(f"Job {job_id}: Downloading from URL: {job.url}")
# Use provided job_manager or create new one
jm = job_manager_instance or JobManager()
local_path = await download_from_url(
job.url,
temp_dir,
job.artist,
job.title,
job_manager=jm,
job_id=job_id
logger.error(
f"Job {job_id}: URL job reached the audio worker without a "
f"downloaded input_media_gcs_path (url={job.url}). URLs must be "
"fetched via the flacfetch service before processing; refusing to "
"download locally."
)
return None
if local_path and os.path.exists(local_path):
# Upload to GCS and update job
gcs_path = f"jobs/{job_id}/input/{os.path.basename(local_path)}"
url = storage.upload_file(local_path, gcs_path)
# Update job with GCS path for lyrics worker
jm.update_job(job_id, {'input_media_gcs_path': gcs_path})
jm.update_file_url(job_id, 'input', 'audio', url)
logger.info(f"Job {job_id}: Downloaded and uploaded audio to GCS: {gcs_path}")
# For URL jobs, trigger lyrics worker now that audio is available
# This is the sequential trigger pattern - audio first, then lyrics
await _trigger_lyrics_worker_after_url_download(job_id)
return local_path
else:
logger.error(f"Job {job_id}: Failed to download from URL: {job.url}")
return None
logger.error(f"Job {job_id}: No input source found (no GCS path, file_urls, or URL)")
logger.error(f"Job {job_id}: No input source found (no GCS path or file_urls)")
return None
except Exception as e:
+59 -4
View File
@@ -61,6 +61,50 @@ TRANSCRIPTION_TIMEOUT_SECONDS = 1200
DEFAULT_AGENTIC_TIMEOUT_SECONDS = 180
def probe_audio_duration_seconds(audio_path: str) -> Optional[float]:
"""Return the audio duration in seconds via ffprobe, or None on failure.
Used to scale the transcription timeout for long inputs. Non-fatal: any
failure returns None and the caller falls back to the floor timeout.
"""
import subprocess
try:
result = subprocess.run(
[
"ffprobe", "-v", "quiet", "-print_format", "json",
"-show_format", audio_path,
],
capture_output=True, text=True, timeout=30,
)
if result.returncode != 0:
return None
fmt = json.loads(result.stdout).get("format", {})
duration = float(fmt.get("duration", 0) or 0)
return duration if duration > 0 else None
except Exception:
return None
def compute_transcription_timeout(audio_duration_seconds: Optional[float], settings=None) -> int:
"""Compute the outer transcription timeout, scaled by audio duration.
Long inputs (e.g. 30+ minute mashups) legitimately take longer to
transcribe, so we scale the safety-net timeout with audio length while
bounding it to [floor, cap]. The cap stays below the Cloud Run Job task
timeout so we raise a clean RuntimeError before the platform hard-kills the
task. When the duration is unknown (probe failed), fall back to the floor.
"""
if settings is None:
settings = get_settings()
floor = settings.transcription_timeout_floor_seconds
cap = settings.transcription_timeout_cap_seconds
if not audio_duration_seconds or audio_duration_seconds <= 0:
return floor
scaled = int(audio_duration_seconds * settings.transcription_timeout_per_audio_second)
return max(floor, min(cap, scaled))
def _configure_agentic_ai():
"""Configure environment variables for agentic AI correction.
@@ -365,6 +409,18 @@ async def process_lyrics_transcription(job_id: str) -> bool:
f"Agentic AI enabled with {timeout_seconds}s timeout"
)
# Scale the outer (safety-net) timeout by audio duration so long
# inputs (e.g. 30+ minute mashups) aren't killed prematurely. A
# fixed 1200s cap previously flapped long tracks to 'failed' even
# when AudioShake would have finished. Bounded by [floor, cap]
# (cap stays under the Cloud Run Job task timeout).
audio_duration_seconds = probe_audio_duration_seconds(audio_path)
outer_timeout = compute_transcription_timeout(audio_duration_seconds, settings)
job_log.info(
f"Transcription timeout set to {outer_timeout}s "
f"(audio duration: {audio_duration_seconds}s)"
)
# Run transcription in thread pool
# When agentic AI is enabled, wrap with outer timeout as safety net
# Inner deadline check in corrector.py will break out of gap loop gracefully
@@ -387,7 +443,6 @@ async def process_lyrics_transcription(job_id: str) -> bool:
# The inner deadline check in corrector.py handles the 3-minute
# correction limit gracefully by returning partial results.
# This outer timeout is a safety net for completely hung LLM calls.
outer_timeout = TRANSCRIPTION_TIMEOUT_SECONDS # Same as non-agentic
try:
result = await asyncio.wait_for(
transcription_coro,
@@ -404,14 +459,14 @@ async def process_lyrics_transcription(job_id: str) -> bool:
f"Lyrics transcription timed out after {outer_timeout}s"
) from None
else:
# Non-agentic mode: use general timeout (10 minutes)
# Non-agentic mode: use the same duration-scaled timeout.
try:
result = await asyncio.wait_for(
transcription_coro,
timeout=TRANSCRIPTION_TIMEOUT_SECONDS
timeout=outer_timeout
)
except asyncio.TimeoutError:
raise Exception(f"Transcription timed out after {TRANSCRIPTION_TIMEOUT_SECONDS} seconds")
raise Exception(f"Transcription timed out after {outer_timeout} seconds")
trans_duration = time.time() - trans_start
trans_span.set_attribute("duration_seconds", trans_duration)
+151 -50
View File
@@ -1,9 +1,10 @@
"""
Stale review processor.
Detects jobs stuck in review (awaiting_review / in_review) and takes action:
Detects jobs stuck in review (awaiting_review / in_review) or awaiting duration
confirmation (awaiting_duration_confirm) and takes action:
- 24h: sends a gentle reminder email with expiry warning
- 48h: auto-cancels the job and refunds the user's credit
- 48h: auto-cancels the job and refunds the user's credits
Called by Cloud Scheduler via an internal endpoint (hourly).
"""
@@ -23,13 +24,28 @@ logger = logging.getLogger(__name__)
REVIEW_REMINDER_HOURS = 24
REVIEW_EXPIRY_HOURS = 48
# Statuses treated as "review" states (1-credit refund via cancel_job)
_REVIEW_STATUSES = {JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW}
# Statuses treated as "duration confirm" states (credits_charged refund)
_DURATION_CONFIRM_STATUSES = {JobStatus.AWAITING_DURATION_CONFIRM}
async def process_stale_reviews() -> Dict[str, Any]:
"""
Query for stale review jobs and take action.
Query for stale review / duration-confirm jobs and take action.
- Jobs in review for >= 48h are auto-cancelled with credit refund
- Jobs in review for >= 24h (but < 48h) get a reminder email
- Jobs in these states for >= 48h are auto-cancelled with credit refund
- Jobs in these states for >= 24h (but < 48h) get a reminder email
Review states (AWAITING_REVIEW, IN_REVIEW):
- 24h reminder: send_review_reminder
- 48h expiry: cancel_job (auto-refunds 1 credit) + send_review_expired
Duration-confirm state (AWAITING_DURATION_CONFIRM):
- 24h reminder: send_duration_confirm_reminder
- 48h expiry: add_credits(credits_charged) + cancel_job + send_duration_confirm_expired
The full credits_charged amount (not flat 1) is refunded.
Excludes made-for-you and tenant jobs.
@@ -44,9 +60,9 @@ async def process_stale_reviews() -> Dict[str, Any]:
jobs_expired = 0
errors = []
# Query for jobs in both blocking review states
# Query for jobs in all blocking states
stale_jobs = []
for status in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
for status in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW, JobStatus.AWAITING_DURATION_CONFIRM]:
try:
jobs = firestore.list_jobs(status=status, limit=500)
stale_jobs.extend(jobs)
@@ -97,48 +113,124 @@ async def process_stale_reviews() -> Dict[str, Any]:
hours_elapsed = (now - blocking_entered_at).total_seconds() / 3600
if hours_elapsed >= REVIEW_EXPIRY_HOURS:
# Auto-expire: cancel job (which refunds credit)
logger.info(
f"Job {job.job_id}: review stale for {hours_elapsed:.1f}h (>={REVIEW_EXPIRY_HOURS}h), "
f"auto-expiring"
)
cancelled = job_manager.cancel_job(
job.job_id,
reason="Review not completed within 48 hours"
)
if cancelled:
jobs_expired += 1
is_duration_confirm = job.status in _DURATION_CONFIRM_STATUSES
# Send expiry notification email
if job.user_email:
if hours_elapsed >= REVIEW_EXPIRY_HOURS:
if is_duration_confirm:
# Duration-confirm expiry: refund full credits_charged, then cancel.
# Check idempotency flag first.
if state_data.get('duration_confirm_expiry_processed'):
continue
logger.info(
f"Job {job.job_id}: duration-confirm stale for {hours_elapsed:.1f}h "
f"(>={REVIEW_EXPIRY_HOURS}h), auto-expiring with credits_charged refund"
)
credits_charged = state_data.get('credits_charged', 0) or 0
credits_refunded = 0
# Refund the full charged amount (not flat 1) BEFORE cancelling.
# We also mark credit_refunded=True on the job first so that
# cancel_job's built-in _refund_credit_for_job skips its 1-credit
# refund and we don't double-charge the user.
if credits_charged > 0 and job.user_email:
try:
from backend.services.user_service import get_user_service
user_service = get_user_service()
credits_balance = user_service.check_credits(job.user_email)
# Look up user locale for email
user_locale = "en"
try:
user = user_service.get_user(job.user_email)
if user and user.locale:
user_locale = user.locale
except Exception:
pass
email_service.send_review_expired(
to_email=job.user_email,
artist=job.artist,
title=job.title,
credits_balance=credits_balance,
locale=user_locale,
ok, _, _ = user_service.add_credits(
job.user_email,
amount=credits_charged,
reason="duration_confirm_expired",
job_id=job.job_id,
)
except Exception as email_err:
if ok:
credits_refunded = credits_charged
# Prevent cancel_job's internal 1-credit refund
firestore.update_job(job.job_id, {'credit_refunded': True})
except Exception as refund_err:
logger.error(
f"Job {job.job_id}: failed to send expiry email: {email_err}"
f"Job {job.job_id}: failed to refund {credits_charged} credits: {refund_err}"
)
cancelled = job_manager.cancel_job(
job.job_id,
reason="Duration confirmation not completed within 48 hours",
)
if cancelled:
jobs_expired += 1
# Set idempotency flag AFTER a successful cancel so that a
# cancel_job failure leaves the job un-flagged and re-processable
# on the next run (the refund is idempotent via add_credits).
try:
firestore.update_job(job.job_id, {
'state_data.duration_confirm_expiry_processed': True,
'state_data.duration_confirm_expiry_processed_at': datetime.now(timezone.utc).isoformat(),
})
except Exception as flag_err:
logger.error(
f"Job {job.job_id}: failed to set duration_confirm_expiry_processed: {flag_err}"
)
if job.user_email:
try:
email_service.send_duration_confirm_expired(
to_email=job.user_email,
artist=job.artist,
title=job.title,
credits_refunded=credits_refunded,
locale="en",
)
except Exception as email_err:
logger.error(
f"Job {job.job_id}: failed to send duration_confirm_expired email: {email_err}"
)
else:
logger.warning(f"Job {job.job_id}: cancel_job returned False")
else:
logger.warning(f"Job {job.job_id}: cancel_job returned False")
# Review-state expiry: cancel job (auto-refunds 1 credit via cancel_job)
logger.info(
f"Job {job.job_id}: review stale for {hours_elapsed:.1f}h (>={REVIEW_EXPIRY_HOURS}h), "
f"auto-expiring"
)
cancelled = job_manager.cancel_job(
job.job_id,
reason="Review not completed within 48 hours"
)
if cancelled:
jobs_expired += 1
# Send expiry notification email
if job.user_email:
try:
from backend.services.user_service import get_user_service
user_service = get_user_service()
credits_balance = user_service.check_credits(job.user_email)
# Look up user locale for email
user_locale = "en"
try:
user = user_service.get_user(job.user_email)
if user and user.locale:
user_locale = user.locale
except Exception:
pass
email_service.send_review_expired(
to_email=job.user_email,
artist=job.artist,
title=job.title,
credits_balance=credits_balance,
locale=user_locale,
)
except Exception as email_err:
logger.error(
f"Job {job.job_id}: failed to send expiry email: {email_err}"
)
else:
logger.warning(f"Job {job.job_id}: cancel_job returned False")
elif hours_elapsed >= REVIEW_REMINDER_HOURS:
# Check if expiry reminder was already sent
@@ -146,11 +238,11 @@ async def process_stale_reviews() -> Dict[str, Any]:
continue
logger.info(
f"Job {job.job_id}: review stale for {hours_elapsed:.1f}h (>={REVIEW_REMINDER_HOURS}h), "
f"Job {job.job_id}: stale for {hours_elapsed:.1f}h (>={REVIEW_REMINDER_HOURS}h), "
f"sending reminder"
)
# Send reminder email
# Send reminder email (different email per status)
if job.user_email:
try:
# Look up user locale for email
@@ -164,13 +256,22 @@ async def process_stale_reviews() -> Dict[str, Any]:
except Exception:
pass
email_service.send_review_reminder(
to_email=job.user_email,
artist=job.artist,
title=job.title,
job_id=job.job_id,
locale=user_locale,
)
if is_duration_confirm:
email_service.send_duration_confirm_reminder(
to_email=job.user_email,
job_id=job.job_id,
artist=job.artist,
title=job.title,
locale=user_locale,
)
else:
email_service.send_review_reminder(
to_email=job.user_email,
artist=job.artist,
title=job.title,
job_id=job.job_id,
locale=user_locale,
)
except Exception as email_err:
logger.error(
f"Job {job.job_id}: failed to send reminder email: {email_err}"
+6
View File
@@ -4,6 +4,12 @@
Free credit grants (welcome credits and feedback bonus credits) are evaluated by an AI model before being approved. This prevents multi-account abuse where users create multiple accounts to farm free karaoke generation credits.
> **Per-job credit charging** (how many credits each job costs) is a separate concern documented in
> [API.md § Credit Enforcement](API.md#credit-enforcement) and
> [ARCHITECTURE.md § Job States](ARCHITECTURE.md#job-states). Jobs are now charged by input audio
> duration (`max(1, ceil(minutes/10))`); inputs over 60 minutes are blocked. This document covers
> only the AI-evaluation gate on *free* credit grants.
The system is **fail-closed**: if anything goes wrong (AI error, unclear response, network issue), credits are NOT granted automatically. Instead, the admin is notified to review manually.
## How It Works
+145 -13
View File
@@ -68,6 +68,91 @@ Status values:
### Jobs
#### Create Job from URL
```http
POST /api/jobs
Content-Type: application/json
{
"url": "https://www.youtube.com/watch?v=...",
"artist": "Artist Name", // optional, auto-detected if omitted
"title": "Song Title", // optional, auto-detected if omitted
"is_private": false, // optional
"duration_seconds": 245.3, // optional — from /api/jobs/estimate; drives pre-flight credit deduction
"acknowledged_credits": 1 // optional — if provided, server validates it equals the computed cost; 409 on mismatch
}
```
Creates a job from a YouTube (or other supported) URL. Credit cost is `max(1, ceil(minutes/10))`
(10-minute tiers). If `duration_seconds` is omitted the system deducts 1 credit as a hold and
settles the true cost after download (see [Duration-Based Pricing](#duration-based-pricing)).
Admin jobs bypass all credit deduction.
`acknowledged_credits` is **optional**. If provided, the server validates it equals the
server-computed credit cost and returns 409 on mismatch (race-condition guard for the UI). If
omitted, the server charges the computed cost without client confirmation.
Returns `JobResponse` (job id, status, etc.).
**Errors:**
- `402` — Insufficient credits (see [Credit Enforcement](#credit-enforcement))
- `409` — `acknowledged_credits` was provided and does not match server-computed cost; client should refresh and re-confirm
- `422` — Input exceeds 60-minute hard limit
#### Estimate URL Duration (pre-flight)
```http
POST /api/jobs/estimate
Content-Type: application/json
{"url": "https://www.youtube.com/watch?v=..."}
```
Probes the URL (via flacfetch `/check-youtube`) **without creating a job or downloading audio**.
Use this before `POST /api/jobs` to show the user the credit cost.
Response:
```json
{
"duration_seconds": 245.3,
"credits": 1,
"blocked": false,
"source": "youtube_metadata"
}
```
- `duration_seconds`: `null` if the probe fails (bot challenge, unsupported URL, etc.)
- `source`: `"youtube_metadata"` | `"unknown"` (probe failed)
- `blocked`: `true` when `duration_seconds > 3600` (60 min) — create will be rejected
- `credits`: computed from `max(1, ceil(duration_seconds / 600))`; `1` when duration unknown
When `duration_seconds` is `null`, warn the user that the final cost will be confirmed after
download and create the job with a 1-credit hold.
#### Confirm Duration (resume paused job)
```http
POST /api/jobs/{job_id}/confirm-duration
Content-Type: application/json
{"acknowledged_credits": 3}
```
Called when a job is paused in `AWAITING_DURATION_CONFIRM` state. Two scenarios:
- **`preflight`** — upload flow: duration measured after file lands in GCS; no charge applied yet.
`acknowledged_credits` must equal the full cost (`pending_additional_credits` in `state_data`).
- **`reconcile`** — post-download: actual duration costs more than was already charged.
`acknowledged_credits` must equal the new total (`credits_charged + pending_additional_credits`).
On success, deducts the owed credits and resumes by triggering both audio and lyrics workers.
Returns the updated job.
**Errors:**
- `402` — Insufficient credits; user should buy more and retry
- `409` — `acknowledged_credits` doesn't match server's current figure (race/refresh); client should re-fetch the job and re-show the dialog
#### Create Job with Upload
```http
@@ -700,11 +785,19 @@ POST /api/audio-search/{job_id}/select
Content-Type: application/json
{
"selection_index": 0
"selection_index": 0,
"acknowledged_credits": 2 // optional — if provided, server validates it equals the computed total; 409 on mismatch
}
```
Selects an audio source from the search results and starts processing.
Selects an audio source from the search results and starts processing. Credits are deducted here
based on the selected result's duration (`max(1, ceil(minutes/10))`). Torrent results display an
"estimated" label because metadata may differ from actual audio length; the cost is reconciled
post-download and may trigger an `AWAITING_DURATION_CONFIRM` pause if the actual duration is longer.
`acknowledged_credits` is **optional**. If provided, the server validates it equals the
server-computed credit total and returns 409 on mismatch. If omitted, the server deducts the
computed cost without client confirmation.
#### Standalone Search (Guided Flow — Step 2)
@@ -860,6 +953,7 @@ POST /api/internal/jobs/{job_id}/trigger-video
|-------|-------------|
| `pending` | Created, not started |
| `downloading` | Processing input |
| `awaiting_duration_confirm` | **Human checkpoint** — cost confirmation required before heavy processing begins (see [Duration-Based Pricing](#duration-based-pricing)) |
| `separating_stage1` | Audio separation (1/2) |
| `separating_stage2` | Audio separation (2/2) |
| `transcribing` | Lyrics transcription |
@@ -1029,24 +1123,56 @@ After payment completes via Stripe webhook:
### Credit Enforcement
Credits are checked and deducted at job creation time. The flow:
#### Duration-Based Pricing
1. **Check** - `user_service.has_credits()` verifies the user has >= 1 credit
2. **Create job** - Job is persisted to Firestore
3. **Deduct** - `user_service.deduct_credit()` atomically deducts 1 credit (with job_id for audit trail)
4. **Refund on failure** - If the job fails, 1 credit is automatically refunded
Credits are charged proportionally to audio duration: `max(1, ceil(minutes / 10))` per job.
Admin users bypass credit checks entirely. New users receive 1 welcome credit. Users can earn 1 additional free credit by submitting product feedback after completing 2+ jobs (see [User Feedback for Credits](#user-feedback-for-credits)).
| Duration | Credits |
|----------|---------|
| 0:00 – 10:00 | 1 |
| 10:01 – 20:00 | 2 |
| 20:01 – 30:00 | 3 |
| 30:01 – 40:00 | 4 |
| 40:01 – 50:00 | 5 |
| 50:01 – 60:00 | 6 |
| 60:01+ | **blocked** (hard limit) |
Inputs over 60 minutes are rejected at creation time (HTTP 422). The backend
`duration_to_credits()` util (`backend/services/pricing.py`) is the single source of truth —
the frontend mirrors the constants for display only. See
`docs/archive/2026-06-04-long-duration-input-handling-design.md` for full design details.
#### Credit Deduction Flow
Credits are deducted N-atomically (not always just 1) at the earliest point duration is known:
- **URL jobs**: deducted at `POST /api/jobs` using the `duration_seconds` from `/api/jobs/estimate`.
If duration is unknown, 1 credit is held and reconciled post-download.
- **Audio search select**: deducted at `/api/audio-search/{job_id}/select` from the result's duration.
- **Upload jobs**: 1 credit is charged at job creation (same as URL jobs without a known duration).
After the audio lands in GCS, the same reconciliation checkpoint runs: ffprobe measures the actual
duration; if the cost exceeds the 1-credit hold the job pauses in `AWAITING_DURATION_CONFIRM`
(reason `reconcile`) for the user to pay the delta; if it costs less an auto-refund is issued.
A reconciliation checkpoint runs immediately before audio separation + transcription is triggered.
If the actual measured duration costs more than was charged, the job pauses in
`AWAITING_DURATION_CONFIRM` for the user to pay the difference. If it costs less, a silent
auto-refund is issued. If the actual duration exceeds 60 minutes, all charged credits are refunded
and the job is cancelled.
Admin users bypass credit checks entirely. New users receive 1 welcome credit. Users can earn 1
additional free credit by submitting product feedback after completing 2+ jobs (see
[User Feedback for Credits](#user-feedback-for-credits)).
#### 402 Response
When a user has no credits, job creation returns HTTP 402:
When a user has insufficient credits, job creation or confirmation returns HTTP 402:
```json
{
"detail": "You're out of credits. Buy more to continue creating karaoke videos.",
"credits_available": 0,
"credits_required": 1,
"credits_required": 3,
"buy_url": "/#pricing"
}
```
@@ -1569,7 +1695,7 @@ Regenerates title and end screen videos using the **current** artist/title metad
Requirements:
- Job must have audio and lyrics processing complete
- Job must be in an allowed state: `complete`, `failed`, `awaiting_review`, `awaiting_instrumental_selection`, `instrumental_selected`, `prep_complete`
- Job must be in an allowed state: `complete`, `failed`, `awaiting_review`, `in_review`, `awaiting_instrumental_selection`, `instrumental_selected`, `prep_complete`
The endpoint:
1. Deletes existing screen files from GCS
@@ -1787,7 +1913,9 @@ POST /api/internal/jobs/{job_id}/check-idle-reminder
Authorization: Bearer ADMIN_TOKEN
```
Called by Cloud Tasks 5 minutes after a job enters a blocking state (primarily `awaiting_review` for combined review). Sends a reminder email if the user is still idle and no reminder has been sent yet.
Called by Cloud Tasks after a job enters a blocking state. Sends a reminder email if the user is still idle and no reminder has been sent yet. Handles two `action_type` cases:
- `review_reminder` — fires 5 minutes after `awaiting_review` (combined lyrics + instrumental review)
- `duration_confirm_reminder` — fires 15 minutes after `awaiting_duration_confirm`
**Note**: With the combined review flow, users complete both lyrics review and instrumental selection in one session. The `awaiting_instrumental_selection` state is only used for finalise-only jobs.
@@ -1889,7 +2017,11 @@ Called by Cloud Scheduler hourly. Processes queued uploads while quota is availa
```http
POST /api/internal/process-stale-reviews
```
Called by Cloud Scheduler hourly. Queries for jobs in `awaiting_review` or `in_review` status, sends reminder emails at 24h, and auto-cancels with credit refund at 48h. Excludes made-for-you and tenant jobs. Returns `{status: "started", message: "..."}` immediately; processing runs in background.
Called by Cloud Scheduler hourly. Queries for jobs in `awaiting_review`, `in_review`, or
`awaiting_duration_confirm` status. Sends reminder emails at 24h; auto-cancels with full credit
refund at 48h (all `credits_charged` are returned for duration-confirm expirations). Excludes
made-for-you and tenant jobs. Returns `{status: "started", message: "..."}` immediately; processing
runs in background.
## Referral System
Loaded 100 of 211 files, more files were not shown because too many files have changed in this diff. Show more