Compare commits

...
23 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 5.5 60be7606a3 fix: stop double Dropbox upload, ignore partial-throttle stalls, pre-import lazy route modules (v0.268.2) (#1136)
## Summary
Follow-ups from #1135.

1. **Every job was uploaded to Dropbox twice.**
`generate_video_orchestrated` runs the orchestrator's Dropbox upload.
`_handle_native_distribution` then builds `stems/` and `lyrics/` and
re-uploaded the **whole** folder (job 8a10a22d: ~53s + ~70s, ~400 MB
twice). Neither pass can simply go:
   - the orchestrator's `dropbox_link` is the one written to the job;
- building the subfolders deletes instrumentals the orchestrator still
needs.
2. **Short (1-2.5s) EVENT_LOOP_STALLs in asyncio internals.** I compared
24h of stalls with each instance's request logs:
- 126 of 128 had no request waiting on them. These are partial CPU
throttling: the watchdog thread gets an occasional time slice, so its
wake gap stayed under the 2s freeze threshold from #1135.
- The apparent overlaps are requests that started one watchdog tick
(~0.26s) before the logged end and finished in ~4ms. They're the
requests that brought the CPU back.
- The only user-felt ones were 3 cold-start `importlib` stalls (3s, 4s,
15s): routes lazily importing modules that pull in `httpx`.

## Changes
- `DropboxService.upload_folder(..., skip_unchanged=True)` lists the
destination once (recursively) and skips files whose Dropbox
`content_hash` (SHA-256 of 4 MiB block hashes) matches. The native pass
uses it, so only new or changed files are sent. Listing errors fall back
to a full upload. It's off by default, so the orchestrator's upload and
other callers are unchanged.
- Watchdog `frozen_gap_s` is now 0.75s (3 missed ticks), down from 2s.
Measured watchdog wake gaps stay ≤0.27s with the loop blocked on sync
I/O, Python CPU work or C-extension CPU work, so real stalls are still
reported.
- Lifespan startup imports `_LAZY_ROUTE_IMPORTS` (httpx + 6 services)
via `asyncio.to_thread` before readiness, bounded at 30s with an ERROR
log on timeout.
- Docs: `LESSONS-LEARNED.md`: the double-upload entry; how to tell a
harmless stall class from a user-felt one.

## Testing
- Backend unit suite: **5908 passed**, 36 skipped.
- New tests:
- `content_hash` matches Dropbox's algorithm (multi-block and empty
files);
- skip-unchanged handles identical, changed and new files, plus
pagination, a missing folder, a listing failure and the off-by-default
case;
  - the native pass uses `skip_unchanged`;
- a short partial-throttle freeze is ignored, while I/O and CPU stalls
are still reported;
- lazy imports run in a worker thread before readiness, failures are
non-fatal, and the timeout doesn't block startup.
- Local CodeRabbit: 3 cycles. Fixed the startup-import race, the
stall-impact criterion in the doc, and the unbounded startup wait.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 17:26:53 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 f2612ac110 fix: close edit→delete refund loop, retry lost YouTube uploads, unblock event loop (v0.268.1) (#1135)
## Summary
Investigation of two 2026-10-08 Discord alerts (plus a third that
arrived mid-session) turned up four issues:

1. **Credit-refund loop.** A brand-new welcome-credit account received a
finished video (job 8a10a22d), clicked **Edit** (status back to
`awaiting_review`), then **deleted** the job and got its credit back.
`delete_job` refunds any non-complete status, and Edit makes a delivered
job look "never completed".
2. **YouTube 410 "Gone" dropped the upload.** The resumable session was
lost 1.3s into the upload. `upload_video` called `execute()` once with
no retries, and the orchestrator only queued quota errors, so any other
failure lost the upload.
3. **EVENT_LOOP_STALL 21s in `upload_json`.** `complete_review` (an
async route) wrote the corrections JSON to GCS directly on the event
loop. Ranking a week of watchdog stacks by route showed the same pattern
in `recover_stuck_jobs` (~260 stalls/week), the YouTube queue processor
(its `_process_single_upload` ran a whole upload on the loop),
`create_job_from_search` (theme prep), `_validate_audio_durations`
(15s), and the sync `run_job` / generation bump inside worker triggers.
4. **False 30s "stall" in asyncio `get_debug`.** Cloud Run CPU
throttling froze the whole instance mid-callback with no request in
flight. The watchdog only discounted freezes where the loop was parked
in `select()`.

## Changes
- **Refund:** `_refund_credit_for_job` skips jobs with `edit_count > 0`
(already delivered). This covers delete, cancel, fail and the 48h review
auto-expiry.
- **YouTube:** on 404/410 the upload restarts with a fresh session (3
attempts, with backoff). `execute(num_retries=3)` lets googleapiclient
resume chunks on 5xx/429 within a session. Any other failure is queued
in `youtube_upload_queue` (`reason="upload_error"`) for the existing
processor, which retries up to 5 times. Admins still get a Discord
warning: "queued for automatic retry".
- **Event loop:**
- New `backend/utils/loop_bridge.py`: `run_in_body_thread` runs sync
route bodies on a dedicated 16-thread pool, so they can't exhaust the
default executor the dispatched coroutines need. `run_on_loop`
dispatches coroutines back to the API loop (`run_coroutine_threadsafe`,
120s timeout).
- `complete_review`: its sync save runs via `to_thread`, and the render
trigger stays on the loop.
- `create_job_from_search`, `recover_stuck_jobs` and
`retry_pending_render_jobs`: bodies run in the route-body pool.
`_retrigger_parked_download` now does its writes in that thread.
- `_validate_audio_durations` and the YouTube queue's
`_process_single_upload` keep their async signatures but run in threads.
The queue's quota and Firestore calls go through `to_thread`.
- `worker_service`: the generation bump and `client.run_job` go through
`to_thread`.
- **Watchdog:** if the watchdog thread itself oversleeps by 2s or more
while the process uses less than 25% CPU, the whole process was frozen.
That time is subtracted from the stall and isn't sampled. Blocking I/O
(the watchdog still wakes on time) and GIL-hogging CPU work (CPU keeps
advancing) are still reported.
- Docs: `API.md` (edit/refund note) and `LESSONS-LEARNED.md`
(mostly-sync routes that await one trigger; throttling freezes).

## Testing
- Backend unit suite: **5863 passed**, 36 skipped (`pytest backend/tests
--ignore=backend/tests/emulator`).
- New tests:
- edited-track refund cases (delete in awaiting_review /
lyrics_complete, cancel);
  - YouTube restart on 410, give up after 3 attempts, no restart on 403;
  - orchestrator queues failed uploads and warns when queueing fails;
  - loop-responsiveness ticker tests for each offloaded path;
  - `run_on_loop` result, exception and timeout-with-cancel;
  - `run_in_body_thread` copies context and uses its own pool;
- watchdog: freeze ignored, I/O stall and CPU hog still reported, freeze
subtracted from a real stall.
- Local CodeRabbit: 3 cycles. Fixed the nested-executor deadlock risk,
the missing `run_on_loop` timeout, the parked-download writes on the
loop, and a coroutine leak. The last cycle had 0 findings.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 16:15:47 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 60687d6cd6 feat(theme): editable + previewed end screen; optional title/end screens (v0.268.0) (#1134)
## Summary
Randy Vild (tenant `randy-vild`) emailed: *"I have completed 3 songs but
all three songs produce the large text at the end even though I have in
my settings smaller text like in my beginning."*

Root cause: the theme editor's size/position sliders only edit
`intro.*`. The end screen has its own `end.*` layout (title 350 /
closing message 400 / yellow capitals artist in Randy's theme). The
editor neither exposed it nor previewed it ("The end screen isn't
previewed").

## Changes
- **End screen tab**: own title/artist colours, size + position sliders
(closing message, song title, artist), show/hide song title / artist
name, capitals toggles, and **Copy title card layout**. That copies the
title card's regions/colours/capitals and moves the closing message just
above the title, or below the artist if there's no room, so they never
overlap.
- **End screen preview**: `theme_preview_service.render_end_screen` uses
the same `VideoGenerator.create_end_video` as `screens_worker`. The
preview column shows the screen for the active tab plus the lyrics
frame; Advanced shows all three.
- **Leave out the title card / end screen**: optional `intro.enabled` /
`end.enabled` (absent = included; not added to the DEFAULT_*
required-field lists). The setting is honoured end to end:
- The screens worker skips the omitted screen and records
`state_data.screens_included`.
- The video worker's prerequisite check and the `/retry` ladder
(`_has_title_screen`, which also requires `screens_progress: complete`)
treat an omitted screen as done.
- The orchestrator sets the omitted screen's path to `None` and gives
the original-vocals guide an intro offset of 0.
- Encoding passes explicit `include_title_screen` /
`include_end_screen=false` to the GCE worker. Without them, its loose
`*title*.png` / `*end*.png` globs would rebuild the screen from
`style/*_background.png`.
- `LocalEncodingService.encode_lossless_mp4` builds the concat from
whichever segments exist (1–3).
  - The portrait renderer drops omitted cards.
- 11 new strings × 33 locales (`endScreenHint` removed). Docs: API.md,
README.md.

## Verification
- `make test` all green: frontend 1665 tests; backend unit, integration
and emulator suites.
- New `backend/tests/test_theme_screen_omission.py`, 28 tests:
  - screens worker for all 4 include combinations;
  - prerequisites and the retry helper;
  - orchestrator config and encoder options;
  - GCE `run_encoding` with decoy theme PNGs present;
  - concat for n = 1/2/3.
- Real-ffmpeg renders:
- end-screen preview (its own background; text size changes only the end
screen);
  - portrait durations with screens omitted.
- Frontend: editor tests for the end tab, copy layout, region toggles
and enable switches, plus unit tests for the `copyTitleCardLayoutToEnd`
util.
- Rendered Randy's real theme locally:
  - as saved, the end screen reproduces the large text;
  - after Copy title card layout, it matches his title card.
- Local CodeRabbit review: 0 findings.

## Deploy notes
- The worker paths changed (`gce_encoding/`,
`local_encoding_service.py`, `karaoke_gen/`), so CI blue-green redeploys
the encoding worker.
- Existing themes are unaffected: they have no `enabled` key.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 15:09:25 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 437e72a29b fix(backend): move blocking credential checks + GDrive validation off the event loop (v0.267.1) (#1133)
## Summary
Two recurring `EVENT_LOOP_STALL`s alerted on 2026-10-07:
- **16s** in `mark_uploads_complete` → `check_dropbox_credentials()` →
expired-token refresh (HTTP + Secret Manager `add_secret_version` +
version cleanup), all on the event loop. Also seen 10-06 14:03, 10-07
05:49/06:00 via `create_job_with_upload_urls`.
- **5-10s** after every job completion in
`trigger_gdrive_validation_endpoint` (sync OIDC token fetch +
`requests.post(timeout=60)`). Seen 7× since 10-04.

These routes `await request.json()` etc., so the v0.264.0 "async route
without await" guard didn't catch them.

## Changes
- `file_upload.py` (`upload_and_create_job`,
`create_job_with_upload_urls`, `mark_uploads_complete`,
`create_job_from_url`) and `audio_search.py` (`search_audio`): 18
`check_*_credentials()` calls → `await asyncio.to_thread(...)`.
Plain-`def` routes were already in the threadpool and are unchanged.
- `internal.py`: `trigger_gdrive_validation` → `asyncio.to_thread`.
- `test_no_blocking_async_routes.py`: new `BLOCKING_CALLS` denylist
guard (credential checks, `trigger_gdrive_validation`, `requests.*`,
`time.sleep`) for direct calls inside `async def` routes, plus a
detector unit test. Run against `origin/main` it flags exactly the 19
sites fixed here.
- LESSONS-LEARNED entry; version 0.267.1.

## Testing
- `make test`: backend 5838 passed, 2021 passed (second backend set),
emulator 150 passed, frontend 1654 passed.
- Local CodeRabbit review: no findings.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 21:25:56 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 9d04274de7 feat(tenant): theme edits reach in-progress tracks + outdated-track re-render prompts (v0.267.0) (#1132)
## Why
Randy Vild edited his portal theme and his next video (RVILD-0003) still
had the old title card. Each job copies the theme when it's created.
This one was created 30 minutes before his edit and was waiting for
encoding capacity when he saved. Edits only reached jobs created
afterwards, finished tracks gave no sign they were outdated, and admins
saw two identical "Re-render" buttons on portal tracks.

## What
- **Theme save → in-progress tracks**
(`services/theme_change_service.py`): every tenant track that hasn't
started rendering gets a fresh copy of the theme. Tracks whose screens
may already exist (`generating_screens`…`in_review`,
`render_pending_capacity`) are flagged `state_data.theme_screens_stale`.
- **Render-worker divert:** a flagged job in `review_complete` goes once
through the screens worker (`LYRICS_COMPLETE` +
`regen_restore_status=review_complete`, the same bounce the theme
re-render uses). The screens worker regenerates the screens and
re-triggers the render. Doing this at render time covers every path into
render (review submit, auto-approve, retry, capacity retry) and never
interrupts someone mid-review. Stale `finals/*.mov` files are deleted
too, so the encoder can't splice the old intro back in.
- **Edit of a finished tenant track** picks up the current theme when
the track's copy is outdated.
- **New endpoints:** `GET /api/tenant/theme/outdated-jobs`, plus `POST
/api/tenant/theme/rerender-outdated`, which is quiet (no per-track
emails), capped at 20 per call, and keeps its blocking I/O off the event
loop. The save response now includes `refreshed_jobs` and
`outdated_job_ids`. Outdated means the theme's `style_params.json` was
written after the job's `theme_applied_at` (or `created_at` if that's
unset).
- **UI:** after a save, the theme editor says how many in-progress
tracks were updated and offers **Re-render all N**. Outdated job cards
get an "Older theme" badge on Re-render. On portal cards, admins see
only the portal Re-render, not the duplicate admin one.
- i18n: 12 new strings, translated into all 33 locales; 3 superseded
keys removed.

## Testing
- `make test` passes (backend unit, emulator and e2e; frontend Jest and
Playwright).
- New `backend/tests/test_theme_change.py` (36 tests, 98% coverage of
the new service), plus a render-worker divert test, editor dialog tests
and OutputLinks tests.
- Local CodeRabbit review: 1 major finding (bulk re-render blocking the
event loop / unbounded), fixed.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 18:32:27 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 0ea2a23766 fix(encoding): worker self-heals after a bad boot; default metadata mTLS off (v0.266.4) (#1131)
## Summary

On 2026-10-06 the primary encoding VM (`encoding-worker-b`) booted
before its network was up. `bootstrap.sh` couldn't download `startup.sh`
from GCS (`Network is unreachable`) and fell back to the image's
`startup-fallback.sh`. That script writes an env file without
`ENCODING_API_KEY` or `GCE_METADATA_MTLS_MODE=none`, so google-auth used
mTLS to the metadata server and every render and preview failed with
`CERTIFICATE_VERIFY_FAILED`. The backend deliberately keeps retrying the
primary on infra errors, so a Randy Vild render (job `ebfe4344`) looped
in `render_pending_capacity` for an hour until the service was restarted
by hand.

## Changes

- **Worker defaults `GCE_METADATA_MTLS_MODE=none`** in
`backend/services/gce_encoding/main.py` before any google import, so
every boot path gets it. Ships with the wheel; no image rebuild needed.
- **Worker self-heal** (`backend/services/gce_encoding/self_heal.py`),
active only on worker VMs (systemd `INVOCATION_ID` **and**
`/opt/encoding-worker/bootstrap.sh`):
- Boot: refuses to start if the API key is missing or it can't get GCP
credentials. uvicorn exits, and systemd re-runs the bootstrap.
- Runtime: after a job fails with an infra/auth error, it waits 30s (so
the backend sees the failure), re-probes credentials, and exits once
idle if they're still failing.
- **Packer bootstrap** (`provision.sh`) retries the `startup.sh`
download for about 2 minutes. The fallback writes
`GCE_METADATA_MTLS_MODE=none` and exits if it can't fetch the API key,
instead of starting unauthenticated. Takes effect with the next image
build.
- **Alerting:** an infra failure while the primary is serving now logs
at ERROR (was WARNING).
- **UI:** `state_data.render_pending_capacity` is cleared once a retried
render reports progress, so the job card stops saying "(waiting for
encoding server availability)" during a healthy render.
- Docs: TROUBLESHOOTING runbook, LESSONS-LEARNED, README.

## Testing

- New: `test_encoding_worker_self_heal.py` (probe/boot/restart logic,
`main.py` wiring, mTLS default) and
`test_render_capacity_marker_clear.py`.
- `make test`: 5799 backend unit, 150 emulator, 1646 frontend, all
passing.
- Local CodeRabbit review: no findings.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 11:55:51 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 950c96fa48 feat(e2e): checkout-only (no-charge) payment mode for daily E2E Stage 1 (v0.266.3) (#1130)
There's no working test card right now (the issuer declines it), so the
daily E2E Stage 1 defaults to a **no-charge** mode until the repo
variable `E2E_REAL_PAYMENT=true` is set.

## Checkout-only mode (`E2E_PAYMENT_MODE=checkout-only`)
- **Unchanged:** real signup via the `e2etest95` referral link, the Buy
Credits dialog, and real Stripe Checkout session creation.
- **Card:** fills the form with Stripe's public test card `4242…`
(`NO_CHARGE_CARD`; no secret needed). The self-healing steps still run,
except `submitPayment`.
- **Checks:** the $0.50 referral price and the Pay button are visible,
then it **stops before Pay**. Live mode always declines that test card,
so even an accidental click can't charge anything.
- **Stage 2:** gets the new account's session token and spends its
signup credit. The test asserts the account has at least 1 credit.
- **Not exercised:** the Stripe payment, the webhook credit grant, the
purchase email, and self-heal PRs (no verified purchase to learn from).
- **Email:** the daily email marks Stage 1 `[checkout-only: no real
payment]`.

## Testing
- Offline suite: 31 passed. The new test checks that no-charge mode
fills the form with the test card, never calls confirm and never leaves
Checkout.
- `--list` loads the production spec in both modes. Lint and typecheck
are clean.
- A live E2E Daily run on this branch (37262437261) is in progress
against prod.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 00:28:56 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 57b319a4b4 fix(e2e): make credit-purchase test.use top-level so the spec loads (v0.266.2) (#1129)
Follow-up to #1128. In `credit-purchase-real.spec.ts`, `test.use({
trace, video, screenshot })` was inside a `describe` block. Those
options force a new worker, so Playwright refuses to load the spec. The
first post-merge E2E Daily run (37256162735) failed Stage 1 in about 1s,
before any test ran. This moves the call to the top level of the file.

Verified: `CI=1 npx playwright test
--config=playwright.production.config.ts --list` loads all 78 production
tests, including the credit-purchase test.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 22:45:46 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 feef49a588 fix(e2e): stop publishing card data/admin token in artifacts; fail fast on card decline (v0.266.1) (#1128)
## Summary
E2E Daily **#200** failed in Stage 1. The cause was **the issuer
declining the test card**: Stripe `confirm` returned 402 `card_error /
card_declined / generic_decline` on all 3 attempts. It was not a Stripe
Checkout change. The self-healing runner still treated it as one: a 90s
verify wait, then 6 Gemini calls "re-entering" a form that was already
correct.

The investigation also found that **every run's artifacts published
secrets** in this public repo:
- the full test card (number, expiry, CVC) in screenshots, videos,
`error-context.md` and the DOM dump;
- `X-Admin-Token` in the trace network logs.

All 140 unexpired `e2e-*` artifacts have already been deleted via the
API. The admin token and the test card still need rotating (Andrew).

## Changes
- **Fail fast on decline:** `stripe-checkout.ts` watches
`/v1/payment_pages/<id>/confirm`. A `card_error` aborts `submitPayment`
immediately with `STRIPE_CARD_DECLINED: …`: no LLM calls, no second Pay
click.
- New `CheckoutStep.abortReason`, honoured by the runner, `pollVerify`
and the LLM loop.
  - Non-card errors (e.g. a missing field) still go to the LLM fallback.
- **Alerts say why:** Stage 1 exposes a `failure_reason` output ("Test
card declined, not a checkout bug (…)"). It appears in Discord and in
the daily email. The Discord payload is now built with `jq` from env, so
Stripe's text never reaches the shell.
- **No secrets in artifacts:**
- The Stripe helper's screenshots mask every input, and the DOM dump
redacts input values.
- The credit-purchase spec turns off trace, video and Playwright's
automatic screenshots.
- `playwright.production.config.ts` turns traces off on CI
(`E2E_TRACE=on` overrides).
  - New `frontend/e2e/scripts/scrub-artifacts.mjs`:
- deletes `*.zip` traces and `e2e-session-token.txt` (and videos with
`--drop-videos`);
    - redacts secret env values and card-number-shaped digit runs;
- with `--blank-inputs`, blanks `<input value>` and ARIA textbox values;
    - deletes any file that still contains a secret.
- Every production-E2E upload (`e2e-daily` ×2, `e2e-tenant-daily`, the
`ci.yml` happy path) now runs the scrubber first and **uploads only if
the scrub succeeded**.
- Docs: `TESTING.md` (decline behaviour, a "E2E Artifacts Are Public"
section), `LESSONS-LEARNED.md`.

## Testing
- `npx playwright test --config=playwright.selfheal.config.ts`: **30
passed**. New tests:
- a declined card fails in ~7s with 0 planner calls and exactly 1
confirm request;
  - the DOM dump contains no typed card values;
  - card-error parsing and the confirm-URL matcher;
- scrubber units (literal/grouped/PAN redaction, short secrets only
blanked inside inputs, deletion rules).
- Ran the scrubber against a copy of the real #200 artifacts: no card
data remains, and traces and videos were removed.
- actionlint: no new findings (only shellcheck info notes; ci.yml:996 is
pre-existing).
- Local CodeRabbit review: 2 findings (shell interpolation of the
reason; extension allowlist in the scrubber), both fixed.
- The full `make test` suite was not run: the change is limited to E2E
helpers, workflows and docs, with no backend or app code.

## Follow-ups (Andrew)
- Rotate the `admin-tokens` secret and the `E2E_ADMIN_TOKEN` repo
secret.
- Replace or unlock the test card; ideally a low-limit virtual card.
Then update the `E2E_STRIPE_CARD_*` secrets and re-run E2E Daily.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 22:25:52 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 3ecea6f2e7 feat(storage): enable real purge with deletion audit log and orphan cleanup mode (v0.266.0) (#1127)
## Summary
Andrew approved this follow-up to #1125 and #1126. It turns on real
deletion, adds an audit log of every deleted object, and adds an
orphan-folder cleanup mode.

### Real deletion on
`STORAGE_RETENTION_DRY_RUN=false` and
`STORAGE_RETENTION_MAX_JOBS_PER_RUN=50` are added to the backend
deploy's `--set-env-vars`. The API service is the only thing that reads
them: it passes `--dry-run` to `storage-retention-job`. That keeps the
setting in one place, so a later deploy can't silently revert it.

### Deletion audit log
- `storage-retention/deletion-logs/<ts>-<mode>.jsonl` has one line per
deleted or failed object: timestamp, run_id, mode, job_id, path,
size_bytes, generation, category and result.
- The log is rewritten after every job or folder, so a crash still
leaves a complete record. Each run also writes
`<ts>-<mode>.summary.json`.
- Deletes are pinned to the logged generation (`if_generation_match`).
- `assert_deletable` refuses any path outside `jobs/{id}/`, so
`storage-retention/` is never touched. No lifecycle rule matches live
objects there.
- The Firestore manifest on each job doc now also records generations
and the log path.

### Orphan cleanup
- `POST /api/internal/storage-retention/orphans` runs on the same Cloud
Run job with `--mode orphans`.
- It targets `jobs/{id}/` folders with no doc in `jobs`, `jobs-dev` or
`youtube_upload_queue`, re-checked live per folder against a fresh
listing.
- It skips any folder with an object modified in the last 30 days, keeps
`input/`, and deletes the rest.
- `encoding_worker_jobs` doesn't count as a record: it's the encoder's
expiring result cache, which deleted jobs leave behind.
- It is a dry-run unless called with
`dry_run=false&confirm=delete-orphan-job-folders`, and the scheduler
never runs it.

### Docs
- `docs/STORAGE-RETENTION.md`: run modes, log locations, jq review
commands and restore one-liners (noncurrent `cp #gen` and soft-delete
`restore`).
- `scripts/storage_retention_report.py`: list runs, summarise a run, or
find which run deleted a path or job.

## Testing
New tests cover the log contents, generation-pinned deletes, per-job
flushing across a crash, the path guard, orphan planning (input kept,
30-day skip, live record re-check, batch limit), and the endpoint and
worker modes. Full backend suite: 5774 passed.

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

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

* **New Features**
* Added admin-triggered orphan-folder cleanup, with dry-run enabled by
default, optional folder limits, and explicit confirmation required for
deletion.
* Added deletion reports and audit logs covering removed objects,
reclaimed space, and failures, plus a read-only tool to review runs and
search records.
* **Bug Fixes**
* Added safeguards to prevent deleting changed objects or files outside
their intended job folders.
* **Documentation**
* Expanded storage-retention guidance with recovery details, review
commands, and cleanup instructions.
* **Chores**
* Set the production cleanup limit to 50 jobs per run and updated the
package version.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-04 11:54:05 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 60e48dbb72 fix(storage): retention pass as a Cloud Run Job and stems-restore screens handoff (v0.265.1) (#1126)
## Summary
This fixes two problems found while verifying #1125 in prod.

1. **The scheduled pass never finished.** It ran as a FastAPI
BackgroundTask, which is starved on the API service:
`cpu-throttling=true` gives it CPU only while a request is open. Running
it synchronously doesn't work either, because Cloudflare cuts requests
at 100s.
- The pass now runs as a new Cloud Run Job, `storage-retention-job`
(us-east4, CPU image `:latest`). Pulumi is already applied (targeted).
   - New CLI: `backend/workers/storage_retention_worker.py`.
- The endpoint starts the job and returns the report path. It returns
503 if the job can't be started.
- The dry-run default is unchanged: the API passes `--dry-run` based on
`STORAGE_RETENTION_DRY_RUN`, which defaults to true.
2. **The regenerate E2E stalled after the stems restore.** The first
screens dispatch had marked `screens_progress=running`, so the restore's
re-trigger was skipped as "already running".
- The stems gate now drops that mark when it hands off, and again on
completion.
- `recover-stuck-jobs` now re-triggers re-render/regenerate jobs that
stay parked at `lyrics_complete` for more than 10 minutes.

## Testing
- New tests cover the worker CLI, the job trigger, the endpoint, the
screens-mark handling and the watchdog. Full backend suite: 5754 passed.

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

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

## Summary by CodeRabbit

* **New Features**
* Scheduled storage-retention runs now launch as managed jobs, with
options for dry runs, report paths, job limits, and orphan handling.
  * Retention jobs can also run locally outside production.

* **Bug Fixes**
* The retention endpoint reports an error when a job cannot be started.
* Stalled regeneration flows can resume screens processing after a lost
dispatch or stems restore.

* **Documentation**
* Updated the architecture overview to describe the managed
storage-retention job workflow.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-04 01:10:39 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 6c3c70654d feat(storage): retention purge (dry-run) and on-demand regenerate (v0.265.0) (#1125)
## Summary
Implements the approved storage-retention plan (2026-10-03): purge
regenerable files from jobs completed more than 30 days ago, and
regenerate them on demand.

### Purge (`backend/services/storage_retention.py`)
- Daily Cloud Scheduler `storage-retention-daily` calls `POST
/api/internal/storage-retention/run` (Pulumi, already applied).
- **DRY-RUN by default** (`STORAGE_RETENTION_DRY_RUN`, default true). It
writes a report to
`gs://karaoke-gen-storage-nomadkaraoke/storage-retention/reports/<ts>-dry-run.json`.
Real deletion needs the env flipped after a human review.
- Walks completed Firestore jobs. Completion time is the newest
`complete` timeline entry.
- **Keeps:** input (incl. `edited.flac`), lyrics, style, review
sessions, audio_edit, uploads, packages, analysis, screen images, the
720p final (both copies), `stems/custom_instrumental.*`,
`stems/vocals_derived.*`, and the root custom/existing instrumentals.
Unknown files are kept too.
- **Purges:** other finals, `videos/`, `previews/`, `encoded/`,
`quick/*.mp4`, `screens/*.mov`, `review-audio/`, and separated stems
(only when the input is kept in `jobs/{id}/input/`).
- **Skips:**
  - finalise-only jobs
  - jobs whose input audio is gone (66 old jobs)
- jobs with an in-flight edit, re-render, visibility change or
regenerate
  - pending YouTube uploads
  - excluded tenants (env)
- Real runs:
  - batched, with a resumable cursor
  - re-check eligibility atomically via a claim
- record `renders_purged_at`, `stems_purged_at` and a `storage_purge`
manifest
  - drop purged `file_urls` entries
- `?job_ids=…&dry_run=false&min_age_days=0` runs a scoped real pass, for
testing. A global real purge only happens through the setting.

### Regenerate (`backend/services/regenerate_service.py`)
- `POST /api/jobs/{id}/regenerate` (owner or admin, rate-limited per job
and per user) plus a job-page **Regenerate video** button and progress
notice. There is also `POST /api/admin/jobs/{id}/regenerate`.
- GCS-only: claim, then screens, render, encode. It uses the existing
lyrics, instrumental selection and style. No brand-code allocation, no
YouTube/Dropbox/GDrive/Discord. The owner is notified when it's done.
- **Stems gate** in the screens worker (`stems_restore.py`): if
`stems_purged_at` is set, it runs the audio-separation job in restore
mode first, and the audio worker re-triggers screens afterwards. This
covers regenerate, admin/theme re-render, private→public, Edit (which
now restores stems before review) and retry.
- Public→private on a job with archived finals regenerates first, then
redistributes (no more "No finals" failure).
- Archived downloads return **410** `output_archived` with a
`regenerate_url`.

### Fixes
- Encoder: the with-backing and clean instrumental lookups no longer
fall back to another instrumental (that was a silent wrong-instrumental
bug); a missing instrumental now fails loudly.
- `existing_instrumental_gcs_path` is persisted at upload to
`jobs/{id}/custom_instrumental.<ext>`, because `uploads/` expires after
7 days. Older jobs get a resolve-and-repoint fallback in the video
worker and orchestrator.
- Bucket noncurrent-version retention reduced from 30 to 7 days (Pulumi,
applied).

## Testing
- New: `test_storage_retention.py` (108), `test_regenerate_service.py`
(66), `test_instrumental_resolution.py` (16), plus edit-flow, upload and
visibility updates. Full backend unit suite: 5731 passed.
- Frontend: OutputLinks regenerate tests and job-status helper tests
(Jest). All 33 locales translated.
- Local read-only dry-run against prod: 538 jobs eligible, about 401 GiB
purgeable.

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

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

* **New Features**
* Added an option to regenerate archived or missing video outputs from a
completed job. Existing publishing links remain unchanged, and job
progress is shown while processing.
* Added automatic restoration of archived audio stems when needed for
regeneration or job edits.
* **Improvements**
* Added scheduled cleanup of eligible files from older completed jobs
while retaining key source and review assets.
* Improved recovery when requested downloads have been archived by
offering a regeneration option.
* Improved handling of saved instrumentals so they remain available for
future processing.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-03 23:59:23 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 33d6ac5d2a fix(backend): build encoding service off the event loop (v0.264.1) (#1124)
## Summary
This is a follow-up to #1120. The new event-loop watchdog's first prod
catch was a 9.9s stall on a fresh instance, culprit
`backend/services/encoding_service.py:1392 in get_encoding_service`. On
first use it imports `google.cloud.compute_v1` (~10s), on the loop, via
`/api/health/detailed`.

- The singleton is now built in the startup warmup thread
(`main._run_background_warmup`).
- `get_encoding_service()` is now thread-safe (double-checked lock), and
it publishes the service only once fully wired.
- The async callers (`check_encoding_worker_status`,
`_run_preview_encode`, `generate_preview_video`) use `await
asyncio.to_thread(get_encoding_service)`.
- The version goes to 0.264.1, which also resolves the 0.264.0 collision
between #1120 and #1122.

## Testing
- Backend unit suite: 5538 passed.
- New tests:
- The health encoding check keeps the loop responsive during a slow
build.
  - The singleton is built exactly once under 5 concurrent threads.

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

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

## Summary by CodeRabbit

* **Reliability**
* Health checks and encoding previews remain responsive while the
encoding service initializes.
  * Concurrent requests safely share a single encoding service instance.
* Service initialization now also runs during startup; if it fails, the
service can still initialize when needed.
* **Documentation**
  * Updated the recent changes log and release version to 0.264.1.

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 14:59:59 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 98883dea8a fix(audio-search): best pick prefers the requested artist among title matches (v0.264.1) (#1123)
## Summary
Follow-up to #1122, found by checking it against a real prod search for
**Braxton Keith - The Chair**: George Strait's 1985 "The Chair" (Spotify
popularity 68) beat Braxton Keith's (65) on the popularity tiebreak. The
result was a confident "Recommended" pick of the wrong artist.

- `getBestResult(results, title, artist)` /
`getSearchConfidence(results, title, artist)`: among confirmed title
matches, those by the requested artist win.
- `isArtistMatch`: tolerates a leading "The", featured artists ("Braxton
Keith, X") and small typos (edit distance ≤ len/5, only for names of 5+
chars, so "U2" ≠ "UB40").
- A Spotify best pick by another artist is no longer a confident tier-2
match.
- `AudioSourceStep` passes the artist.

## Test plan
- [x] New tests: the real George Strait vs Braxton Keith case,
another-artist-only Spotify → tier 3, `isArtistMatch` cases (89 in the
audio-search suites)
- [x] Checked against the real prod search results: best = Braxton Keith
"The Chair" (Single 2025), tier 2
- [x] Local CodeRabbit: 1 finding (short-name fuzzy match) fixed

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 14:47:06 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 4e43449559 fix(backend): stop API event-loop freezes + identify users in degradation telemetry (v0.264.0) (#1120)
## Summary
The "Reconnecting" pill and the "servers unavailable" banner (164 / 49
events, 2026-09-19 → 10-02) were mostly caused by the single API
instance's **event loop freezing for 20–45s**. Every request on the
instance, `/api/health` included, completed at the same moment. The full
evidence and plan are in
`docs/archive/2026-10-03-backend-loop-freezes-telemetry-plan.md`.

### What froze the loop, and the fix for each
- **Screens worker:** it ran as a post-response `async def`
BackgroundTask doing 4K PIL renders, GCS transfers and ffmpeg transcodes
on the loop. Under `--cpu-throttling` it was also CPU-starved. **Fix:**
it now runs inline in its Cloud Tasks request (CPU stays allocated,
failures still return 200 so Cloud Tasks doesn't double-run it), with
the heavy steps in `asyncio.to_thread`. Also offloaded: style load,
timing signals, pre-apply.
- **Matplotlib font cache:** it was rebuilt on every new instance (17/28
episodes). **Fix:** it's pre-built in `Dockerfile.base`
(`MPLCONFIGDIR=/opt/mplconfig`), and pyplot is imported lazily.
- **Hourly stale-review cron:** an `async def` with zero awaits doing
≤1500 reads and SMTP sends. **Fix:** it runs in a thread.
- **166 `async def` routes that never awaited** (sync
Firestore/GCS/email/Gemini on the loop, e.g. magic-link verify).
**Fix:** they're now plain `def`, so they run in FastAPI's threadpool.
The new AST guard `test_no_blocking_async_routes.py` fails CI on new
ones. It also flags sync routes that call
`asyncio.create_task`/`get_running_loop`; that caught `confirm_duration`
and `trigger_youtube_queue_processing`, which stay async.

### Safety net
- `backend/services/loop_watchdog.py`: a heartbeat plus a daemon thread.
Any stall over 1s logs `EVENT_LOOP_STALL` with the loop thread's stack
and a `culprit=file:line`. Stalls of 5s or more are written to
`client_events` as `server_loop_stall`.
- Pulumi: the log metric `backend/event_loop_stalls` plus an alert on ≥2
stalls of ≥10s in 30 min. **This still needs a local `pulumi up`.**
Pulumi is never applied by CI, and the admin gcloud login has expired.

### Telemetry gaps fixed
- **Identity:** `user_email` used to be hard-coded to null. The frontend
now sends its session token, and the server resolves `user_email`,
`is_admin`, `is_internal` and `is_test`. A client-sent email is ignored.
- **New fields:** `device_fingerprint` (the existing FingerprintJS
visitorId), `tab_id`, `episode_id`, and `tenant`.
- **New event:** `banner_recovered`, carrying `duration_ms` and
`peak_status`.
- **Report:** `scripts/client_events_report.py` summarises the data,
excluding admin/internal/test accounts by default.

## Testing
- `make test` passes: backend 5529, plus the emulator suite, karaoke_gen
unit tests, and frontend Jest 1623.
- New tests:
- Watchdog: a deterministic state machine plus detection of a real
blocking call.
- Event-loop responsiveness: a ticker keeps ticking while the heavy
steps run.
  - Screens inline and failure semantics.
  - `client_events` identity and fields.
  - The AST guard.
  - The report summary.
  - Frontend reporter and banner episode tests.
- Local CodeRabbit CLI review: 0 findings.

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

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 14:17:51 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 4015b24857 feat(audio-search): title-matched best pick; Spotify track match is Recommended, not 'Limited sources' (v0.264.0) (#1122)
## Summary
Live kjbox night 2026-10-01: a singer's make-it for **Braxton Keith -
The Chair** got 10 Spotify results (3 were the right track) and no
torrents. Because Spotify counts as "not lossless", the search was
**tier 3 "Limited sources found"** with a wrong-track best pick ("I Own
This Bar"), so the singer pasted a YouTube link. That then hit the
YouTube bot-check.

- `getBestResult(results, searchTitle)`: when any torrent/Spotify result
is a **confirmed** track-name match, only those compete. YouTube is
never promoted this way. Ties go to seeders, then popularity
(`view_count`). If nothing in the pool ranks, the fallback stays within
the matches.
- `isConfirmedTitleMatch`: the track filename must actually be compared
and equal to the title, ignoring only trailing version suffixes (`(feat.
…)`, `[…]`, ` - 2013 Remaster`). "The Chairman" ≠ "The Chair"; "7
Rings", "Mr. Brightside" and "(I Can't Get No) Satisfaction" work.
- `checkFilenameMismatch` now strips only real audio extensions. Before,
"Mr. Brightside" lost ". Brightside" as an "extension".
- `getSearchConfidence`: a title-matched Spotify best pick is **tier 2**
(Recommended), with no "No lossless sources" warning and a "Spotify
audio" reason.

kjbox ports this 1:1 in `static-sing/audio_rank.js` (separate PR).

## Test plan
- [x] `audio-search-utils.test.ts`: 10 new tests from the real Braxton
Keith results plus edge cases (86 total)
- [x] Full frontend jest: 1617 passed
- [x] Local CodeRabbit: 3 cycles, all findings fixed

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 14:08:12 -04:00
github-actions[bot] 7ea86a8dda test(e2e): self-heal Stripe Checkout (fillPostalCode) (#1119)
## 🩹 Stripe Checkout self-heal

Stripe changed its hosted checkout page. In [run
#197](https://github.com/nomadkaraoke/karaoke-gen/actions/runs/37140934446)
every deterministic variant of **fillPostalCode** failed; the Gemini
fallback completed the step(s), and the purchase was then **verified
server-side** (credit granted).

This PR only adds the recipe(s) to `learned-variants.json`, so future
runs replay them deterministically (no LLM). It auto-merges once CI
passes.

### Learned recipes
```json
[
  {
    "stepId": "fillPostalCode",
    "model": "gemini-3.5-flash-lite",
    "llmCalls": 1,
    "actions": [
      {
        "type": "fill",
        "target": {
          "by": "css",
          "css": "#billingPostalCode",
          "frameUrlIncludes": "checkout.stripe.com/c/pay"
        },
        "value": "{{POSTAL_CODE}}"
      }
    ]
  }
]
```

@coderabbitai ignore

🤖 Generated by the E2E Daily self-healing workflow

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-03 18:07:21 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 c8461e56d0 fix(e2e): self-heal CI approval — correct pending detection, re-approve open PRs (#1121)
## Summary
This fixes the approval step from #1118, found by the live test on run
37140934446. That run reported `approved=true`, but bot PR #1119's CI
run was still `action_required`: the old check treated *any* existing
`pull_request` run as already running.

- `approve_ci` now succeeds only once a `pull_request` CI run exists
that is past `action_required`. It approves pending runs as it finds
them.
- When a self-heal PR is already open, the job now runs `approve_ci` for
that PR instead of exiting. So a stuck bot PR gets unstuck on the next
run.
- Polling is tolerant of transient `gh`/`jq` failures (from the local
CodeRabbit review). An empty branch name fails fast.

## Testing
- `actionlint` is clean for the changed lines; local CodeRabbit review:
2 findings, both fixed.
- After merge: a forced-LLM run on `main` will hit the "PR already open"
path for #1119. That approves its CI with the workflow's own token and
should let it auto-merge with no manual input.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 17:50:38 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 1c9104a79d fix(e2e): self-heal job approves its PR's CI run (no manual step) (#1118)
## Summary
This follows #1116. The live test of the self-heal loop (bot PR #1117)
merged, but only after one manual step: approving its CI run.

- **Approve the bot PR's CI run.** A bot-authored PR's `pull_request` CI
run is created as **action_required** (waiting for approval), and until
it runs it outranks the passing CI Gate from the dispatched run. The
`self-heal-pr` job now approves that run via `POST
/actions/runs/{id}/approve`. If approval fails, it dispatches `ci.yml`
and the Discord alert says the PR needs a one-click approval, with a
link.
- **Ruleset dependency, now documented.**
`require_extra_approval_for_unattributed_changes` is now set to `false`
on the `protect main` ruleset (11423976). It's a newer GitHub setting
that defaults to true and blocks bot-authored PRs until a human
approves. This is recorded in `docs/TESTING.md` and
`docs/LESSONS-LEARNED.md`.

## Testing
- `actionlint` is clean for the changed lines.
- After merge: a forced-LLM run on `main` on a step with no learned
recipe yet (`fillPostalCode`) will open a fresh bot PR and exercise
approval → CI → auto-merge without manual input.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 17:30:35 +00:00
github-actions[bot] 84f709ea0e test(e2e): self-heal Stripe Checkout (selectCard) (#1117)
## 🩹 Stripe Checkout self-heal

Stripe changed its hosted checkout page. In [run
#196](https://github.com/nomadkaraoke/karaoke-gen/actions/runs/37139075045)
every deterministic variant of **selectCard** failed; the Gemini
fallback completed the step(s), and the purchase was then **verified
server-side** (credit granted).

This PR only adds the recipe(s) to `learned-variants.json`, so future
runs replay them deterministically (no LLM). It auto-merges once CI
passes.

### Learned recipes
```json
[
  {
    "stepId": "selectCard",
    "model": "gemini-3.1-flash-lite",
    "llmCalls": 3,
    "actions": [
      {
        "type": "click",
        "target": {
          "by": "css",
          "css": "[data-testid='card-accordion-item']",
          "frameUrlIncludes": "checkout.stripe.com/c/pay"
        }
      }
    ]
  }
]
```

@coderabbitai ignore

🤖 Generated by the E2E Daily self-healing workflow

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-03 17:29:06 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 4768164a94 feat(e2e): self-healing Stripe Checkout (LLM fallback + auto-merging fix PRs) (#1116)
## Summary
Stripe's hosted checkout page has broken the daily E2E **5 times since
April** (#916, #919, #945, #1115…). Each fix added another selector, and
each new Stripe change still needed a human. This PR makes the Stripe
stage repair itself, with no manual steps.

**How it works.** `stripe-checkout.ts` now runs the checkout as verified
steps (`selectCard`, `fillCardNumber`, `fillCardExpiry`, `fillCardCvc`,
`fillCardholderName`, `fillPostalCode`, `uncheckSaveInfo`,
`submitPayment`). Each step tries, in order:
1. **learned variants** (`learned-variants.json`, newest first),
2. the existing hand-written **built-in** selectors,
3. a **Gemini fallback** that drives the page one action at a time until
the step's check passes. Model list: `gemini-3.5-flash-lite` →
`gemini-3.1-flash-lite` → `gemini-3.8-flash`; IDs that aren't available
are skipped.

A step only counts as done when its **check** passes, never just because
a click didn't throw (the root cause of run #192's misleading failure).

**Fully self-healing loop.** When the LLM repairs a step *and* the
purchase is confirmed server-side (credit granted), the new
`self-heal-pr` job (on `main` only):
- opens a **data-only** PR that changes only `learned-variants.json`
(label `e2e-self-heal`, `@coderabbitai ignore`),
- enables auto-merge,
- dispatches `ci.yml` on the branch, because PRs opened with the
workflow token don't trigger CI.

The next run replays the recipe without the LLM. Discord and the daily
email report 🩹 when this happens, and only one self-heal PR is open at a
time.

**Safety**
- Card data never reaches the LLM. It may only use per-step
`{{CARD_NUMBER}}`-style placeholders, which are substituted locally.
Field values and card-number-like digit runs are redacted from what it
sees, and inputs are masked in screenshots. Tests assert no secret
appears in the prompt.
- Guardrails refuse clicks on Link/Klarna/Cash App/Bank/"Back to…", and
on the final Pay button outside `submitPayment`. They check the
**resolved element** (text, aria-label, test ID, submit type), not just
the model's label.
- The Pay step's check is "redirected to the success page OR credit
granted server-side" (throttled), so the fallback never submits twice.
The cancel URL doesn't count as success.

**Gemini key:** the AI Studio `gemini-api-key`, billed outside the
nomadkaraoke project. A `GEMINI_API_KEY` repo secret is used if set;
otherwise it's read from Secret Manager via keyless login, and the
credential file is deleted before the tests run. With no key, the test
runs deterministic-only, as before.

Also passes the existing `E2E_STRIPE_ZIP` secret, which was never wired
up.

## Testing
- **Offline:** `playwright.selfheal.config.ts`, 21 tests with fixture
Stripe pages served on fake checkout.stripe.com/js.stripe.com and a stub
LLM. Covers: known layout uses no LLM; unknown layout → LLM repairs it →
recipe learned → replayed without the LLM; no secrets reach the LLM;
guardrails, including CSS targets; deterministic-only failure mode; unit
tests for redaction, merging and frame keys. Added to CI's smoke job.
- **Live (real Stripe, real Gemini) on this branch,** with
`self_heal_force_llm=selectCard`:
- [run
37137960148](https://github.com/nomadkaraoke/karaoke-gen/actions/runs/37137960148):
`gemini-3.5-flash-lite` completed "choose Card" in one call, credit
granted 1→2. This exposed the session ID in Stripe's URL path, now
fixed.
- [run
37138459027](https://github.com/nomadkaraoke/karaoke-gen/actions/runs/37138459027):
repeated after the review fixes. Recipe
`[data-testid="card-accordion-item"]` @ `checkout.stripe.com/c/pay`,
credit granted.
  - The PR-opening job is skipped on branches by design.
- After merge, I'll dispatch once on `main` with
`self_heal_force_llm=selectCard` to exercise the PR → CI → auto-merge
path.
- Local CodeRabbit review: 2 findings, both fixed.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 17:02:12 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 2b68cca183 fix(e2e): expand Stripe Checkout card accordion (daily E2E run #192) (#1115)
## Summary
Daily E2E Stage 1 failed (run #192): `Could not find card field:
cardNumber in any frame`.

**Root cause:** Stripe changed its Checkout payment-method accordion.
The Card row is now a plain `Card` text label with a visually-hidden
`button "Pay with card"`. There is no longer a radio/button named
`Card`, so the helper never expanded the accordion. This only affects
the test. Customers can still pay.

(Runs #190/#191 on Oct 1-2 failed for a different, already-fixed reason:
the Postmark 403 outage, so the magic-link email was never sent.)

## Changes
- `frontend/e2e/helpers/stripe-checkout.ts`: the chooser now matches
`Card` / `Pay with card` (radio, button, or exact label text). If the
fields still don't appear, it dispatches a click on the hidden `Pay with
card` button. On failure it writes
`test-results/stripe-checkout-dom.html` so the next markup change can be
diagnosed from the artifacts.

## Testing
- Type-checks; `playwright --list` loads the spec.
- Not run end to end yet: that needs a live Stripe charge ($0.50).
Verify with a `workflow_dispatch` of *E2E Daily Test* on this branch, or
the next scheduled run.

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

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

* **Tests**
* Automated checkout checks now recognize additional card-selection
options, including card choices presented as buttons or radio options,
and retry when card fields are slow to appear. If the fields remain
unavailable, the checks save diagnostic details from the checkout frames
to help investigate the issue. These updates affect the checkout test
process; no changes to the customer-facing payment flow are described.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 16:31:02 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 d6972f10aa infra(monitoring): alert when Postmark SMTP-fallback sends fail + document static-IP options (#1114)
## Summary
This is a follow-up to #1112/#1113 and decide#147. Postmark confirmed
(ticket #11562402) that the nginx 403s are an IP-reputation block on
shared Google us-central1 egress IPs, and they won't lift it. The SMTP
fallback is working in prod: on 2026-10-02 between 19:10 and 20:17 UTC,
12 of 12 blocked sends were delivered with 0 failures. To save money,
we're **deferring** a static egress IP and adding a free tripwire
instead.

## Changes
- `infrastructure/modules/monitoring.py`:
`create_email_delivery_observability()` adds:
- A log-based metric `email/postmark_smtp_fallback_failures`, plus an
alert policy ("Email - Postmark SMTP fallback failing (emails being
lost)") that fires on any failed fallback send in karaoke-backend **or**
karaoke-decide.
- The filter matches **both** `jsonPayload.message` (gen logs structured
JSON) and `textPayload` (decide logs plain text).
- `docs/archive/2026-10-02-postmark-ip-block-options.md`: full write-up
covering the evidence, Postmark's answer, how the fallback works, the
alert, and the static-IP options. It includes **measured costs**:
reusing the existing `github-runners-nat` with a reserved IP is
~$4–7/mo. It also has Pulumi steps, NAT sizing, and how to verify the
reserved IP is used.
- `docs/TROUBLESHOOTING.md` and `infrastructure/monitoring/README.md`
link to it.

## Testing / rollout
- Filter validated against real logs:
  - 0 failures, which is correct.
- Positive control on the gen JSON branch: 12/12 real fallback sends
matched.
  - Positive control on the decide text branch: 5/5 real lines matched.
- `pulumi preview` showed: +2 to create, 274 unchanged.
- **Already applied locally with `pulumi up`** (repo rule). The first
apply hit the log-metric propagation race, and re-running succeeded;
that gotcha is now documented in the code. The alert is live, enabled,
and has the email channel attached.
- Cost: $0 now. Alert policies cost $0.35/mo from 2027-09-01.

Local CodeRabbit review: 2 findings (Cloud NAT sizing, reserved-IP
verification in the options doc), both addressed.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 18:42:29 -04:00
194 changed files with 16398 additions and 1128 deletions

No files matched your search

+28 -2
View File
@@ -181,6 +181,12 @@ jobs:
working-directory: frontend
run: npx playwright test smoke.spec.ts --project=chromium --reporter=line
# Offline (fixture pages + stub LLM) tests for the self-healing Stripe
# Checkout runner used by the daily production E2E.
- name: Run self-healing Stripe runner tests
working-directory: frontend
run: npx playwright test --config=playwright.selfheal.config.ts --reporter=line
- name: Upload Playwright report
if: failure()
uses: actions/upload-artifact@v4
@@ -288,8 +294,19 @@ jobs:
--reporter=list \
--timeout=3600000
- name: Upload test artifacts
- name: Scrub secrets from artifacts (public repo)
id: scrub
if: always()
working-directory: frontend
env:
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token }}
run: node e2e/scripts/scrub-artifacts.mjs test-results playwright-report
- name: Upload test artifacts
if: always() && steps.scrub.outcome == 'success'
uses: actions/upload-artifact@v4
with:
name: e2e-happy-path-results
@@ -2021,7 +2038,7 @@ jobs:
--max-instances 20 \
--min-instances 0 \
--clear-vpc-connector \
--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,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-5-5,AUTO_CORRECT_COMPARE_MODELS=claude-opus-5-5;gemini-3.8-flash,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--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,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-5-5,AUTO_CORRECT_COMPARE_MODELS=claude-opus-5-5;gemini-3.8-flash,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,STORAGE_RETENTION_DRY_RUN=false,STORAGE_RETENTION_MAX_JOBS_PER_RUN=50,EDGE_AUTH_MODE=enforce,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 "ANTHROPIC_API_KEY=anthropic-api-key:latest,GEMINI_API_KEY=gemini-api-key:latest,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,EDGE_ORIGIN_SECRET=edge-origin-secret:latest,KARAOKEHUNT_FORWARDER_SECRET=karaokehunt-forwarder-secret:latest,KJBOX_PARTNER_SECRET=kjbox-partner-secret:latest"
# R3/R4 — smoke the tagged candidate revision BEFORE it serves any traffic.
@@ -2110,6 +2127,15 @@ jobs:
--project ${{ env.PROJECT_ID }} \
--quiet
# Storage-retention job (CPU, us-east4): pin to this commit's image so
# the deletion code (generation-pinned deletes + audit log) always
# matches the API that starts it.
gcloud run jobs update storage-retention-job \
--image "$CPU_JOBS_IMAGE" \
--region us-east4 \
--project ${{ env.PROJECT_ID }} \
--quiet
# Audio separation job (GPU, us-east4) — uses GPU image
gcloud run jobs update audio-separation-job \
--image "$GPU_IMAGE" \
+296 -9
View File
@@ -33,6 +33,11 @@ on:
required: false
default: 'false'
type: boolean
self_heal_force_llm:
description: 'Self-healing test: comma-separated Stripe step ids to force through the LLM fallback (e.g. selectCard). Learned recipes still open an auto-merge PR.'
required: false
default: ''
type: string
permissions:
contents: read
@@ -46,10 +51,17 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 15
if: ${{ github.event.inputs.skip_payment != 'true' && github.event.inputs.use_test_token != 'true' }}
permissions:
contents: read
id-token: write # keyless GCP auth, only to read the Gemini key for self-healing
outputs:
session_token: ${{ steps.extract_token.outputs.token }}
result: ${{ steps.test_result.outputs.result }}
failure_reason: ${{ steps.test_result.outputs.failure_reason }}
healed: ${{ steps.self_heal.outputs.healed }}
env:
HAS_GEMINI_SECRET: ${{ secrets.GEMINI_API_KEY != '' }}
steps:
- name: Checkout code
@@ -74,6 +86,48 @@ jobs:
working-directory: frontend
run: mkdir -p test-results
# ── Self-healing Stripe Checkout: LLM fallback key ───────────────────
# The Stripe step runner (frontend/e2e/helpers/self-healing) falls back
# to Gemini when every deterministic variant of a step fails. The key is
# the AI Studio key (billed outside the nomadkaraoke project). Prefer a
# GEMINI_API_KEY repo secret; otherwise read it from Secret Manager via
# keyless auth. All of this is best-effort: without a key the test runs
# deterministic-only, exactly as before.
- name: Authenticate to Google Cloud (Gemini key)
id: gcp_auth
if: ${{ env.HAS_GEMINI_SECRET != 'true' }}
continue-on-error: true
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
if: steps.gcp_auth.outcome == 'success'
continue-on-error: true
uses: google-github-actions/setup-gcloud@v2
- name: Load Gemini key for self-healing fallback
continue-on-error: true
env:
GEMINI_SECRET: ${{ secrets.GEMINI_API_KEY }}
GCP_AUTHED: ${{ steps.gcp_auth.outcome == 'success' }}
run: |
KEY="$GEMINI_SECRET"
if [ -z "$KEY" ] && [ "$GCP_AUTHED" = "true" ]; then
KEY=$(gcloud secrets versions access latest --secret=gemini-api-key --project=nomadkaraoke 2>/dev/null || true)
fi
# Drop the deployer credentials before any test code runs.
if [ -n "${GOOGLE_GHA_CREDS_PATH:-}" ]; then rm -f "$GOOGLE_GHA_CREDS_PATH"; fi
if [ -n "${CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE:-}" ]; then rm -f "$CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE"; fi
if [ -n "$KEY" ]; then
echo "::add-mask::$KEY"
echo "GEMINI_API_KEY=$KEY" >> "$GITHUB_ENV"
echo "Self-healing LLM fallback: enabled"
else
echo "::warning::Self-healing LLM fallback disabled (no Gemini key) — Stripe steps run deterministic-only"
fi
- name: Ensure testmail.app domain is allowlisted
run: |
curl -sf -X POST \
@@ -93,9 +147,14 @@ jobs:
E2E_STRIPE_CARD_EXPIRY: ${{ secrets.E2E_STRIPE_CARD_EXPIRY }}
E2E_STRIPE_CARD_CVC: ${{ secrets.E2E_STRIPE_CARD_CVC }}
E2E_STRIPE_CARDHOLDER_NAME: ${{ secrets.E2E_STRIPE_CARDHOLDER_NAME }}
E2E_STRIPE_ZIP: ${{ secrets.E2E_STRIPE_ZIP }}
E2E_SELF_HEAL_FORCE_LLM: ${{ inputs.self_heal_force_llm || '' }}
# No real card available → 'checkout-only' (no charge). Set the repo variable
# E2E_REAL_PAYMENT=true to go back to buying a credit with E2E_STRIPE_CARD_*.
E2E_PAYMENT_MODE: ${{ vars.E2E_REAL_PAYMENT == 'true' && 'real' || 'checkout-only' }}
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
run: |
echo "=== Stage 1: Credit Purchase via Real Stripe ==="
echo "=== Stage 1: Credit Purchase via Real Stripe (mode: $E2E_PAYMENT_MODE) ==="
echo "Time: $(date)"
npx playwright test credit-purchase-real.spec.ts \
--config=playwright.production.config.ts \
@@ -115,8 +174,46 @@ jobs:
echo "result=success" >> "$GITHUB_OUTPUT"
else
echo "result=failure" >> "$GITHUB_OUTPUT"
# A declined card is an issuer/card problem, not a broken checkout —
# say so in the alerts (marker comes from e2e/helpers/stripe-checkout.ts).
REASON=$(grep -m1 -o 'STRIPE_CARD_DECLINED:.*' frontend/test-output-payment.log 2>/dev/null | sed 's/ — .*//' | tr -d '"\\' || true)
if [ -n "$REASON" ]; then
echo "failure_reason=Test card declined, not a checkout bug (${REASON#STRIPE_CARD_DECLINED: }). Check the card/issuer for a fraud hold, then re-run." >> "$GITHUB_OUTPUT"
echo "::error::$REASON"
fi
fi
- name: Detect self-healed Stripe steps
id: self_heal
if: always()
working-directory: frontend
run: |
REPORT=test-results/self-heal/self-heal-report.json
LEARNED=test-results/self-heal/learned-variants.json
if [ -f "$REPORT" ]; then
{
echo "### Stripe Checkout self-healing"
echo '```json'
jq '{flowVerified, llmCalls, learnedWritten, added, outcomes: [.outcomes[] | {stepId, status, via, variant, model, reason}]}' "$REPORT"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
fi
# Only promote recipes from a run whose purchase was verified server-side.
if [ "${{ steps.test_result.outputs.result }}" = "success" ] && [ -f "$LEARNED" ]; then
echo "healed=true" >> "$GITHUB_OUTPUT"
echo "::warning::Stripe Checkout changed — LLM fallback healed it; an auto-merge PR will record the new variant"
else
echo "healed=false" >> "$GITHUB_OUTPUT"
fi
- name: Upload self-heal learned variants
if: steps.self_heal.outputs.healed == 'true'
uses: actions/upload-artifact@v4
with:
name: self-heal-learned-${{ github.run_number }}
path: frontend/test-results/self-heal/
retention-days: 30
- name: Extract session token
id: extract_token
if: steps.test_result.outputs.result == 'success'
@@ -132,8 +229,21 @@ jobs:
echo "token=" >> $GITHUB_OUTPUT
fi
- name: Upload artifacts
- name: Scrub secrets from artifacts (public repo)
id: scrub
if: always()
working-directory: frontend
env:
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
E2E_STRIPE_CARD_NUMBER: ${{ secrets.E2E_STRIPE_CARD_NUMBER }}
E2E_STRIPE_CARD_EXPIRY: ${{ secrets.E2E_STRIPE_CARD_EXPIRY }}
E2E_STRIPE_CARD_CVC: ${{ secrets.E2E_STRIPE_CARD_CVC }}
E2E_SESSION_TOKEN: ${{ steps.extract_token.outputs.token }}
run: node e2e/scripts/scrub-artifacts.mjs --drop-videos --blank-inputs test-results test-output-payment.log
- name: Upload artifacts
if: always() && steps.scrub.outcome == 'success'
uses: actions/upload-artifact@v4
with:
name: e2e-payment-results-${{ github.run_number }}
@@ -144,15 +254,180 @@ jobs:
- name: Discord notification (failure)
if: steps.test_result.outputs.result == 'failure'
env:
# Via env + jq, never ${{ }} in the script: the reason contains Stripe's message text.
REASON: ${{ steps.test_result.outputs.failure_reason || 'Payment flow is broken. Customers may not be receiving credits.' }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
RUN_NUMBER: ${{ github.run_number }}
WEBHOOK: ${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}
run: |
curl -s -H "Content-Type: application/json" \
-d "{\"embeds\": [{\"title\": \"🚨 E2E Daily Test FAILED — Stage 1: Credit Purchase\", \"description\": \"Payment flow is broken. Customers may not be receiving credits.\n\n**Run:** #${{ github.run_number }}\n**Details:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": 15158332}]}" \
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
jq -n --arg reason "$REASON" --arg run "$RUN_NUMBER" --arg url "$RUN_URL" \
'{embeds: [{title: "🚨 E2E Daily Test FAILED — Stage 1: Credit Purchase", description: "\($reason)\n\n**Run:** #\($run)\n**Details:** \($url)", color: 15158332}]}' |
curl -s -H "Content-Type: application/json" -d @- "$WEBHOOK"
- name: Fail if test failed
if: steps.test_result.outputs.result == 'failure'
run: exit 1
# =========================================================================
# Self-heal: record LLM-discovered Stripe variants via an auto-merging PR
# =========================================================================
# One Stripe layout change → one LLM-healed run → one data-only PR (only
# learned-variants.json) that auto-merges, so the next run replays the
# recipe deterministically. No human in the loop.
#
# Merge gates for a bot PR (all verified live with #1117, 2026-10-03):
# - its `pull_request` CI run is created "action_required" and, until run,
# supersedes other CI Gate results → we approve it via the API;
# - the `protect main` ruleset's require_extra_approval_for_unattributed_changes
# (GitHub default true since ~Aug 2026) would demand a human review for
# bot-authored changes → set to false on ruleset 11423976;
# - review threads must be resolved → `@coderabbitai ignore` in the body.
self-heal-pr:
name: "Self-heal: auto-merge PR"
runs-on: ubuntu-latest
timeout-minutes: 10
needs: e2e-credit-purchase
# Only learn from main — branch runs (e.g. testing self_heal_force_llm on a
# feature branch) must not open PRs against main.
if: always() && needs.e2e-credit-purchase.outputs.healed == 'true' && github.ref == 'refs/heads/main'
permissions:
contents: write
pull-requests: write
actions: write
outputs:
pr_url: ${{ steps.pr.outputs.pr_url }}
unchanged: ${{ steps.pr.outputs.unchanged }}
steps:
- name: Checkout main
uses: actions/checkout@v4
with:
ref: main
- name: Download learned variants
uses: actions/download-artifact@v4
with:
name: self-heal-learned-${{ github.run_number }}
path: /tmp/self-heal
- name: Open auto-merge PR
id: pr
env:
GH_TOKEN: ${{ github.token }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
TARGET=frontend/e2e/helpers/self-healing/learned-variants.json
# A bot-authored PR's `pull_request` CI run is created as
# "action_required" (awaiting approval) and, until it runs, supersedes
# any other CI Gate result for the ruleset. Approve it; succeed once a
# pull_request run exists that is past approval.
approve_ci() {
local branch=$1 runs pending active
for _ in $(seq 1 18); do
runs=$(gh run list --workflow ci.yml --branch "$branch" --event pull_request --json databaseId,status,conclusion) || { sleep 10; continue; }
pending=$(jq -r '.[] | select(.conclusion == "action_required" or .status == "waiting" or .status == "action_required") | .databaseId' <<<"$runs") || pending=""
active=$(jq '[.[] | select(.conclusion != "action_required" and .status != "waiting" and .status != "action_required")] | length' <<<"$runs") || active=0
for id in $pending; do
if gh api -X POST "repos/${{ github.repository }}/actions/runs/$id/approve" >/dev/null; then
echo "Approved CI run $id"
else
echo "::warning::Could not approve CI run $id with GITHUB_TOKEN"
fi
done
if [ -z "$pending" ] && [ "$active" -gt 0 ]; then
echo "CI is running for $branch"
return 0
fi
sleep 10
done
return 1
}
REPORT=/tmp/self-heal/self-heal-report.json
OPEN=$(gh pr list --label e2e-self-heal --state open --json url --jq '.[0].url // ""')
if [ -n "$OPEN" ]; then
echo "A self-heal PR is already open ($OPEN) — not opening another; making sure its CI can run"
echo "pr_url=$OPEN" >> "$GITHUB_OUTPUT"
OPEN_BRANCH=$(gh pr view "$OPEN" --json headRefName --jq .headRefName || true)
if [ -z "$OPEN_BRANCH" ] || ! approve_ci "$OPEN_BRANCH"; then
echo "ci_needs_approval=true" >> "$GITHUB_OUTPUT"
fi
exit 0
fi
cp /tmp/self-heal/learned-variants.json "$TARGET"
if git diff --quiet -- "$TARGET"; then
echo "learned-variants.json unchanged vs main — nothing to do"
echo "unchanged=true" >> "$GITHUB_OUTPUT"
exit 0
fi
STEPS=$(jq -r '[.outcomes[] | select(.status == "healed") | .stepId] | unique | join(", ")' "$REPORT")
BRANCH="self-heal/stripe-checkout-${{ github.run_id }}"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git checkout -b "$BRANCH"
git add "$TARGET"
git commit -m "test(e2e): self-heal Stripe Checkout steps: $STEPS" -m "Learned by the LLM fallback in $RUN_URL (purchase verified server-side)."
git push origin "$BRANCH"
gh label create e2e-self-heal --color FBCA04 --description "Auto-generated by the self-healing Stripe E2E" 2>/dev/null || true
{
echo "## 🩹 Stripe Checkout self-heal"
echo
echo "Stripe changed its hosted checkout page. In [run #${{ github.run_number }}]($RUN_URL) every deterministic variant of **$STEPS** failed; the Gemini fallback completed the step(s), and the purchase was then **verified server-side** (credit granted)."
echo
echo "This PR only adds the recipe(s) to \`learned-variants.json\`, so future runs replay them deterministically (no LLM). It auto-merges once CI passes."
echo
echo "### Learned recipes"
echo '```json'
jq '[.outcomes[] | select(.status == "healed") | {stepId, model, llmCalls, actions}]' "$REPORT"
echo '```'
echo
echo "@coderabbitai ignore"
echo
echo "🤖 Generated by the E2E Daily self-healing workflow"
} > /tmp/pr-body.md
PR_URL=$(gh pr create --base main --head "$BRANCH" --label e2e-self-heal \
--title "test(e2e): self-heal Stripe Checkout ($STEPS)" --body-file /tmp/pr-body.md)
echo "pr_url=$PR_URL" >> "$GITHUB_OUTPUT"
gh pr merge "$PR_URL" --auto --squash
if approve_ci "$BRANCH"; then
echo "Opened $PR_URL (auto-merge enabled, CI approved)"
else
# Fallback: dispatched CI (allowed from GITHUB_TOKEN) puts a CI Gate
# check on the head SHA if no pull_request run ever appears.
gh workflow run ci.yml --ref "$BRANCH"
echo "ci_needs_approval=true" >> "$GITHUB_OUTPUT"
echo "::warning::CI for $PR_URL may need a one-click approval (PR → Checks → Approve and run)"
fi
- name: Discord notification (self-heal)
# Recipe already on main (e.g. merged between checkout and now) → nothing to report.
if: always() && steps.pr.outputs.unchanged != 'true'
run: |
PR="${{ steps.pr.outputs.pr_url }}"
if [ -n "$PR" ] && [ "${{ steps.pr.outputs.ci_needs_approval }}" = "true" ]; then
TITLE="🩹 E2E self-healed Stripe — PR needs a CI approval click"
DESC="LLM fallback healed a Stripe Checkout change. The auto-merge PR's CI run awaits approval (open the PR → Checks → Approve and run): $PR"
COLOR=16776960
elif [ -n "$PR" ]; then
TITLE="🩹 E2E self-healed a Stripe Checkout change"
DESC="Stripe changed its checkout page; the LLM fallback got through and the purchase was verified. Auto-merge PR: $PR"
COLOR=16776960
else
TITLE="⚠️ E2E self-heal PR could not be opened"
DESC="The LLM fallback healed a Stripe step but opening the PR failed — see the run."
COLOR=15105570
fi
curl -s -H "Content-Type: application/json" \
-d "{\"embeds\": [{\"title\": \"$TITLE\", \"description\": \"$DESC\n\n**Run:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": $COLOR}]}" \
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
# =========================================================================
# Stage 2: Happy Path (uses credit from Stage 1)
# =========================================================================
@@ -254,8 +529,19 @@ jobs:
echo "result=failure" >> "$GITHUB_OUTPUT"
fi
- name: Upload test artifacts
- name: Scrub secrets from artifacts (public repo)
id: scrub
if: always()
working-directory: frontend
env:
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token || needs.e2e-credit-purchase.outputs.session_token || '' }}
run: node e2e/scripts/scrub-artifacts.mjs test-results playwright-report test-output-happy-path.log
- name: Upload test artifacts
if: always() && steps.scrub.outcome == 'success'
uses: actions/upload-artifact@v4
with:
name: e2e-happy-path-results-${{ github.run_number }}
@@ -266,7 +552,7 @@ jobs:
retention-days: 30
- name: Upload video recordings
if: always()
if: always() && steps.scrub.outcome == 'success'
uses: actions/upload-artifact@v4
with:
name: e2e-happy-path-videos-${{ github.run_number }}
@@ -309,7 +595,7 @@ jobs:
notify:
name: "Notify"
runs-on: ubuntu-latest
needs: [e2e-credit-purchase, e2e-happy-path]
needs: [e2e-credit-purchase, e2e-happy-path, self-heal-pr]
if: always()
steps:
@@ -336,8 +622,9 @@ jobs:
E2E Daily Test Results
======================
Stage 1 (Credit Purchase): ${{ needs.e2e-credit-purchase.result || 'skipped' }}
Stage 1 (Credit Purchase): ${{ needs.e2e-credit-purchase.result || 'skipped' }}${{ vars.E2E_REAL_PAYMENT != 'true' && ' [checkout-only: no real payment]' || '' }}${{ needs.e2e-credit-purchase.outputs.failure_reason && format(' — {0}', needs.e2e-credit-purchase.outputs.failure_reason) || '' }}
Stage 2 (Happy Path): ${{ needs.e2e-happy-path.result || 'skipped' }}
Stripe self-heal: ${{ needs.e2e-credit-purchase.outputs.healed == 'true' && format('Stripe changed its checkout; LLM fallback healed it. Auto-merge PR: {0}', needs.self-heal-pr.outputs.pr_url || (needs.self-heal-pr.outputs.unchanged == 'true' && '(already on main)' || '(failed to open — see run)')) || 'not needed' }}
Run: #${{ github.run_number }}
Trigger: ${{ github.event_name }}
+10 -1
View File
@@ -83,8 +83,17 @@ jobs:
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
continue-on-error: true
- name: Upload logs
- name: Scrub secrets from artifacts (public repo)
id: scrub
if: always()
working-directory: frontend
env:
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
run: node e2e/scripts/scrub-artifacts.mjs test-results playwright-report e2e-output.log
- name: Upload logs
if: always() && steps.scrub.outcome == 'success'
uses: actions/upload-artifact@v4
with:
name: e2e-tenant-${{ matrix.tenant }}-${{ github.run_number }}
+12
View File
@@ -73,6 +73,18 @@ RUN --mount=type=cache,target=/root/.cache/pip \
pip install --upgrade pip && \
pip install -e .
# Pre-build matplotlib's font cache at BUILD time. Without it, the first
# `import matplotlib.pyplot` on every new Cloud Run instance scanned all the
# Noto fonts above (20-40s of GIL-holding CPU) and froze the API's event loop
# — prod logged "Matplotlib is building the font cache" in 17 of 28
# "servers unavailable" banner episodes (2026-10-03 analysis). The cache lives
# in MPLCONFIGDIR so it ships in the image instead of the in-memory $HOME.
ENV MPLCONFIGDIR=/opt/mplconfig
RUN mkdir -p /opt/mplconfig && \
python -c "import matplotlib; matplotlib.use('Agg'); import matplotlib.font_manager as fm; print(len(fm.fontManager.ttflist), 'fonts cached')" && \
ls /opt/mplconfig/fontlist-*.json && \
chmod -R a+rwX /opt/mplconfig
# Now copy actual source code (AFTER deps installed, so code changes don't
# invalidate the expensive pip install layer in registry cache)
COPY karaoke_gen /app/karaoke_gen
+85 -36
View File
@@ -463,7 +463,7 @@ class CacheStatsResponse(BaseModel):
# =============================================================================
@router.get("/audio-searches", response_model=AudioSearchListResponse)
async def list_audio_searches(
def list_audio_searches(
limit: int = 50,
status_filter: Optional[str] = None,
exclude_test: bool = True,
@@ -670,7 +670,7 @@ async def clear_audio_search_cache(
@router.post("/jobs/{job_id}/reset-worker-state")
async def reset_worker_state(
def reset_worker_state(
job_id: str,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
@@ -880,7 +880,7 @@ def _extract_files_recursive(
@router.get("/jobs/{job_id}/files", response_model=JobFilesResponse)
async def get_job_files(
def get_job_files(
job_id: str,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
@@ -1075,7 +1075,7 @@ async def update_job(
f"Auto-deleting outputs for job {job_id} (toggled to private by {admin_email})"
)
# Call the delete-outputs endpoint directly (same module)
await delete_job_outputs(job_id, auth_data)
await asyncio.to_thread(delete_job_outputs, job_id, auth_data)
auto_deleted = True
except HTTPException:
# delete_job_outputs raises HTTPException on validation failures,
@@ -1588,7 +1588,7 @@ ALL_WORKER_PROGRESS_KEYS = [
@router.post("/jobs/{job_id}/clear-workers", response_model=ClearWorkersResponse)
async def clear_worker_state(
def clear_worker_state(
job_id: str,
auth_data: AuthResult = Depends(require_admin),
):
@@ -1676,7 +1676,7 @@ TERMINAL_STATES = {"complete", "prep_complete", "failed", "cancelled"}
@router.post("/jobs/{job_id}/delete-outputs", response_model=DeleteOutputsResponse)
async def delete_job_outputs(
def delete_job_outputs(
job_id: str,
auth_data: AuthResult = Depends(require_admin),
):
@@ -1881,7 +1881,7 @@ class OrphanedOutputsCleanupRequest(BaseModel):
@router.post("/orphaned-outputs/cleanup")
async def cleanup_orphaned_outputs(
def cleanup_orphaned_outputs(
req: OrphanedOutputsCleanupRequest,
auth_data: AuthResult = Depends(require_admin),
) -> dict:
@@ -1999,7 +1999,7 @@ async def cleanup_orphaned_outputs(
@router.get("/jobs/{job_id}/completion-message", response_model=CompletionMessageResponse)
async def get_job_completion_message(
def get_job_completion_message(
job_id: str,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
@@ -2063,7 +2063,7 @@ async def get_job_completion_message(
@router.post("/jobs/{job_id}/send-completion-email", response_model=SendCompletionEmailResponse)
async def send_job_completion_email(
def send_job_completion_email(
job_id: str,
request: SendCompletionEmailRequest,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
@@ -2141,7 +2141,7 @@ class MintLoginLinkRequest(BaseModel):
@router.post("/users/{email}/login-link")
async def mint_user_login_link(
def mint_user_login_link(
email: str,
request: MintLoginLinkRequest,
auth_data: AuthResult = Depends(require_admin),
@@ -2180,7 +2180,7 @@ class ImpersonateUserResponse(BaseModel):
@router.post("/users/{email}/impersonate", response_model=ImpersonateUserResponse)
async def impersonate_user(
def impersonate_user(
email: str,
auth_data: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
@@ -2398,6 +2398,55 @@ async def regenerate_screens(
)
# =============================================================================
# Admin Regenerate (storage retention) Endpoint
# =============================================================================
class AdminRegenerateRequest(BaseModel):
"""Request body for POST /api/admin/jobs/{job_id}/regenerate."""
notify_customer: bool = Field(
False, description="Email/push the customer when the regenerate completes",
)
@router.post("/jobs/{job_id}/regenerate")
async def admin_regenerate_job(
job_id: str,
body: Optional[AdminRegenerateRequest] = None,
auth_data: AuthResult = Depends(require_admin),
):
"""
Rebuild a completed job's GCS outputs (storage retention), admin only.
Re-separates stems first if they were purged, then regenerates screens,
the lyrics video, every final and the packages in GCS. Unlike
``/rerender`` nothing is deleted or re-published (YouTube/Dropbox/GDrive
untouched, same brand code). No rate limit.
"""
from backend.services.regenerate_service import RegenerateService
from backend.services.theme_rerender_service import RerenderError
body = body or AdminRegenerateRequest()
admin_email = auth_data.user_email or "unknown"
job_manager = JobManager()
job = await asyncio.to_thread(job_manager.get_job, job_id)
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
try:
result = await RegenerateService(job_manager).start(
job, requested_by=admin_email, source="admin", notify_customer=body.notify_customer,
)
except RerenderError as e:
raise HTTPException(status_code=e.status_code, detail=str(e))
return {
"status": "processing",
"job_id": job_id,
"needs_stems": result["needs_stems"],
"notify_customer": body.notify_customer,
"message": "Regenerate started (GCS only; nothing re-published).",
}
# =============================================================================
# Admin Re-render Endpoint
# =============================================================================
@@ -2863,7 +2912,7 @@ OVERRIDE_AUDIO_ALLOWED_STATES = {
@router.post("/jobs/{job_id}/override-audio-source", response_model=OverrideAudioSourceResponse)
async def override_audio_source(
def override_audio_source(
job_id: str,
request: OverrideAudioSourceRequest,
auth_data: AuthResult = Depends(require_admin),
@@ -3168,7 +3217,7 @@ class WebhookEventItem(BaseModel):
@router.get("/payments/summary", response_model=RevenueSummaryResponse)
async def get_payment_summary(
def get_payment_summary(
days: int = 30,
exclude_test: bool = True,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
@@ -3183,7 +3232,7 @@ async def get_payment_summary(
@router.get("/payments/revenue-chart", response_model=List[RevenueChartPoint])
async def get_revenue_chart(
def get_revenue_chart(
days: int = 30,
group_by: str = "day",
exclude_test: bool = True,
@@ -3196,7 +3245,7 @@ async def get_revenue_chart(
@router.get("/payments", response_model=PaymentListResponse)
async def list_payments(
def list_payments(
limit: int = 50,
offset: int = 0,
order_type: Optional[str] = None,
@@ -3216,7 +3265,7 @@ async def list_payments(
@router.get("/payments/balance", response_model=StripeBalanceResponse)
async def get_stripe_balance(
def get_stripe_balance(
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
"""Get current Stripe account balance."""
@@ -3226,7 +3275,7 @@ async def get_stripe_balance(
@router.get("/payments/payouts", response_model=List[PayoutItem])
async def get_payouts(
def get_payouts(
limit: int = 20,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
@@ -3237,7 +3286,7 @@ async def get_payouts(
@router.get("/payments/disputes", response_model=List[DisputeItem])
async def get_disputes(
def get_disputes(
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
"""Get open and recent disputes."""
@@ -3247,7 +3296,7 @@ async def get_disputes(
@router.get("/payments/webhook-events", response_model=List[WebhookEventItem])
async def get_webhook_events(
def get_webhook_events(
limit: int = 50,
event_type: Optional[str] = None,
status: Optional[str] = None,
@@ -3260,7 +3309,7 @@ async def get_webhook_events(
@router.get("/payments/by-user/{email}")
async def get_user_payments(
def get_user_payments(
email: str,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
@@ -3271,7 +3320,7 @@ async def get_user_payments(
@router.get("/users/{email}/emails")
async def get_user_emails(
def get_user_emails(
email: str,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
@@ -3282,7 +3331,7 @@ async def get_user_emails(
@router.get("/emails/{message_id}")
async def get_email_detail(
def get_email_detail(
message_id: str,
source: str = "postmark",
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
@@ -3302,7 +3351,7 @@ async def get_email_detail(
@router.get("/payments/{session_id}")
async def get_payment_detail(
def get_payment_detail(
session_id: str,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
@@ -3316,7 +3365,7 @@ async def get_payment_detail(
@router.post("/payments/{session_id}/refund", response_model=RefundResponse)
async def refund_payment(
def refund_payment(
session_id: str,
request: RefundRequest,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
@@ -3374,7 +3423,7 @@ async def refund_payment(
@router.post("/payments/normalize-emails")
async def normalize_payment_emails(
def normalize_payment_emails(
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
"""One-time backfill: lowercase all customer_email values in stripe_payments."""
@@ -3384,7 +3433,7 @@ async def normalize_payment_emails(
@router.post("/backfill/user-stats")
async def backfill_user_stats(
def backfill_user_stats(
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
"""One-time backfill: recalculate total_jobs_completed and total_spent for all users."""
@@ -3877,7 +3926,7 @@ async def get_audio_edit_review_detail(
@router.get("/abuse/related/{email}")
async def find_related_accounts(
def find_related_accounts(
email: str,
auth_result: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
@@ -3927,7 +3976,7 @@ async def find_related_accounts(
@router.get("/abuse/correlations")
async def find_account_correlations(
def find_account_correlations(
auth_result: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
@@ -3977,7 +4026,7 @@ async def find_account_correlations(
@router.get("/abuse/suspicious")
async def find_suspicious_accounts(
def find_suspicious_accounts(
min_jobs: int = 2,
max_spend: int = 0,
auth_result: AuthResult = Depends(require_admin),
@@ -4016,7 +4065,7 @@ async def find_suspicious_accounts(
@router.get("/abuse/by-ip/{ip_address:path}")
async def find_users_by_ip(
def find_users_by_ip(
ip_address: str,
auth_result: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
@@ -4041,7 +4090,7 @@ async def find_users_by_ip(
@router.get("/abuse/by-fingerprint/{fingerprint}")
async def find_users_by_fingerprint(
def find_users_by_fingerprint(
fingerprint: str,
auth_result: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
@@ -4066,7 +4115,7 @@ async def find_users_by_fingerprint(
@router.post("/abuse/backfill-ips")
async def backfill_signup_ips(
def backfill_signup_ips(
auth_result: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
@@ -4165,7 +4214,7 @@ class IpBatchRequest(BaseModel):
@router.get("/abuse/ip-info/{ip_address:path}")
async def get_ip_info(
def get_ip_info(
ip_address: str,
auth_result: AuthResult = Depends(require_admin),
):
@@ -4175,7 +4224,7 @@ async def get_ip_info(
@router.post("/abuse/ip-info/batch")
async def get_ip_info_batch(
def get_ip_info_batch(
request: IpBatchRequest,
auth_result: AuthResult = Depends(require_admin),
):
@@ -4317,7 +4366,7 @@ class CommunityRequestListResponse(BaseModel):
@router.get("/community-requests", response_model=CommunityRequestListResponse)
async def list_community_requests(
def list_community_requests(
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
"""Full history of requests-board submissions across every status — who asked,
@@ -4371,7 +4420,7 @@ class CommunityReviewActionResponse(BaseModel):
@router.get("/community-reviews", response_model=CommunityReviewListResponse)
async def list_community_reviews(
def list_community_reviews(
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
"""List requests-board picks the daily picker flagged because an existing
+6 -6
View File
@@ -729,17 +729,17 @@ async def search_audio(
credential_manager = get_credential_manager()
if effective_enable_youtube_upload:
result = credential_manager.check_youtube_credentials()
result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
if result.status != CredentialStatus.VALID:
invalid_services.append(f"youtube ({result.message})")
if effective_dropbox_path:
result = credential_manager.check_dropbox_credentials()
result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
if result.status != CredentialStatus.VALID:
invalid_services.append(f"dropbox ({result.message})")
if effective_gdrive_folder_id:
result = credential_manager.check_gdrive_credentials()
result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
if result.status != CredentialStatus.VALID:
invalid_services.append(f"gdrive ({result.message})")
@@ -1111,7 +1111,7 @@ async def search_audio_standalone(
@router.get("/audio-search/{job_id}/results")
async def get_audio_search_results(
def get_audio_search_results(
job_id: str,
auth_result: AuthResult = Depends(require_auth)
):
@@ -1436,7 +1436,7 @@ async def provide_url_for_job(
@router.post("/audio-search/{job_id}/attach-upload-url", response_model=AttachUploadUrlsResponse)
async def attach_upload_url(
def attach_upload_url(
job_id: str,
request: Request,
body: AttachUploadUrlsRequest,
@@ -1471,7 +1471,7 @@ async def attach_upload_url(
@router.post("/audio-search/{job_id}/attach-upload-complete", response_model=AttachResponse)
async def attach_upload_complete(
def attach_upload_complete(
job_id: str,
request: Request,
background_tasks: BackgroundTasks,
+8 -8
View File
@@ -91,7 +91,7 @@ class CredentialValidationResponse(BaseModel):
# ===========================================================================
@router.get("/status", response_model=AllCredentialsStatusResponse)
async def get_credentials_status():
def get_credentials_status():
"""
Get the status of all OAuth credentials.
@@ -126,7 +126,7 @@ async def get_credentials_status():
@router.get("/status/{service}", response_model=CredentialStatusResponse)
async def get_service_credential_status(service: str, request: Request):
def get_service_credential_status(service: str, request: Request):
"""
Get the status of a specific service's OAuth credentials.
@@ -155,7 +155,7 @@ async def get_service_credential_status(service: str, request: Request):
@router.post("/validate", response_model=CredentialValidationResponse)
async def validate_credentials(request: CredentialValidationRequest, http_request: Request):
def validate_credentials(request: CredentialValidationRequest, http_request: Request):
"""
Validate that credentials are available for requested services.
@@ -200,7 +200,7 @@ async def validate_credentials(request: CredentialValidationRequest, http_reques
# ===========================================================================
@router.post("/youtube/device", response_model=DeviceAuthStartResponse)
async def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
"""
Start YouTube device authorization flow.
@@ -238,7 +238,7 @@ async def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] =
@router.get("/youtube/device/{device_code}", response_model=DeviceAuthPollResponse)
async def poll_youtube_device_auth(device_code: str):
def poll_youtube_device_auth(device_code: str):
"""
Poll for YouTube device authorization completion.
@@ -263,7 +263,7 @@ async def poll_youtube_device_auth(device_code: str):
@router.post("/gdrive/device", response_model=DeviceAuthStartResponse)
async def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
"""
Start Google Drive device authorization flow.
@@ -296,7 +296,7 @@ async def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = N
@router.get("/gdrive/device/{device_code}", response_model=DeviceAuthPollResponse)
async def poll_gdrive_device_auth(device_code: str):
def poll_gdrive_device_auth(device_code: str):
"""
Poll for Google Drive device authorization completion.
"""
@@ -316,7 +316,7 @@ async def poll_gdrive_device_auth(device_code: str):
# ===========================================================================
@router.post("/test-alert")
async def test_credential_alert(background_tasks: BackgroundTasks, request: Request):
def test_credential_alert(background_tasks: BackgroundTasks, request: Request):
"""
Test the credential alert mechanism.
+1 -1
View File
@@ -445,7 +445,7 @@ def _bucket(status: str, pending_search: bool) -> str:
@router.get("/{batch_id}", response_model=BulkBatchResponse)
async def bulk_batch(
def bulk_batch(
request: Request,
batch_id: str,
auth_result: AuthResult = Depends(require_auth),
+78 -2
View File
@@ -10,6 +10,17 @@ metadata to review frequency and context later. Two sinks per event:
2. A Firestore doc in ``client_events`` — survives log retention, cheap to
aggregate for "how often are users seeing this?" reviews.
Identity (2026-10-03): the client sends its session token (if any) and the
server resolves ``user_email`` / ``is_admin`` / ``is_internal`` / ``is_test``
from it — a client-supplied email is never trusted (and is ignored). Each
event also carries the FingerprintJS ``device_fingerprint`` (same visitorId the
magic-link abuse checks use), a per-tab ``tab_id`` and an ``episode_id`` that
groups one degradation episode (first banner → ``banner_recovered``).
The watchdog in ``backend/services/loop_watchdog.py`` writes server-side
``server_loop_stall`` docs into the same collection; clients cannot submit
that type.
Unauthenticated (review-token users must be able to report) and rate-limited
per IP, mirroring /api/client-errors. The limiter is process-local, so the
effective ceiling is 120/min/IP × live instances — acceptable for this threat
@@ -23,10 +34,12 @@ import logging
import time
from datetime import datetime, timezone
from typing import Any, Literal, Optional
from urllib.parse import urlparse
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel, Field, field_validator
from backend.utils.test_data import is_internal_email, is_test_email
from backend.services.error_monitor.frontend_ingestion import (
RateLimiter,
is_bot_user_agent,
@@ -48,6 +61,7 @@ EventType = Literal[
"banner_reconnecting",
"banner_unavailable",
"banner_waking",
"banner_recovered",
"lyrics_load_failed",
"waveform_slow",
"waveform_failed",
@@ -67,7 +81,12 @@ class ClientEventPayload(BaseModel):
type: EventType
url: str = Field("", max_length=2048)
job_id: Optional[str] = Field(None, max_length=64)
# Legacy field from pre-2026-10-03 frontends — accepted but IGNORED (the
# server resolves identity from the bearer token instead).
user_email: Optional[str] = Field(None, max_length=320)
device_fingerprint: Optional[str] = Field(None, max_length=128)
tab_id: Optional[str] = Field(None, max_length=64)
episode_id: Optional[str] = Field(None, max_length=64)
locale: str = Field("en", max_length=10)
release: str = Field("", max_length=64)
# Small free-form context (stall age, http status, elapsed ms, probe state…).
@@ -94,6 +113,51 @@ def _capped_detail(detail: Optional[dict]) -> dict[str, Any]:
return out
_TENANT_HOST_EXCLUDE = {"gen", "www", "api", "app", "decide", "localhost"}
def _tenant_from_url(url: str) -> Optional[str]:
"""``randy-vild.nomadkaraoke.com/...`` → ``randy-vild``; consumer hosts → None."""
try:
host = (urlparse(url).hostname or "").lower()
except ValueError:
return None
if not host.endswith(".nomadkaraoke.com"):
return None
sub = host[: -len(".nomadkaraoke.com")]
if not sub or "." in sub or sub in _TENANT_HOST_EXCLUDE:
return None
return sub
def _resolve_identity(request: Request) -> dict[str, Any]:
"""Resolve the caller from its bearer token. Never raises; anonymous on failure."""
identity: dict[str, Any] = {
"user_email": None, "is_admin": False, "is_internal": False, "is_test": False,
}
auth = request.headers.get("authorization", "")
if not auth.lower().startswith("bearer "):
return identity
token = auth[7:].strip()
if not token:
return identity
try:
from backend.services.auth_service import get_auth_service
result = get_auth_service().validate_token_full(token)
except Exception:
logger.debug("client_event token resolution failed", exc_info=True)
return identity
if not result.is_valid:
return identity
email = result.user_email
identity["user_email"] = email
identity["is_admin"] = bool(result.is_admin)
identity["is_internal"] = bool(email and is_internal_email(email))
identity["is_test"] = bool(email and is_test_email(email))
return identity
@router.post("", status_code=202)
def report_client_event(payload: ClientEventPayload, request: Request) -> dict:
client_ip = request.client.host if request.client else "unknown"
@@ -104,11 +168,20 @@ def report_client_event(payload: ClientEventPayload, request: Request) -> dict:
if is_bot_user_agent(user_agent):
return {"status": "ignored"}
# Sync handler → runs in FastAPI's threadpool, so the token lookup
# (Firestore) never touches the event loop.
identity = _resolve_identity(request)
event = {
"type": payload.type,
"source": "client",
"url": sanitize_url(payload.url),
"tenant": _tenant_from_url(payload.url),
"job_id": payload.job_id,
"user_email": payload.user_email,
**identity,
"device_fingerprint": payload.device_fingerprint,
"tab_id": payload.tab_id,
"episode_id": payload.episode_id,
"locale": payload.locale,
"release": payload.release,
"user_agent": user_agent,
@@ -118,10 +191,13 @@ def report_client_event(payload: ClientEventPayload, request: Request) -> dict:
# Sink 1: structured log line — correlate with backend symptoms in Logging.
logger.info(
"client_event type=%s job_id=%s user=%s url=%s release=%s detail=%s",
"client_event type=%s job_id=%s user=%s admin=%s fp=%s episode=%s url=%s release=%s detail=%s",
event["type"],
event["job_id"],
event["user_email"],
event["is_admin"],
event["device_fingerprint"],
event["episode_id"],
event["url"],
event["release"],
event["detail"],
+47 -21
View File
@@ -610,17 +610,17 @@ async def upload_and_create_job(
credential_manager = get_credential_manager()
if effective_enable_youtube_upload and not is_private:
result = credential_manager.check_youtube_credentials()
result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
if result.status != CredentialStatus.VALID:
invalid_services.append(f"youtube ({result.message})")
if dist.dropbox_path:
result = credential_manager.check_dropbox_credentials()
result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
if result.status != CredentialStatus.VALID:
invalid_services.append(f"dropbox ({result.message})")
if dist.gdrive_folder_id and not is_private:
result = credential_manager.check_gdrive_credentials()
result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
if result.status != CredentialStatus.VALID:
invalid_services.append(f"gdrive ({result.message})")
@@ -930,7 +930,7 @@ async def upload_and_create_job(
distribution_services: Dict[str, Any] = {}
if dist.dropbox_path:
dropbox_result = credential_manager.check_dropbox_credentials()
dropbox_result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
distribution_services["dropbox"] = {
"enabled": True,
"path": dist.dropbox_path,
@@ -939,7 +939,7 @@ async def upload_and_create_job(
}
if dist.gdrive_folder_id:
gdrive_result = credential_manager.check_gdrive_credentials()
gdrive_result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
distribution_services["gdrive"] = {
"enabled": True,
"folder_id": dist.gdrive_folder_id,
@@ -948,7 +948,7 @@ async def upload_and_create_job(
}
if effective_enable_youtube_upload:
youtube_result = credential_manager.check_youtube_credentials()
youtube_result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
distribution_services["youtube"] = {
"enabled": True,
"credentials_valid": youtube_result.status == CredentialStatus.VALID,
@@ -1105,8 +1105,20 @@ async def _validate_audio_durations(
Returns:
Tuple of (is_valid, audio_duration, instrumental_duration)
"""
# Two GCS downloads + two full decodes (15s+ seen in prod) — never on the loop.
return await asyncio.to_thread(
_validate_audio_durations_sync, storage, audio_gcs_path, instrumental_gcs_path, tolerance_seconds
)
def _validate_audio_durations_sync(
storage: StorageService,
audio_gcs_path: str,
instrumental_gcs_path: str,
tolerance_seconds: float,
) -> Tuple[bool, float, float]:
from pydub import AudioSegment
temp_dir = tempfile.mkdtemp(prefix="duration_check_")
try:
# Download audio file
@@ -1315,17 +1327,17 @@ async def create_job_with_upload_urls(
credential_manager = get_credential_manager()
if effective_enable_youtube_upload and not effective_is_private:
result = credential_manager.check_youtube_credentials()
result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
if result.status != CredentialStatus.VALID:
invalid_services.append(f"youtube ({result.message})")
if dist.dropbox_path:
result = credential_manager.check_dropbox_credentials()
result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
if result.status != CredentialStatus.VALID:
invalid_services.append(f"dropbox ({result.message})")
if dist.gdrive_folder_id and not effective_is_private:
result = credential_manager.check_gdrive_credentials()
result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
if result.status != CredentialStatus.VALID:
invalid_services.append(f"gdrive ({result.message})")
@@ -1652,6 +1664,20 @@ async def mark_uploads_complete(
logger.warning(f"Duration validation failed with error: {e}. Proceeding without validation.")
# Don't block the job if we can't validate - the video worker will fail more gracefully
# uploads/ expires after 7 days: keep the user's instrumental at the job
# root (where the video pipeline stages it anyway) so later re-renders,
# regenerates and edits still have it.
if (update_data.get('existing_instrumental_gcs_path') or '').startswith('uploads/'):
from backend.utils.existing_instrumental import persistent_instrumental_path
source = update_data['existing_instrumental_gcs_path']
dest = persistent_instrumental_path(job_id, source)
try:
storage_service.copy_blob(source, dest)
update_data['existing_instrumental_gcs_path'] = dest
logger.info(f"Job {job_id}: persisted existing instrumental {source} -> {dest}")
except Exception as e:
logger.warning(f"Job {job_id}: couldn't persist existing instrumental {source}: {e}")
# Add style assets to update if any
if style_assets:
update_data['style_assets'] = style_assets
@@ -1681,7 +1707,7 @@ async def mark_uploads_complete(
updated_job = job_manager.get_job(job_id)
if updated_job.dropbox_path:
dropbox_result = credential_manager.check_dropbox_credentials()
dropbox_result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
distribution_services["dropbox"] = {
"enabled": True,
"path": updated_job.dropbox_path,
@@ -1689,7 +1715,7 @@ async def mark_uploads_complete(
}
if updated_job.gdrive_folder_id:
gdrive_result = credential_manager.check_gdrive_credentials()
gdrive_result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
distribution_services["gdrive"] = {
"enabled": True,
"folder_id": updated_job.gdrive_folder_id,
@@ -1697,7 +1723,7 @@ async def mark_uploads_complete(
}
if updated_job.enable_youtube_upload:
youtube_result = credential_manager.check_youtube_credentials()
youtube_result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
distribution_services["youtube"] = {
"enabled": True,
"credentials_valid": youtube_result.status == CredentialStatus.VALID,
@@ -1885,7 +1911,7 @@ class ValidateUrlResponse(BaseModel):
@router.post("/jobs/validate-url", response_model=ValidateUrlResponse)
async def validate_job_url(
def validate_job_url(
request: Request,
body: ValidateUrlRequest,
auth_result: AuthResult = Depends(require_auth),
@@ -2015,17 +2041,17 @@ async def create_job_from_url(
credential_manager = get_credential_manager()
if effective_enable_youtube_upload and not body.is_private:
result = credential_manager.check_youtube_credentials()
result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
if result.status != CredentialStatus.VALID:
invalid_services.append(f"youtube ({result.message})")
if dist.dropbox_path:
result = credential_manager.check_dropbox_credentials()
result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
if result.status != CredentialStatus.VALID:
invalid_services.append(f"dropbox ({result.message})")
if dist.gdrive_folder_id and not body.is_private:
result = credential_manager.check_gdrive_credentials()
result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
if result.status != CredentialStatus.VALID:
invalid_services.append(f"gdrive ({result.message})")
@@ -2239,7 +2265,7 @@ def _get_gcs_path_for_finalise_file(job_id: str, file_type: str, filename: str)
@router.post("/jobs/create-finalise-only")
async def create_finalise_only_job(
def create_finalise_only_job(
request: Request,
body: CreateFinaliseOnlyJobRequest,
auth_result: AuthResult = Depends(require_auth)
@@ -2476,7 +2502,7 @@ async def create_finalise_only_job(
@router.post("/jobs/{job_id}/finalise-uploads-complete")
async def mark_finalise_uploads_complete(
def mark_finalise_uploads_complete(
job_id: str,
background_tasks: BackgroundTasks,
body: UploadsCompleteRequest,
@@ -2702,7 +2728,7 @@ async def mark_finalise_uploads_complete(
# ============================================================================
@router.post("/jobs/{job_id}/style-upload-urls")
async def get_style_upload_urls(
def get_style_upload_urls(
job_id: str,
body: StyleUploadUrlsRequest,
auth_result: AuthResult = Depends(require_auth),
@@ -2782,7 +2808,7 @@ async def get_style_upload_urls(
@router.post("/jobs/{job_id}/style-uploads-complete")
async def complete_style_uploads(
def complete_style_uploads(
job_id: str,
body: StyleUploadsCompleteRequest,
auth_result: AuthResult = Depends(require_auth),
+5 -4
View File
@@ -1,6 +1,7 @@
"""
Health check routes.
"""
import asyncio
import os
import logging
import subprocess
@@ -217,7 +218,7 @@ async def check_flacfetch_service_status() -> Dict[str, Any]:
async def check_encoding_worker_status() -> Dict[str, Any]:
"""Check if GCE encoding worker is available and healthy."""
encoding_service = get_encoding_service()
encoding_service = await asyncio.to_thread(get_encoding_service)
if not encoding_service.is_configured:
return {
@@ -335,7 +336,7 @@ def check_audio_separator_status() -> Dict[str, Any]:
@router.get("/health/audio-separator")
async def audio_separator_health() -> Dict[str, Any]:
def audio_separator_health() -> Dict[str, Any]:
"""
Return audio separation status (installed audio-separator package version).
@@ -546,7 +547,7 @@ async def detailed_health_check() -> Dict[str, Any]:
@router.get("/health/preload-status")
async def preload_status() -> Dict[str, Any]:
def preload_status() -> Dict[str, Any]:
"""
Check status of preloaded resources for performance optimization.
@@ -608,7 +609,7 @@ async def preload_status() -> Dict[str, Any]:
@router.get("/health/job-consistency")
async def job_consistency_check(
def job_consistency_check(
status: Optional[str] = None,
limit: int = 50
) -> Dict[str, Any]:
+236 -20
View File
@@ -28,6 +28,7 @@ from backend.workers.render_video_worker import process_render_video
from backend.api.dependencies import require_admin
from backend.services.auth_service import AuthResult, UserType
from backend.services.job_manager import JobManager, PREP_PHASE_STATUSES
from backend.utils.loop_bridge import run_in_body_thread, run_on_loop
from backend.services.tracing import (
extract_trace_context,
start_span_with_context,
@@ -141,7 +142,7 @@ async def sync_disposable_domains_endpoint(
@router.post("/workers/audio", response_model=WorkerResponse)
async def trigger_audio_worker(
def trigger_audio_worker(
request: WorkerRequest,
http_request: Request,
background_tasks: BackgroundTasks,
@@ -225,7 +226,7 @@ async def analyze_vocal_gaps_endpoint(
@router.post("/workers/lyrics", response_model=WorkerResponse)
async def trigger_lyrics_worker(
def trigger_lyrics_worker(
request: WorkerRequest,
http_request: Request,
background_tasks: BackgroundTasks,
@@ -338,19 +339,41 @@ async def trigger_screens_worker(
add_span_event("worker_skipped", {"reason": skip_response.status})
return skip_response
# Add task to background tasks
background_tasks.add_task(generate_screens, job_id)
from backend.config import get_settings
if not get_settings().enable_cloud_tasks:
# Direct-HTTP mode (local dev): the caller uses a 30s timeout, so keep
# the fire-and-forget background task there.
background_tasks.add_task(generate_screens, job_id)
add_span_event("worker_started")
return WorkerResponse(
status="started",
job_id=job_id,
message="Screens generation worker started"
)
# Cloud Tasks mode (prod): run the worker INLINE and respond when it's done.
# As a post-response BackgroundTask it ran on throttled CPU
# (--cpu-throttling only allocates CPU while a request is open) and
# its sync work blocked the event loop for every other request; inline,
# the open request keeps CPU allocated and the heavy steps run in worker
# threads. generate_screens handles its own failures (marks the job
# failed), so always 200 — a non-2xx would make Cloud Tasks re-run it.
add_span_event("worker_started")
try:
ok = await generate_screens(job_id)
except Exception as e: # noqa: BLE001 — never trigger a Cloud Tasks retry storm
logger.exception(f"[job:{job_id}] screens worker raised: {e}")
ok = False
return WorkerResponse(
status="started",
status="completed" if ok else "failed",
job_id=job_id,
message="Screens generation worker started"
message="Screens generation finished" if ok else "Screens generation failed",
)
@router.post("/workers/video", response_model=WorkerResponse)
async def trigger_video_worker(
def trigger_video_worker(
request: WorkerRequest,
http_request: Request,
background_tasks: BackgroundTasks,
@@ -391,7 +414,7 @@ async def trigger_video_worker(
@router.post("/workers/render-video", response_model=WorkerResponse)
async def trigger_render_video_worker(
def trigger_render_video_worker(
request: WorkerRequest,
http_request: Request,
background_tasks: BackgroundTasks,
@@ -563,7 +586,7 @@ async def check_idle_reminder(
@router.post("/youtube-queue/process")
async def process_youtube_upload_queue(
def process_youtube_upload_queue(
http_request: Request,
background_tasks: BackgroundTasks,
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
@@ -603,7 +626,7 @@ async def process_youtube_upload_queue(
@router.post("/process-stale-reviews")
async def process_stale_reviews_endpoint(
def process_stale_reviews_endpoint(
http_request: Request,
background_tasks: BackgroundTasks,
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
@@ -649,7 +672,7 @@ async def process_stale_reviews_endpoint(
@router.post("/youtube-backfill/run")
async def youtube_backfill_run_endpoint(
def youtube_backfill_run_endpoint(
http_request: Request,
background_tasks: BackgroundTasks,
max_updates: Optional[int] = None,
@@ -685,6 +708,119 @@ async def youtube_backfill_run_endpoint(
}
@router.post("/storage-retention/run")
async def storage_retention_run_endpoint(
dry_run: Optional[bool] = None,
job_ids: Optional[str] = None,
min_age_days: Optional[int] = None,
max_jobs: Optional[int] = None,
include_orphans: bool = False,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
"""
Purge regenerable files of old completed jobs (storage retention).
Called daily by Cloud Scheduler. DRY-RUN unless STORAGE_RETENTION_DRY_RUN is
false: it then only writes a report to GCS (path returned). See
backend/services/storage_retention.py for the policy.
Manual/testing params:
- ``job_ids=a,b`` scopes the pass to those jobs and runs synchronously
(returns the full report). Only a scoped pass may override ``dry_run=false``
or ``min_age_days`` — a global real purge only happens via the setting.
- ``max_jobs`` caps the jobs planned/purged; ``include_orphans`` adds a
report section on jobs/ folders with no Firestore doc (report only).
"""
from datetime import datetime, timezone
from backend.config import get_settings
from backend.services.storage_retention import StorageRetentionService
settings = get_settings()
if not settings.storage_retention_enabled:
return {"status": "disabled", "message": "STORAGE_RETENTION_ENABLED is false"}
scoped = [j.strip() for j in (job_ids or "").split(",") if j.strip()]
if not scoped:
if dry_run is False and settings.storage_retention_dry_run:
raise HTTPException(
status_code=400,
detail="A global real purge needs STORAGE_RETENTION_DRY_RUN=false; pass job_ids to scope a real run.",
)
if min_age_days is not None:
raise HTTPException(status_code=400, detail="min_age_days can only be overridden with job_ids")
effective_dry_run = settings.storage_retention_dry_run if dry_run is None else dry_run
if scoped:
report = await asyncio.to_thread(
StorageRetentionService().run,
dry_run=effective_dry_run, job_ids=scoped, min_age_days=min_age_days, max_jobs=max_jobs,
)
return {"status": "complete", "report": report}
now = datetime.now(timezone.utc)
report_path = StorageRetentionService.default_report_path(now, effective_dry_run)
# A full pass takes minutes: run it as the storage-retention-job Cloud Run
# Job. (The API service throttles CPU outside requests, which starves a
# BackgroundTask, and Cloudflare cuts requests at 100s.)
from backend.services.worker_service import get_worker_service
started = await get_worker_service().trigger_storage_retention_job(
dry_run=effective_dry_run, report_path=report_path,
max_jobs=max_jobs, include_orphans=include_orphans,
)
if not started:
raise HTTPException(status_code=503, detail="Couldn't start the storage-retention job")
return {
"status": "started",
"dry_run": effective_dry_run,
"report_path": f"gs://{settings.gcs_bucket_name}/{report_path}",
}
ORPHAN_DELETE_CONFIRMATION = "delete-orphan-job-folders"
@router.post("/storage-retention/orphans")
async def storage_retention_orphans_endpoint(
dry_run: bool = True,
confirm: Optional[str] = None,
max_folders: Optional[int] = None,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
"""
One-off cleanup of ``jobs/{id}/`` folders with no job record: keep ``input/``,
delete everything else (backend/services/storage_retention.py purge_orphans).
DRY-RUN unless ``dry_run=false&confirm=delete-orphan-job-folders``. Independent
of STORAGE_RETENTION_DRY_RUN and never run by the scheduler. Runs as the
storage-retention-job Cloud Run Job; the report path is returned.
"""
from datetime import datetime, timezone
from backend.config import get_settings
from backend.services.storage_retention import REPORT_PREFIX
from backend.services.worker_service import get_worker_service
if not dry_run and confirm != ORPHAN_DELETE_CONFIRMATION:
raise HTTPException(
status_code=400,
detail=f"A real orphan cleanup needs confirm={ORPHAN_DELETE_CONFIRMATION}",
)
settings = get_settings()
now = datetime.now(timezone.utc)
report_path = f"{REPORT_PREFIX}/{now.strftime('%Y%m%dT%H%M%SZ')}-orphans-{'dry-run' if dry_run else 'run'}.json"
started = await get_worker_service().trigger_storage_retention_job(
dry_run=dry_run, report_path=report_path, mode="orphans", max_folders=max_folders,
)
if not started:
raise HTTPException(status_code=503, detail="Couldn't start the storage-retention job")
return {
"status": "started",
"mode": "orphans",
"dry_run": dry_run,
"report_path": f"gs://{settings.gcs_bucket_name}/{report_path}",
}
@router.post("/community-daily-pick")
async def community_daily_pick_endpoint(
http_request: Request,
@@ -796,7 +932,10 @@ async def trigger_gdrive_validation_endpoint(
add_span_attribute("brand_code", str(brand_code))
try:
result = trigger_gdrive_validation(brand_code=brand_code, expect_cdg=expect_cdg)
# Sync OIDC fetch + HTTP POST (up to 60s) — off the event loop.
result = await asyncio.to_thread(
trigger_gdrive_validation, brand_code=brand_code, expect_cdg=expect_cdg
)
if result is None:
return {"status": "skipped", "message": "GDRIVE_VALIDATOR_URL not configured"}
@@ -814,6 +953,16 @@ async def retry_pending_render_jobs(
http_request: Request,
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
):
"""Cron: auto-retry RENDER_PENDING_CAPACITY jobs — see ``_retry_pending_render_jobs_sync``.
Firestore scans + updates run in a worker thread (they stalled the loop on
every tick); render triggers run back on the loop.
"""
loop = asyncio.get_running_loop()
return await run_in_body_thread(_retry_pending_render_jobs_sync, http_request, loop)
def _retry_pending_render_jobs_sync(http_request: Request, loop: asyncio.AbstractEventLoop):
"""
Auto-retry jobs parked in RENDER_PENDING_CAPACITY.
@@ -938,7 +1087,7 @@ async def retry_pending_render_jobs(
continue
try:
await worker_service.trigger_render_video_worker(job_id)
run_on_loop(loop, worker_service.trigger_render_video_worker(job_id))
retried.append(job_id)
logger.info(f"[job:{job_id}] Auto-retry triggered")
except Exception as e:
@@ -971,6 +1120,17 @@ async def recover_stuck_jobs(
http_request: Request,
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
):
"""Cron watchdog for stuck jobs — see ``_recover_stuck_jobs_sync``.
Its Firestore scans were the #1 event-loop staller (~260 stalls in a week,
up to 5s each), so the scan runs in a worker thread; worker re-triggers run
back on the loop.
"""
loop = asyncio.get_running_loop()
return await run_in_body_thread(_recover_stuck_jobs_sync, http_request, loop)
def _recover_stuck_jobs_sync(http_request: Request, loop: asyncio.AbstractEventLoop):
"""
Detect and recover jobs stuck in a processing status.
@@ -1060,7 +1220,7 @@ async def recover_stuck_jobs(
# a failing audio-worker (helper returns False after an external dispatch)
# can't fan out to every queried job in one tick.
retried_this_tick += 1
if await _retrigger_parked_download(job_manager, worker_service, job_id):
if _retrigger_parked_download(job_manager, worker_service, job_id, loop):
download_retried.append(job_id)
# --- Orphaned renders: re-park for automatic retry ---
@@ -1102,7 +1262,7 @@ async def recover_stuck_jobs(
continue
logger.warning(f"[job:{job_id}] REVIEW_COMPLETE stalled >10 min with no render — re-triggering")
try:
if await worker_service.trigger_render_video_worker(job_id):
if run_on_loop(loop, worker_service.trigger_render_video_worker(job_id)):
render_retriggered.append(job_id)
except Exception as e:
logger.warning(f"[job:{job_id}] render re-trigger failed: {e}")
@@ -1138,11 +1298,59 @@ async def recover_stuck_jobs(
"no screens — re-triggering"
)
try:
if await job_manager.advance_to_screens_if_ready(job_id):
if run_on_loop(loop, job_manager.advance_to_screens_if_ready(job_id)):
screens_retriggered.append(job_id)
except Exception as e:
logger.warning(f"[job:{job_id}] screens re-trigger failed: {e}")
# --- Storage-retention stems restore whose audio job died silently ---
# (hard-killed GPU task: no except block ran, the job sits at
# lyrics_complete with stems_restore=running forever). Fail it so the
# customer/admin gets a Retry button; the retry re-runs the restore.
stems_restore_failed = []
from backend.services.stems_restore import restore_stalled
lc_query = jobs_ref.where(
filter=FieldFilter("status", "==", JobStatus.LYRICS_COMPLETE.value)
).limit(SCREENS_RECOVERY_SCAN_LIMIT).stream()
regen_screens_retriggered = []
for doc in lc_query:
data = doc.to_dict() or {}
sd = data.get("state_data") or {}
job_id = data.get("job_id", doc.id)
# A re-render / regenerate / visibility flow parks the job at
# lyrics_complete only until its screens dispatch starts (which moves it
# to generating_screens within seconds). Still here after 10 min with no
# stems restore running = the dispatch was lost (or skipped by a stale
# screens_progress mark): clear the mark and re-trigger.
if sd.get("regen_restore_status") and not sd.get("stems_restore"):
if len(regen_screens_retriggered) >= SCREENS_RETRIGGERS_PER_TICK:
continue
job = job_manager.get_job(job_id)
age = _job_updated_age_seconds(job) if job else None
if job and age is not None and age > PREP_SCREENS_STALL_SECONDS:
from google.cloud.firestore_v1 import DELETE_FIELD as _DEL
logger.warning(f"[job:{job_id}] Re-render parked at lyrics_complete >10 min — re-triggering screens")
job_manager.update_job(job_id, {"state_data.screens_progress": _DEL})
try:
if run_on_loop(loop, worker_service.trigger_screens_worker(job_id)):
regen_screens_retriggered.append(job_id)
except Exception as e: # noqa: BLE001
logger.warning(f"[job:{job_id}] re-render screens re-trigger failed: {e}")
continue
if not sd.get("stems_restore"):
continue
job = job_manager.get_job(job_id)
if not job or not restore_stalled(job):
continue
logger.warning(f"[job:{job_id}] Stems restore stalled >60 min — failing for retry")
job_manager.update_job(job_id, {"state_data.stems_restore.status": "failed"})
job_manager.mark_job_failed(
job_id=job_id,
error_message="Restoring this track's audio stems timed out. Retry the job to try again.",
error_details={"stage": "stems_restore", "reason": "stalled"},
)
stems_restore_failed.append(job_id)
logger.info(
f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} "
f"download_parked={len(download_parked)} download_retried={len(download_retried)} "
@@ -1171,6 +1379,8 @@ async def recover_stuck_jobs(
"render_retriggered_count": len(render_retriggered),
"screens_retriggered_jobs": screens_retriggered,
"screens_retriggered_count": len(screens_retriggered),
"stems_restore_failed_jobs": stems_restore_failed,
"regen_screens_retriggered_jobs": regen_screens_retriggered,
}
@@ -1293,8 +1503,14 @@ def _park_download_for_retry(job_manager: JobManager, job_id: str, reason: str)
))
async def _retrigger_parked_download(job_manager: JobManager, worker_service, job_id: str) -> bool:
"""Re-trigger the audio download for a DOWNLOAD_PENDING_RETRY job."""
def _retrigger_parked_download(
job_manager: JobManager, worker_service, job_id: str, loop: asyncio.AbstractEventLoop
) -> bool:
"""Re-trigger the audio download for a DOWNLOAD_PENDING_RETRY job.
Called from the recover-stuck-jobs worker thread: the Firestore writes run
here, only the trigger coroutine goes back to the loop.
"""
from backend.models.job import JobStatus
job_manager.update_job(job_id, {"error_message": None, "error_details": None})
@@ -1308,7 +1524,7 @@ async def _retrigger_parked_download(job_manager: JobManager, worker_service, jo
logger.warning(f"[job:{job_id}] Could not transition parked download for retry")
return False
try:
await worker_service.trigger_audio_download_worker(job_id)
run_on_loop(loop, worker_service.trigger_audio_download_worker(job_id))
logger.info(f"[job:{job_id}] Parked download re-triggered")
return True
except Exception as e: # noqa: BLE001
+245 -36
View File
@@ -19,6 +19,7 @@ from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request,
from datetime import datetime, timezone
from google.cloud.exceptions import NotFound
from backend.utils.loop_bridge import run_in_body_thread, run_on_loop
from backend.utils.request_helpers import get_client_ip
from backend.models.job import Job, JobCreate, JobResponse, JobStatus
from backend.models.requests import (
@@ -36,6 +37,7 @@ from backend.services.tempo_label import apply_tempo_to_title
from backend.services.worker_service import get_worker_service
from backend.services.storage_service import StorageService
from backend.services.theme_service import get_theme_service
from backend.services.theme_rerender_service import RerenderError
from backend.config import get_settings
from backend.services.tracing import add_span_attribute
from backend.api.dependencies import require_admin, require_auth
@@ -50,6 +52,7 @@ from backend.models.requests import ChangeVisibilityRequest, ChangeVisibilityRes
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 backend.workers.style_helper import screen_included
from pydantic import BaseModel, Field, HttpUrl, validator
@@ -76,7 +79,7 @@ async def _trigger_workers_parallel(job_id: str) -> None:
@router.post("", response_model=JobResponse)
async def create_job(
def create_job(
request: URLSubmissionRequest,
http_request: Request,
background_tasks: BackgroundTasks,
@@ -210,7 +213,7 @@ async def create_job(
@router.get("/{job_id}", response_model=Job)
async def get_job(
def get_job(
job_id: str,
request: Request,
auth_result: AuthResult = Depends(require_auth)
@@ -275,7 +278,7 @@ class EditTrackResponse(BaseModel):
@router.post("/{job_id}/edit", response_model=EditTrackResponse)
async def edit_completed_track(
def edit_completed_track(
job_id: str,
request: EditTrackRequest,
http_request: Request,
@@ -311,6 +314,11 @@ async def edit_completed_track(
detail=t(locale, "jobs.notCompleted", status=job.status)
)
# Storage retention is deleting this job's files right now (seconds).
from backend.services.storage_retention import PURGE_IN_PROGRESS_MESSAGE, purge_in_progress
if purge_in_progress(job):
raise HTTPException(status_code=409, detail=PURGE_IN_PROGRESS_MESSAGE)
# Prevent editing if outputs already deleted (edit already in progress)
if job.outputs_deleted_at:
raise HTTPException(
@@ -451,6 +459,13 @@ async def edit_completed_track(
for key in list(file_urls.get('screens', {}).keys()):
update_payload[f"file_urls.screens.{key}"] = DELETE_FIELD
# Tenant track made with an older theme: the edited version uses the current one.
try:
from backend.services.theme_change_service import edit_theme_update
update_payload.update(edit_theme_update(job, screens_regenerating=metadata_updated))
except Exception as e:
logger.warning(f"Couldn't apply the current theme to edited job {job_id}: {e}")
# Add timeline event with structured metadata
edit_number = (job.edit_count if hasattr(job, 'edit_count') else 0) + 1
timeline_event = {
@@ -471,7 +486,11 @@ async def edit_completed_track(
job_ref.update(update_payload)
# --- Phase 4: Transition state ---
if metadata_updated:
# Storage retention archived this track's stems: review needs them, so go
# through the screens worker, which re-separates them before review opens.
from backend.services.regenerate_service import stems_need_restore
stems_restore_needed = stems_need_restore(job)
if metadata_updated or stems_restore_needed:
# Metadata changed → screens need regeneration.
# Transition to LYRICS_COMPLETE so screens worker can run
# (LYRICS_COMPLETE → GENERATING_SCREENS is a valid transition;
@@ -480,7 +499,10 @@ async def edit_completed_track(
job_id,
JobStatus.LYRICS_COMPLETE,
progress=55,
message="Regenerating screens with updated metadata",
message=(
"Regenerating screens with updated metadata" if metadata_updated
else "Restoring audio stems before review"
),
)
background_tasks.add_task(worker_service.trigger_screens_worker, job_id)
else:
@@ -536,6 +558,9 @@ _SUMMARY_STATE_DATA_KEYS = {
'batch_id',
'bulk_auto_selected',
'awaiting_upload',
'regenerate',
'stems_restore',
'instrumental_selection',
}
_SUMMARY_FILE_URLS_KEYS = {'finals', 'videos', 'packages'}
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete', 'cancelled']
@@ -565,8 +590,10 @@ def _is_auto_retry_pending(state_data: Optional[Dict[str, Any]]) -> bool:
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.
def _has_title_screen(file_urls: Dict[str, Any], state_data: Optional[Dict[str, Any]] = None) -> bool:
"""Return True if the screens stage is done: a title screen image (jpg or png)
was generated, or the theme leaves the title screen out and the screens worker
finished.
Used by the /retry endpoint to decide whether to resume from the render
stage or rewind further. The actual screen URLs live under format-specific
@@ -575,9 +602,15 @@ def _has_title_screen(file_urls: Dict[str, Any]) -> bool:
completed-review jobs back to AWAITING_REVIEW.
"""
screens = file_urls.get('screens') or {}
if not isinstance(screens, dict):
return False
return any(k == 'title' or k.startswith('title_') for k in screens)
if isinstance(screens, dict) and any(k == 'title' or k.startswith('title_') for k in screens):
return True
# No title image by design: rely on the screens worker's completion marker
# (cleared by every re-render/regeneration, so a stale "omitted" can't count).
state_data = state_data or {}
return (
not screen_included(state_data, 'title')
and (state_data.get('screens_progress') or {}).get('stage') == 'complete'
)
def _prune_state_data(data: Dict[str, Any]) -> Dict[str, Any]:
@@ -612,7 +645,7 @@ def _search_filter_jobs(jobs: List[Dict[str, Any]], search: str) -> List[Dict[st
@router.get("", response_model=None)
async def list_jobs(
def list_jobs(
request: Request,
status: Optional[JobStatus] = None,
environment: Optional[str] = None,
@@ -762,7 +795,7 @@ async def list_jobs(
@router.delete("/{job_id}")
async def delete_job(
def delete_job(
job_id: str,
request: Request,
delete_files: bool = True,
@@ -834,7 +867,7 @@ async def delete_job(
@router.delete("")
async def bulk_delete_jobs(
def bulk_delete_jobs(
request: Request,
environment: Optional[str] = None,
client_id: Optional[str] = None,
@@ -946,7 +979,7 @@ async def bulk_delete_jobs(
# ============================================================================
@router.get("/{job_id}/review-data")
async def get_review_data(
def get_review_data(
job_id: str,
request: Request,
auth_result: AuthResult = Depends(require_auth)
@@ -1011,7 +1044,7 @@ async def get_review_data(
@router.post("/{job_id}/start-review")
async def start_review(
def start_review(
job_id: str,
request: StartReviewRequest,
http_request: Request,
@@ -1049,7 +1082,7 @@ async def start_review(
@router.post("/{job_id}/corrections")
async def submit_corrections(
def submit_corrections(
job_id: str,
submission: CorrectionsSubmission,
http_request: Request,
@@ -1151,7 +1184,7 @@ async def submit_corrections(
@router.post("/{job_id}/edit-log")
async def submit_edit_log(
def submit_edit_log(
job_id: str,
edit_log: Dict[str, Any],
request: Request,
@@ -1561,7 +1594,7 @@ async def _get_audio_duration_ffprobe_signed(job_id: str, job, storage: StorageS
@router.post("/{job_id}/complete-review")
async def complete_review(
def complete_review(
job_id: str,
request: Request,
background_tasks: BackgroundTasks,
@@ -1655,7 +1688,7 @@ async def complete_review(
@router.post("/{job_id}/select-instrumental")
async def select_instrumental(
def select_instrumental(
job_id: str,
selection: InstrumentalSelection,
request: Request,
@@ -1725,7 +1758,7 @@ async def select_instrumental(
@router.get("/{job_id}/download-urls")
async def get_download_urls(
def get_download_urls(
job_id: str,
request: Request,
auth_result: AuthResult = Depends(require_auth)
@@ -1784,6 +1817,31 @@ DOWNLOAD_FILENAME_SUFFIXES = {
}
def _archived_output(job, category: str, file_key: str) -> bool:
"""True if storage retention purged this download (recorded in the job's manifest)."""
if not (getattr(job, 'renders_purged_at', None) or getattr(job, 'stems_purged_at', None)):
return False
manifest = getattr(job, 'storage_purge', None) or {}
for entry in manifest.get('files') or []:
path = (entry or {}).get('path') or ''
rel = path.split('/', 2)[-1] if path.startswith('jobs/') else path
if rel.startswith(f"{category}/{file_key}.") or rel == f"{category}/{file_key}":
return True
return False
def _archived_error(job, locale: str) -> HTTPException:
"""410 Gone with a machine-readable code so clients can offer/trigger a regenerate."""
return HTTPException(
status_code=410,
detail={
"code": "output_archived",
"message": t(locale, "jobs.fileNoLongerAvailable"),
"regenerate_url": f"/api/jobs/{job.job_id}/regenerate",
},
)
def _cleanup_temp_file(path: Optional[str]) -> None:
"""Best-effort removal of a temp file created for a download that failed
before streaming started (so it never reaches the iterator's cleanup)."""
@@ -1796,7 +1854,7 @@ def _cleanup_temp_file(path: Optional[str]) -> None:
@router.get("/{job_id}/download/{category}/{file_key}")
async def download_file(
def download_file(
job_id: str,
category: str,
file_key: str,
@@ -1823,16 +1881,21 @@ async def download_file(
file_urls = job.file_urls or {}
category_files = file_urls.get(category)
if not category_files:
raise HTTPException(status_code=404, detail=f"Category '{category}' not found")
if isinstance(category_files, dict):
gcs_path = category_files.get(file_key)
else:
elif category_files:
gcs_path = category_files if file_key == category else None
else:
gcs_path = None
if not gcs_path:
# Archived by storage retention: tell clients (UI, kjbox) it can be
# regenerated rather than a plain 404.
if _archived_output(job, category, file_key):
raise _archived_error(job, locale)
if not category_files:
raise HTTPException(status_code=404, detail=f"Category '{category}' not found")
raise HTTPException(status_code=404, detail=f"File '{file_key}' not found in '{category}'")
# Determine content type based on file extension
@@ -1915,6 +1978,8 @@ async def download_file(
# doesn't trip the error-monitor.
_cleanup_temp_file(tmp_path)
logger.warning(f"Download requested for missing object {gcs_path}")
if getattr(job, 'renders_purged_at', None) or getattr(job, 'stems_purged_at', None):
raise _archived_error(job, locale)
raise HTTPException(status_code=404, detail=t(locale, "jobs.fileNoLongerAvailable"))
except Exception as e:
_cleanup_temp_file(tmp_path)
@@ -1923,7 +1988,7 @@ async def download_file(
@router.post("/{job_id}/cancel")
async def cancel_job(
def cancel_job(
job_id: str,
request: CancelJobRequest,
http_request: Request,
@@ -2037,12 +2102,13 @@ async def retry_job(
# resume it correctly.
theme_rerender = state_data.get('theme_rerender') or {}
if (theme_rerender.get('theme_id') and original_status == JobStatus.FAILED
and not _has_title_screen(file_urls)):
and not _has_title_screen(file_urls, state_data)):
from backend.services.theme_rerender_service import RerenderError, ThemeRerenderService
try:
await ThemeRerenderService(job_manager).start(
job, theme_id=theme_rerender['theme_id'],
requested_by=auth_result.user_email or "unknown",
notify_customer=theme_rerender.get('notify_customer', True),
)
except RerenderError as e:
raise HTTPException(status_code=e.status_code, detail=str(e))
@@ -2057,7 +2123,7 @@ async def retry_job(
# keeping the admin's notify_customer choice. Its published outputs were
# already removed on the first attempt (recorded in the marker).
if (admin_rerender and original_status in (JobStatus.FAILED, JobStatus.CANCELLED)
and not _has_title_screen(file_urls)):
and not _has_title_screen(file_urls, state_data)):
from backend.services.admin_rerender_service import AdminRerenderService
from backend.services.theme_rerender_service import RerenderError
try:
@@ -2075,6 +2141,53 @@ async def retry_job(
"retry_stage": "admin_rerender",
}
# A failed storage-retention regenerate: re-run it (re-claims the job and
# restores purged stems first) until its screens exist; after that the
# branches below resume it (the marker keeps the run GCS-only).
from backend.services.regenerate_service import active_regenerate, stems_need_restore, RegenerateService
from backend.services.theme_rerender_service import RerenderError
regenerate = active_regenerate(job)
if (regenerate and original_status in (JobStatus.FAILED, JobStatus.CANCELLED)
and (not _has_title_screen(file_urls, state_data) or stems_need_restore(job))):
try:
await RegenerateService(job_manager).start(
job,
requested_by=auth_result.user_email or "unknown",
source=regenerate.get('source') or 'retry',
notify_customer=bool(regenerate.get('notify_customer', True)),
after=regenerate.get('after'),
)
except RerenderError as e:
raise HTTPException(status_code=e.status_code, detail=str(e))
return {
"status": "success",
"job_status": "lyrics_complete",
"message": "Job retry: re-running the regenerate",
"retry_stage": "regenerate",
}
# Stems archived by storage retention (e.g. an Edit whose stems restore
# failed): go back through the screens worker, which restores them first.
if stems_need_restore(job) and file_urls.get('lyrics', {}).get('corrections'):
from google.cloud.firestore_v1 import DELETE_FIELD as _DEL
# A manual retry gets a fresh set of automatic restore attempts.
job_manager.update_job(job_id, {'error_message': None, 'error_details': None,
'state_data.stems_restore': _DEL})
if not job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.LYRICS_COMPLETE,
progress=45,
message="Retrying: restoring audio stems",
):
raise HTTPException(status_code=500, detail="Failed to transition job status for retry")
background_tasks.add_task(worker_service.trigger_screens_worker, job_id)
return {
"status": "success",
"job_status": "lyrics_complete",
"message": "Job retry started: restoring audio stems",
"retry_stage": "stems_restore",
}
# If we have a video with vocals and instrumental selection, retry video generation
if (file_urls.get('videos', {}).get('with_vocals') and
state_data.get('instrumental_selection')):
@@ -2114,7 +2227,7 @@ async def retry_job(
# Review completion is proven by instrumental_selection in state_data
# (set only when user submits the review endpoint)
elif (file_urls.get('lyrics', {}).get('corrections') and
_has_title_screen(file_urls) and
_has_title_screen(file_urls, state_data) and
state_data.get('instrumental_selection')):
logger.info(f"Job {job_id}: Has corrections, screens, and completed review — retrying from render stage")
@@ -2151,7 +2264,7 @@ async def retry_job(
# If we have corrections and screens but review was NOT completed,
# return to awaiting_review so the user can review lyrics
elif (file_urls.get('lyrics', {}).get('corrections') and
_has_title_screen(file_urls)):
_has_title_screen(file_urls, state_data)):
logger.info(f"Job {job_id}: Has corrections and screens but review not completed — returning to review")
@@ -2323,7 +2436,7 @@ async def retry_job(
@router.post("/{job_id}/choose-different-audio")
async def choose_different_audio(
def choose_different_audio(
job_id: str,
request: Request,
auth_result: AuthResult = Depends(require_auth)
@@ -2370,7 +2483,7 @@ async def choose_different_audio(
@router.get("/{job_id}/logs")
async def get_worker_logs(
def get_worker_logs(
job_id: str,
request: Request,
since_index: int = 0,
@@ -2598,7 +2711,7 @@ def _run_distribution_cleanup(job_id: str, job) -> dict:
@router.post("/{job_id}/cleanup-distribution")
async def cleanup_distribution(
def cleanup_distribution(
job_id: str,
request: Request,
delete_job: bool = True,
@@ -2673,6 +2786,25 @@ async def create_job_from_search(
background_tasks: BackgroundTasks,
body: CreateFromSearchRequest,
auth_result: AuthResult = Depends(require_auth)
) -> JobResponse:
"""Create a job from a search session — see ``_create_job_from_search_sync``.
The work is almost all sync Firestore/GCS I/O (theme prep's upload_json
stalled the loop 5-9s), so it runs in a worker thread; only the audio
download trigger runs back on the loop.
"""
loop = asyncio.get_running_loop()
return await run_in_body_thread(
_create_job_from_search_sync, request, background_tasks, body, auth_result, loop
)
def _create_job_from_search_sync(
request: Request,
background_tasks: BackgroundTasks,
body: CreateFromSearchRequest,
auth_result: AuthResult,
loop: asyncio.AbstractEventLoop,
) -> JobResponse:
"""
Create a karaoke job from a previously completed standalone search session.
@@ -2874,7 +3006,7 @@ async def create_job_from_search(
# Trigger audio download as a Cloud Run Job (survives instance shutdown)
worker_service = get_worker_service()
triggered = await worker_service.trigger_audio_download_worker(job_id)
triggered = run_on_loop(loop, worker_service.trigger_audio_download_worker(job_id))
if not triggered:
job_manager.fail_job(job_id, "Failed to trigger audio download worker")
raise HTTPException(status_code=500, detail="Failed to trigger audio download worker")
@@ -2953,11 +3085,88 @@ async def change_visibility(
reprocessing_required=result["reprocessing_required"],
)
except RerenderError as e:
# Old track whose finals were archived and can't be regenerated right now.
raise HTTPException(status_code=e.status_code, detail=str(e))
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)}")
# =============================================================================
# Regenerate (storage retention) Endpoint
# =============================================================================
@router.post("/{job_id}/regenerate")
async def regenerate_job_outputs(
job_id: str,
http_request: Request,
auth_result: AuthResult = Depends(require_auth),
):
"""
Regenerate a finished track's video files after storage retention archived them.
Old tracks keep their 720p video and CDG/TXT packages; the other formats
(4K, lossless, with-vocals, ...) and, for some, the separated audio stems
are archived after 30 days. This rebuilds them in storage — re-running audio
separation first if needed — from the track's existing reviewed lyrics,
instrumental choice and style. Nothing is re-published (YouTube, Dropbox,
Google Drive stay as they are). The owner is emailed when it's ready.
Rate-limited per track and per user (admins exempt).
"""
locale = get_locale_from_request(http_request)
job_manager = JobManager()
job = await asyncio.to_thread(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):
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
from backend.services.regenerate_service import (
RegenerateService,
check_and_record_rate_limit,
renders_missing,
validate_regenerate,
)
reason = validate_regenerate(job)
if not reason and not auth_result.is_admin and not renders_missing(job):
reason = "This track's video files are all available — there's nothing to regenerate."
if reason:
conflict = any(marker in reason for marker in ("already", "right now", "in progress"))
raise HTTPException(status_code=409 if conflict else 400, detail=reason)
requested_by = auth_result.user_email or "unknown"
if not auth_result.is_admin:
refusal = await asyncio.to_thread(
check_and_record_rate_limit, job_manager.firestore.db, job, requested_by, get_settings(),
)
if refusal:
raise HTTPException(status_code=429, detail=refusal)
source = "admin" if auth_result.is_admin else "customer"
client_id = (http_request.headers.get("X-Client-Id") or "").strip().lower()
if client_id == "kjbox":
source = "kjbox"
try:
result = await RegenerateService(job_manager).start(
job, requested_by=requested_by, source=source,
# The owner is always told when their track is ready again (kjbox /
# admin triggers too — the files are theirs).
notify_customer=True,
)
except RerenderError as e:
raise HTTPException(status_code=e.status_code, detail=str(e))
logger.info(f"[job:{job_id}] Regenerate started by {requested_by} (source={source}, needs_stems={result['needs_stems']})")
return {
"status": "processing",
"job_id": job_id,
"needs_stems": result["needs_stems"],
"message": "Regenerating your video files. This usually takes 10-30 minutes; we'll email you when they're ready.",
}
# =============================================================================
# Re-render With Current Theme Endpoint
# =============================================================================
+3 -3
View File
@@ -147,7 +147,7 @@ def _pretend_sent() -> SendCodeResponse:
# ------------------------------------------------------------------ endpoints
@router.post("/auth/send-code", response_model=SendCodeResponse)
async def send_code(
def send_code(
body: SendCodeRequest,
http_request: Request,
svc: KjboxPartnerService = Depends(get_kjbox_service),
@@ -221,7 +221,7 @@ async def send_code(
@router.post("/auth/verify-code", response_model=VerifyCodeResponse)
async def verify_code(
def verify_code(
body: VerifyCodeRequest,
http_request: Request,
svc: KjboxPartnerService = Depends(get_kjbox_service),
@@ -296,7 +296,7 @@ async def verify_code(
@router.post("/credits/show-credit", response_model=ShowCreditResponse)
async def show_credit(
def show_credit(
body: ShowCreditRequest,
svc: KjboxPartnerService = Depends(get_kjbox_service),
user_service: UserService = Depends(get_user_service),
+1 -1
View File
@@ -88,7 +88,7 @@ class TestNotificationResponse(BaseModel):
# Routes
@router.get("/vapid-public-key", response_model=VapidPublicKeyResponse)
async def get_vapid_public_key():
def get_vapid_public_key():
"""
Get the VAPID public key for push subscription.
+11 -11
View File
@@ -88,7 +88,7 @@ class SuccessResponse(BaseModel):
# =============================================================================
@router.get("/blocklists", response_model=BlocklistsResponse)
async def get_blocklists(
def get_blocklists(
auth_result: AuthResult = Depends(require_admin),
):
"""Get all blocklist data with domain source separation."""
@@ -98,7 +98,7 @@ async def get_blocklists(
@router.post("/blocklists/disposable-domains", response_model=SuccessResponse)
async def add_disposable_domain(
def add_disposable_domain(
request: DomainRequest,
auth_result: AuthResult = Depends(require_admin),
):
@@ -118,7 +118,7 @@ async def add_disposable_domain(
@router.delete("/blocklists/disposable-domains/{domain}", response_model=SuccessResponse)
async def remove_disposable_domain(
def remove_disposable_domain(
domain: str,
auth_result: AuthResult = Depends(require_admin),
):
@@ -136,7 +136,7 @@ async def remove_disposable_domain(
@router.post("/blocklists/allowlisted-domains", response_model=SuccessResponse)
async def add_allowlisted_domain(
def add_allowlisted_domain(
request: DomainRequest,
auth_result: AuthResult = Depends(require_admin),
):
@@ -150,7 +150,7 @@ async def add_allowlisted_domain(
@router.delete("/blocklists/allowlisted-domains/{domain}", response_model=SuccessResponse)
async def remove_allowlisted_domain(
def remove_allowlisted_domain(
domain: str,
auth_result: AuthResult = Depends(require_admin),
):
@@ -187,7 +187,7 @@ async def trigger_sync(
@router.post("/blocklists/blocked-emails", response_model=SuccessResponse)
async def add_blocked_email(
def add_blocked_email(
request: EmailRequest,
auth_result: AuthResult = Depends(require_admin),
):
@@ -207,7 +207,7 @@ async def add_blocked_email(
@router.delete("/blocklists/blocked-emails/{email}", response_model=SuccessResponse)
async def remove_blocked_email(
def remove_blocked_email(
email: str,
auth_result: AuthResult = Depends(require_admin),
):
@@ -225,7 +225,7 @@ async def remove_blocked_email(
@router.post("/blocklists/blocked-ips", response_model=SuccessResponse)
async def add_blocked_ip(
def add_blocked_ip(
request: IPRequest,
auth_result: AuthResult = Depends(require_admin),
):
@@ -245,7 +245,7 @@ async def add_blocked_ip(
@router.delete("/blocklists/blocked-ips/{ip_address}", response_model=SuccessResponse)
async def remove_blocked_ip(
def remove_blocked_ip(
ip_address: str,
auth_result: AuthResult = Depends(require_admin),
):
@@ -267,7 +267,7 @@ async def remove_blocked_ip(
# =============================================================================
@router.get("/youtube-queue", response_model=YouTubeQueueListResponse)
async def get_youtube_queue(
def get_youtube_queue(
auth_result: AuthResult = Depends(require_admin),
):
"""
@@ -288,7 +288,7 @@ async def get_youtube_queue(
@router.post("/youtube-queue/{job_id}/retry", response_model=SuccessResponse)
async def retry_youtube_upload(
def retry_youtube_upload(
job_id: str,
auth_result: AuthResult = Depends(require_admin),
):
+15 -15
View File
@@ -41,7 +41,7 @@ class GenerateFlyerRequest(BaseModel):
@router.get("/r/{code}", response_model=ReferralInterstitialResponse)
async def get_referral_interstitial(code: str, no_track: bool = False):
def get_referral_interstitial(code: str, no_track: bool = False):
"""
Public endpoint: get interstitial data for a referral link.
@@ -76,14 +76,14 @@ async def get_referral_interstitial(code: str, no_track: bool = False):
@router.get("/me")
async def get_my_dashboard(auth=Depends(require_auth)):
def get_my_dashboard(auth=Depends(require_auth)):
"""Get referral dashboard data for the authenticated user."""
service = get_referral_service()
return service.get_dashboard_data(auth.user_email)
@router.put("/me")
async def update_my_link(
def update_my_link(
updates: UpdateReferralLinkRequest,
auth=Depends(require_auth),
):
@@ -108,7 +108,7 @@ async def update_my_link(
@router.post("/me/connect")
async def start_stripe_connect(auth=Depends(require_auth)):
def start_stripe_connect(auth=Depends(require_auth)):
"""Start Stripe Connect onboarding for the authenticated user."""
# Check if user already has a Connect account
from backend.services.user_service import get_user_service
@@ -129,7 +129,7 @@ async def start_stripe_connect(auth=Depends(require_auth)):
@router.post("/me/connect/dashboard-link")
async def get_connect_dashboard_link(auth=Depends(require_auth)):
def get_connect_dashboard_link(auth=Depends(require_auth)):
"""Get a login link to the Stripe Express dashboard for managing payout settings."""
from backend.services.user_service import get_user_service
user = get_user_service().get_user(auth.user_email)
@@ -145,7 +145,7 @@ async def get_connect_dashboard_link(auth=Depends(require_auth)):
@router.post("/me/connect/update-link")
async def get_connect_update_link(auth=Depends(require_auth)):
def get_connect_update_link(auth=Depends(require_auth)):
"""Get a link to update Stripe Connect account info (re-onboarding)."""
from backend.services.user_service import get_user_service
user = get_user_service().get_user(auth.user_email)
@@ -165,7 +165,7 @@ class VanityRequest(BaseModel):
@router.post("/me/vanity-request")
async def request_vanity_url(
def request_vanity_url(
request: VanityRequest,
auth=Depends(require_auth),
):
@@ -215,7 +215,7 @@ async def request_vanity_url(
@router.post("/me/flyer")
async def generate_flyer(
def generate_flyer(
request: GenerateFlyerRequest,
auth=Depends(require_auth),
):
@@ -249,7 +249,7 @@ async def generate_flyer(
@router.post("/admin/vanity")
async def create_vanity_link(
def create_vanity_link(
request: CreateReferralLinkRequest,
auth=Depends(require_admin),
):
@@ -276,7 +276,7 @@ async def create_vanity_link(
@router.get("/admin/vanity-requests")
async def list_vanity_requests(
def list_vanity_requests(
status: str = Query("pending", pattern="^(pending|approved|denied)$"),
auth=Depends(require_admin),
):
@@ -293,7 +293,7 @@ async def list_vanity_requests(
@router.post("/admin/vanity-requests/{request_id}/approve")
async def approve_vanity_request(
def approve_vanity_request(
request_id: str,
auth=Depends(require_admin),
):
@@ -332,7 +332,7 @@ async def approve_vanity_request(
@router.post("/admin/vanity-requests/{request_id}/deny")
async def deny_vanity_request(
def deny_vanity_request(
request_id: str,
auth=Depends(require_admin),
):
@@ -346,7 +346,7 @@ async def deny_vanity_request(
@router.get("/admin/links")
async def list_links(
def list_links(
limit: int = Query(50, ge=1, le=200),
offset: int = Query(0, ge=0),
auth=Depends(require_admin),
@@ -406,7 +406,7 @@ async def admin_apply_discount(
@router.put("/admin/links/{code}")
async def update_link(
def update_link(
code: str,
updates: UpdateReferralLinkRequest,
auth=Depends(require_admin),
@@ -429,7 +429,7 @@ async def update_link(
@router.post("/admin/links/{code}/flyer")
async def admin_generate_flyer(
def admin_generate_flyer(
code: str,
request: GenerateFlyerRequest,
auth=Depends(require_admin),
+3 -3
View File
@@ -79,7 +79,7 @@ def _to_public(req: SongRequest, your_vote: Optional[int] = None) -> SongRequest
@router.get("/requests", response_model=BoardResponse)
async def list_requests(
def list_requests(
viewer_email: Optional[str] = Depends(optional_user_email),
):
"""The ranked board: active requests + recently published, with the caller's vote."""
@@ -134,7 +134,7 @@ async def submit_request(
@router.post("/requests/{request_id}/vote", response_model=SongRequestPublic)
async def vote(
def vote(
request_id: str,
body: VoteBody,
auth_result: AuthResult = Depends(require_auth),
@@ -158,7 +158,7 @@ async def vote(
@router.get("/me", response_model=DailyVoteStatus)
async def my_daily_status(
def my_daily_status(
auth_result: AuthResult = Depends(require_auth),
):
"""The caller's daily-vote status (has today's vote been used, and on what)."""
+58 -45
View File
@@ -512,7 +512,7 @@ async def _run_preview_encode(
"""GCE encode → local fallback → error marker (the cancellable inner body)."""
job_id = job.job_id
storage = StorageService()
encoding_service = get_encoding_service()
encoding_service = await asyncio.to_thread(get_encoding_service)
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
with job_log_context(job_id, worker="preview"):
@@ -546,7 +546,7 @@ async def _run_preview_encode(
# Cross-job search endpoint MUST be registered before {job_id} routes
# to avoid FastAPI matching "sessions" as a job_id path parameter.
@router.get("/sessions/search")
async def search_review_sessions(
def search_review_sessions(
q: str = "",
limit: int = 20,
auth_info: Tuple[str, str] = Depends(require_auth)
@@ -1282,6 +1282,42 @@ async def complete_review(
After saving, triggers the render video worker which will use the
pre-selected instrumental (no separate instrumental selection step).
"""
# Validation + GCS/Firestore writes are all sync (the corrections upload alone
# took 21s on 2026-10-08, freezing every request on the instance) — run them
# in a worker thread; only the render dispatch below runs on the loop.
instrumental_selection = await asyncio.to_thread(_save_review_completion, job_id, updated_data)
# Trigger the render video worker. AWAIT the dispatch (don't fire-and-forget)
# so the Cloud Task / Cloud Run Job dispatch is guaranteed enqueued before we
# return — a background asyncio task can be dropped if the Cloud Run instance
# is recycled right after the response, stranding the job at REVIEW_COMPLETE.
# If the dispatch itself fails we DON'T fail the user's approval: the job is
# safely at REVIEW_COMPLETE and the recover-stuck-jobs watchdog re-triggers
# render for REVIEW_COMPLETE jobs with no render underway within ~5 min.
from backend.services.worker_service import get_worker_service
worker_service = get_worker_service()
try:
await worker_service.trigger_render_video_worker(job_id)
logger.info(f"Job {job_id}: Combined review complete, render video worker triggered")
except Exception as e:
logger.error(
f"Job {job_id}: render trigger failed after review completion "
f"(watchdog will recover): {e}",
exc_info=True,
)
return {
"status": "success",
"instrumental_selection": instrumental_selection,
}
def _save_review_completion(job_id: str, updated_data: Dict[str, Any]) -> str:
"""Validate a review submission, persist it and move the job to REVIEW_COMPLETE.
Sync (blocking GCS + Firestore I/O) — call via ``asyncio.to_thread``.
Returns the resolved instrumental selection.
"""
job_manager = JobManager()
storage = StorageService()
@@ -1398,30 +1434,7 @@ async def complete_review(
progress=70,
message=f"Review complete (instrumental: {instrumental_selection}), rendering video"
)
# Trigger the render video worker. AWAIT the dispatch (don't fire-and-forget)
# so the Cloud Task / Cloud Run Job dispatch is guaranteed enqueued before we
# return — a background asyncio task can be dropped if the Cloud Run instance
# is recycled right after the response, stranding the job at REVIEW_COMPLETE.
# If the dispatch itself fails we DON'T fail the user's approval: the job is
# safely at REVIEW_COMPLETE and the recover-stuck-jobs watchdog re-triggers
# render for REVIEW_COMPLETE jobs with no render underway within ~5 min.
from backend.services.worker_service import get_worker_service
worker_service = get_worker_service()
try:
await worker_service.trigger_render_video_worker(job_id)
logger.info(f"Job {job_id}: Combined review complete, render video worker triggered")
except Exception as e:
logger.error(
f"Job {job_id}: render trigger failed after review completion "
f"(watchdog will recover): {e}",
exc_info=True,
)
return {
"status": "success",
"instrumental_selection": instrumental_selection,
}
return instrumental_selection
except HTTPException:
raise
@@ -1621,7 +1634,7 @@ async def auto_correct_suggestions(
@router.post("/{job_id}/handlers")
async def update_handlers(
def update_handlers(
job_id: str,
enabled_handlers: list,
auth_info: Tuple[str, str] = Depends(require_review_auth)
@@ -1637,7 +1650,7 @@ async def update_handlers(
@router.post("/{job_id}/add-lyrics")
async def add_lyrics(
def add_lyrics(
job_id: str,
data: Dict[str, str],
auth_info: Tuple[str, str] = Depends(require_review_auth)
@@ -1755,7 +1768,7 @@ async def add_lyrics(
@router.post("/{job_id}/search-lyrics")
async def search_lyrics(
def search_lyrics(
job_id: str,
data: Dict[str, Any],
auth_info: Tuple[str, str] = Depends(require_review_auth)
@@ -1919,7 +1932,7 @@ async def generate_preview_video(
job_manager = JobManager()
storage = StorageService()
settings = get_settings()
encoding_service = get_encoding_service()
encoding_service = await asyncio.to_thread(get_encoding_service)
job = job_manager.get_job(job_id)
if not job:
@@ -2092,7 +2105,7 @@ async def generate_preview_video(
@router.get("/{job_id}/preview-video/{preview_hash}")
async def get_preview_video(
def get_preview_video(
job_id: str,
preview_hash: str,
auth_info: Tuple[str, str] = Depends(require_review_auth)
@@ -2131,7 +2144,7 @@ async def get_preview_video(
@router.get("/{job_id}/preview-video/{preview_hash}/status")
async def get_preview_video_status(
def get_preview_video_status(
job_id: str,
preview_hash: str,
auth_info: Tuple[str, str] = Depends(require_review_auth)
@@ -2166,7 +2179,7 @@ async def get_preview_video_status(
@router.post("/{job_id}/v1/annotations")
async def submit_annotation(
def submit_annotation(
job_id: str,
payload: Dict[str, Any],
auth_info: Tuple[str, str] = Depends(require_review_auth)
@@ -2206,7 +2219,7 @@ async def submit_annotation(
@router.get("/{job_id}/v1/annotations/stats")
async def get_annotation_stats(
def get_annotation_stats(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
@@ -2463,7 +2476,7 @@ async def get_waveform_data(
@router.post("/{job_id}/sessions")
async def save_review_session(
def save_review_session(
job_id: str,
data: Dict[str, Any],
auth_info: Tuple[str, str] = Depends(require_review_auth)
@@ -2541,7 +2554,7 @@ async def save_review_session(
@router.get("/{job_id}/sessions")
async def list_review_sessions(
def list_review_sessions(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
@@ -2573,7 +2586,7 @@ async def list_review_sessions(
@router.get("/{job_id}/sessions/{session_id}")
async def get_review_session(
def get_review_session(
job_id: str,
session_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth)
@@ -2614,7 +2627,7 @@ async def get_review_session(
@router.delete("/{job_id}/sessions/{session_id}")
async def delete_review_session(
def delete_review_session(
job_id: str,
session_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth)
@@ -2646,7 +2659,7 @@ async def delete_review_session(
@router.post("/{job_id}/audio-edit-sessions")
async def save_audio_edit_session(
def save_audio_edit_session(
job_id: str,
data: Dict[str, Any],
auth_info: Tuple[str, str] = Depends(require_review_auth),
@@ -2706,7 +2719,7 @@ async def save_audio_edit_session(
@router.get("/{job_id}/audio-edit-sessions")
async def list_audio_edit_sessions(
def list_audio_edit_sessions(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
@@ -2719,7 +2732,7 @@ async def list_audio_edit_sessions(
@router.get("/{job_id}/audio-edit-sessions/{session_id}")
async def get_audio_edit_session(
def get_audio_edit_session(
job_id: str,
session_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
@@ -2747,7 +2760,7 @@ async def get_audio_edit_session(
@router.delete("/{job_id}/audio-edit-sessions/{session_id}")
async def delete_audio_edit_session(
def delete_audio_edit_session(
job_id: str,
session_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
@@ -2836,7 +2849,7 @@ def _build_audio_edit_response(
@router.get("/{job_id}/input-audio-info")
async def get_input_audio_info(
def get_input_audio_info(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
@@ -3059,7 +3072,7 @@ async def apply_audio_edit(
@router.post("/{job_id}/audio-edit/undo")
async def undo_audio_edit(
def undo_audio_edit(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
@@ -3110,7 +3123,7 @@ async def undo_audio_edit(
@router.post("/{job_id}/audio-edit/redo")
async def redo_audio_edit(
def redo_audio_edit(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
+3 -3
View File
@@ -20,7 +20,7 @@ router = APIRouter(prefix="/api/tenant", tags=["tenant"])
@router.get("/config", response_model=TenantConfigResponse)
async def get_tenant_config(
def get_tenant_config(
request: Request,
tenant: Optional[str] = Query(
None,
@@ -81,7 +81,7 @@ async def get_tenant_config(
@router.get("/config/{tenant_id}", response_model=TenantConfigResponse)
async def get_tenant_config_by_id(tenant_id: str):
def get_tenant_config_by_id(tenant_id: str):
"""
Get tenant configuration by explicit tenant ID.
@@ -102,7 +102,7 @@ async def get_tenant_config_by_id(tenant_id: str):
@router.get("/asset/{tenant_id}/{asset_name}")
async def get_tenant_asset(tenant_id: str, asset_name: str):
def get_tenant_asset(tenant_id: str, asset_name: str):
"""
Get a signed URL for a tenant asset (logo, favicon, etc.).
+2 -2
View File
@@ -169,13 +169,13 @@ async def _read_asset(upload: Optional[UploadFile], label: str) -> Optional[Tupl
@router.get("", response_model=TenantListResponse)
async def admin_list_tenants(auth_data: AuthResult = Depends(require_admin)):
def admin_list_tenants(auth_data: AuthResult = Depends(require_admin)):
"""List all white-label tenants."""
return TenantListResponse(tenants=[TenantSummary(**t) for t in list_tenants()])
@router.get("/_template", response_model=TenantTemplateResponse)
async def admin_tenant_theme_template(auth_data: AuthResult = Depends(require_admin)):
def admin_tenant_theme_template(auth_data: AuthResult = Depends(require_admin)):
"""Return the default Nomad theme's full style_params as an editing starting point."""
try:
return TenantTemplateResponse(style_params=get_default_style_params())
+107 -4
View File
@@ -29,6 +29,7 @@ from backend.services.tenant_theme_service import (
save_tenant_theme,
store_uploaded_asset,
)
from backend.services.theme_change_service import outdated_jobs, refresh_inflight_jobs
from backend.services.theme_preview_service import ThemePreviewError, render_theme_preview
from backend.services.tenant_admin_service import _theme_id_for
@@ -86,8 +87,10 @@ class PreviewRequest(BaseModel):
class PreviewResponse(BaseModel):
title_card: str # data:image/jpeg;base64,...
# data:image/jpeg;base64,... — null for a screen the theme leaves out of videos.
title_card: Optional[str] = None
karaoke_frame: str
end_screen: Optional[str] = None
class SaveRequest(BaseModel):
@@ -161,10 +164,110 @@ async def preview_theme(body: PreviewRequest, config: TenantConfig = Depends(req
return PreviewResponse(**images.as_data_urls())
@router.put("", response_model=ThemeResponse)
def save_theme(body: SaveRequest, config: TenantConfig = Depends(require_tenant_member)):
class SaveResponse(ThemeResponse):
# In-progress tracks switched to the new theme by this save.
refreshed_jobs: int = 0
# The caller's finished tracks made with an older theme (re-render to update).
outdated_job_ids: List[str] = Field(default_factory=list)
class OutdatedJobsResponse(BaseModel):
theme_updated_at: Optional[str] = None
job_ids: List[str]
class RerenderOutdatedResponse(BaseModel):
started: List[str]
failed: Dict[str, str]
# Outdated tracks beyond this call's cap (ask again to start them).
remaining: List[str] = Field(default_factory=list)
# Tracks started per bulk call: bounds the request time and the burst of
# render/encode work it queues. The UI offers the remainder again.
MAX_BULK_RERENDER = 20
def _owner_scope(auth_result: AuthResult) -> Optional[str]:
"""Admins act on all the portal's tracks; members only on their own."""
return None if auth_result.is_admin else auth_result.user_email
@router.put("", response_model=SaveResponse)
def save_theme(
body: SaveRequest,
config: TenantConfig = Depends(require_tenant_member),
auth_result: AuthResult = Depends(require_auth),
):
try:
save_tenant_theme(config, body.style_params)
return ThemeResponse(**get_theme_for_editor(config))
theme = get_theme_for_editor(config)
except TenantValidationError as exc:
_raise_http(exc)
theme_id = _theme_id_for(config)
# Never fail the save over the follow-up work: the theme is already stored.
refreshed = 0
try:
refreshed = refresh_inflight_jobs(config.id, theme_id)["updated"]
except Exception:
logger.exception(f"Tenant '{config.id}': refreshing in-progress tracks after theme save failed")
outdated: List[str] = []
try:
outdated = outdated_jobs(config.id, theme_id, _owner_scope(auth_result))["job_ids"]
except Exception:
logger.exception(f"Tenant '{config.id}': listing outdated tracks after theme save failed")
return SaveResponse(**theme, refreshed_jobs=refreshed, outdated_job_ids=outdated)
@router.get("/outdated-jobs", response_model=OutdatedJobsResponse)
def get_outdated_jobs(
config: TenantConfig = Depends(require_tenant_member),
auth_result: AuthResult = Depends(require_auth),
):
"""Finished tracks made with an older version of the theme (re-render to update)."""
return OutdatedJobsResponse(**outdated_jobs(config.id, _theme_id_for(config), _owner_scope(auth_result)))
@router.post("/rerender-outdated", response_model=RerenderOutdatedResponse)
async def rerender_outdated(
config: TenantConfig = Depends(require_tenant_member),
auth_result: AuthResult = Depends(require_auth),
):
"""Re-render every outdated finished track with the current theme.
Quiet: no per-track "your video is ready" email/push (one per track would
flood the inbox); the portal shows progress on each track.
"""
from backend.services.job_manager import JobManager
from backend.services.theme_rerender_service import RerenderError, ThemeRerenderService
theme_id = _theme_id_for(config)
job_ids = (await run_in_threadpool(
outdated_jobs, config.id, theme_id, _owner_scope(auth_result)
))["job_ids"]
batch, remaining = job_ids[:MAX_BULK_RERENDER], job_ids[MAX_BULK_RERENDER:]
job_manager = JobManager()
service = ThemeRerenderService(job_manager)
started: List[str] = []
failed: Dict[str, str] = {}
for job_id in batch:
job = await run_in_threadpool(job_manager.get_job, job_id)
if job is None:
continue
try:
await service.start(
job, theme_id=theme_id,
requested_by=auth_result.user_email or "unknown",
notify_customer=False,
)
started.append(job_id)
except RerenderError as e:
failed[job_id] = str(e)
except Exception as e:
logger.exception(f"[job:{job_id}] Bulk theme re-render failed to start")
failed[job_id] = "Couldn't start the re-render."
logger.info(
f"Tenant '{config.id}': bulk re-render started {len(started)}, failed {len(failed)}, "
f"remaining {len(remaining)}"
)
return RerenderOutdatedResponse(started=started, failed=failed, remaining=remaining)
+4 -4
View File
@@ -22,7 +22,7 @@ router = APIRouter(prefix="/themes", tags=["themes"])
@router.get("", response_model=ThemesListResponse)
async def list_themes(request: Request) -> ThemesListResponse:
def list_themes(request: Request) -> ThemesListResponse:
"""
List all available themes.
@@ -74,7 +74,7 @@ async def get_translation_preview(language: str, request: Request) -> dict:
@router.get("/{theme_id}", response_model=ThemeDetailResponse)
async def get_theme(theme_id: str, request: Request) -> ThemeDetailResponse:
def get_theme(theme_id: str, request: Request) -> ThemeDetailResponse:
"""
Get detailed information about a specific theme.
@@ -113,7 +113,7 @@ async def get_theme(theme_id: str, request: Request) -> ThemeDetailResponse:
@router.get("/{theme_id}/preview")
async def get_theme_preview(theme_id: str, request: Request) -> dict:
def get_theme_preview(theme_id: str, request: Request) -> dict:
"""
Get a signed URL for the theme's preview image.
@@ -158,7 +158,7 @@ async def get_theme_preview(theme_id: str, request: Request) -> dict:
@router.get("/{theme_id}/youtube-description")
async def get_theme_youtube_description(theme_id: str, request: Request) -> dict:
def get_theme_youtube_description(theme_id: str, request: Request) -> dict:
"""
Get the YouTube description template for a theme.
+20 -20
View File
@@ -215,7 +215,7 @@ def _precompute_credit_eval(token: str, email: str, collection: Optional[str] =
@router.post("/auth/magic-link", response_model=SendMagicLinkResponse)
async def send_magic_link(
def send_magic_link(
request: SendMagicLinkRequest,
http_request: Request,
user_service: UserService = Depends(get_user_service),
@@ -504,7 +504,7 @@ def complete_verified_login(
@router.get("/auth/verify", response_model=VerifyMagicLinkResponse)
async def verify_magic_link(
def verify_magic_link(
token: str,
http_request: Request,
user_service: UserService = Depends(get_user_service),
@@ -628,7 +628,7 @@ class ClaimWelcomeCreditResponse(BaseModel):
@router.post("/claim-welcome-credit", response_model=ClaimWelcomeCreditResponse)
async def claim_welcome_credit(
def claim_welcome_credit(
auth_result: AuthResult = Depends(require_auth),
user_service: UserService = Depends(get_user_service),
):
@@ -658,7 +658,7 @@ class MagicLinkStatusResponse(BaseModel):
@router.get("/auth/link-status", response_model=MagicLinkStatusResponse)
async def magic_link_status(
def magic_link_status(
token: str,
user_service: UserService = Depends(get_user_service),
):
@@ -680,7 +680,7 @@ async def magic_link_status(
@router.post("/auth/resend-from-token", response_model=ResendFromTokenResponse)
async def resend_magic_link_from_token(
def resend_magic_link_from_token(
request: ResendFromTokenRequest,
http_request: Request,
user_service: UserService = Depends(get_user_service),
@@ -831,7 +831,7 @@ async def resend_magic_link_from_token(
@router.post("/auth/logout", response_model=LogoutResponse)
async def logout(
def logout(
request: Request,
authorization: Optional[str] = Header(None),
user_service: UserService = Depends(get_user_service),
@@ -856,7 +856,7 @@ async def logout(
# =============================================================================
@router.get("/me", response_model=UserProfileResponse)
async def get_current_user(
def get_current_user(
request: Request,
authorization: Optional[str] = Header(None),
user_service: UserService = Depends(get_user_service),
@@ -913,7 +913,7 @@ async def get_current_user(
# =============================================================================
@router.get("/credits/packages", response_model=CreditPackagesResponse)
async def list_credit_packages():
def list_credit_packages():
"""
List available credit packages for purchase.
@@ -934,7 +934,7 @@ async def list_credit_packages():
@router.post("/credits/checkout", response_model=CreateCheckoutResponse)
async def create_checkout(
def create_checkout(
request: CreateCheckoutRequest,
stripe_service: StripeService = Depends(get_stripe_service),
):
@@ -975,7 +975,7 @@ async def create_checkout(
@router.post("/made-for-you/checkout", response_model=CreateCheckoutResponse)
async def create_made_for_you_checkout(
def create_made_for_you_checkout(
request: MadeForYouCheckoutRequest,
http_request: Request,
stripe_service: StripeService = Depends(get_stripe_service),
@@ -1701,7 +1701,7 @@ async def stripe_webhook(
# =============================================================================
@router.get("/feedback/eligibility", response_model=FeedbackEligibilityResponse)
async def check_feedback_eligibility(
def check_feedback_eligibility(
request: Request,
authorization: Optional[str] = Header(None),
user_service: UserService = Depends(get_user_service),
@@ -1741,7 +1741,7 @@ async def check_feedback_eligibility(
@router.post("/feedback", response_model=UserFeedbackResponse)
async def submit_user_feedback(
def submit_user_feedback(
http_request: Request,
request: UserFeedbackRequest,
authorization: Optional[str] = Header(None),
@@ -1965,7 +1965,7 @@ class UserDetailResponse(BaseModel):
@router.get("/admin/users", response_model=UserListResponsePaginated)
async def list_users(
def list_users(
limit: int = 50,
offset: int = 0,
search: Optional[str] = None,
@@ -2063,7 +2063,7 @@ async def list_users(
@router.get("/admin/users/{email}/detail", response_model=UserDetailResponse)
async def get_user_detail(
def get_user_detail(
email: str,
request: Request,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
@@ -2166,7 +2166,7 @@ async def get_user_detail(
@router.post("/admin/users", response_model=AdminCreateUserResponse, status_code=201)
async def admin_create_user(
def admin_create_user(
request: AdminCreateUserRequest,
auth_data: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
@@ -2228,7 +2228,7 @@ async def admin_create_user(
@router.post("/admin/credits", response_model=AddCreditsResponse)
async def add_credits_to_user(
def add_credits_to_user(
request: AddCreditsRequest,
auth_data: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
@@ -2265,7 +2265,7 @@ async def add_credits_to_user(
@router.post("/admin/users/{email}/disable")
async def disable_user(
def disable_user(
email: str,
request: Request,
auth_data: AuthResult = Depends(require_admin),
@@ -2286,7 +2286,7 @@ async def disable_user(
@router.post("/admin/users/{email}/enable")
async def enable_user(
def enable_user(
email: str,
request: Request,
auth_data: AuthResult = Depends(require_admin),
@@ -2307,7 +2307,7 @@ async def enable_user(
@router.delete("/admin/users/{email}")
async def delete_user(
def delete_user(
email: str,
request: Request,
auth_data: AuthResult = Depends(require_admin),
@@ -2333,7 +2333,7 @@ async def delete_user(
@router.post("/admin/users/{email}/role")
async def set_user_role(
def set_user_role(
email: str,
role: UserRole,
request: Request,
+21
View File
@@ -67,6 +67,10 @@ class Settings(BaseSettings):
# Application
environment: str = os.getenv("ENVIRONMENT", "development")
# Event-loop stall watchdog (backend/services/loop_watchdog.py): logs the
# blocking stack when the single uvicorn loop stops ticking for >1s, and
# records stalls >=5s to Firestore client_events (production only).
loop_watchdog_enabled: bool = os.getenv("LOOP_WATCHDOG_ENABLED", "true").lower() in ("true", "1", "yes")
log_level: str = os.getenv("LOG_LEVEL", "INFO")
# Processing
@@ -409,6 +413,23 @@ class Settings(BaseSettings):
# Where the daily progress + completion emails are sent.
youtube_backfill_report_email: str = os.getenv("YOUTUBE_BACKFILL_REPORT_EMAIL", "andrew@nomadkaraoke.com")
# Storage retention (backend/services/storage_retention.py): a daily job purges
# regenerable files (big finals, rendered videos, stems, ...) from jobs
# completed more than `storage_retention_min_age_days` ago. DRY-RUN BY DEFAULT:
# it only writes a report until STORAGE_RETENTION_DRY_RUN=false is set after a
# human has reviewed one.
storage_retention_enabled: bool = os.getenv("STORAGE_RETENTION_ENABLED", "true").lower() in ("true", "1", "yes")
storage_retention_dry_run: bool = os.getenv("STORAGE_RETENTION_DRY_RUN", "true").lower() not in ("false", "0", "no")
storage_retention_min_age_days: int = int(os.getenv("STORAGE_RETENTION_MIN_AGE_DAYS", "30"))
# Real (non-dry) runs purge at most this many jobs per run, resuming from a cursor.
storage_retention_max_jobs_per_run: int = int(os.getenv("STORAGE_RETENTION_MAX_JOBS_PER_RUN", "50"))
# Comma-separated tenant ids whose jobs are never purged.
storage_retention_excluded_tenants: str = os.getenv("STORAGE_RETENTION_EXCLUDED_TENANTS", "")
# Customer "Regenerate video" limits (per job / per user, rolling 24h).
regenerate_max_per_job_per_day: int = int(os.getenv("REGENERATE_MAX_PER_JOB_PER_DAY", "3"))
regenerate_max_per_user_per_day: int = int(os.getenv("REGENERATE_MAX_PER_USER_PER_DAY", "10"))
# Default CDG/TXT generation settings
# When True, CDG and TXT packages are generated by default (when a theme is set)
# These can be overridden per-request via explicit enable_cdg/enable_txt parameters
+77
View File
@@ -4,6 +4,7 @@ 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 asyncio
import logging
import threading
import time
@@ -70,6 +71,35 @@ def validate_credentials_on_startup():
logger.error(f"Failed to validate credentials on startup: {e}")
# Modules that route handlers import lazily. On a fresh instance the first such
# import ran ON the event loop: httpx/httpcore (via flacfetch_client /
# worker_service) froze it 3-15s on cold disk reads (EVENT_LOOP_STALL in
# importlib, 2026-10-08). Lifespan startup imports them in a worker thread before
# readiness — a background thread alone would still race the first request.
_LAZY_ROUTE_IMPORTS = (
"httpx",
"backend.services.worker_service",
"backend.services.flacfetch_client",
"backend.services.catalog_proxy_service",
"backend.services.ip_geolocation_service",
"backend.services.email_validation_service",
"backend.services.musicbrainz_service",
)
LAZY_ROUTE_IMPORT_TIMEOUT_S = 30
def _import_lazy_route_modules() -> None:
import importlib
for module in _LAZY_ROUTE_IMPORTS:
try:
importlib.import_module(module)
except Exception as e:
logger.warning(f"Startup import of {module} failed (will import lazily): {e}")
def _run_background_warmup():
"""Warm caches that used to block startup (runs in a daemon thread).
@@ -103,6 +133,16 @@ def _run_background_warmup():
except Exception as e:
logger.warning(f"Langfuse preload failed (will initialize lazily): {e}")
# 4. Encoding service singleton — its first construction imports
# google.cloud.compute_v1 (~10s on a fresh instance). Build it here, off the
# event loop, before /api/health/detailed or a preview encode needs it.
try:
from backend.services.encoding_service import get_encoding_service
get_encoding_service()
except Exception as e:
logger.warning(f"Encoding service warmup failed (will build lazily): {e}")
# Validate OAuth credentials (alerting only, nothing depends on it)
try:
validate_credentials_on_startup()
@@ -126,6 +166,19 @@ async def lifespan(app: FastAPI):
# URL). No-op outside production. (Fallback audit 2026-06-09, Theme 7.)
validate_production_config()
# Off the loop, but before readiness (Cloud Run holds requests meanwhile).
# Bounded so a hung cold-disk read can't keep the instance from ever going
# ready; the import keeps running in its thread and routes fall back to it.
try:
await asyncio.wait_for(
asyncio.to_thread(_import_lazy_route_modules), timeout=LAZY_ROUTE_IMPORT_TIMEOUT_S
)
except asyncio.TimeoutError:
logger.error(
f"Startup import of lazy route modules exceeded {LAZY_ROUTE_IMPORT_TIMEOUT_S}s; "
"continuing startup (first requests may import them on the event loop)"
)
# NLP model / credential warmup runs in the background so it doesn't gate
# readiness — Cloud Run holds all routed requests until lifespan startup
# returns, and these preloads were ~7.5s of the ~16s cold start.
@@ -133,8 +186,32 @@ async def lifespan(app: FastAPI):
target=_run_background_warmup, name="startup-warmup", daemon=True
).start()
# asyncio.to_thread's default executor is min(32, cpu+4) ≈ 6 threads on our
# 2 vCPUs. The screens worker, stale-review cron, auto-correct and many
# review endpoints all offload into it (mostly I/O-bound), so size it up —
# otherwise review-page requests queue behind a few long-running jobs.
import concurrent.futures
asyncio.get_running_loop().set_default_executor(
concurrent.futures.ThreadPoolExecutor(max_workers=48, thread_name_prefix="to-thread")
)
# Event-loop stall watchdog: makes "every request froze for 30s" episodes
# self-diagnosing (logs the blocking stack; records >=5s stalls in prod).
watchdog = None
if settings.loop_watchdog_enabled:
from backend.services.loop_watchdog import LoopWatchdog, firestore_stall_recorder
watchdog = LoopWatchdog(
recorder=firestore_stall_recorder if settings.environment == "production" else None,
)
watchdog.start()
yield
if watchdog is not None:
await watchdog.stop()
# Shutdown - best-effort parking of any still-registered workers.
#
# Reality check (incident 2026-09-13, job 41e06b90): Cloud Run services
+11
View File
@@ -306,6 +306,9 @@ class Job(BaseModel):
# Theme configuration (pre-made themes from GCS)
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
# When the theme was last re-snapshotted onto the job after creation (theme
# edit refresh, re-render, Edit). None = the creation-time snapshot (created_at).
theme_applied_at: Optional[datetime] = None
color_overrides: Dict[str, str] = Field(default_factory=dict)
"""
User color overrides applied on top of theme. Keys:
@@ -391,6 +394,14 @@ class Job(BaseModel):
outputs_deleted_at: Optional[datetime] = None # Timestamp when outputs were deleted by admin
outputs_deleted_by: Optional[str] = None # Admin email who deleted outputs
# Storage retention (backend/services/storage_retention.py): set when the
# daily purge deleted this job's regenerable renders / separated stems.
# Cleared when they're rebuilt (regenerate / re-render / stems restore).
renders_purged_at: Optional[datetime] = None
stems_purged_at: Optional[datetime] = None
renders_regenerated_at: Optional[datetime] = None # last GCS-only regenerate
storage_purge: Optional[Dict[str, Any]] = None # manifest of the last purge
# Credit refund tracking (prevents double-refund on cancel→delete or fail→delete)
credit_refunded: bool = False
+23 -5
View File
@@ -187,20 +187,35 @@ def claim_with_youtube_queue(
def clear_admin_rerender_update(job) -> Dict[str, Any]:
"""Firestore update that drops the marker (empty if there is none)."""
"""Firestore update that drops the marker (empty if there is none).
Also drops a storage-retention regenerate marker: every caller (admin
reset/restart, Edit, visibility change, delete outputs) starts a new run.
"""
update: Dict[str, Any] = {}
if raw_admin_rerender_marker(job):
return {f"state_data.{ADMIN_RERENDER_MARKER}": DELETE_FIELD}
return {}
update[f"state_data.{ADMIN_RERENDER_MARKER}"] = DELETE_FIELD
from backend.services.regenerate_service import clear_regenerate_update
update.update(clear_regenerate_update(job))
return update
def suppress_customer_notifications(job) -> bool:
"""True if this run's customer-facing notifications must be skipped.
Only an active admin re-render the admin didn't opt into announcing
suppresses them; normal jobs and the tenant theme re-render always notify.
suppresses them; normal jobs and a single tenant theme re-render notify.
"""
marker = active_admin_rerender(job)
return bool(marker) and not marker.get("notify_customer", False)
if marker:
return not marker.get("notify_customer", False)
# A bulk "re-render all outdated tracks" theme re-render is started quietly.
theme_marker = (getattr(job, "state_data", None) or {}).get("theme_rerender") or {}
if theme_marker.get("notify_customer") is False:
return True
# A storage-retention regenerate notifies unless it was started quietly.
from backend.services.regenerate_service import regenerate_suppresses_notifications
return regenerate_suppresses_notifications(job)
def admin_rerender_brand_code(job) -> Optional[str]:
@@ -228,6 +243,9 @@ def validate_admin_rerender(job) -> Optional[str]:
return f"Only completed jobs can be re-rendered (current status: {job.status})."
if getattr(job, "outputs_deleted_at", None):
return "This job's outputs were deleted, so it can't be re-rendered."
from backend.services.storage_retention import PURGE_IN_PROGRESS_MESSAGE, purge_in_progress
if purge_in_progress(job):
return PURGE_IN_PROGRESS_MESSAGE
if getattr(job, "prep_only", False) or getattr(job, "finalise_only", False):
return "Prep-only / finalise-only jobs can't be re-rendered."
state_data = job.state_data or {}
+3 -2
View File
@@ -154,8 +154,9 @@ async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any
elif not audio_complete:
timing_info = {"status": "pending_audio"}
else:
signals = _compute_timing_signals(
job_id, corrections, ai_suggestions, stems, storage
signals = await asyncio.to_thread(
_compute_timing_signals,
job_id, corrections, ai_suggestions, stems, storage,
)
if signals is None:
timing_info = {"status": "no_lead_stem"}
+13 -9
View File
@@ -19,6 +19,7 @@ its existing client-side on-load auto-apply. Auto-approval must never strand a j
"""
from __future__ import annotations
import asyncio
import logging
from datetime import datetime, timezone
from typing import Any, Dict, Optional
@@ -51,32 +52,33 @@ async def ensure_and_pre_apply(job_id: str, *, generate_on_miss: bool = True) ->
storage = StorageService()
corrections_path = CORRECTIONS_PATH.format(job_id=job_id)
if not storage.file_exists(corrections_path):
# All GCS/Firestore calls below are sync — run them off the event loop.
if not await asyncio.to_thread(storage.file_exists, corrections_path):
return {"outcome": "skipped", "reason": "no_corrections"}
updated_path = CORRECTIONS_UPDATED_PATH.format(job_id=job_id)
if storage.file_exists(updated_path):
if await asyncio.to_thread(storage.file_exists, updated_path):
# Already applied once (executor auto-complete, a prior pre-apply run,
# or a human edit). Never clobber existing corrections_updated.json.
try:
existing = storage.download_json(updated_path)
existing = await asyncio.to_thread(storage.download_json, updated_path)
if ((existing.get("metadata") or {}).get("auto_approval")):
return {"outcome": "skipped", "reason": "already_applied"}
except Exception:
pass
return {"outcome": "skipped", "reason": "corrections_updated_exists"}
corrections = storage.download_json(corrections_path)
corrections = await asyncio.to_thread(storage.download_json, corrections_path)
# 1) Ensure the proactive suggestion cache exists (generate on miss, unless
# the caller — e.g. the load-time path — asked to only apply an existing
# cache so the request doesn't block on an LLM call).
ai_suggestions = _load_ai_suggestions(storage, job_id)
ai_suggestions = await asyncio.to_thread(_load_ai_suggestions, storage, job_id)
if ai_suggestions is None and generate_on_miss and settings.auto_correct_proactive_enabled:
logger.info(f"[job:{job_id}] pre-apply: cache miss, generating suggestions synchronously")
from backend.workers.auto_correct_worker import process_proactive_auto_correct
await process_proactive_auto_correct(job_id) # bounded (180s) + best-effort
ai_suggestions = _load_ai_suggestions(storage, job_id)
ai_suggestions = await asyncio.to_thread(_load_ai_suggestions, storage, job_id)
if ai_suggestions is None:
# Unknown suggestion set (proactive disabled or generation failed) —
@@ -84,7 +86,7 @@ async def ensure_and_pre_apply(job_id: str, *, generate_on_miss: bool = True) ->
return {"outcome": "skipped", "reason": "no_suggestions_cache"}
# 2) Apply with the executor's sanity gates.
result = build_applied_segments(corrections, ai_suggestions)
result = await asyncio.to_thread(build_applied_segments, corrections, ai_suggestions)
if result.get("aborted"):
logger.info(f"[job:{job_id}] pre-apply aborted ({result['aborted']}) — UI will apply client-side")
return {"outcome": "skipped", "reason": result["aborted"]}
@@ -115,11 +117,13 @@ async def ensure_and_pre_apply(job_id: str, *, generate_on_miss: bool = True) ->
except Exception: # pragma: no cover - google libs always present in prod
PreconditionFailed = () # type: ignore[assignment]
try:
storage.upload_json(updated_path, updated, if_generation_match=0)
await asyncio.to_thread(storage.upload_json, updated_path, updated, if_generation_match=0)
except PreconditionFailed:
logger.info(f"[job:{job_id}] pre-apply raced a concurrent write — theirs wins")
return {"outcome": "skipped", "reason": "raced_concurrent_write"}
JobManager().update_file_url(job_id, "lyrics", "corrections_updated", updated_path)
await asyncio.to_thread(
JobManager().update_file_url, job_id, "lyrics", "corrections_updated", updated_path
)
logger.info(
f"[job:{job_id}] pre-apply saved corrections_updated.json "
+63
View File
@@ -8,6 +8,7 @@ replacing rclone for server-side operations. It handles:
Credentials are loaded from Google Cloud Secret Manager.
"""
import hashlib
import json
import logging
import os
@@ -19,6 +20,22 @@ from google.cloud import secretmanager
logger = logging.getLogger(__name__)
_DROPBOX_HASH_BLOCK = 4 * 1024 * 1024
def dropbox_content_hash(path: str) -> str:
"""Dropbox ``content_hash`` of a local file: SHA-256 of the concatenated
SHA-256 digests of each 4 MiB block (https://www.dropbox.com/developers/reference/content-hash)."""
overall = hashlib.sha256()
with open(path, "rb") as f:
while True:
block = f.read(_DROPBOX_HASH_BLOCK)
if not block:
break
overall.update(hashlib.sha256(block).digest())
return overall.hexdigest()
class DropboxService:
"""Dropbox operations using native Python SDK."""
@@ -284,11 +301,46 @@ class DropboxService:
)
cursor.offset = file_obj.tell()
def _remote_content_hashes(self, remote_path: str) -> dict:
"""``{path_lower: content_hash}`` for every file under ``remote_path``.
Best-effort: a missing folder is empty, and any other error returns ``{}``
(the caller then uploads everything, as before).
"""
from dropbox.exceptions import ApiError
from dropbox.files import FileMetadata
try:
result = self.client.files_list_folder(remote_path, recursive=True)
except ApiError as e:
err = e.error
if err.is_path() and err.get_path().is_not_found():
return {}
logger.warning(f"Couldn't list {remote_path} to skip unchanged files: {e}")
return {}
except Exception as e:
logger.warning(f"Couldn't list {remote_path} to skip unchanged files: {e}")
return {}
hashes = {}
try:
while True:
for entry in result.entries:
if isinstance(entry, FileMetadata) and entry.content_hash:
hashes[entry.path_lower] = entry.content_hash
if not result.has_more:
break
result = self.client.files_list_folder_continue(result.cursor)
except Exception as e:
logger.warning(f"Couldn't finish listing {remote_path} to skip unchanged files: {e}")
return {}
return hashes
def upload_folder(
self,
local_dir: str,
remote_path: str,
exclude_suffixes: Sequence[str] = (),
skip_unchanged: bool = False,
) -> None:
"""
Recursively upload all files and subdirectories to Dropbox folder.
@@ -298,6 +350,9 @@ class DropboxService:
remote_path: Dropbox destination folder path
exclude_suffixes: Filename suffixes to skip (see
dropbox_skip_suffixes_for). Skipped files stay on local disk / GCS.
skip_unchanged: Don't re-upload files already in the folder with the
same Dropbox content hash (one recursive listing up front). Used
when a second pass adds files to a folder that was just uploaded.
"""
# Ensure remote path starts with /
if not remote_path.startswith("/"):
@@ -305,8 +360,11 @@ class DropboxService:
logger.info(f"Uploading folder {local_dir} to {remote_path}")
remote_hashes = self._remote_content_hashes(remote_path) if skip_unchanged else {}
uploaded_count = 0
skipped_count = 0
unchanged_count = 0
for root, _dirs, files in os.walk(local_dir):
# Calculate the relative path from local_dir to current root
rel_root = os.path.relpath(root, local_dir)
@@ -322,12 +380,17 @@ class DropboxService:
continue
local_file = os.path.join(root, filename)
remote_file = f"{current_remote}/{filename}"
remote_hash = remote_hashes.get(remote_file.lower())
if remote_hash and remote_hash == dropbox_content_hash(local_file):
unchanged_count += 1
continue
self.upload_file(local_file, remote_file)
uploaded_count += 1
logger.info(
f"Uploaded {uploaded_count} files to {remote_path}"
+ (f" (skipped {skipped_count} excluded)" if skipped_count else "")
+ (f" ({unchanged_count} already up to date)" if unchanged_count else "")
)
def create_shared_link(self, path: str) -> str:
+7 -1
View File
@@ -137,7 +137,7 @@ class EncodingInput:
Contains all the paths and metadata needed to encode a karaoke video.
"""
# Required input files
title_video_path: str # Title card video (MOV)
title_video_path: Optional[str] # Title card video (MOV); None = theme omits it
karaoke_video_path: str # Main karaoke video with vocals (MOV/MKV)
instrumental_audio_path: str # Instrumental audio track (FLAC)
@@ -465,6 +465,12 @@ class GCEEncodingBackend(EncodingBackend):
if existing_instrumental:
encoding_config["existing_instrumental"] = existing_instrumental
# Screens the theme leaves out: the encoder must skip them rather than
# rebuild them from whatever matching PNG it finds in the job folder.
for flag in ("include_title_screen", "include_end_screen"):
if input_config.options.get(flag) is False:
encoding_config[flag] = False
countdown_padding = input_config.options.get("countdown_padding_seconds")
if countdown_padding:
encoding_config["countdown_padding_seconds"] = countdown_padding
+44 -19
View File
@@ -17,6 +17,7 @@ Usage:
import asyncio
import logging
import threading
import os
import time
import uuid
@@ -1381,25 +1382,49 @@ class EncodingService:
_encoding_service: Optional[EncodingService] = None
_encoding_service_lock = threading.Lock()
def get_encoding_service() -> EncodingService:
"""Get the singleton encoding service instance."""
"""Get the singleton encoding service instance.
First construction imports ``google.cloud.compute_v1`` (a ~10s import on a
fresh Cloud Run instance) — the startup warmup thread builds it in the
background, and async callers should use ``asyncio.to_thread`` so a cold
call can't freeze the event loop (watchdog caught a 9.9s stall here in
/api/health/detailed, 2026-10-03).
"""
global _encoding_service
if _encoding_service is None:
_encoding_service = EncodingService()
# Wire up worker manager for dynamic URL resolution
try:
from backend.services.encoding_worker_manager import EncodingWorkerManager
from google.cloud import compute_v1, firestore
settings = get_settings()
db = firestore.Client(project=settings.google_cloud_project)
compute_client = compute_v1.InstancesClient()
manager = EncodingWorkerManager(
db=db,
compute_client=compute_client,
project_id=settings.google_cloud_project,
)
_encoding_service.set_worker_manager(manager)
except Exception:
# Fallback to static URL if worker manager setup fails
pass
if _encoding_service is not None:
return _encoding_service
with _encoding_service_lock:
if _encoding_service is not None:
return _encoding_service
_build_encoding_service()
return _encoding_service
def _build_encoding_service() -> None:
"""Construct + wire the singleton; publish it only once fully wired, so the
lock-free fast path in get_encoding_service never sees a half-built one."""
global _encoding_service
if _encoding_service is not None:
return
service = EncodingService()
# Wire up worker manager for dynamic URL resolution
try:
from backend.services.encoding_worker_manager import EncodingWorkerManager
from google.cloud import compute_v1, firestore
settings = get_settings()
db = firestore.Client(project=settings.google_cloud_project)
compute_client = compute_v1.InstancesClient()
manager = EncodingWorkerManager(
db=db,
compute_client=compute_client,
project_id=settings.google_cloud_project,
)
service.set_worker_manager(manager)
except Exception:
# Fallback to static URL if worker manager setup fails
pass
_encoding_service = service
+5 -1
View File
@@ -627,7 +627,11 @@ class EncodingWorkerManager:
zone = config.active_override_zone
if not vm:
# Primary pair was serving — see docstring; leave selection untouched.
logger.warning(
# Logged at ERROR so it alerts: on 2026-10-06 a primary that booted
# without its env failed every job for an hour while this was a WARNING.
# The worker now restarts itself (gce_encoding/self_heal.py); if this
# keeps firing, that self-heal isn't working.
logger.error(
"Active encoding worker hit an infra failure while the primary was "
"serving; leaving selection unchanged for bounded retry: %s", reason,
)
+2
View File
@@ -256,6 +256,8 @@ class FirestoreService:
'job_id', 'status', 'progress', 'created_at', 'updated_at', 'artist', 'title',
'error_message', 'error_details.code', 'error_details.stage',
'error_details.stall_minutes', 'error_details.keep_trying', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
'renders_purged_at', 'stems_purged_at', 'finalise_only', 'prep_only',
'state_data.regenerate', 'state_data.stems_restore', 'state_data.instrumental_selection',
'made_for_you', 'customer_email', 'locale',
'url', 'filename', 'existing_instrumental_gcs_path',
'audio_search_artist', 'audio_search_title',
+52 -13
View File
@@ -15,11 +15,21 @@ from contextlib import asynccontextmanager
from pathlib import Path
from typing import Optional
# Force google-auth to reach the metadata server over plain HTTP. google-auth
# >=2.40 switches to mTLS over HTTPS when /run/google-mds-mtls/ certs exist, and
# that handshake fails with CERTIFICATE_VERIFY_FAILED on our images. startup.sh
# sets this in the systemd env file, but the Packer-baked startup-fallback.sh
# (used when GCS is unreachable at boot) does not, which broke every job on
# 2026-10-06. Defaulting it here covers every boot path. Must run before any
# google library is imported.
os.environ.setdefault("GCE_METADATA_MTLS_MODE", "none")
from fastapi import FastAPI, BackgroundTasks, HTTPException, Header, Depends
from google.cloud import storage
from packaging.version import Version
from pydantic import BaseModel
from . import self_heal
from .persistence import JobStatePersister
from backend.utils.audio_filenames import local_audio_filename
@@ -88,8 +98,28 @@ def _persist(job_id: str) -> None:
persister.save(state)
def _has_active_jobs() -> bool:
return any(j.get("status") in ("running", "pending") for j in jobs.values())
def _self_heal_after_failure(error: Exception) -> None:
"""Restart the worker if a job failed because the VM itself can't reach GCP."""
try:
self_heal.schedule_restart_if_unhealthy(str(error), _has_active_jobs)
except Exception as exc: # noqa: BLE001 — must never mask the job failure
logger.warning("Self-heal scheduling failed: %r", exc)
@asynccontextmanager
async def lifespan(app: FastAPI):
# Refuse to serve if this boot came up broken (no API key / no GCP
# credentials, e.g. bootstrap fell back because the network wasn't up yet).
# Failing startup makes uvicorn exit; systemd then re-runs the bootstrap.
problem = await asyncio.to_thread(self_heal.boot_health_problem)
if problem:
logger.critical("Encoding worker booted unhealthy, exiting for systemd restart: %s", problem)
raise RuntimeError(f"Encoding worker booted unhealthy: {problem}")
# Startup: read back any in-progress jobs from Firestore. They were
# interrupted by the restart that brought us here — their work_dir is
# gone, so mark them failed with the restart code so polls return a
@@ -856,21 +886,20 @@ def resolve_instrumental(work_dir: Path, config: dict):
"*custom_instrumental*.aac", "*Instrumental Custom*",
)
elif instrumental_selection == "with_backing":
# User selected instrumental with backing vocals
# User selected instrumental with backing vocals. NO generic fallback:
# "*instrumental*.flac" used to match instrumental_clean.flac (or a kept
# custom_instrumental.flac) whenever the with-backing stem was missing,
# silently shipping the wrong instrumental. Missing => fail loudly.
instrumental = find_file(
work_dir,
"*instrumental_with_backing*.flac", "*Instrumental Backing*.flac",
"*with_backing*.flac", "*Backing*.flac",
"*instrumental*.flac", "*Instrumental*.flac",
"*instrumental*.wav"
)
else:
# Default to clean instrumental
# Default to clean instrumental — never fall back to a with-backing or
# custom/user instrumental (same silent-wrong-instrumental risk).
instrumental = find_file(
work_dir,
"*instrumental_clean*.flac", "*Instrumental Clean*.flac",
"*instrumental*.flac", "*Instrumental*.flac",
"*instrumental*.wav"
)
return instrumental
@@ -1057,15 +1086,20 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
# Title/end screens: look for MOV first, fall back to generating from PNG.
# Since PR #640 right-sized Cloud Run to 2Gi, the screens_worker only generates
# PNG/JPG images — MOV video generation now happens here on the GCE worker.
title_video = find_file(work_dir, "screens/title.mov", "*Title*.mov", "*title*.mov")
end_video = find_file(work_dir, "screens/end.mov", "*End*.mov", "*end*.mov")
# A theme may leave a screen out. Don't look for it at all then: the loose globs
# below also match theme assets (style/cdg_title_background.png,
# style/end_background.png) and old finals, which would bring it back.
include_title = config.get("include_title_screen", True) is not False
include_end = config.get("include_end_screen", True) is not False
title_video = find_file(work_dir, "screens/title.mov", "*Title*.mov", "*title*.mov") if include_title else None
end_video = find_file(work_dir, "screens/end.mov", "*End*.mov", "*end*.mov") if include_end else None
# Get intro/end video durations from style config (default 5s)
intro_duration = config.get("intro_video_duration", 5)
end_duration = config.get("end_video_duration", 5)
# Generate title MOV from PNG if missing or invalid (< 1KB = empty shell)
if not title_video or title_video.stat().st_size < 1024:
if include_title and (not title_video or title_video.stat().st_size < 1024):
title_png = find_file(work_dir, "screens/title.png", "*Title*.png", "*title*.png")
if title_png:
title_mov_path = title_png.parent / "title.mov"
@@ -1075,7 +1109,7 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
logger.warning(f"Title MOV is only {title_video.stat().st_size} bytes and no PNG found")
# Generate end MOV from PNG if missing or invalid
if not end_video or (end_video and end_video.stat().st_size < 1024):
if include_end and (not end_video or end_video.stat().st_size < 1024):
end_png = find_file(work_dir, "screens/end.png", "*End*.png", "*end*.png")
if end_png:
end_mov_path = end_png.parent / "end.mov"
@@ -1130,8 +1164,10 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
logger.info(f" Countdown padding: {countdown_padding_seconds}s - will be handled by LocalEncodingService")
# Validate required files
if not title_video:
if include_title and not title_video:
raise ValueError(f"No title video found in {work_dir}. Check screens/ subdirectory.")
if not include_title or not include_end:
logger.info(f" Theme omits screens: title={'kept' if include_title else 'omitted'}, end={'kept' if include_end else 'omitted'}")
if not karaoke_video:
raise ValueError(f"No karaoke video found in {work_dir}")
if not instrumental:
@@ -1145,7 +1181,7 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
# Build encoding config with proper file names
# Note: countdown_padding_seconds is passed to LocalEncodingService which handles padding
encoding_config = EncodingConfig(
title_video=str(title_video),
title_video=str(title_video) if title_video else None,
karaoke_video=str(karaoke_video),
instrumental_audio=str(instrumental),
end_video=str(end_video) if end_video else None,
@@ -1298,6 +1334,7 @@ async def process_job(job_id: str, request: EncodeRequest):
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
_persist(job_id)
_self_heal_after_failure(e)
async def process_preview_job(job_id: str, request: EncodePreviewRequest):
@@ -1328,6 +1365,7 @@ async def process_preview_job(job_id: str, request: EncodePreviewRequest):
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
_persist(job_id)
_self_heal_after_failure(e)
async def process_render_video_job(job_id: str, request: RenderVideoRequest):
@@ -1370,6 +1408,7 @@ async def process_render_video_job(job_id: str, request: RenderVideoRequest):
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
_persist(job_id)
_self_heal_after_failure(e)
@app.post("/encode-preview")
+148
View File
@@ -0,0 +1,148 @@
"""Self-healing for an encoding worker that booted into a broken state.
Incident 2026-10-06 (job ebfe4344): the primary VM booted before its network was
up, so ``bootstrap.sh`` could not download the CI-managed ``startup.sh`` from GCS
and fell back to the Packer-baked ``startup-fallback.sh``. That fallback wrote an
env file with no ``ENCODING_API_KEY`` and no ``GCE_METADATA_MTLS_MODE=none``, so
google-auth talked mTLS to the metadata server and every job failed with
``CERTIFICATE_VERIFY_FAILED``. The worker still answered /health, and the backend
deliberately keeps retrying the primary on infra errors, so customer renders
looped for an hour until someone ran ``systemctl restart encoding-worker``.
This module performs that restart automatically. Exiting the process makes
systemd (``Restart=always``) re-run ``ExecStartPre=bootstrap.sh``, which, now that
the network is up, downloads the real ``startup.sh`` and rewrites the env file.
Only active on an encoding-worker VM running under systemd (``INVOCATION_ID`` is
set by systemd for every service process, and the Packer image installs
``/opt/encoding-worker/bootstrap.sh``), so local runs, CI and tests never exit.
"""
import logging
import os
import threading
import time
from typing import Callable, Optional
from backend.services.encoding_errors import is_worker_infra_error
logger = logging.getLogger(__name__)
# Credential probe: a few attempts so a single metadata-server blip doesn't
# restart a healthy worker.
PROBE_ATTEMPTS = 3
PROBE_RETRY_SECONDS = 5.0
# After an infra-failed job, wait before checking/restarting so the backend's
# status poll (every ~10s) sees the "failed" status first and parks the job for
# retry rather than hitting a vanished worker.
RESTART_DELAY_SECONDS = 30.0
_restart_lock = threading.Lock()
_restart_pending = False
BOOTSTRAP_PATH = "/opt/encoding-worker/bootstrap.sh"
def running_on_worker_vm() -> bool:
"""True only for the encoding-worker systemd service on a worker VM."""
return bool(os.environ.get("INVOCATION_ID")) and os.path.exists(BOOTSTRAP_PATH)
def _refresh_default_credentials() -> None:
import google.auth
import google.auth.transport.requests
credentials, _ = google.auth.default(
scopes=["https://www.googleapis.com/auth/cloud-platform"]
)
credentials.refresh(google.auth.transport.requests.Request())
def probe_credentials(
attempts: int = PROBE_ATTEMPTS,
retry_seconds: float = PROBE_RETRY_SECONDS,
refresh: Callable[[], None] = _refresh_default_credentials,
) -> Optional[str]:
"""Try to fetch a service-account token. Returns None if healthy, else the last error."""
last_error = ""
for attempt in range(1, attempts + 1):
try:
refresh()
return None
except Exception as e: # noqa: BLE001 — any failure means "can't authenticate"
last_error = str(e) or repr(e)
logger.warning(
"Credential probe failed (attempt %d/%d): %s", attempt, attempts, last_error
)
if attempt < attempts:
time.sleep(retry_seconds)
return last_error
def boot_health_problem(probe: Callable[[], Optional[str]] = probe_credentials) -> Optional[str]:
"""Describe why this worker booted broken, or None if it is fine to serve.
Returns None outside systemd so local/dev runs are unaffected.
"""
if not running_on_worker_vm():
return None
problems = []
if not os.environ.get("ENCODING_API_KEY"):
problems.append("ENCODING_API_KEY is not set (startup fell back without the real env)")
probe_error = probe()
if probe_error:
problems.append(f"cannot obtain GCP credentials: {probe_error}")
return "; ".join(problems) or None
def schedule_restart_if_unhealthy(
error_text: str,
has_active_jobs: Callable[[], bool],
*,
delay_seconds: float = RESTART_DELAY_SECONDS,
probe: Callable[[], Optional[str]] = probe_credentials,
exit_process: Callable[[int], None] = os._exit,
) -> bool:
"""After a job failed with a VM infra/auth error, restart the worker if it is still broken.
Runs in a daemon thread: waits ``delay_seconds``, re-probes credentials, and if
they still fail, waits for in-flight jobs to drain and exits so systemd
re-bootstraps the service. Returns True if a check was scheduled.
"""
global _restart_pending
if not running_on_worker_vm() or not is_worker_infra_error(error_text):
return False
with _restart_lock:
if _restart_pending:
return False
_restart_pending = True
def _run() -> None:
global _restart_pending
try:
while True:
time.sleep(delay_seconds)
probe_error = probe()
if not probe_error:
logger.info("Credentials healthy again after infra failure; not restarting")
return
if has_active_jobs():
logger.warning(
"Credentials still failing but jobs are in flight; "
"re-checking before restarting: %s", probe_error,
)
continue
logger.critical(
"Encoding worker cannot authenticate to GCP (%s); exiting so systemd "
"re-runs the bootstrap", probe_error,
)
exit_process(1)
return
finally:
with _restart_lock:
_restart_pending = False
threading.Thread(target=_run, name="encoding-worker-self-heal", daemon=True).start()
return True
+31 -2
View File
@@ -20,6 +20,7 @@ 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
from backend.utils.keyed_lock import job_lock
logger = logging.getLogger(__name__)
@@ -487,7 +488,18 @@ class JobManager:
return True
def transition_to_state(
def transition_to_state(self, job_id: str, *args, **kwargs) -> bool:
"""Validate + apply a status transition (see _transition_to_state_unlocked).
Serialized per job within this instance: route handlers run in the
threadpool, so two concurrent requests (e.g. a double-clicked Complete)
could otherwise both pass validation and both transition/trigger
workers. (They used to be serialized by running on the event loop.)
"""
with job_lock(job_id):
return self._transition_to_state_unlocked(job_id, *args, **kwargs)
def _transition_to_state_unlocked(
self,
job_id: str,
new_status: JobStatus,
@@ -1034,6 +1046,18 @@ class JobManager:
# default to 1. payment_bypassed admin/no-email jobs have
# credits_charged=0 and must not be refunded.
state_data = job.state_data or {}
# A re-run of an already-delivered track (storage-retention
# regenerate, admin/theme re-render) was paid for when it first
# completed — cancelling the re-run must not refund that credit.
if any(state_data.get(k) for k in ("regenerate", "admin_rerender", "theme_rerender")):
logger.info(f"Job {job_id}: cancelled re-run of a delivered track, skipping refund")
return False
# Same for a customer edit: "Edit" reopens a completed (delivered) track
# for review, so a delete/cancel/fail after it must not refund — otherwise
# complete → edit → delete returns the credit for a video already received.
if job.edit_count:
logger.info(f"Job {job_id}: edited track was already delivered, skipping refund")
return False
credits_charged = int(state_data.get("credits_charged", 1))
if credits_charged == 0:
@@ -1312,8 +1336,13 @@ class JobManager:
"""
Cancel a job.
Only jobs in non-terminal states can be cancelled.
Only jobs in non-terminal states can be cancelled. Serialized per job
within this instance so a double-clicked Cancel can't refund twice.
"""
with job_lock(job_id):
return self._cancel_job_unlocked(job_id, reason)
def _cancel_job_unlocked(self, job_id: str, reason: Optional[str]) -> bool:
job = self.get_job(job_id)
if not job:
return False
+20 -23
View File
@@ -25,7 +25,7 @@ logger = logging.getLogger(__name__)
@dataclass
class EncodingConfig:
"""Configuration for video encoding."""
title_video: str # Path to title video
title_video: Optional[str] # Path to title video (None = theme omits the title screen)
karaoke_video: str # Path to karaoke video (with vocals)
instrumental_audio: str # Path to instrumental audio
end_video: Optional[str] = None # Optional path to end credits video
@@ -369,16 +369,16 @@ class LocalEncodingService:
def encode_lossless_mp4(
self,
title_video: str,
title_video: Optional[str],
karaoke_video: str,
output_file: str,
end_video: Optional[str] = None,
) -> bool:
"""
Create lossless 4K MP4 by concatenating title, karaoke, and optionally end videos.
Create lossless 4K MP4 by concatenating the title (if any), karaoke and end (if any) videos.
Args:
title_video: Path to title video
title_video: Path to title video, or None when the theme omits the title screen
karaoke_video: Path to karaoke video
output_file: Path for output file
end_video: Optional path to end credits video
@@ -386,34 +386,31 @@ class LocalEncodingService:
Returns:
True if successful, False otherwise
"""
# Quote file paths
title_quoted = shlex.quote(os.path.abspath(title_video))
karaoke_quoted = shlex.quote(os.path.abspath(karaoke_video))
# Build filter and inputs for concatenation
# (path, hardware-decode) per concat segment, in order
segments = []
if title_video:
segments.append((title_video, True))
segments.append((karaoke_video, True))
if end_video and os.path.isfile(end_video):
end_quoted = shlex.quote(os.path.abspath(end_video))
extra_input = f"-i {end_quoted}"
concat_filter = (
'-filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0][2:v:0][2:a:0]'
'concat=n=3:v=1:a=1[outv][outa]"'
)
else:
extra_input = ""
concat_filter = (
'-filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0]'
'concat=n=2:v=1:a=1[outv][outa]"'
segments.append((end_video, False))
def inputs(hwaccel: bool) -> str:
return " ".join(
(f"{self.hwaccel_decode_flags} " if hwaccel and hw else "") + f"-i {shlex.quote(os.path.abspath(path))}"
for path, hw in segments
)
streams = "".join(f"[{i}:v:0][{i}:a:0]" for i in range(len(segments)))
concat_filter = f'-filter_complex "{streams}concat=n={len(segments)}:v=1:a=1[outv][outa]"'
gpu_command = (
f"{self._ffmpeg_base_command} {self.hwaccel_decode_flags} -i {title_quoted} "
f"{self.hwaccel_decode_flags} -i {karaoke_quoted} {extra_input} "
f"{self._ffmpeg_base_command} {inputs(True)} "
f'{concat_filter} -map "[outv]" -map "[outa]" -c:v {self.video_encoder} '
f'{self._get_nvenc_quality_settings("lossless")} -c:a pcm_s16le '
f'{self.MP4_FLAGS} "{output_file}"'
)
cpu_command = (
f"{self._ffmpeg_base_command} -i {title_quoted} -i {karaoke_quoted} {extra_input} "
f"{self._ffmpeg_base_command} {inputs(False)} "
f'{concat_filter} -map "[outv]" -map "[outa]" -c:v libx264 -c:a pcm_s16le '
f'{self.MP4_FLAGS} "{output_file}"'
)
+339
View File
@@ -0,0 +1,339 @@
"""Event-loop stall watchdog.
The API runs ONE uvicorn process with ONE asyncio event loop per Cloud Run
instance. Any synchronous work executed on that loop (sync Firestore/GCS/HTTP
calls, PIL/ffmpeg, a first ``import matplotlib.pyplot``…) freezes *every*
request on the instance — including ``/api/health`` — which users see as the
"Reconnecting" pill / "temporarily unavailable" banner. (Analysis 2026-10-03:
docs/archive/2026-10-03-backend-loop-freezes-telemetry-plan.md.)
This module makes such freezes self-diagnosing:
* an asyncio heartbeat task stamps ``last_tick`` every ``tick_s``;
* a daemon thread notices when the stamp goes stale (> ``stall_threshold_s``)
and captures the *event-loop thread's* Python stack via
``sys._current_frames()`` — i.e. the exact line that is blocking — resampling
at ``sample_at_s`` so a long freeze shows where it actually spent its time;
* when the loop resumes it logs ``EVENT_LOOP_STALL ended duration_ms=…``
(WARNING, or ERROR at ``error_threshold_s`` — the alerting log metric keys on
that), and for stalls ≥ ``record_threshold_s`` hands a summary to
``recorder`` (Firestore ``client_events`` type ``server_loop_stall`` in prod),
so server-side cause and user-visible impact live in one collection.
The thread only reads frames and a float; it never touches the loop, so it is
safe to run alongside it. Recording happens on the watchdog thread (sync
Firestore is fine there).
"""
from __future__ import annotations
import asyncio
import logging
import os
import sys
import threading
import time
import traceback
from datetime import datetime, timezone
from typing import Any, Callable, Optional
logger = logging.getLogger(__name__)
# Frames from these path fragments are "ours" — the innermost one is reported
# as the culprit (the stdlib/library frame below it is usually just the I/O).
_OWN_CODE_MARKERS = ("/backend/", "/karaoke_gen/")
_MAX_STACK_FRAMES = 30
_MAX_STACK_CHARS = 8000
Recorder = Callable[[dict], None]
# Innermost frames that mean "the loop is idle, waiting for I/O" — not blocked.
_IDLE_FUNCS = {"select", "poll", "epoll", "kqueue", "control", "_run_once"}
_IDLE_FILES = ("selectors.py", "base_events.py")
def _is_idle_frame(frame) -> bool:
"""True when the loop thread is parked in the selector (idle), not running code."""
if frame is None:
return False
code = frame.f_code
return code.co_name in _IDLE_FUNCS and code.co_filename.endswith(_IDLE_FILES)
def _format_stack(frame) -> tuple[str, str]:
"""Return (stack_text, culprit) for a frame; culprit = innermost own-code frame."""
if frame is None:
return "", ""
summary = traceback.extract_stack(frame)[-_MAX_STACK_FRAMES:]
culprit = ""
for fs in reversed(summary):
if any(m in fs.filename for m in _OWN_CODE_MARKERS) and "loop_watchdog" not in fs.filename:
short = fs.filename.split("/app/")[-1]
culprit = f"{short}:{fs.lineno} in {fs.name}"
break
if not culprit and summary:
fs = summary[-1]
culprit = f"{fs.filename}:{fs.lineno} in {fs.name}"
text = "".join(traceback.format_list(summary))[-_MAX_STACK_CHARS:]
return text, culprit
class LoopWatchdog:
def __init__(
self,
*,
tick_s: float = 0.25,
stall_threshold_s: float = 1.0,
error_threshold_s: float = 10.0,
record_threshold_s: float = 5.0,
sample_at_s: tuple[float, ...] = (1.0, 5.0, 15.0),
recorder: Optional[Recorder] = None,
clock: Callable[[], float] = time.monotonic,
cpu_clock: Callable[[], float] = time.process_time,
frozen_gap_s: float = 0.75,
frozen_cpu_ratio: float = 0.25,
) -> None:
self.tick_s = tick_s
self.stall_threshold_s = stall_threshold_s
self.error_threshold_s = error_threshold_s
self.record_threshold_s = record_threshold_s
self.sample_at_s = tuple(sorted(sample_at_s))
self.recorder = recorder
self._clock = clock
self._cpu_clock = cpu_clock
# Cloud Run --cpu-throttling freezes the WHOLE process between requests —
# sometimes mid-callback, where the "loop parked in select()" check can't
# see it (2026-10-08: a 30s "stall" in asyncio's get_debug on an instance
# with no requests in flight). Signature: this watchdog thread itself
# oversleeps by >= frozen_gap_s while the process burns almost no CPU
# (a blocking I/O call lets this thread wake on time; GIL-hogging CPU
# work burns CPU). That frozen time is discounted from the stall.
# 0.75s = 3 missed ticks: measured wake gaps stay <= 0.27s under sync I/O,
# pure-Python CPU and C-extension CPU on the loop, while partial throttling
# gives short 1-2.5s freezes (126 of 128 asyncio-internal "stalls" on
# 2026-10-08 had no request waiting on them).
self.frozen_gap_s = frozen_gap_s
self.frozen_cpu_ratio = frozen_cpu_ratio
self._last_check: Optional[float] = None
self._last_cpu = 0.0
self._stall_frozen_s = 0.0
self._last_tick = clock()
self._loop_thread_id: Optional[int] = None
self._heartbeat_task: Optional[asyncio.Task] = None
self._thread: Optional[threading.Thread] = None
self._stop = threading.Event()
# Current-stall state (only touched by the watchdog thread).
self._in_stall = False
self._stall_started_tick = 0.0
self._samples: list[dict[str, Any]] = []
self._next_sample_idx = 0
# ----- lifecycle -------------------------------------------------------
def start(self) -> None:
"""Start heartbeat + watchdog thread. Must be called from inside the loop."""
if self._thread is not None:
return
self._loop_thread_id = threading.get_ident()
self._last_tick = self._clock()
self._heartbeat_task = asyncio.get_running_loop().create_task(self._heartbeat())
self._stop.clear()
self._thread = threading.Thread(target=self._run, name="loop-watchdog", daemon=True)
self._thread.start()
logger.info(
"Event-loop watchdog started (stall>=%.1fs logged, >=%.1fs recorded, >=%.1fs error)",
self.stall_threshold_s, self.record_threshold_s, self.error_threshold_s,
)
async def stop(self) -> None:
self._stop.set()
if self._heartbeat_task is not None:
self._heartbeat_task.cancel()
try:
await self._heartbeat_task
except (asyncio.CancelledError, Exception):
pass
self._heartbeat_task = None
self._thread = None
async def _heartbeat(self) -> None:
while True:
self._last_tick = self._clock()
await asyncio.sleep(self.tick_s)
def _run(self) -> None:
while not self._stop.wait(self.tick_s):
try:
self.check()
except Exception: # pragma: no cover — must never kill the thread
logger.exception("loop watchdog check failed")
# ----- detection (called from the watchdog thread; unit-testable) ------
def _sample(self, age: float) -> None:
frame = sys._current_frames().get(self._loop_thread_id) if self._loop_thread_id else None
if _is_idle_frame(frame):
# Loop is parked in select(): not blocked. This is what a CPU-throttled
# idle Cloud Run instance looks like when CPU returns (the watchdog
# thread can wake before the heartbeat does). Record it so _finish
# can drop an all-idle "stall" as a false positive.
self._samples.append({"at_s": round(age, 1), "culprit": "", "stack": "", "idle": True})
return
stack, culprit = _format_stack(frame)
if self._samples and self._samples[-1]["stack"] == stack:
return # identical to the previous sample — nothing new to learn
self._samples.append({"at_s": round(age, 1), "culprit": culprit, "stack": stack, "idle": False})
level = logging.ERROR if age >= self.error_threshold_s else logging.WARNING
logger.log(
level,
"EVENT_LOOP_STALL in progress age_ms=%d culprit=%s\n%s",
int(age * 1000), culprit, stack,
extra={"loop_stall_age_ms": int(age * 1000), "loop_stall_culprit": culprit},
)
def _frozen_gap(self, now: float) -> float:
"""Seconds since the previous check during which the whole process was frozen."""
cpu = self._cpu_clock()
prev_check, prev_cpu = self._last_check, self._last_cpu
self._last_check, self._last_cpu = now, cpu
if prev_check is None:
return 0.0
gap = now - prev_check
if gap >= self.frozen_gap_s and (cpu - prev_cpu) < gap * self.frozen_cpu_ratio:
return gap
return 0.0
def check(self, now: Optional[float] = None) -> None:
now = self._clock() if now is None else now
frozen = self._frozen_gap(now)
last = self._last_tick
age = now - last
if not self._in_stall:
if age >= self.stall_threshold_s:
self._in_stall = True
self._stall_started_tick = last
self._samples = []
self._next_sample_idx = 0
self._stall_frozen_s = 0.0
else:
return
# Only the part of the frozen gap after the last heartbeat belongs to this stall.
self._stall_frozen_s += min(frozen, age)
# In a stall: has the heartbeat resumed?
if last > self._stall_started_tick:
# The heartbeat that ended the stall fired one tick_s after the
# previous one would have, so subtract the nominal sleep.
duration = max(0.0, last - self._stall_started_tick - self.tick_s)
self._finish(duration)
return
if frozen:
# Just thawed: the loop's stack shows where the freeze caught it, not
# what blocked it. Skip the samples due during the freeze.
while (
self._next_sample_idx < len(self.sample_at_s)
and age >= self.sample_at_s[self._next_sample_idx]
):
self._next_sample_idx += 1
return
while (
self._next_sample_idx < len(self.sample_at_s)
and age >= self.sample_at_s[self._next_sample_idx]
):
self._next_sample_idx += 1
self._sample(age)
def _finish(self, duration: float) -> None:
samples = self._samples
frozen_s = self._stall_frozen_s
self._in_stall = False
self._samples = []
self._stall_frozen_s = 0.0
if frozen_s:
logger.debug(
"loop watchdog: discounted %dms of process freeze (CPU throttling) from a %dms gap",
int(frozen_s * 1000), int(duration * 1000),
)
duration = max(0.0, duration - frozen_s)
if duration < self.stall_threshold_s:
return
if samples and all(s.get("idle") for s in samples):
# Every sample saw the loop idle in select() — a throttled/idle gap
# (no CPU allocated between requests), not a blocking call.
logger.debug("loop watchdog: ignored idle gap of %dms", int(duration * 1000))
return
samples = [s for s in samples if not s.get("idle")]
culprits = [s["culprit"] for s in samples if s["culprit"]]
# The longest-lived sample is the most representative of the freeze.
main_culprit = culprits[-1] if culprits else ""
level = logging.ERROR if duration >= self.error_threshold_s else logging.WARNING
logger.log(
level,
"EVENT_LOOP_STALL ended duration_ms=%d culprit=%s",
int(duration * 1000), main_culprit,
extra={
"loop_stall_duration_ms": int(duration * 1000),
"loop_stall_culprit": main_culprit,
"loop_stall_culprits": culprits,
},
)
if self.recorder is not None and duration >= self.record_threshold_s:
try:
self.recorder({
"duration_ms": int(duration * 1000),
"culprit": main_culprit,
"culprits": culprits,
"stack": samples[-1]["stack"] if samples else "",
})
except Exception:
logger.exception("Failed to record loop stall (non-fatal)")
# ----- production recorder ---------------------------------------------------
_instance_id: Optional[str] = None
def _cloud_run_instance_id() -> str:
"""Best-effort Cloud Run instance id from the metadata server (cached)."""
global _instance_id
if _instance_id is not None:
return _instance_id
_instance_id = ""
try:
import requests
resp = requests.get(
"http://metadata.google.internal/computeMetadata/v1/instance/id",
headers={"Metadata-Flavor": "Google"},
timeout=1,
)
if resp.ok:
_instance_id = resp.text.strip()
except Exception:
pass
return _instance_id
def firestore_stall_recorder(stall: dict) -> None:
"""Persist a stall as a ``client_events`` doc (type ``server_loop_stall``)."""
from google.cloud import firestore # type: ignore[import]
from backend.version import VERSION
doc = {
"type": "server_loop_stall",
"source": "server",
"created_at": datetime.now(timezone.utc),
"release": VERSION,
"revision": os.getenv("K_REVISION", ""),
"instance_id": _cloud_run_instance_id(),
"detail": {
"duration_ms": stall["duration_ms"],
"culprit": stall["culprit"][:300],
},
"culprits": [c[:300] for c in stall.get("culprits", [])][:5],
"stack": stall.get("stack", "")[:_MAX_STACK_CHARS],
}
firestore.Client(project="nomadkaraoke").collection("client_events").add(doc)
+367
View File
@@ -0,0 +1,367 @@
"""
Regenerate a completed job's GCS outputs on demand (storage retention).
The storage-retention job (backend/services/storage_retention.py) purges the big
regenerable files of jobs completed >30 days ago — every final except the 720p,
the rendered lyrics video, previews and (where the input audio is kept) the
separated stems. This service brings them back:
1. claim the job atomically: COMPLETE -> LYRICS_COMPLETE with
``state_data.regen_restore_status = "review_complete"`` (the mechanism shared
with the admin/theme re-render and the private->public visibility flow) and
the ``state_data.regenerate`` marker;
2. trigger the screens worker. If the job's stems were purged
(``stems_purged_at``), the screens worker first re-runs audio separation from
the job's input (``input_media_gcs_path``, i.e. ``input/edited.flac`` for
audio-edited jobs) — see ``backend/workers/screens_worker.py`` stems gate and
the audio worker's restore mode;
3. screens -> render -> video worker, using the job's EXISTING reviewed lyrics,
instrumental selection (custom/uploaded instrumentals are never purged) and
style snapshot.
Unlike the admin re-render this is GCS-ONLY: the video worker skips the whole
distribution stage (no YouTube/Dropbox/Google Drive changes, no new brand code,
no Discord post) while the marker is active, and keeps the job's published links.
The customer is emailed/pushed on completion unless ``notify_customer`` is False.
``after="change_to_private"`` chains a public->private visibility change once
the finals are back (redistribution needs the full finals set).
Like the admin re-render the marker records the job's ``review_token`` at claim,
so a later trip through review retires it; a FAILED regenerate keeps it, so
``POST /api/jobs/{id}/retry`` (or another regenerate) resumes it.
"""
import asyncio
import hashlib
import logging
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional
from google.cloud import firestore
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
from backend.models.job import JobStatus
from backend.services.firestore_service import log_to_job
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.theme_rerender_service import (
RerenderConflictError,
RerenderError,
claim_for_rerender,
delete_regenerated_artifacts,
)
logger = logging.getLogger(__name__)
REGENERATE_MARKER = "regenerate"
_LOG_SOURCE = "regenerate"
RATE_LIMIT_COLLECTION = "regenerate_rate_limits"
AFTER_CHANGE_TO_PRIVATE = "change_to_private"
_ALLOWED_AFTER = {None, AFTER_CHANGE_TO_PRIVATE}
# Finals the UI / redistribution need; any missing => renders must be regenerated.
_REQUIRED_FINAL_KEYS = ("lossy_4k_mp4", "lossy_720p_mp4")
# --- Marker helpers ------------------------------------------------------------
def raw_regenerate_marker(job) -> Dict[str, Any]:
state_data = getattr(job, "state_data", None)
marker = state_data.get(REGENERATE_MARKER) if isinstance(state_data, dict) else None
return marker if isinstance(marker, dict) else {}
def active_regenerate(job) -> Dict[str, Any]:
"""The marker if it belongs to the job's current run (same review_token), else ``{}``."""
marker = raw_regenerate_marker(job)
if marker and "review_token" in marker:
if marker["review_token"] != getattr(job, "review_token", None):
return {}
return marker
def clear_regenerate_update(job) -> Dict[str, Any]:
if raw_regenerate_marker(job):
return {f"state_data.{REGENERATE_MARKER}": DELETE_FIELD}
return {}
def regenerate_brand_code(job) -> Optional[str]:
return active_regenerate(job).get("brand_code") or None
def regenerate_suppresses_notifications(job) -> bool:
marker = active_regenerate(job)
return bool(marker) and not marker.get("notify_customer", True)
def is_gcs_only_run(job) -> bool:
"""True while a regenerate is rebuilding this job's GCS outputs (no distribution)."""
return bool(active_regenerate(job))
def renders_missing(job) -> bool:
"""True if the job's big finals are gone (purged, or never recorded)."""
if getattr(job, "renders_purged_at", None):
return True
finals = (getattr(job, "file_urls", None) or {}).get("finals") or {}
if not isinstance(finals, dict):
return True
return not all(finals.get(key) for key in _REQUIRED_FINAL_KEYS)
def stems_need_restore(job) -> bool:
"""True if the job's separated stems were purged and must be re-separated first.
Bring-your-own-instrumental and finalise-only jobs never had separated
stems to restore.
"""
if getattr(job, "existing_instrumental_gcs_path", None):
return False
if getattr(job, "finalise_only", False):
return False
return bool(getattr(job, "stems_purged_at", None))
# --- Validation ------------------------------------------------------------------
def _claimable_statuses(job) -> set:
statuses = {JobStatus.COMPLETE.value}
if active_regenerate(job):
statuses.update({JobStatus.FAILED.value, JobStatus.CANCELLED.value})
return statuses
def validate_regenerate(job, after: Optional[str] = None) -> Optional[str]:
"""Return a reason the job can't be regenerated, or None if it can."""
from backend.services.storage_retention import PURGE_IN_PROGRESS_MESSAGE, purge_in_progress
status = job.status.value if hasattr(job.status, "value") else job.status
if status not in _claimable_statuses(job):
return f"Only finished tracks can be regenerated (current status: {status})."
if getattr(job, "outputs_deleted_at", None):
return "This track's outputs were deleted, so it can't be regenerated."
if getattr(job, "prep_only", False) or getattr(job, "finalise_only", False):
return "This track type can't be regenerated."
state_data = job.state_data or {}
if state_data.get("visibility_change_in_progress") and after != AFTER_CHANGE_TO_PRIVATE:
return "A visibility change is in progress for this track."
from backend.services.admin_rerender_service import active_admin_rerender
if active_admin_rerender(job) or state_data.get("theme_rerender"):
return "This track is already being re-rendered."
if purge_in_progress(job):
return PURGE_IN_PROGRESS_MESSAGE
if not state_data.get("instrumental_selection"):
return "This track has no instrumental selection to regenerate with."
if not ((job.file_urls or {}).get("lyrics") or {}).get("corrections"):
return "This track has no reviewed lyrics to regenerate with."
if not getattr(job, "input_media_gcs_path", None):
return "This track's original audio is no longer available, so it can't be regenerated."
if not getattr(job, "theme_id", None):
return "This track has no video style to regenerate with."
return None
# --- Rate limiting ------------------------------------------------------------------
def _recent(timestamps: List[str], now: datetime, window: timedelta) -> List[str]:
out = []
for ts in timestamps or []:
try:
dt = datetime.fromisoformat(str(ts).replace("Z", "+00:00"))
except ValueError:
continue
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
if now - dt < window:
out.append(dt.isoformat())
return out
def check_and_record_rate_limit(db, job, user_email: str, settings, now: Optional[datetime] = None) -> Optional[str]:
"""Customer limits: N regenerations per job and M per user in a rolling 24h.
Returns a refusal message, or None (and records the request) if allowed.
"""
from backend.config import get_settings
settings = settings or get_settings()
now = now or datetime.now(timezone.utc)
window = timedelta(hours=24)
job_recent = _recent((job.state_data or {}).get("regenerate_requests") or [], now, window)
if len(job_recent) >= settings.regenerate_max_per_job_per_day:
return "This track was regenerated recently. Please try again tomorrow."
key = hashlib.sha256((user_email or "unknown").strip().lower().encode()).hexdigest()[:32]
user_ref = db.collection(RATE_LIMIT_COLLECTION).document(key)
@firestore.transactional
def record(transaction):
snap = user_ref.get(transaction=transaction)
user_recent = _recent((snap.to_dict() or {}).get("requests") if snap.exists else [], now, window)
if len(user_recent) >= settings.regenerate_max_per_user_per_day:
return False
transaction.set(user_ref, {"requests": user_recent + [now.isoformat()], "updated_at": now})
return True
if not record(db.transaction()):
return "You've regenerated several tracks today. Please try again tomorrow."
return None
# --- Service ---------------------------------------------------------------------
class RegenerateService:
def __init__(
self,
job_manager: Optional[JobManager] = None,
storage: Optional[StorageService] = None,
):
self.job_manager = job_manager or JobManager()
self.storage = storage or StorageService()
async def start(
self,
job,
requested_by: str,
source: str = "customer",
notify_customer: bool = True,
after: Optional[str] = None,
) -> Dict[str, Any]:
"""Claim the job and kick off the GCS-only regenerate.
Raises RerenderError (400/500/503) or RerenderConflictError (409).
Returns ``{"needs_stems": bool, "brand_code": ...}``.
"""
if after not in _ALLOWED_AFTER:
raise RerenderError(f"Unknown follow-up action: {after}")
reason = validate_regenerate(job, after=after)
if reason:
raise RerenderError(reason)
job_id = job.job_id
input_path = getattr(job, "input_media_gcs_path", None)
if not await asyncio.to_thread(self.storage.file_exists, input_path):
raise RerenderError(
"This track's original audio is no longer available, so it can't be regenerated."
)
update, context = self._build_claim(job, requested_by, source, notify_customer, after)
await asyncio.to_thread(
claim_for_rerender, self.job_manager.firestore.db, job_id, update, _claimable_statuses(job),
)
try:
await asyncio.to_thread(self._after_claim, job, context)
from backend.services.worker_service import get_worker_service
triggered = await get_worker_service().trigger_screens_worker(job_id)
except Exception as e:
logger.exception(f"[job:{job_id}] Regenerate failed after claim")
await asyncio.to_thread(self._fail_run, job_id, f"Regenerate failed to start: {e}", "start_error")
raise RerenderError(
"The regeneration failed to start. Please try again.", status_code=500,
) from e
if not triggered:
await asyncio.to_thread(
self._fail_run, job_id, "Regenerate couldn't start the screens worker.", "screens_trigger_failed",
)
raise RerenderError("Couldn't start the regeneration. Please try again.", status_code=503)
await asyncio.to_thread(
log_to_job, job_id, _LOG_SOURCE, "INFO",
f"Regenerate started by {requested_by} ({source}); stems restore first: {context['needs_stems']}",
)
return {"needs_stems": context["needs_stems"], "brand_code": context["brand_code"]}
def _build_claim(self, job, requested_by, source, notify_customer, after):
state_data = job.state_data or {}
previous = active_regenerate(job)
brand_code = state_data.get("brand_code") or previous.get("brand_code")
needs_stems = stems_need_restore(job)
now = datetime.now(timezone.utc)
message = (
f"Regenerate requested by {requested_by} ({source}): rebuilding GCS outputs only "
f"(no YouTube/Dropbox/Google Drive changes){'; re-separating stems first' if needs_stems else ''}"
)
# Only customer-triggered runs count towards the customer's daily limit.
requests = _recent(state_data.get("regenerate_requests") or [], now, timedelta(hours=24))
if source == "customer":
requests = requests + [now.isoformat()]
update: Dict[str, Any] = {
"status": JobStatus.LYRICS_COMPLETE.value,
"progress": 50,
"error_message": None,
"error_details": None,
"state_data.regen_restore_status": "review_complete",
"state_data.audio_complete": True,
"state_data.lyrics_complete": True,
"state_data.screens_progress": DELETE_FIELD,
"state_data.render_progress": DELETE_FIELD,
"state_data.video_progress": DELETE_FIELD,
"state_data.encoding_progress": DELETE_FIELD,
"state_data.stems_restore": DELETE_FIELD,
"state_data.regenerate_requests": requests,
f"state_data.{REGENERATE_MARKER}": {
"requested_by": requested_by,
"requested_at": now.isoformat(),
"source": source,
"notify_customer": bool(notify_customer),
"brand_code": brand_code,
"after": after,
"needs_stems": needs_stems,
"review_token": getattr(job, "review_token", None),
},
# Stale screens/lyrics video are deleted below; drop their file_urls.
"file_urls.screens": DELETE_FIELD,
"file_urls.videos.with_vocals": DELETE_FIELD,
"updated_at": now,
"timeline": ArrayUnion([{
"status": JobStatus.LYRICS_COMPLETE.value,
"timestamp": now.isoformat(),
"message": message,
"metadata": {
"action": "regenerate_initiated",
"initiated_by": requested_by,
"source": source,
"needs_stems": needs_stems,
"after": after,
},
}]),
}
if after == AFTER_CHANGE_TO_PRIVATE:
update["state_data.visibility_change_in_progress"] = True
return update, {"brand_code": brand_code, "needs_stems": needs_stems, "message": message}
def _after_claim(self, job, context) -> None:
log_to_job(job.job_id, _LOG_SOURCE, "INFO", context["message"])
delete_regenerated_artifacts(self.storage, job.job_id)
def _fail_run(self, job_id: str, error: str, reason: str) -> None:
logger.error(f"[job:{job_id}] {error}")
try:
self.job_manager.update_job(job_id, {
"status": JobStatus.FAILED.value,
"error_message": error,
"error_details": {"stage": "regenerate", "reason": reason},
"state_data.regen_restore_status": DELETE_FIELD,
})
log_to_job(job_id, _LOG_SOURCE, "ERROR", error)
except Exception:
logger.exception(f"[job:{job_id}] Failed to mark regenerate as failed")
__all__ = [
"REGENERATE_MARKER",
"RegenerateService",
"RerenderConflictError",
"RerenderError",
"active_regenerate",
"check_and_record_rate_limit",
"clear_regenerate_update",
"is_gcs_only_run",
"regenerate_brand_code",
"regenerate_suppresses_notifications",
"renders_missing",
"stems_need_restore",
"validate_regenerate",
]
+155
View File
@@ -0,0 +1,155 @@
"""
Restore a job's separated stems after storage retention purged them.
The storage-retention job deletes the separated stems of old jobs (they're
regenerable: re-run separation on the kept input audio) and stamps
``stems_purged_at``. Every flow that rebuilds a completed job goes through the
screens worker — regenerate, admin re-render, theme re-render, private->public
visibility change, Edit — so the screens worker gates on this module: if the
job's stems were purged it starts the audio-separation Cloud Run Job in RESTORE
mode instead of generating screens, and the audio worker re-triggers the screens
worker once the stems are back. Review (Edit flow) and the encoder then find the
stems exactly where they always were.
``state_data.stems_restore = {status: running|failed, attempts, started_at}``
tracks the restore; ``attempts`` bounds automatic re-runs.
"""
import logging
from datetime import datetime, timezone
from typing import Optional
from google.cloud.firestore_v1 import DELETE_FIELD
logger = logging.getLogger(__name__)
STEMS_RESTORE_KEY = "stems_restore"
MAX_AUTO_ATTEMPTS = 3
STALE_RUNNING_SECONDS = 60 * 60
NOT_NEEDED = "not_needed"
STARTED = "started"
IN_PROGRESS = "in_progress"
FAILED = "failed"
def restore_marker(job) -> dict:
marker = (getattr(job, "state_data", None) or {}).get(STEMS_RESTORE_KEY)
return marker if isinstance(marker, dict) else {}
def _age_seconds(iso: Optional[str]) -> Optional[float]:
if not iso:
return None
try:
started = datetime.fromisoformat(str(iso).replace("Z", "+00:00"))
except ValueError:
return None
if started.tzinfo is None:
started = started.replace(tzinfo=timezone.utc)
return (datetime.now(timezone.utc) - started).total_seconds()
def is_restore_run(job) -> bool:
"""True when the audio worker was started to restore purged stems.
Keyed on the marker existing (any status), not just ``running``: when a
restore attempt fails, Cloud Run retries the task after the worker already
marked it failed — that retry must still run in restore mode.
"""
from backend.services.regenerate_service import stems_need_restore
return stems_need_restore(job) and bool(restore_marker(job))
async def maybe_start_stems_restore(job, job_manager, job_log=None) -> str:
"""Screens-worker gate. Returns NOT_NEEDED, STARTED, IN_PROGRESS or FAILED."""
from backend.services.regenerate_service import stems_need_restore
if not stems_need_restore(job):
return NOT_NEEDED
job_id = job.job_id
marker = restore_marker(job)
if marker.get("status") == "running":
age = _age_seconds(marker.get("started_at"))
if age is not None and age < STALE_RUNNING_SECONDS:
logger.info(f"[job:{job_id}] Stems restore already running; skipping duplicate screens dispatch")
job_manager.update_job(job_id, {"state_data.screens_progress": DELETE_FIELD})
return IN_PROGRESS
attempts = int(marker.get("attempts") or 0)
if attempts >= MAX_AUTO_ATTEMPTS:
message = (
"Couldn't restore this track's audio stems (archived to save space) after "
f"{attempts} attempts. Retry the job to try again."
)
job_manager.update_job(job_id, {"state_data.screens_progress": DELETE_FIELD})
job_manager.mark_job_failed(
job_id=job_id, error_message=message,
error_details={"stage": "stems_restore", "attempts": attempts},
)
return FAILED
now = datetime.now(timezone.utc).isoformat()
job_manager.update_job(job_id, {
f"state_data.{STEMS_RESTORE_KEY}": {
"status": "running", "attempts": attempts + 1, "started_at": now,
},
# This screens dispatch ends here (the restore re-triggers screens), so
# drop the "running" idempotency mark /api/internal/workers/screens set —
# otherwise the re-trigger is skipped as "already running". Duplicate
# dispatches meanwhile are absorbed by the stems_restore marker.
"state_data.screens_progress": DELETE_FIELD,
"message": "Restoring audio stems",
"updated_at": datetime.now(timezone.utc),
})
if job_log is not None:
job_log.info("Stems were archived by storage retention: re-running audio separation first")
from backend.services.worker_service import get_worker_service
triggered = await get_worker_service().trigger_audio_worker(job_id)
if not triggered:
job_manager.update_job(job_id, {f"state_data.{STEMS_RESTORE_KEY}.status": "failed",
"state_data.screens_progress": DELETE_FIELD})
job_manager.mark_job_failed(
job_id=job_id,
error_message="Couldn't start audio separation to restore this track's stems. Retry the job.",
error_details={"stage": "stems_restore", "reason": "audio_trigger_failed"},
)
return FAILED
logger.info(f"[job:{job_id}] Stems restore started (attempt {attempts + 1})")
return STARTED
async def complete_stems_restore(job_id: str, job_manager) -> bool:
"""Audio worker (restore mode) finished: clear the markers and resume screens."""
update = {
"stems_purged_at": None,
f"state_data.{STEMS_RESTORE_KEY}": DELETE_FIELD,
"state_data.screens_progress": DELETE_FIELD,
}
# A Cloud Run task retry succeeded after an earlier attempt marked the job
# FAILED: put it back where the restore started so screens can continue.
job = job_manager.get_job(job_id)
status = getattr(getattr(job, "status", None), "value", getattr(job, "status", None))
if status == "failed" and ((getattr(job, "error_details", None) or {}).get("stage")
in ("audio_separation", "download_audio", "stems_restore")):
update.update({"status": "lyrics_complete", "error_message": None, "error_details": None})
job_manager.update_job(job_id, update)
from backend.services.worker_service import get_worker_service
triggered = await get_worker_service().trigger_screens_worker(job_id)
if not triggered:
logger.error(f"[job:{job_id}] Stems restored but the screens worker couldn't be triggered")
return triggered
def restore_stalled(job, now: Optional[datetime] = None) -> bool:
"""A ``running`` restore whose audio job died without reporting back."""
marker = restore_marker(job)
if marker.get("status") != "running":
return False
age = _age_seconds(marker.get("started_at"))
return age is not None and age > STALE_RUNNING_SECONDS
def mark_restore_failed(job_id: str, job_manager) -> None:
try:
job_manager.update_job(job_id, {f"state_data.{STEMS_RESTORE_KEY}.status": "failed"})
except Exception: # noqa: BLE001
logger.exception(f"[job:{job_id}] Couldn't mark stems restore failed")
+992
View File
@@ -0,0 +1,992 @@
"""
Storage retention: purge regenerable files from old completed jobs.
Policy (docs/archive/2026-10-03-gen-storage-retention-plan.md, approved by
Andrew 2026-10-03). For jobs completed more than ``min_age_days`` (30) ago:
KEEP forever
- ``input/*`` (incl. ``input/edited.flac``), ``lyrics/**``, ``style/**``,
``review_sessions/**``, ``audio_edit*/**``, ``uploads/**``
- the 720p final (``finals/*(Final Karaoke Lossy 720p).mp4`` and the
canonical ``finals/lossy_720p_mp4.mp4`` copy) — the one ready-made download
- ``packages/*`` (CDG/TXT zips), ``screens/*.png|jpg``, ``analysis/*``
- user-made instrumentals: ``stems/custom_instrumental.*`` and the staged
copies at the job root (``custom_instrumental.*`` / ``existing_instrumental.*``)
— they hold user mute edits / uploads, which aren't stored anywhere else
- ``stems/vocals_derived.*`` (cheap waveform helper of bring-your-own-
instrumental jobs; separation doesn't recreate it)
- anything not explicitly on the purge list (unknown files are kept)
PURGE (regenerated on demand by backend/services/regenerate_service.py)
- every other ``finals/*``, ``videos/*``, ``previews/*``, ``encoded/*``,
``quick/*.mp4``, ``screens/*.mov``, ``review-audio/*``
- separated stems (``stems/*`` apart from the kept ones above) — only when the
input audio is still in ``jobs/{id}/`` so separation can be re-run
Never touched
- finalise-only jobs (their videos/screens/stems are user-uploaded SOURCES and
they can't be regenerated), jobs whose input audio is gone (nothing could be
re-rendered), jobs mid-edit / re-render / visibility change, jobs with a
pending deferred YouTube upload, excluded tenants
- anything outside ``jobs/{job_id}/``
The job walks Firestore (it knows each job's type) rather than using a bucket
lifecycle rule. It is DRY-RUN by default (settings.storage_retention_dry_run):
it then only writes a report (GCS JSON + log summary). Real runs record
``renders_purged_at`` / ``stems_purged_at`` + a ``storage_purge`` manifest on the
job and drop the purged entries from ``file_urls`` so the UI offers
"Regenerate video". Idempotent, batched (``max_jobs``) with a resumable cursor.
"""
from __future__ import annotations
import logging
import os
import re
import time
from collections import Counter
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, Iterable, List, Optional, Tuple
logger = logging.getLogger(__name__)
POLICY_VERSION = 1
REPORT_PREFIX = "storage-retention/reports"
# Audit trail of every object deleted (kept forever; never touched by any purge
# or lifecycle rule — see docs/STORAGE-RETENTION.md).
DELETION_LOG_PREFIX = "storage-retention/deletion-logs"
MODE_JOB_PURGE = "job_purge"
MODE_ORPHAN = "orphan"
ORPHAN_QUIET_DAYS = 30
# Firestore collections whose doc id == the jobs/{id}/ folder name and that mean
# "this folder still belongs to something". encoding_worker_jobs is NOT one: it's
# the encoder's expiring result cache, left behind by deleted jobs.
ORPHAN_RECORD_COLLECTIONS = ("jobs", "jobs-dev", "youtube_upload_queue")
STATE_COLLECTION = "storage_retention"
STATE_DOC = "state"
SCAN_PAGE_SIZE = 200
# A purge claims the job for this long; a regenerate/edit started meanwhile waits.
PURGE_IN_PROGRESS_KEY = "storage_purge_in_progress"
PURGE_CLAIM_STALE_SECONDS = 30 * 60
# Purge categories that count as "renders" (vs stems).
RENDER_CATEGORIES = frozenset({
"finals", "videos", "previews", "encoded", "quick", "screens_mov", "review_audio",
})
STEM_CATEGORIES = frozenset({"stems"})
KEEP = "keep"
PURGE = "purge"
_KEEP_PREFIXES = (
"input/", "lyrics/", "style/", "review_sessions/", "audio_edit", "uploads/",
"packages/", "analysis/",
)
_KEPT_STEM_STEMS = ("custom_instrumental", "vocals_derived")
_ROOT_INSTRUMENTAL_STEMS = ("custom_instrumental", "existing_instrumental")
# --------------------------------------------------------------------------------
# Policy (pure functions)
# --------------------------------------------------------------------------------
def classify_file(rel_path: str, finalise_only: bool = False, stems_purgeable: bool = True) -> Tuple[str, str]:
"""Return ``(KEEP|PURGE, category)`` for a path relative to ``jobs/{job_id}/``."""
rel = rel_path.lstrip("/")
name = os.path.basename(rel)
stem = os.path.splitext(name)[0].lower()
ext = os.path.splitext(name)[1].lower()
if "/" not in rel:
if stem in _ROOT_INSTRUMENTAL_STEMS:
return KEEP, "user_instrumental"
return KEEP, "other"
top = rel.split("/", 1)[0]
if rel.startswith(_KEEP_PREFIXES):
return KEEP, top
if top == "finals":
from backend.services.encoding_interface import classify_encoded_output
if classify_encoded_output(name) == "mp4_720p":
return KEEP, "final_720p"
return PURGE, "finals"
if top == "videos":
# Finalise-only: the user uploaded videos/with_vocals.* (a source file).
return (KEEP, "source_video") if finalise_only else (PURGE, "videos")
if top == "previews":
return PURGE, "previews"
if top == "encoded":
return PURGE, "encoded"
if top == "quick":
return (PURGE, "quick") if ext == ".mp4" else (KEEP, "quick_other")
if top == "review-audio":
return PURGE, "review_audio"
if top == "screens":
if ext == ".mov":
return (KEEP, "source_screen") if finalise_only else (PURGE, "screens_mov")
return KEEP, "screens_image"
if top == "stems":
if stem.startswith(_KEPT_STEM_STEMS):
return KEEP, "user_instrumental" if stem.startswith("custom_instrumental") else "stems_kept"
if finalise_only:
return KEEP, "source_stem"
if not stems_purgeable:
return KEEP, "stems_unrecoverable"
return PURGE, "stems"
return KEEP, "other"
def _parse_ts(value: Any) -> Optional[datetime]:
if value is None:
return None
if isinstance(value, datetime):
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
try:
dt = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
except (TypeError, ValueError):
return None
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
def completed_at(job: Dict[str, Any]) -> Optional[datetime]:
"""When the job last completed: the newest ``complete`` timeline entry.
Every re-render / regenerate / edit appends a new one, so the 30-day window
restarts whenever fresh finals are made. Falls back to ``updated_at``.
"""
latest = None
for entry in job.get("timeline") or []:
if not isinstance(entry, dict) or entry.get("status") != "complete":
continue
ts = _parse_ts(entry.get("timestamp"))
if ts and (latest is None or ts > latest):
latest = ts
return latest or _parse_ts(job.get("updated_at"))
def _input_path(job: Dict[str, Any]) -> Optional[str]:
# Only input_media_gcs_path: it's what separation, render and regenerate read.
path = job.get("input_media_gcs_path")
if not isinstance(path, str) or not path:
return None
if path.startswith("gs://"):
path = path.split("/", 3)[-1]
return path
def regenerable_reason(job: Dict[str, Any]) -> Optional[str]:
"""Why a regenerate of this job couldn't run (so its renders must be kept)."""
state_data = job.get("state_data") or {}
if not state_data.get("instrumental_selection"):
return "no_instrumental_selection"
if not ((job.get("file_urls") or {}).get("lyrics") or {}).get("corrections"):
return "no_reviewed_lyrics"
if not job.get("theme_id"):
return "no_theme"
return None
def job_skip_reason(
job: Dict[str, Any],
now: datetime,
min_age_days: int,
excluded_tenants: Iterable[str] = (),
) -> Optional[str]:
"""Why this job must not be purged (or None if it's a candidate)."""
if job.get("status") != "complete":
return "not_complete"
if job.get("finalise_only"):
return "finalise_only"
if job.get("prep_only"):
return "prep_only"
if job.get("outputs_deleted_at"):
return "outputs_deleted"
tenant = job.get("tenant_id") or ""
if tenant and tenant in set(excluded_tenants):
return "excluded_tenant"
state_data = job.get("state_data") or {}
for marker in ("visibility_change_in_progress", "admin_rerender", "theme_rerender", "regenerate"):
if state_data.get(marker):
return f"active_{marker}"
if state_data.get("youtube_upload_queued"):
return "youtube_upload_queued"
claim = _parse_ts(state_data.get(PURGE_IN_PROGRESS_KEY))
if claim and (now - claim).total_seconds() < PURGE_CLAIM_STALE_SECONDS:
return "purge_in_progress"
done = completed_at(job)
if done is None:
return "no_completion_time"
if now - done < timedelta(days=min_age_days):
return "too_recent"
# Only purge what a regenerate could rebuild.
reason = regenerable_reason(job)
if reason:
return f"not_regenerable_{reason}"
return None
def purge_in_progress(job) -> bool:
"""True while the retention job is deleting this job's files (Job model or dict)."""
state_data = job.get("state_data") if isinstance(job, dict) else getattr(job, "state_data", None)
claim = _parse_ts((state_data or {}).get(PURGE_IN_PROGRESS_KEY)) if isinstance(state_data, dict) else None
return bool(claim) and (datetime.now(timezone.utc) - claim).total_seconds() < PURGE_CLAIM_STALE_SECONDS
PURGE_IN_PROGRESS_MESSAGE = "This track's files are being archived right now. Try again in a few minutes."
@dataclass
class JobPlan:
job_id: str
purge: List[Tuple[str, int, str]] = field(default_factory=list) # (blob path, bytes, category)
kept_bytes: int = 0
stems_purgeable: bool = True
stems_note: Optional[str] = None
skip_reason: Optional[str] = None
generations: Dict[str, Any] = field(default_factory=dict)
@property
def purge_bytes(self) -> int:
return sum(size for _, size, _ in self.purge)
def bytes_by_category(self) -> Dict[str, int]:
out: Counter = Counter()
for _, size, category in self.purge:
out[category] += size
return dict(out)
@property
def purges_renders(self) -> bool:
return any(c in RENDER_CATEGORIES for _, _, c in self.purge)
@property
def purges_stems(self) -> bool:
return any(c in STEM_CATEGORIES for _, _, c in self.purge)
def _listing_entries(listing) -> List[Tuple[str, int, Any]]:
"""Normalise a listing of ``(name, size)``, ``(name, size, gen)`` or meta dicts."""
out = []
for item in listing:
if isinstance(item, dict):
out.append((item["name"], int(item.get("size") or 0), item.get("generation")))
elif len(item) >= 3:
out.append((item[0], int(item[1] or 0), item[2]))
else:
out.append((item[0], int(item[1] or 0), None))
return out
def plan_job(job: Dict[str, Any], listing) -> JobPlan:
"""Decide what to purge for one (already eligible) job from its GCS listing."""
job_id = job["job_id"]
prefix = f"jobs/{job_id}/"
plan = JobPlan(job_id=job_id)
entries = _listing_entries(listing)
names = {name for name, _, _ in entries}
# Re-rendering needs the input audio (render worker + separation). If it's
# gone (e.g. pre-persistence jobs whose input expired from uploads/), nothing
# could ever be regenerated: keep everything.
input_path = _input_path(job)
if not input_path or not input_path.startswith(prefix) or input_path not in names:
plan.skip_reason = "input_unavailable"
return plan
finalise_only = bool(job.get("finalise_only"))
# Bring-your-own-instrumental jobs never ran separation, so "re-separate"
# isn't part of their pipeline — leave whatever stems they have.
if job.get("existing_instrumental_gcs_path"):
plan.stems_purgeable = False
plan.stems_note = "existing_instrumental"
for name, size, generation in entries:
if not name.startswith(prefix): # defence in depth: never outside jobs/{id}/
continue
action, category = classify_file(
name[len(prefix):], finalise_only=finalise_only, stems_purgeable=plan.stems_purgeable,
)
if action == PURGE:
plan.purge.append((name, size, category))
plan.generations[name] = generation
else:
plan.kept_bytes += size
return plan
def assert_deletable(path: str) -> None:
"""Hard guard: retention code only ever deletes inside a jobs/{id}/ folder."""
parts = path.split("/")
if len(parts) < 3 or parts[0] != "jobs" or not parts[1] or path.startswith(DELETION_LOG_PREFIX):
raise ValueError(f"refusing to delete outside jobs/{{id}}/: {path}")
def log_category(category: str) -> str:
"""Category label used in the deletion log (finals, review-audio, screens-mov, ...)."""
return category.replace("_", "-")
class DeletionLog:
"""Append-only JSONL audit log of one run's deletions, flushed to GCS in batches.
``storage-retention/deletion-logs/<run-ts>-<mode>.jsonl`` holds one line per
attempted delete; it is re-uploaded (whole) after every batch so a crash
mid-run still leaves a complete record of what was deleted up to the last
flush (the batch in flight is at most ``flush_every`` lines / one job).
"""
def __init__(self, storage, run_ts: datetime, mode: str, flush_every: int = 200):
self.storage = storage
self.mode = mode
self.run_id = f"{run_ts.strftime('%Y%m%dT%H%M%SZ')}-{mode}"
self.path = f"{DELETION_LOG_PREFIX}/{self.run_id}.jsonl"
self.summary_path = f"{DELETION_LOG_PREFIX}/{self.run_id}.summary.json"
self.flush_every = flush_every
self._lines: List[str] = []
self._unflushed = 0
self.totals: Counter = Counter()
self.counts: Counter = Counter()
self.failures = 0
self.jobs: set = set()
# Set when the audit log couldn't be written: callers stop deleting.
self.flush_error: Optional[str] = None
def record(self, job_id: str, path: str, size: int, generation, category: str,
result: str, error: Optional[str] = None) -> None:
import json
entry = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"run_id": self.run_id,
"mode": self.mode,
"job_id": job_id,
"path": path,
"size_bytes": int(size or 0),
"generation": str(generation) if generation is not None else None,
"category": category,
"result": result,
}
if error:
entry["error"] = error[:500]
self._lines.append(json.dumps(entry, ensure_ascii=False))
self._unflushed += 1
if result == "deleted":
self.totals[category] += int(size or 0)
self.counts[category] += 1
self.jobs.add(job_id)
elif result == "failed":
self.failures += 1
if self._unflushed >= self.flush_every:
self.flush()
def flush(self) -> None:
if not self._lines:
return
try:
self.storage.upload_text(self.path, "\n".join(self._lines) + "\n", content_type="application/x-ndjson")
self._unflushed = 0
self.flush_error = None
except Exception as e: # noqa: BLE001 - recorded; the run stops deleting
self.flush_error = str(e)
logger.error(f"storage retention: deletion log flush failed ({self.path}): {e}")
def write_summary(self, extra: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
summary = {
"run_id": self.run_id,
"mode": self.mode,
"deletion_log": self.path,
"objects_deleted": sum(self.counts.values()),
"jobs": len(self.jobs),
"bytes_deleted": sum(self.totals.values()),
"gib_deleted": round(sum(self.totals.values()) / 2**30, 3),
"bytes_by_category": dict(self.totals),
"objects_by_category": dict(self.counts),
"failures": self.failures,
"log_flush_error": self.flush_error,
"written_at": datetime.now(timezone.utc).isoformat(),
**(extra or {}),
}
self.flush()
try:
self.storage.upload_json(self.summary_path, summary)
except Exception as e: # noqa: BLE001
logger.error(f"storage retention: summary write failed ({self.summary_path}): {e}")
return summary
def orphan_candidates(entries: Iterable[Dict[str, Any]], known_ids: set) -> Dict[str, List[Dict[str, Any]]]:
"""Group ``jobs/{id}/...`` objects whose id has no job record."""
folders: Dict[str, List[Dict[str, Any]]] = {}
for meta in entries:
parts = meta["name"].split("/")
if len(parts) < 3 or parts[0] != "jobs" or not parts[1]:
continue
if parts[1] in known_ids:
continue
folders.setdefault(parts[1], []).append(meta)
return folders
def plan_orphan_folder(job_id: str, objects: List[Dict[str, Any]], now: datetime,
quiet_days: int = ORPHAN_QUIET_DAYS) -> Dict[str, Any]:
"""Keep ``input/``; everything else in an orphan folder is deleted (if quiet)."""
prefix = f"jobs/{job_id}/"
latest = None
for meta in objects:
updated = _parse_ts(meta.get("updated"))
if updated and (latest is None or updated > latest):
latest = updated
keep, purge = [], []
for meta in objects:
if not meta["name"].startswith(prefix):
continue
(keep if meta["name"][len(prefix):].startswith("input/") else purge).append(meta)
skip = None
if latest is None or now - latest < timedelta(days=quiet_days):
skip = "recently_modified"
return {
"job_id": job_id,
"latest_update": latest.isoformat() if latest else None,
"skip_reason": skip,
"purge": purge,
"keep": keep,
"purge_bytes": sum(int(m.get("size") or 0) for m in purge),
"keep_bytes": sum(int(m.get("size") or 0) for m in keep),
}
def file_url_deletions(file_urls: Dict[str, Any], purged_paths: Iterable[str]) -> List[str]:
"""Firestore field paths under ``file_urls`` that reference purged blobs."""
purged = set(purged_paths)
def norm(value: str) -> str:
return value.split("/", 3)[-1] if value.startswith("gs://") else value
out: List[str] = []
for category, entries in (file_urls or {}).items():
if isinstance(entries, dict):
for key, value in entries.items():
if isinstance(value, str) and norm(value) in purged and _safe_key(category) and _safe_key(key):
out.append(f"file_urls.{category}.{key}")
elif isinstance(entries, str) and norm(entries) in purged and _safe_key(category):
out.append(f"file_urls.{category}")
return out
_SAFE_KEY = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
def _safe_key(key: str) -> bool:
return bool(_SAFE_KEY.match(str(key)))
# --------------------------------------------------------------------------------
# Service
# --------------------------------------------------------------------------------
def _run_in_transaction(db, fn):
"""Run ``fn(transaction)`` in a Firestore transaction (retried on contention)."""
from google.cloud import firestore
return firestore.transactional(fn)(db.transaction())
_PROJECTION = [
"job_id", "status", "timeline", "updated_at", "finalise_only", "prep_only", "theme_id",
"storage_purge.status", "state_data.instrumental_selection",
"outputs_deleted_at", "tenant_id", "input_media_gcs_path", "file_urls",
"existing_instrumental_gcs_path", "renders_purged_at", "stems_purged_at",
"state_data.visibility_change_in_progress", "state_data.admin_rerender",
"state_data.theme_rerender", "state_data.regenerate",
"state_data.youtube_upload_queued", f"state_data.{PURGE_IN_PROGRESS_KEY}",
]
class StorageRetentionService:
def __init__(self, db=None, storage=None, settings=None, job_manager=None):
from backend.config import get_settings
self.settings = settings or get_settings()
if storage is None:
from backend.services.storage_service import StorageService
storage = StorageService()
self.storage = storage
if db is None:
from backend.services.firestore_service import FirestoreService
db = FirestoreService().db
self.db = db
self._job_manager = job_manager
@property
def jobs_collection(self):
return self.db.collection(self.settings.firestore_collection)
# --- run ----------------------------------------------------------------------
def run(
self,
dry_run: Optional[bool] = None,
job_ids: Optional[List[str]] = None,
max_jobs: Optional[int] = None,
min_age_days: Optional[int] = None,
include_orphans: bool = False,
report_path: Optional[str] = None,
now: Optional[datetime] = None,
) -> Dict[str, Any]:
"""Plan (and unless dry-run, execute) one retention pass. Returns the report.
- ``dry_run`` defaults to settings.storage_retention_dry_run (True).
- ``job_ids`` scopes the pass to those jobs (no cursor).
- Dry runs without ``max_jobs`` cover every completed job (full report);
real runs purge at most ``max_jobs`` (settings default) per pass,
resuming from the stored cursor.
"""
started = time.time()
now = now or datetime.now(timezone.utc)
dry_run = self.settings.storage_retention_dry_run if dry_run is None else bool(dry_run)
min_age = self.settings.storage_retention_min_age_days if min_age_days is None else int(min_age_days)
excluded = [t.strip() for t in (self.settings.storage_retention_excluded_tenants or "").split(",") if t.strip()]
if max_jobs is None and not dry_run and not job_ids:
max_jobs = self.settings.storage_retention_max_jobs_per_run
use_cursor = not job_ids and not dry_run
report: Dict[str, Any] = {
"policy_version": POLICY_VERSION,
"dry_run": dry_run,
"started_at": now.isoformat(),
"min_age_days": min_age,
"max_jobs": max_jobs,
"excluded_tenants": excluded,
"scoped_job_ids": job_ids or None,
"jobs": [],
"skipped": Counter(),
"errors": [],
}
totals: Counter = Counter()
deletion_log = None if dry_run else DeletionLog(self.storage, now, MODE_JOB_PURGE)
if deletion_log:
report["deletion_log"] = deletion_log.path
report["deletion_summary"] = deletion_log.summary_path
processed = 0
scanned = 0
last_id = None
exhausted = True
for job in self._iter_jobs(job_ids, use_cursor):
if max_jobs is not None and processed >= max_jobs:
exhausted = False
break
scanned += 1
last_id = job.get("job_id")
reason = job_skip_reason(job, now, min_age, excluded)
if reason is None and self._already_purged(job):
reason = "already_purged"
if reason:
report["skipped"][reason] += 1
continue
try:
listing = self.storage.list_blob_meta(f"jobs/{job['job_id']}/")
plan = plan_job(job, listing)
except Exception as e: # noqa: BLE001 - one bad job never stops the pass
logger.exception(f"[job:{job.get('job_id')}] storage retention: planning failed")
report["errors"].append({"job_id": job.get("job_id"), "error": str(e)})
continue
if plan.skip_reason:
report["skipped"][plan.skip_reason] += 1
continue
if not plan.purge:
report["skipped"]["nothing_to_purge"] += 1
continue
entry = {
"job_id": plan.job_id,
"tenant_id": job.get("tenant_id") or None,
"completed_at": (completed_at(job) or now).isoformat(),
"purge_bytes": plan.purge_bytes,
"kept_bytes": plan.kept_bytes,
"bytes_by_category": plan.bytes_by_category(),
"stems_kept_reason": plan.stems_note,
"files": [{"path": p, "bytes": s, "category": c} for p, s, c in plan.purge],
}
if not dry_run:
try:
entry["result"] = self._execute(job["job_id"], plan, now, min_age, excluded, deletion_log)
except Exception as e: # noqa: BLE001
logger.exception(f"[job:{plan.job_id}] storage retention: purge failed")
entry["result"] = {"status": "error", "error": str(e)}
report["errors"].append({"job_id": plan.job_id, "error": str(e)})
report["jobs"].append(entry)
if deletion_log and deletion_log.flush_error:
# The audit log is a required safety record: no more deletes.
report["errors"].append({"job_id": plan.job_id,
"error": f"deletion log not persisted, run stopped: {deletion_log.flush_error}"})
exhausted = False
break
if not dry_run and entry["result"].get("status") != "purged":
continue
processed += 1
for category, size in plan.bytes_by_category().items():
totals[category] += size
if use_cursor:
self._save_cursor(None if exhausted else last_id)
if deletion_log:
report["deletion_totals"] = deletion_log.write_summary(
{"report_path": report_path or self.default_report_path(now, dry_run)})
report["skipped"] = dict(report["skipped"])
report["summary"] = {
"jobs_scanned": scanned,
"jobs_to_purge" if dry_run else "jobs_purged": processed,
"bytes_total": sum(totals.values()),
"gib_total": round(sum(totals.values()) / 2**30, 2),
"gib_by_category": {k: round(v / 2**30, 2) for k, v in sorted(totals.items())},
"bytes_by_category": dict(totals),
"duration_seconds": round(time.time() - started, 1),
}
if include_orphans:
try:
report["orphans"] = self.orphan_job_folders()
except Exception as e: # noqa: BLE001
report["orphans"] = {"error": str(e)}
report["report_path"] = report_path or self.default_report_path(now, dry_run)
try:
self.storage.upload_json(report["report_path"], report)
except Exception as e: # noqa: BLE001
logger.error(f"storage retention: failed to write report {report['report_path']}: {e}")
report["report_write_error"] = str(e)
s = report["summary"]
logger.info(
f"STORAGE_RETENTION {'DRY-RUN' if dry_run else 'RUN'} complete: scanned={scanned} "
f"{'would_purge' if dry_run else 'purged'}={processed} jobs, {s['gib_total']} GiB "
f"by_category={s['gib_by_category']} skipped={report['skipped']} "
f"errors={len(report['errors'])} report=gs://{self.settings.gcs_bucket_name}/{report['report_path']}"
)
return report
@staticmethod
def default_report_path(now: datetime, dry_run: bool) -> str:
return f"{REPORT_PREFIX}/{now.strftime('%Y%m%dT%H%M%SZ')}-{'dry-run' if dry_run else 'run'}.json"
# --- helpers ------------------------------------------------------------------
def _already_purged(self, job: Dict[str, Any]) -> bool:
"""Skip the GCS listing for jobs already purged since their last completion."""
if ((job.get("storage_purge") or {}).get("status")) == "pending":
return False # an interrupted purge: finish it
renders = _parse_ts(job.get("renders_purged_at"))
if not renders:
return False
done = completed_at(job)
if done and done > renders:
return False # regenerated since — eligible again after its own window
stems = _parse_ts(job.get("stems_purged_at"))
stems_done = stems is not None or bool(job.get("existing_instrumental_gcs_path"))
return stems_done
def _iter_jobs(self, job_ids: Optional[List[str]], use_cursor: bool):
if job_ids:
for job_id in job_ids:
snap = self.jobs_collection.document(job_id).get()
if snap.exists:
data = snap.to_dict() or {}
data.setdefault("job_id", snap.id)
yield data
return
from google.cloud.firestore_v1.base_query import FieldFilter
cursor = self._load_cursor() if use_cursor else None
while True:
query = (
self.jobs_collection
.where(filter=FieldFilter("status", "==", "complete"))
.order_by("__name__")
.select(_PROJECTION)
.limit(SCAN_PAGE_SIZE)
)
if cursor:
query = query.start_after({"__name__": self.jobs_collection.document(cursor)})
docs = list(query.stream())
for snap in docs:
data = snap.to_dict() or {}
data.setdefault("job_id", snap.id)
data["job_id"] = data.get("job_id") or snap.id
yield data
if len(docs) < SCAN_PAGE_SIZE:
return
cursor = docs[-1].id
def _state_ref(self):
return self.db.collection(STATE_COLLECTION).document(STATE_DOC)
def _load_cursor(self) -> Optional[str]:
try:
snap = self._state_ref().get()
return (snap.to_dict() or {}).get("cursor_job_id") if snap.exists else None
except Exception as e: # noqa: BLE001
logger.warning(f"storage retention: couldn't load cursor: {e}")
return None
def _save_cursor(self, job_id: Optional[str]) -> None:
try:
self._state_ref().set(
{"cursor_job_id": job_id, "updated_at": datetime.now(timezone.utc)}, merge=True,
)
except Exception as e: # noqa: BLE001
logger.warning(f"storage retention: couldn't save cursor: {e}")
def _claim(self, job_id: str, plan: "JobPlan", now: datetime, min_age: int, excluded: List[str]) -> bool:
"""Atomically re-check eligibility on the live doc and mark the purge in progress.
The purge markers (``renders_purged_at`` / ``stems_purged_at``) and a
PENDING manifest are written HERE, before anything is deleted: if the
run dies mid-way, regenerate still knows to rebuild (and re-separate),
and the next pass finishes the job (``storage_purge.status == pending``).
"""
ref = self.jobs_collection.document(job_id)
def claim(transaction):
snap = ref.get(transaction=transaction)
if not snap.exists:
return False
data = snap.to_dict() or {}
data.setdefault("job_id", job_id)
if job_skip_reason(data, now, min_age, excluded):
return False
update: Dict[str, Any] = {
f"state_data.{PURGE_IN_PROGRESS_KEY}": now.isoformat(),
"storage_purge": {
"status": "pending",
"started_at": now.isoformat(),
"policy_version": POLICY_VERSION,
"planned_bytes": plan.purge_bytes,
"planned_files": len(plan.purge),
},
}
if plan.purges_renders:
update["renders_purged_at"] = now
if plan.purges_stems:
update["stems_purged_at"] = now
transaction.update(ref, update)
return True
return _run_in_transaction(self.db, claim)
def _execute(self, job_id: str, plan: JobPlan, now: datetime, min_age: int, excluded: List[str],
deletion_log: Optional["DeletionLog"] = None) -> Dict[str, Any]:
from google.cloud.firestore_v1 import DELETE_FIELD
if not self._claim(job_id, plan, now, min_age, excluded):
return {"status": "skipped", "reason": "no_longer_eligible"}
ref = self.jobs_collection.document(job_id)
deleted: List[Tuple[str, int, str]] = []
failures: List[Dict[str, str]] = []
try:
for path, size, category in plan.purge:
if not path.startswith(f"jobs/{job_id}/"):
continue
generation = plan.generations.get(path)
try:
assert_deletable(path)
self.storage.delete_file(path, ignore_missing=True, if_generation_match=generation)
deleted.append((path, size, category))
if deletion_log:
deletion_log.record(job_id, path, size, generation, log_category(category), "deleted")
except Exception as e: # noqa: BLE001
failures.append({"path": path, "error": str(e)})
if deletion_log:
deletion_log.record(job_id, path, size, generation, log_category(category), "failed", str(e))
if deletion_log:
deletion_log.flush()
snap = ref.get()
file_urls = (snap.to_dict() or {}).get("file_urls") or {} if snap.exists else {}
update: Dict[str, Any] = {f"state_data.{PURGE_IN_PROGRESS_KEY}": DELETE_FIELD}
for field_path in file_url_deletions(file_urls, [p for p, _, _ in deleted]):
update[field_path] = DELETE_FIELD
by_category: Counter = Counter()
for _, size, category in deleted:
by_category[category] += size
if any(c in RENDER_CATEGORIES for _, _, c in deleted):
update["renders_purged_at"] = now
if any(c in STEM_CATEGORIES for _, _, c in deleted):
update["stems_purged_at"] = now
update["storage_purge"] = {
"status": "complete",
"purged_at": now.isoformat(),
"policy_version": POLICY_VERSION,
"bytes": sum(by_category.values()),
"bytes_by_category": dict(by_category),
"files": [{"path": p, "bytes": s, "category": c,
"generation": str(plan.generations.get(p)) if plan.generations.get(p) is not None else None}
for p, s, c in deleted],
"failures": failures,
"deletion_log": deletion_log.path if deletion_log else None,
}
ref.update(update)
except Exception:
try:
ref.update({f"state_data.{PURGE_IN_PROGRESS_KEY}": DELETE_FIELD})
except Exception: # noqa: BLE001
pass
raise
try:
from backend.services.firestore_service import log_to_job
log_to_job(
job_id, "storage-retention", "INFO",
f"Storage retention purged {len(deleted)} regenerable files "
f"({sum(by_category.values()) / 2**20:.0f} MiB); regenerate on demand",
{"bytes_by_category": dict(by_category), "failures": failures},
)
except Exception: # noqa: BLE001
pass
return {
"status": "purged" if deleted else "skipped",
"deleted": len(deleted),
"failures": failures,
}
# --- orphan folders -----------------------------------------------------------
def _known_job_ids(self) -> set:
return {snap.id for snap in self.jobs_collection.select(["status"]).stream()}
def orphan_job_folders(self) -> Dict[str, Any]:
"""``jobs/{id}/`` folders with no Firestore job doc (report only)."""
known = self._known_job_ids()
sizes: Counter = Counter()
for name, size in self.storage.list_files_with_sizes("jobs/"):
parts = name.split("/")
if len(parts) > 2 and parts[1] not in known:
sizes[parts[1]] += size
total = sum(sizes.values())
return {
"folders": len(sizes),
"gib_total": round(total / 2**30, 2),
"largest": [{"job_id": k, "gib": round(v / 2**30, 2)} for k, v in sizes.most_common(20)],
}
def _record_holder(self, job_id: str) -> Optional[str]:
"""Collection that (still) has a record for this folder id, checked live."""
for name in ORPHAN_RECORD_COLLECTIONS:
if self.db.collection(name).document(job_id).get().exists:
return name
return None
def purge_orphans(
self,
dry_run: bool = True,
max_folders: Optional[int] = None,
quiet_days: int = ORPHAN_QUIET_DAYS,
report_path: Optional[str] = None,
now: Optional[datetime] = None,
) -> Dict[str, Any]:
"""Delete everything but ``input/`` from job folders that have no job record.
Candidates come from one bucket listing vs. the ``jobs`` collection; each
folder is then re-checked LIVE before acting: no record in any of
ORPHAN_RECORD_COLLECTIONS, re-listed fresh, and no object modified in the
last ``quiet_days`` days. Dry-run by default.
"""
started = time.time()
now = now or datetime.now(timezone.utc)
known = self._known_job_ids()
candidates = orphan_candidates(self.storage.list_blob_meta("jobs/"), known)
deletion_log = None if dry_run else DeletionLog(self.storage, now, MODE_ORPHAN)
report: Dict[str, Any] = {
"mode": MODE_ORPHAN,
"dry_run": dry_run,
"started_at": now.isoformat(),
"quiet_days": quiet_days,
"record_collections": list(ORPHAN_RECORD_COLLECTIONS),
"candidates": len(candidates),
"folders": [],
"skipped": Counter(),
"not_orphans": [],
"errors": [],
}
if deletion_log:
report["deletion_log"] = deletion_log.path
report["deletion_summary"] = deletion_log.summary_path
acted = 0
purge_bytes = keep_bytes = skipped_bytes = 0
by_ext: Counter = Counter()
for job_id in sorted(candidates):
if max_folders is not None and acted >= max_folders:
report["skipped"]["batch_limit"] += 1
continue
try:
holder = self._record_holder(job_id)
if holder:
report["skipped"]["has_record"] += 1
report["not_orphans"].append({"job_id": job_id, "collection": holder})
continue
fresh = self.storage.list_blob_meta(f"jobs/{job_id}/")
plan = plan_orphan_folder(job_id, fresh, now, quiet_days)
except Exception as e: # noqa: BLE001
report["errors"].append({"job_id": job_id, "error": str(e)})
continue
if plan["skip_reason"]:
report["skipped"][plan["skip_reason"]] += 1
skipped_bytes += plan["purge_bytes"] + plan["keep_bytes"]
continue
if not plan["purge"]:
report["skipped"]["nothing_to_purge"] += 1
keep_bytes += plan["keep_bytes"]
continue
acted += 1
purge_bytes += plan["purge_bytes"]
keep_bytes += plan["keep_bytes"]
for meta in plan["purge"]:
rel = meta["name"].split("/", 2)[2]
by_ext[rel.split("/", 1)[0] if "/" in rel else "(root)"] += int(meta.get("size") or 0)
folder = {
"job_id": job_id, "latest_update": plan["latest_update"],
"purge_bytes": plan["purge_bytes"], "keep_bytes": plan["keep_bytes"],
"purge_objects": len(plan["purge"]), "kept_input_objects": len(plan["keep"]),
}
if not dry_run:
deleted = failed = 0
for meta in plan["purge"]:
path, size, gen = meta["name"], int(meta.get("size") or 0), meta.get("generation")
try:
assert_deletable(path)
self.storage.delete_file(path, ignore_missing=True, if_generation_match=gen)
deletion_log.record(job_id, path, size, gen, "orphan-nonInput", "deleted")
deleted += 1
except Exception as e: # noqa: BLE001
deletion_log.record(job_id, path, size, gen, "orphan-nonInput", "failed", str(e))
failed += 1
deletion_log.flush()
folder.update({"deleted": deleted, "failed": failed})
report["folders"].append(folder)
if deletion_log and deletion_log.flush_error:
report["errors"].append({"job_id": job_id,
"error": f"deletion log not persisted, run stopped: {deletion_log.flush_error}"})
break
report["skipped"] = dict(report["skipped"])
report["summary"] = {
"folders_acted" if not dry_run else "folders_to_purge": acted,
"gib_to_delete" if dry_run else "gib_deleted": round(purge_bytes / 2**30, 2),
"gib_input_kept": round(keep_bytes / 2**30, 2),
"gib_skipped_recent": round(skipped_bytes / 2**30, 2),
"gib_by_top_level_dir": {k: round(v / 2**30, 2) for k, v in by_ext.most_common()},
"duration_seconds": round(time.time() - started, 1),
}
report["report_path"] = report_path or (
f"{REPORT_PREFIX}/{now.strftime('%Y%m%dT%H%M%SZ')}-orphans-{'dry-run' if dry_run else 'run'}.json")
if deletion_log:
report["deletion_totals"] = deletion_log.write_summary({"report_path": report["report_path"]})
try:
self.storage.upload_json(report["report_path"], report)
except Exception as e: # noqa: BLE001
report["report_write_error"] = str(e)
logger.info(
f"STORAGE_RETENTION ORPHANS {'DRY-RUN' if dry_run else 'RUN'}: candidates={len(candidates)} "
f"summary={report['summary']} skipped={report['skipped']} errors={len(report['errors'])} "
f"report=gs://{self.settings.gcs_bucket_name}/{report['report_path']}"
)
return report
+34 -2
View File
@@ -298,7 +298,8 @@ class StorageService:
logger.error(f"Error generating signed {method} URL for {blob_path}: {e}")
raise
def delete_file(self, blob_path: str, ignore_missing: bool = False) -> bool:
def delete_file(self, blob_path: str, ignore_missing: bool = False,
if_generation_match: Optional[int] = None) -> bool:
"""Delete a file from GCS.
Args:
@@ -314,7 +315,12 @@ class StorageService:
"""
try:
blob = self.bucket.blob(blob_path)
blob.delete()
if if_generation_match is not None:
# Only delete the exact version that was planned/logged; a newer
# write since then raises PreconditionFailed.
blob.delete(if_generation_match=if_generation_match)
else:
blob.delete()
logger.info(f"Deleted gs://{settings.gcs_bucket_name}/{blob_path}")
return True
except NotFound:
@@ -365,6 +371,32 @@ class StorageService:
logger.error(f"Error listing files with prefix {prefix}: {e}")
raise
def list_files_with_sizes(self, prefix: str) -> list:
"""List ``(name, size_bytes)`` for every object under ``prefix``."""
try:
return [(blob.name, int(blob.size or 0)) for blob in self.bucket.list_blobs(prefix=prefix)]
except Exception as e:
logger.error(f"Error listing files with prefix {prefix}: {e}")
raise
def list_blob_meta(self, prefix: str) -> list:
"""List ``{name, size, generation, updated}`` for every object under ``prefix``."""
try:
return [
{"name": b.name, "size": int(b.size or 0), "generation": b.generation, "updated": b.updated}
for b in self.bucket.list_blobs(prefix=prefix)
]
except Exception as e:
logger.error(f"Error listing files with prefix {prefix}: {e}")
raise
def upload_text(self, destination_path: str, text: str, content_type: str = "text/plain") -> str:
"""Upload a text object (overwrites)."""
blob = self.bucket.blob(destination_path)
blob.cache_control = NO_STORE_CACHE_CONTROL
blob.upload_from_string(text, content_type=content_type)
return destination_path
def get_file_size(self, blob_path: str) -> Optional[int]:
"""Size in bytes of a GCS object, or None if it doesn't exist."""
blob = self.bucket.get_blob(blob_path)
+3
View File
@@ -153,6 +153,9 @@ def sanitize_style_params(
for section in ("intro", "end"):
if "existing_image" in styles[section]:
styles[section]["existing_image"] = None
# Optional on/off switch for including the screen in videos (absent = on).
if "enabled" in styles[section] and not isinstance(styles[section]["enabled"], bool):
raise TenantValidationError(f"{section}.enabled must be true or false.")
for section, field in IMAGE_FIELDS:
value = styles[section].get(field)
+265
View File
@@ -0,0 +1,265 @@
"""
Keep a tenant's tracks in step with its theme after a theme edit.
A job snapshots its theme at creation (``jobs/{id}/style/style_params.json`` +
``style_assets``) and renders from that copy, so a theme edit used to reach only
jobs created afterwards — tracks already in progress (and Edits of finished
tracks) still came out in the old look.
On every theme save, tracks that haven't started rendering get the new theme:
* their style snapshot is replaced, so anything rendered from now on (lyrics
video, screens not yet generated) uses it;
* if their title/end screens may already exist, ``state_data.theme_screens_stale``
is set. When the render worker picks the job up it diverts once through the
screens worker (LYRICS_COMPLETE + ``regen_restore_status=review_complete``,
the same bounce the theme re-render uses), which regenerates the screens and
re-triggers the render. Doing this at render time — rather than right away —
never disturbs a user who is in the middle of reviewing.
Finished tracks can't be refreshed without re-rendering, so they are reported
as "outdated" (theme saved after their snapshot) for the UI to offer a
re-render (``outdated_jobs`` / ``rerender_outdated``).
"""
import logging
from datetime import datetime, timezone
from typing import Dict, List, Optional
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
from backend.models.job import JobStatus
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
logger = logging.getLogger(__name__)
THEME_SCREENS_STALE_KEY = "theme_screens_stale"
# Not yet rendering: swapping the style snapshot is safe. RENDER_PENDING_CAPACITY
# re-enters the render worker from scratch on its auto-retry. REVIEW_COMPLETE is
# excluded — the render worker may already be loading the old style.
_PRE_SCREENS_STATUSES = frozenset({
JobStatus.PENDING, JobStatus.SEARCHING_AUDIO, JobStatus.AWAITING_AUDIO_SELECTION,
JobStatus.DOWNLOADING_AUDIO, JobStatus.DOWNLOAD_PENDING_RETRY, JobStatus.DOWNLOADING,
JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT, JobStatus.AUDIO_EDIT_COMPLETE,
JobStatus.AWAITING_DURATION_CONFIRM, JobStatus.SEPARATING_STAGE1, JobStatus.SEPARATING_STAGE2,
JobStatus.AUDIO_COMPLETE, JobStatus.TRANSCRIBING, JobStatus.CORRECTING,
JobStatus.LYRICS_COMPLETE,
})
# Screens may already exist (or are being made from the old snapshot right now).
_SCREENS_MADE_STATUSES = frozenset({
JobStatus.GENERATING_SCREENS, JobStatus.APPLYING_PADDING, JobStatus.AWAITING_REVIEW,
JobStatus.IN_REVIEW, JobStatus.RENDER_PENDING_CAPACITY,
})
REFRESHABLE_STATUSES = _PRE_SCREENS_STATUSES | _SCREENS_MADE_STATUSES
def _status_value(status) -> str:
return status.value if hasattr(status, "value") else str(status)
def _as_utc(value) -> Optional[datetime]:
if value is None:
return None
if isinstance(value, str):
try:
value = datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
return None
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value
def theme_updated_at(theme_id: str, storage: Optional[StorageService] = None) -> Optional[datetime]:
"""When the theme's style was last saved (its style_params.json write time)."""
from backend.services.theme_service import THEMES_PREFIX
storage = storage or StorageService()
try:
blob = storage.bucket.get_blob(f"{THEMES_PREFIX}/{theme_id}/style_params.json")
except Exception as e:
logger.warning(f"Couldn't read theme '{theme_id}' timestamp: {e}")
return None
return _as_utc(blob.updated) if blob is not None else None
def job_theme_applied_at(job) -> Optional[datetime]:
"""When the job's style snapshot was taken (creation unless re-snapshotted)."""
return _as_utc(getattr(job, "theme_applied_at", None)) or _as_utc(getattr(job, "created_at", None))
def snapshot_theme_update(job, theme_id: str) -> Dict:
"""Copy ``theme_id``'s current style onto the job; return the Firestore fields to set.
Writes the job's style folder (GCS) immediately — callers apply the returned
fields themselves (often inside a larger update).
"""
from backend.api.routes.file_upload import _prepare_theme_for_job
style_params_path, style_assets, _ = _prepare_theme_for_job(
job.job_id, theme_id, getattr(job, "color_overrides", None) or None
)
if not style_params_path:
raise ValueError(f"Theme '{theme_id}' has no style to apply.")
return {
"theme_id": theme_id,
"style_params_gcs_path": style_params_path,
"style_assets": style_assets,
"theme_applied_at": datetime.now(timezone.utc),
}
def refresh_inflight_jobs(tenant_id: str, theme_id: str, job_manager: Optional[JobManager] = None) -> Dict[str, int]:
"""Apply the just-saved theme to every tenant track that hasn't started rendering.
Returns ``{"updated": n, "failed": m}``. Best-effort per job: one bad job
never blocks the save or the other jobs.
"""
job_manager = job_manager or JobManager()
updated = failed = 0
jobs = job_manager.list_jobs(tenant_id=tenant_id, limit=1000)
for job in jobs:
if job.status not in REFRESHABLE_STATUSES or getattr(job, "theme_id", None) != theme_id:
continue
try:
update = snapshot_theme_update(job, theme_id)
if job.status in _SCREENS_MADE_STATUSES:
update[f"state_data.{THEME_SCREENS_STALE_KEY}"] = True
update["timeline"] = ArrayUnion([{
"status": _status_value(job.status),
"timestamp": datetime.now(timezone.utc).isoformat(),
"message": "Theme updated: this track will use the new look",
}])
if _update_if_status(job_manager, job.job_id, update, REFRESHABLE_STATUSES):
updated += 1
except Exception as e:
failed += 1
logger.error(f"[job:{job.job_id}] Theme refresh failed: {e}", exc_info=True)
logger.info(f"Tenant '{tenant_id}' theme saved: refreshed {updated} in-progress tracks ({failed} failed)")
return {"updated": updated, "failed": failed}
def _update_if_status(job_manager: JobManager, job_id: str, update: Dict, allowed) -> bool:
"""Apply ``update`` iff the job is still in one of ``allowed`` statuses (transactional)."""
from backend.services.theme_rerender_service import RerenderConflictError, claim_for_rerender
try:
claim_for_rerender(job_manager.firestore.db, job_id, update, {_status_value(s) for s in allowed})
return True
except RerenderConflictError:
logger.info(f"[job:{job_id}] Theme refresh skipped: job moved on")
return False
async def divert_for_stale_screens(job, job_manager: JobManager, storage: Optional[StorageService] = None) -> bool:
"""Render-worker hook: regenerate theme-stale screens before rendering.
Returns True when the job was handed to the screens worker (the render worker
must stop; the screens worker re-triggers it). Returns False to render now.
"""
state_data = job.state_data or {}
if not state_data.get(THEME_SCREENS_STALE_KEY) or job.status != JobStatus.REVIEW_COMPLETE:
return False
from backend.services.theme_rerender_service import (
RerenderConflictError,
claim_for_rerender,
delete_regenerated_artifacts,
)
job_id = job.job_id
now = datetime.now(timezone.utc)
update = {
"status": JobStatus.LYRICS_COMPLETE.value,
f"state_data.{THEME_SCREENS_STALE_KEY}": DELETE_FIELD,
"state_data.regen_restore_status": JobStatus.REVIEW_COMPLETE.value,
"state_data.audio_complete": True,
"state_data.lyrics_complete": True,
"state_data.screens_progress": DELETE_FIELD,
"file_urls.screens": DELETE_FIELD,
"updated_at": now,
"timeline": ArrayUnion([{
"status": JobStatus.LYRICS_COMPLETE.value,
"timestamp": now.isoformat(),
"message": "Regenerating title and end screens with the updated theme",
}]),
}
try:
claim_for_rerender(job_manager.firestore.db, job_id, update, {JobStatus.REVIEW_COMPLETE.value})
except RerenderConflictError:
# Another trigger already moved the job on (e.g. a duplicate dispatch diverted it).
logger.info(f"[job:{job_id}] Stale-screens divert: job no longer review_complete, skipping render")
return True
# Old screens, and (for an Edit of a finished track) old finals MOVs the
# encoder would otherwise splice back in.
delete_regenerated_artifacts(storage or StorageService(), job_id)
from backend.services.worker_service import get_worker_service
if await get_worker_service().trigger_screens_worker(job_id):
logger.info(f"[job:{job_id}] Theme changed since screens were made: regenerating before render")
return True
# Couldn't hand off: put the job back and render with fresh screens on the
# next attempt (flag restored) rather than stranding it.
logger.error(f"[job:{job_id}] Stale-screens divert: failed to trigger screens worker, restoring review_complete")
job_manager.update_job(job_id, {
"status": JobStatus.REVIEW_COMPLETE.value,
"state_data.regen_restore_status": DELETE_FIELD,
f"state_data.{THEME_SCREENS_STALE_KEY}": True,
})
raise RuntimeError("Couldn't regenerate screens for the updated theme")
def outdated_jobs(tenant_id: str, theme_id: str, user_email: Optional[str],
job_manager: Optional[JobManager] = None,
storage: Optional[StorageService] = None) -> Dict:
"""Finished tracks made with an older version of the theme that can be re-rendered.
``user_email`` scopes to the caller's own tracks (None = all, for admins).
"""
from backend.services.theme_rerender_service import validate_rerender
job_manager = job_manager or JobManager()
updated_at = theme_updated_at(theme_id, storage)
result = {"theme_updated_at": updated_at.isoformat() if updated_at else None, "job_ids": []}
if updated_at is None:
return result
# Same (tenant_id, user_email) query shape as the portal's job list, so it
# needs no extra composite index; status is filtered here.
jobs = job_manager.list_jobs(tenant_id=tenant_id, user_email=user_email, limit=1000)
for job in jobs:
if job.status != JobStatus.COMPLETE or getattr(job, "theme_id", None) != theme_id:
continue
applied = job_theme_applied_at(job)
if applied is None or applied >= updated_at:
continue
if validate_rerender(job) is None:
result["job_ids"].append(job.job_id)
return result
def edit_theme_update(job, screens_regenerating: bool) -> Dict:
"""Fields that make an Edit of a finished tenant track use the current theme.
Empty for non-tenant jobs or when the track already has the current theme.
``screens_regenerating``: the Edit already regenerates the screens (metadata
change), which will pick up the new snapshot — no stale flag needed.
"""
tenant_id = getattr(job, "tenant_id", None)
if not tenant_id or not getattr(job, "theme_id", None):
return {}
from backend.services.tenant_admin_service import _theme_id_for
from backend.services.tenant_service import get_tenant_service
config = get_tenant_service().get_tenant_config(tenant_id)
if config is None:
return {}
theme_id = _theme_id_for(config)
if theme_id != job.theme_id:
return {}
updated_at = theme_updated_at(theme_id)
applied = job_theme_applied_at(job)
if updated_at is None or (applied is not None and applied >= updated_at):
return {}
update = snapshot_theme_update(job, theme_id)
if not screens_regenerating:
update[f"state_data.{THEME_SCREENS_STALE_KEY}"] = True
logger.info(f"[job:{job.job_id}] Edit: applying the current theme '{theme_id}'")
return update
+49 -13
View File
@@ -1,11 +1,13 @@
"""
Exact previews of a (draft) theme: the real title card and one karaoke-video frame.
Exact previews of a (draft) theme: the real title card, one karaoke-video frame and
the real end screen.
Used by the tenant theme editor. Both images come from the SAME renderers production
uses, fed the draft ``style_params`` exactly the way a render job would see them:
- **Title card**: ``karaoke_gen.video_generator.VideoGenerator.create_title_video``
with ``intro_video_duration=0`` (PNG only — what ``screens_worker`` does on Cloud Run).
- **End screen**: ``VideoGenerator.create_end_video`` the same way (``end_video_duration=0``).
- **Karaoke frame**: ``SegmentResizer`` → ``SubtitlesGenerator.generate_ass`` (the
generator's 4K layout: ``font_size`` default 250, ``line_height = font_size``,
``max_line_length`` default 36) → one frame burned with the same ffmpeg ``ass``
@@ -87,12 +89,18 @@ def font_family_name(font_file: str) -> str:
@dataclass
class PreviewImages:
title_card: bytes # JPEG
karaoke_frame: bytes # JPEG
# JPEGs. A screen the theme omits from videos (``enabled: false``) isn't rendered.
title_card: Optional[bytes]
karaoke_frame: bytes
end_screen: Optional[bytes] = None
def as_data_urls(self) -> Dict[str, str]:
enc = lambda b: "data:image/jpeg;base64," + base64.b64encode(b).decode() # noqa: E731
return {"title_card": enc(self.title_card), "karaoke_frame": enc(self.karaoke_frame)}
def as_data_urls(self) -> Dict[str, Optional[str]]:
enc = lambda b: "data:image/jpeg;base64," + base64.b64encode(b).decode() if b else None # noqa: E731
return {
"title_card": enc(self.title_card),
"karaoke_frame": enc(self.karaoke_frame),
"end_screen": enc(self.end_screen),
}
# ---------------------------------------------------------------------------
@@ -220,22 +228,26 @@ def _to_jpeg(png_path: str) -> bytes:
return buf.getvalue()
def render_title_card(styles: Dict, artist: str, title: str, workdir: str) -> bytes:
"""Title card exactly as screens_worker renders it (PNG via PIL, no video)."""
from karaoke_gen.style_loader import DEFAULT_INTRO_STYLE
def _screen_generator():
from karaoke_gen.video_generator import VideoGenerator
fmt = {**DEFAULT_INTRO_STYLE, **(styles.get("intro") or {})}
generator = VideoGenerator(
return VideoGenerator(
logger=logger,
ffmpeg_base_command="ffmpeg -hide_banner -nostats -loglevel error",
render_bounding_boxes=False,
output_png=True,
output_jpg=False,
)
def render_title_card(styles: Dict, artist: str, title: str, workdir: str) -> bytes:
"""Title card exactly as screens_worker renders it (PNG via PIL, no video)."""
from karaoke_gen.style_loader import DEFAULT_INTRO_STYLE
fmt = {**DEFAULT_INTRO_STYLE, **(styles.get("intro") or {})}
noext = os.path.join(workdir, "title")
try:
generator.create_title_video(
_screen_generator().create_title_video(
artist=artist,
title=title,
format=fmt,
@@ -249,6 +261,27 @@ def render_title_card(styles: Dict, artist: str, title: str, workdir: str) -> by
return _to_jpeg(f"{noext}.png")
def render_end_screen(styles: Dict, artist: str, title: str, workdir: str) -> bytes:
"""End screen exactly as screens_worker renders it (PNG via PIL, no video)."""
from karaoke_gen.style_loader import DEFAULT_END_STYLE
fmt = {**DEFAULT_END_STYLE, **(styles.get("end") or {})}
noext = os.path.join(workdir, "end")
try:
_screen_generator().create_end_video(
artist=artist,
title=title,
format=fmt,
output_image_filepath_noext=noext,
output_video_filepath=os.path.join(workdir, "end.mov"),
existing_end_image=fmt.get("existing_image"),
end_video_duration=0,
)
except Exception as exc:
raise ThemePreviewError(f"End screen render failed: {exc}") from exc
return _to_jpeg(f"{noext}.png")
def _sample_segments(lines: List[str], translations: Optional[List[str]] = None):
"""Evenly-timed segments: line i starts at 2+3i s, words spread over 2.5 s.
@@ -406,11 +439,14 @@ def render_theme_preview(
_CACHE.move_to_end(key)
return _CACHE[key]
from karaoke_gen.style_loader import screen_enabled
styles = resolve_assets(style_params, theme_id, storage)
with tempfile.TemporaryDirectory(prefix="theme-preview-") as workdir:
result = PreviewImages(
title_card=render_title_card(styles, artist, title, workdir),
title_card=render_title_card(styles, artist, title, workdir) if screen_enabled(styles, "intro") else None,
karaoke_frame=render_karaoke_frame(styles, lines, workdir),
end_screen=render_end_screen(styles, artist, title, workdir) if screen_enabled(styles, "end") else None,
)
with _cache_lock:
_CACHE[key] = result
+20 -6
View File
@@ -20,6 +20,7 @@ the job's existing brand code (see rerender_brand_code). Jobs published to
YouTube/GDrive are rejected — those would need the delete/redistribute dance of
the visibility flow, which tenants don't use.
"""
import asyncio
import logging
from datetime import datetime, timezone
from typing import Optional
@@ -77,6 +78,9 @@ def validate_rerender(job) -> Optional[str]:
return f"Only finished tracks can be re-rendered (current status: {job.status})."
if getattr(job, "outputs_deleted_at", None):
return "This track's outputs were deleted, so it can't be re-rendered."
from backend.services.storage_retention import PURGE_IN_PROGRESS_MESSAGE, purge_in_progress
if purge_in_progress(job):
return PURGE_IN_PROGRESS_MESSAGE
if not getattr(job, "theme_id", None):
return "This track wasn't made from a theme, so there's nothing to re-apply."
if getattr(job, "prep_only", False) or getattr(job, "finalise_only", False):
@@ -109,7 +113,12 @@ def rerender_brand_code(job) -> Optional[str]:
return code
# Admin re-render (only while its marker belongs to the current run).
from backend.services.admin_rerender_service import admin_rerender_brand_code
return admin_rerender_brand_code(job)
code = admin_rerender_brand_code(job)
if code:
return code
# GCS-only regenerate (storage retention): same brand code, nothing re-published.
from backend.services.regenerate_service import regenerate_brand_code
return regenerate_brand_code(job)
def delete_regenerated_artifacts(storage: StorageService, job_id: str) -> None:
@@ -172,7 +181,7 @@ class ThemeRerenderService:
self.job_manager = job_manager or JobManager()
self.storage = storage or StorageService()
async def start(self, job, theme_id: str, requested_by: str) -> None:
async def start(self, job, theme_id: str, requested_by: str, notify_customer: bool = True) -> None:
"""Re-snapshot ``theme_id`` onto the job and kick off the re-render.
Raises RerenderConflictError if the job stopped being COMPLETE (e.g. a
@@ -187,8 +196,9 @@ class ThemeRerenderService:
# claim so a failure here leaves the job untouched; overwriting the style
# copy of a still-complete job is harmless (its finals are already made).
from backend.api.routes.file_upload import _prepare_theme_for_job
style_params_path, style_assets, _ = _prepare_theme_for_job(
job_id, theme_id, getattr(job, "color_overrides", None) or None
# GCS / Firestore calls are blocking: keep them off the event loop.
style_params_path, style_assets, _ = await asyncio.to_thread(
_prepare_theme_for_job, job_id, theme_id, getattr(job, "color_overrides", None) or None
)
if not style_params_path:
raise RerenderError(f"Theme '{theme_id}' has no style to apply.", status_code=500)
@@ -200,12 +210,15 @@ class ThemeRerenderService:
"theme_id": theme_id,
"style_params_gcs_path": style_params_path,
"style_assets": style_assets,
"theme_applied_at": now,
"error_message": None,
"error_details": None,
"state_data.regen_restore_status": "review_complete",
"state_data.audio_complete": True,
"state_data.lyrics_complete": True,
"state_data.screens_progress": DELETE_FIELD,
# Screens are regenerated by this run anyway.
"state_data.theme_screens_stale": DELETE_FIELD,
"state_data.render_progress": DELETE_FIELD,
"state_data.video_progress": DELETE_FIELD,
"state_data.encoding_progress": DELETE_FIELD,
@@ -213,6 +226,7 @@ class ThemeRerenderService:
"requested_by": requested_by,
"requested_at": now.isoformat(),
"theme_id": theme_id,
"notify_customer": notify_customer,
"brand_code": (job.state_data or {}).get("brand_code")
or ((job.state_data or {}).get("theme_rerender") or {}).get("brand_code"),
},
@@ -227,9 +241,9 @@ class ThemeRerenderService:
"message": f"Re-render with current theme '{theme_id}' requested by {requested_by}",
}]),
}
self._claim(job_id, update, _claimable_statuses(job))
await asyncio.to_thread(self._claim, job_id, update, _claimable_statuses(job))
self._delete_stale_artifacts(job_id)
await asyncio.to_thread(self._delete_stale_artifacts, job_id)
from backend.services.worker_service import get_worker_service
triggered = await get_worker_service().trigger_screens_worker(job_id)
+9 -1
View File
@@ -19,6 +19,7 @@ from google.cloud import firestore
from google.cloud.firestore_v1 import FieldFilter
from google.cloud.firestore_v1 import Increment
from backend.utils.keyed_lock import user_lock
from backend.config import get_settings
from backend.models.user import (
User,
@@ -1056,7 +1057,14 @@ class UserService:
# Credit Operations
# =========================================================================
def add_credits(
def add_credits(self, email: str, *args, **kwargs) -> Tuple[bool, int, str]:
"""Add credits (see _add_credits_unlocked). Serialized per user within this
instance — the read-modify-write isn't transactional, and threadpool route
handlers could otherwise interleave two grants and lose one."""
with user_lock(email):
return self._add_credits_unlocked(email, *args, **kwargs)
def _add_credits_unlocked(
self,
email: str,
amount: int,
+18 -1
View File
@@ -53,7 +53,7 @@ class VisibilityChangeService:
return None
async def change_to_private(self, job_id: str, job, user_email: str) -> dict:
async def change_to_private(self, job_id: str, job, user_email: str, regenerate_if_missing: bool = True) -> dict:
"""
Change a public job to private (fast path).
@@ -70,6 +70,23 @@ class VisibilityChangeService:
"""
logger.info(f"[job:{job_id}] Starting visibility change: public -> private (by {user_email})")
# Storage retention may have purged the big finals of an old job. The
# private archive needs the full set, so regenerate them (GCS-only) first;
# the video worker runs this change again once they're back.
from backend.services.regenerate_service import AFTER_CHANGE_TO_PRIVATE, RegenerateService
if regenerate_if_missing and getattr(job, "renders_purged_at", None):
logger.info(f"[job:{job_id}] Finals missing (storage retention): regenerating before going private")
await RegenerateService(self.job_manager).start(
job, requested_by=user_email, source="visibility_change",
notify_customer=False, after=AFTER_CHANGE_TO_PRIVATE,
)
return {
"status": "processing",
"message": "This track's video files were archived. They're being regenerated first, "
"then the track will move to private automatically (about 15-30 minutes).",
"reprocessing_required": True,
}
db = self.job_manager.firestore.db
job_ref = db.collection("jobs").document(job_id)
+56 -3
View File
@@ -453,6 +453,58 @@ class WorkerService:
)
return False
async def trigger_storage_retention_job(
self,
dry_run: bool,
report_path: str,
max_jobs: Optional[int] = None,
include_orphans: bool = False,
mode: str = "job_purge",
max_folders: Optional[int] = None,
) -> bool:
"""Start the storage-retention pass as the ``storage-retention-job`` Cloud Run Job.
A full pass takes minutes; the API service throttles CPU outside requests
and Cloudflare cuts requests at 100s, so it can't run in the request.
"""
args = ["--dry-run", "true" if dry_run else "false", "--report-path", report_path]
if max_jobs is not None:
args += ["--max-jobs", str(int(max_jobs))]
if include_orphans:
args.append("--include-orphans")
if mode != "job_purge":
args += ["--mode", mode]
if max_folders is not None:
args += ["--max-folders", str(int(max_folders))]
if not self._use_cloud_tasks and not is_production():
return self._run_worker_module_locally("storage_retention_worker", args, log_prefix="[storage-retention]")
try:
from google.cloud import run_v2
project = self.settings.google_cloud_project
if not project:
logger.error("GOOGLE_CLOUD_PROJECT not set, cannot trigger storage-retention-job")
return False
job_name = f"projects/{project}/locations/{self.settings.cpu_jobs_region}/jobs/storage-retention-job"
request = run_v2.RunJobRequest(
name=job_name,
overrides=run_v2.RunJobRequest.Overrides(
container_overrides=[
run_v2.RunJobRequest.Overrides.ContainerOverride(
args=["python", "-m", "backend.workers.storage_retention_worker", *args],
)
]
),
)
operation = await self._run_job_with_retry(
run_v2.JobsClient(), request, log_prefix="[storage-retention]"
)
logger.info(f"[storage-retention] Started Cloud Run Job storage-retention-job: {operation.metadata}")
return True
except Exception as e:
logger.error(f"[storage-retention] Failed to trigger storage-retention-job: {e}", exc_info=True)
return False
async def trigger_audio_worker(self, job_id: str) -> bool:
"""
Trigger audio separation worker.
@@ -573,7 +625,7 @@ class WorkerService:
uses Cloud Run Jobs for execution (supports >30 min encoding).
Otherwise, uses Cloud Tasks or direct HTTP.
"""
self._bump_worker_generation(job_id)
await asyncio.to_thread(self._bump_worker_generation, job_id) # Firestore write
self._start_encoding_worker_warmup(job_id)
if self._use_cloud_tasks and self.settings.use_cloud_run_jobs_for_video:
return await self._trigger_cloud_run_job(job_id)
@@ -611,7 +663,8 @@ class WorkerService:
last_exc: Optional[Exception] = None
for attempt in range(1, _RUN_JOB_MAX_ATTEMPTS + 1):
try:
return client.run_job(request=request)
# Sync gRPC call (~1s) — keep it off the event loop.
return await asyncio.to_thread(client.run_job, request=request)
except _TRANSIENT_RUN_JOB_ERRORS as e:
last_exc = e
if attempt >= _RUN_JOB_MAX_ATTEMPTS:
@@ -743,7 +796,7 @@ class WorkerService:
rendering_video (incident 2026-09-13, job 41e06b90 — same class as
incident 2026-03-08 which migrated the video worker to Cloud Run Jobs).
"""
self._bump_worker_generation(job_id)
await asyncio.to_thread(self._bump_worker_generation, job_id) # Firestore write
self._start_encoding_worker_warmup(job_id)
if self._use_cloud_tasks and self.settings.use_cloud_run_jobs_for_render:
return await self._trigger_worker_cloud_run_job(
+37 -10
View File
@@ -13,6 +13,7 @@ This service handles:
import logging
import os
import time
from typing import Optional, Dict, Any, Tuple
from thefuzz import fuzz
@@ -32,6 +33,15 @@ class YouTubeUploadService:
YOUTUBE_URL_PREFIX = "https://www.youtube.com/watch?v="
SCOPES = ["https://www.googleapis.com/auth/youtube"]
# Resumable-upload robustness. Within one upload session, googleapiclient
# resumes chunks itself on 5xx/429/rate-limit responses (``num_retries``).
# A 404/410 means YouTube dropped the session entirely ("Gone") — nothing
# was created, so the only fix is a fresh session from byte 0.
UPLOAD_NUM_RETRIES = 3
UPLOAD_SESSION_ATTEMPTS = 3
UPLOAD_SESSION_LOST_STATUSES = (404, 410)
UPLOAD_RESTART_BACKOFF_SECONDS = 5
def __init__(
self,
credentials: Optional[Dict[str, Any]] = None,
@@ -372,16 +382,7 @@ class YouTubeUploadService:
}.get(ext, "video/*")
# Upload video
self.logger.info(f"Authenticating with YouTube...")
media_file = MediaFileUpload(video_path, mimetype=mime_type, resumable=True)
self.logger.info(f"Uploading video to YouTube...")
request = self.youtube_service.videos().insert(
part="snippet,status",
body=body,
media_body=media_file
)
response = request.execute()
response = self._execute_resumable_insert(video_path, mime_type, body)
video_id = response.get("id")
video_url = f"{self.YOUTUBE_URL_PREFIX}{video_id}"
@@ -408,6 +409,32 @@ class YouTubeUploadService:
return video_id, video_url
def _execute_resumable_insert(self, video_path: str, mime_type: str, body: Dict[str, Any]) -> Dict[str, Any]:
"""Run ``videos.insert`` as a resumable upload, restarting if the session is lost."""
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload
for attempt in range(1, self.UPLOAD_SESSION_ATTEMPTS + 1):
media_file = MediaFileUpload(video_path, mimetype=mime_type, resumable=True)
self.logger.info(f"Uploading video to YouTube (attempt {attempt}/{self.UPLOAD_SESSION_ATTEMPTS})...")
request = self.youtube_service.videos().insert(
part="snippet,status",
body=body,
media_body=media_file
)
try:
return request.execute(num_retries=self.UPLOAD_NUM_RETRIES)
except HttpError as e:
status = getattr(e.resp, "status", None)
if status not in self.UPLOAD_SESSION_LOST_STATUSES or attempt == self.UPLOAD_SESSION_ATTEMPTS:
raise
delay = self.UPLOAD_RESTART_BACKOFF_SECONDS * attempt
self.logger.warning(
f"YouTube upload session lost (HTTP {status}), restarting upload in {delay}s: {e}"
)
time.sleep(delay)
raise RuntimeError("unreachable") # loop always returns or raises
# Singleton instance and factory function (following existing service pattern)
_youtube_upload_service: Optional[YouTubeUploadService] = None
@@ -101,6 +101,22 @@ async def test_matching_durations_do_not_cancel(mocks):
await _call(_auth(email=None, is_admin=True))
mocks["job_manager"].cancel_job.assert_not_called()
update = mocks["job_manager"].update_job.call_args[0][1]
# uploads/ expires after 7 days: the instrumental is persisted at the job root.
assert update["existing_instrumental_gcs_path"] == "jobs/job-1/custom_instrumental.wav"
mocks["storage"].copy_blob.assert_any_call(
"uploads/job-1/audio/existing_instrumental.wav", "jobs/job-1/custom_instrumental.wav"
)
@pytest.mark.asyncio
async def test_instrumental_persist_failure_keeps_upload_path(mocks):
mocks["storage"].copy_blob.side_effect = RuntimeError("gcs down")
with patch("backend.api.routes.file_upload._validate_audio_durations",
new_callable=AsyncMock, return_value=(True, 200.0, 200.2)), \
patch("backend.api.routes.file_upload.get_credential_manager"):
await _call(_auth(email=None, is_admin=True))
update = mocks["job_manager"].update_job.call_args[0][1]
assert update["existing_instrumental_gcs_path"] == "uploads/job-1/audio/existing_instrumental.wav"
@@ -119,7 +135,8 @@ async def test_alignable_mismatch_uses_conformed_instrumental(mocks):
conform.assert_awaited_once()
mocks["job_manager"].cancel_job.assert_not_called()
update = mocks["job_manager"].update_job.call_args[0][1]
assert update["existing_instrumental_gcs_path"] == conformed
assert update["existing_instrumental_gcs_path"] == "jobs/job-1/custom_instrumental.flac"
mocks["storage"].copy_blob.assert_any_call(conformed, "jobs/job-1/custom_instrumental.flac")
mocks["job_manager"].update_state_data.assert_any_call("job-1", "instrumental_conformed", info)
+1
View File
@@ -18,6 +18,7 @@ if 'FIRESTORE_EMULATOR_HOST' not in os.environ:
os.environ.setdefault('GCS_BUCKET_NAME', 'test-bucket')
os.environ.setdefault('FIRESTORE_COLLECTION', 'jobs')
os.environ.setdefault('ENVIRONMENT', 'test')
os.environ.setdefault('LOOP_WATCHDOG_ENABLED', 'false')
# Gemini Developer API key: never let a test fall through to Secret Manager.
os.environ.setdefault('GEMINI_API_KEY', 'test-gemini-key')
+2 -4
View File
@@ -281,8 +281,7 @@ class TestSubmitFeedbackEmailIntegration:
)
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
result = asyncio.get_event_loop().run_until_complete(
submit_user_feedback(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc)
result = (submit_user_feedback(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc)
)
# Verify email notification was called with matching args
@@ -338,8 +337,7 @@ class TestSubmitFeedbackEmailIntegration:
)
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
result = asyncio.get_event_loop().run_until_complete(
submit_user_feedback(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc)
result = (submit_user_feedback(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc)
)
# User still gets credits even though email failed
+2 -1
View File
@@ -32,7 +32,8 @@ def _make_job(
title="Test Song",
outputs_deleted_at=None,
dropbox_path="/Tracks-Organized",
file_urls={"finals": {"lossy_4k_mp4": "gs://test/4k.mp4"}},
file_urls={"finals": {"lossy_4k_mp4": "gs://test/4k.mp4", "lossy_720p_mp4": "gs://test/720p.mp4"}},
renders_purged_at=None,
)
+115
View File
@@ -92,3 +92,118 @@ class TestReportClientEvent:
assert all(len(v) <= 200 for v in capped.values())
assert client_events._capped_detail(None) == {}
assert client_events._capped_detail("not a dict") == {}
class TestIdentityAndNewFields:
"""2026-10-03: identity is resolved server-side from the bearer token."""
def _auth_result(self, email, is_admin=False, valid=True):
r = MagicMock()
r.is_valid = valid
r.user_email = email
r.is_admin = is_admin
return r
def _post_with_token(self, client, auth_result, **overrides):
svc = MagicMock()
svc.validate_token_full.return_value = auth_result
with patch("backend.services.auth_service.get_auth_service", return_value=svc):
resp = client.post(
"/api/client-events",
json=_event(**overrides),
headers={"Authorization": "Bearer sess-token"},
)
return resp, svc
def _doc(self, db):
(doc,) = db.collection.return_value.add.call_args[0]
return doc
def test_anonymous_has_no_identity(self, client, fresh_limiter_and_db):
client.post("/api/client-events", json=_event())
doc = self._doc(fresh_limiter_and_db)
assert doc["user_email"] is None
assert doc["is_admin"] is False
assert doc["source"] == "client"
def test_client_supplied_email_is_ignored(self, client, fresh_limiter_and_db):
client.post("/api/client-events", json=_event(user_email="spoof@example.com"))
assert self._doc(fresh_limiter_and_db)["user_email"] is None
def test_token_resolves_customer(self, client, fresh_limiter_and_db):
resp, svc = self._post_with_token(client, self._auth_result("fan@gmail.com"))
assert resp.status_code == 202
svc.validate_token_full.assert_called_once_with("sess-token")
doc = self._doc(fresh_limiter_and_db)
assert doc["user_email"] == "fan@gmail.com"
assert (doc["is_admin"], doc["is_internal"], doc["is_test"]) == (False, False, False)
def test_token_resolves_admin_internal(self, client, fresh_limiter_and_db):
self._post_with_token(client, self._auth_result("andrew@nomadkaraoke.com", is_admin=True))
doc = self._doc(fresh_limiter_and_db)
assert doc["is_admin"] is True
assert doc["is_internal"] is True
def test_token_resolves_test_account(self, client, fresh_limiter_and_db):
self._post_with_token(client, self._auth_result("k1.test-1@inbox.testmail.app"))
assert self._doc(fresh_limiter_and_db)["is_test"] is True
def test_invalid_token_is_anonymous_not_error(self, client, fresh_limiter_and_db):
resp, _ = self._post_with_token(client, self._auth_result(None, valid=False))
assert resp.status_code == 202
assert self._doc(fresh_limiter_and_db)["user_email"] is None
def test_auth_service_crash_is_anonymous_not_error(self, client, fresh_limiter_and_db):
with patch("backend.services.auth_service.get_auth_service", side_effect=RuntimeError("x")):
resp = client.post(
"/api/client-events", json=_event(), headers={"Authorization": "Bearer t"}
)
assert resp.status_code == 202
assert self._doc(fresh_limiter_and_db)["user_email"] is None
def test_fingerprint_tab_episode_and_tenant_persisted(self, client, fresh_limiter_and_db):
client.post(
"/api/client-events",
json=_event(
url="https://randy-vild.nomadkaraoke.com/en/app/",
device_fingerprint="635a6066abc",
tab_id="tab-1",
episode_id="ep-1",
),
)
doc = self._doc(fresh_limiter_and_db)
assert doc["device_fingerprint"] == "635a6066abc"
assert doc["tab_id"] == "tab-1"
assert doc["episode_id"] == "ep-1"
assert doc["tenant"] == "randy-vild"
def test_consumer_host_has_no_tenant(self, client, fresh_limiter_and_db):
client.post("/api/client-events", json=_event())
assert self._doc(fresh_limiter_and_db)["tenant"] is None
def test_banner_recovered_accepted(self, client, fresh_limiter_and_db):
resp = client.post(
"/api/client-events",
json=_event(type="banner_recovered", detail={"duration_ms": 31000, "peak_status": "unavailable"}),
)
assert resp.status_code == 202
assert self._doc(fresh_limiter_and_db)["type"] == "banner_recovered"
def test_server_loop_stall_rejected_from_clients(self, client):
resp = client.post("/api/client-events", json=_event(type="server_loop_stall"))
assert resp.status_code == 422
@pytest.mark.parametrize(
"url,expected",
[
("https://randy-vild.nomadkaraoke.com/en/app/", "randy-vild"),
("https://vocalstar.nomadkaraoke.com/x", "vocalstar"),
("https://gen.nomadkaraoke.com/en/app/", None),
("https://nomadkaraoke.com/", None),
("https://evil.com/?x=.nomadkaraoke.com", None),
("", None),
],
)
def test_tenant_from_url(url, expected):
assert client_events._tenant_from_url(url) == expected
@@ -0,0 +1,56 @@
"""Unit tests for scripts/client_events_report.py (summary logic only)."""
import importlib.util
from datetime import datetime, timezone
from pathlib import Path
_spec = importlib.util.spec_from_file_location(
"client_events_report",
Path(__file__).resolve().parents[2] / "scripts" / "client_events_report.py",
)
report = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(report)
T = datetime(2026, 10, 3, 12, tzinfo=timezone.utc)
def _ev(type_, **kw):
return {"type": type_, "created_at": T, "source": "client", **kw}
def test_excludes_admin_internal_test_by_default():
events = [
_ev("banner_unavailable", user_email="fan@gmail.com"),
_ev("banner_unavailable", user_email="andrew@nomadkaraoke.com", is_admin=True, is_internal=True),
_ev("banner_reconnecting", user_email="x@inbox.testmail.app", is_test=True),
]
out = report.summarise(events, include_noise=False)
assert "excluded 2" in out
assert "fan@gmail.com" in out
assert "andrew@" not in out
out_all = report.summarise(events, include_noise=True)
assert "andrew@nomadkaraoke.com" in out_all
def test_episode_durations_and_stall_culprits():
events = [
_ev("banner_recovered", detail={"duration_ms": 30000, "peak_status": "unavailable"}),
_ev("banner_recovered", detail={"duration_ms": 12000, "peak_status": "reconnecting"}),
{"type": "server_loop_stall", "source": "server", "created_at": T,
"detail": {"duration_ms": 31000, "culprit": "backend/workers/screens_worker.py:774 in x"}},
]
out = report.summarise(events, include_noise=False)
assert "2 recovered" in out
assert "max 30.0s" in out
assert "Server event-loop stalls >=5s: 1" in out
assert "screens_worker.py:774" in out
def test_anonymous_devices_grouped_by_fingerprint_and_legacy_tenant():
events = [
_ev("banner_unavailable", device_fingerprint="abcdef123456", url="https://randy-vild.nomadkaraoke.com/en/app/"),
_ev("banner_unavailable", url="https://gen.nomadkaraoke.com/en/app/"),
]
out = report.summarise(events, include_noise=False)
assert "fp:abcdef1234" in out
assert "(anonymous)" in out
assert "randy-vild=1" in out
+1 -1
View File
@@ -120,7 +120,7 @@ async def test_list_community_requests_maps_all_statuses():
svc.list_all.return_value = [published, open_req]
with patch("backend.services.song_request_service.get_song_request_service",
MagicMock(return_value=svc)):
res = await list_community_requests(auth_data=("admin", None, 0))
res = list_community_requests(auth_data=("admin", None, 0))
assert [r.id for r in res.requests] == ["pub", "op"]
pub = res.requests[0]
assert pub.status == "published"
+38 -3
View File
@@ -144,11 +144,13 @@ class TestCreditRefundOnJobFailure:
amount instead of a hard-coded 1.
"""
def _mock_job(self, credits_charged=1, credit_refunded=False, user_email="user@test.com"):
def _mock_job(self, credits_charged=1, credit_refunded=False, user_email="user@test.com",
edit_count=0):
"""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.edit_count = edit_count
job.state_data = {"credits_charged": credits_charged}
return job
@@ -258,11 +260,12 @@ class TestCreditRefundOnJobCancellation:
"""
def _mock_job(self, credits_charged=1, credit_refunded=False,
user_email="user@test.com", status=None):
user_email="user@test.com", status=None, edit_count=0):
"""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.edit_count = edit_count
job.state_data = {"credits_charged": credits_charged}
job.status = status or JobStatus.PENDING
return job
@@ -299,6 +302,19 @@ class TestCreditRefundOnJobCancellation:
"user@test.com", amount=4, reason="job_cancelled", job_id="job123"
)
def test_cancel_of_edited_track_skips_refund(
self, job_manager, mock_firestore_service, mock_user_service
):
"""Cancelling a re-edit of a delivered track doesn't refund the original credit."""
mock_job = self._mock_job(credits_charged=1, status=JobStatus.AWAITING_REVIEW, edit_count=2)
mock_firestore_service.get_job.return_value = mock_job
mock_firestore_service.update_job_status.return_value = True
with patch('backend.services.auth_service.is_admin_email', return_value=False):
job_manager.cancel_job("job123")
mock_user_service.add_credits.assert_not_called()
def test_cancel_guard_prevents_double_refund_when_credit_refunded(
self, job_manager, mock_firestore_service, mock_user_service
):
@@ -372,10 +388,11 @@ class TestCreditRefundOnJobDeletion:
"""
def _mock_job(self, credits_charged=1, credit_refunded=False,
user_email="user@test.com", status=None):
user_email="user@test.com", status=None, edit_count=0):
job = Mock(spec=Job)
job.user_email = user_email
job.credit_refunded = credit_refunded
job.edit_count = edit_count
job.state_data = {"credits_charged": credits_charged}
job.status = status or JobStatus.PENDING
job.output_files = {}
@@ -440,6 +457,24 @@ class TestCreditRefundOnJobDeletion:
mock_user_service.add_credits.assert_not_called()
@pytest.mark.parametrize("status", [JobStatus.AWAITING_REVIEW, JobStatus.LYRICS_COMPLETE])
def test_no_refund_on_delete_of_edited_track(
self, job_manager, mock_firestore_service, mock_user_service, status
):
"""Complete → Edit → Delete must not refund: the track was already delivered.
Edit reopens a completed job (AWAITING_REVIEW, or LYRICS_COMPLETE when
metadata changed), so its status alone looks "never completed".
"""
mock_job = self._mock_job(credits_charged=1, status=status, edit_count=1)
mock_firestore_service.get_job.return_value = mock_job
with patch('backend.services.auth_service.is_admin_email', return_value=False):
job_manager.delete_job("job123")
mock_user_service.add_credits.assert_not_called()
mock_firestore_service.delete_job.assert_called_once_with("job123")
def test_delete_refund_failure_does_not_block_deletion(
self, job_manager, mock_firestore_service, mock_user_service
):
@@ -806,6 +806,42 @@ class TestVideoWorkerDistribution:
# Should log warning about not configured
mock_job_log.warning.assert_called()
@pytest.mark.asyncio
async def test_handle_native_distribution_dropbox_skips_unchanged(self):
"""The second Dropbox pass only sends what the orchestrator didn't already upload."""
from backend.workers.video_worker import _handle_native_distribution
mock_job = MagicMock()
mock_job.dropbox_path = "/Tracks"
mock_job.brand_prefix = "NOMAD"
mock_job.gdrive_folder_id = None
mock_job.is_private = False
mock_job.keep_brand_code = None
mock_job.artist = "Eli"
mock_job.title = "The Comeback"
mock_job.state_data = {}
mock_dropbox = MagicMock()
mock_dropbox.is_configured = True
mock_dropbox.create_shared_link.return_value = "https://dropbox/link"
dist = MagicMock(dropbox_path="/Tracks", brand_prefix="NOMAD", gdrive_folder_id=None)
with patch('backend.services.dropbox_service.get_dropbox_service', return_value=mock_dropbox), \
patch('backend.services.job_defaults_service.get_effective_distribution_for_job', return_value=dist), \
patch('backend.services.theme_rerender_service.rerender_brand_code', return_value=None):
await _handle_native_distribution(
job_id="test-123",
job=mock_job,
job_log=MagicMock(),
job_manager=MagicMock(),
temp_dir="/tmp/test",
result={"brand_code": "NOMAD-1754", "dropbox_link": "https://dropbox/link"},
)
args, kwargs = mock_dropbox.upload_folder.call_args
assert args == ("/tmp/test", "/Tracks/NOMAD-1754 - Eli - The Comeback")
assert kwargs["skip_unchanged"] is True
@pytest.mark.asyncio
async def test_handle_native_distribution_gdrive_not_configured(self):
"""Test Google Drive upload skipped when service not configured."""
+119
View File
@@ -658,3 +658,122 @@ class TestEnsureFolderAndMissingPaths:
)
with pytest.raises(ApiError):
service.list_folders("/Tracks-New")
class TestUploadFolderSkipUnchanged:
"""The video worker's second Dropbox pass (after the orchestrator uploaded the
same folder) must only send new/changed files, not re-upload everything."""
def _service(self):
from backend.services.dropbox_service import DropboxService
service = DropboxService()
service._client = Mock()
return service
@staticmethod
def _file_entry(path_lower, content_hash):
from dropbox.files import FileMetadata
entry = Mock(spec=FileMetadata)
entry.path_lower = path_lower
entry.content_hash = content_hash
return entry
def _listing(self, entries, has_more=False, cursor="c1"):
result = Mock()
result.entries = entries
result.has_more = has_more
result.cursor = cursor
return result
def test_content_hash_matches_dropbox_algorithm(self, tmp_path):
import hashlib
from backend.services.dropbox_service import dropbox_content_hash
block = 4 * 1024 * 1024
data = b"a" * block + b"b" * 10 # two blocks
f = tmp_path / "x.bin"
f.write_bytes(data)
expected = hashlib.sha256(
hashlib.sha256(data[:block]).digest() + hashlib.sha256(data[block:]).digest()
).hexdigest()
assert dropbox_content_hash(str(f)) == expected
empty = tmp_path / "empty.bin"
empty.write_bytes(b"")
assert dropbox_content_hash(str(empty)) == hashlib.sha256(b"").hexdigest()
def test_skips_identical_uploads_new_and_changed(self, tmp_path):
from backend.services.dropbox_service import dropbox_content_hash
(tmp_path / "Song (Final Karaoke Lossy 4k).mp4").write_bytes(b"video")
(tmp_path / "Song (Karaoke).cdg").write_bytes(b"cdg-new")
(tmp_path / "stems").mkdir()
(tmp_path / "stems" / "Song (Vocals).flac").write_bytes(b"vocals")
service = self._service()
service._client.files_list_folder.return_value = self._listing([
self._file_entry(
"/tracks/nomad-1 - song/song (final karaoke lossy 4k).mp4",
dropbox_content_hash(str(tmp_path / "Song (Final Karaoke Lossy 4k).mp4")),
),
self._file_entry("/tracks/nomad-1 - song/song (karaoke).cdg", "stale-hash"),
])
with patch.object(service, "upload_file") as up:
service.upload_folder(str(tmp_path), "/Tracks/NOMAD-1 - Song", skip_unchanged=True)
uploaded = sorted(call.args[1] for call in up.call_args_list)
assert uploaded == [
"/Tracks/NOMAD-1 - Song/Song (Karaoke).cdg", # changed
"/Tracks/NOMAD-1 - Song/stems/Song (Vocals).flac", # new
]
service._client.files_list_folder.assert_called_once_with("/Tracks/NOMAD-1 - Song", recursive=True)
def test_listing_paginates(self, tmp_path):
from backend.services.dropbox_service import dropbox_content_hash
(tmp_path / "a.txt").write_bytes(b"a")
(tmp_path / "b.txt").write_bytes(b"b")
service = self._service()
service._client.files_list_folder.return_value = self._listing(
[self._file_entry("/f/a.txt", dropbox_content_hash(str(tmp_path / "a.txt")))], has_more=True
)
service._client.files_list_folder_continue.return_value = self._listing(
[self._file_entry("/f/b.txt", dropbox_content_hash(str(tmp_path / "b.txt")))]
)
with patch.object(service, "upload_file") as up:
service.upload_folder(str(tmp_path), "/f", skip_unchanged=True)
up.assert_not_called()
def test_missing_folder_uploads_everything(self, tmp_path):
from dropbox.exceptions import ApiError
from dropbox.files import ListFolderError, LookupError as DbxLookupError
(tmp_path / "a.txt").write_bytes(b"a")
service = self._service()
service._client.files_list_folder.side_effect = ApiError(
"req", ListFolderError.path(DbxLookupError.not_found), "msg", "hdr"
)
with patch.object(service, "upload_file") as up:
service.upload_folder(str(tmp_path), "/new", skip_unchanged=True)
up.assert_called_once()
def test_listing_failure_falls_back_to_full_upload(self, tmp_path):
(tmp_path / "a.txt").write_bytes(b"a")
(tmp_path / "b.txt").write_bytes(b"b")
service = self._service()
service._client.files_list_folder.side_effect = RuntimeError("network down")
with patch.object(service, "upload_file") as up:
service.upload_folder(str(tmp_path), "/f", skip_unchanged=True)
assert up.call_count == 2
def test_default_does_not_list_or_skip(self, tmp_path):
(tmp_path / "a.txt").write_bytes(b"a")
service = self._service()
with patch.object(service, "upload_file") as up:
service.upload_folder(str(tmp_path), "/f")
service._client.files_list_folder.assert_not_called()
up.assert_called_once()
@@ -332,3 +332,38 @@ class TestEditPreservesTempoLabel:
_, payload = self._edit(client, mock_job_manager, complete_job, auth_headers,
{"title": "Better Name"}, None, "Test Song")
assert payload["title"] == "Better Name"
class TestEditStemsPurgedTrack:
"""Storage retention purged the stems: review needs them, so the edit goes
through the screens worker (which re-separates first) instead of straight
to AWAITING_REVIEW."""
def test_stems_purged_edit_restores_stems_before_review(
self, client, complete_job, mock_job_manager, mock_worker_service, auth_headers
):
complete_job.stems_purged_at = datetime.now(UTC)
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
assert response.status_code == 200
assert response.json()["metadata_updated"] is False
mock_job_manager.transition_to_state.assert_called_once_with(
"test-edit-123",
JobStatus.LYRICS_COMPLETE,
progress=55,
message="Restoring audio stems before review",
)
mock_worker_service.trigger_screens_worker.assert_called_once_with("test-edit-123")
def test_bring_your_own_instrumental_job_goes_straight_to_review(
self, client, complete_job, mock_job_manager, auth_headers
):
complete_job.stems_purged_at = datetime.now(UTC)
complete_job.existing_instrumental_gcs_path = "jobs/test-edit-123/custom_instrumental.wav"
client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
assert mock_job_manager.transition_to_state.call_args.args[1] == JobStatus.AWAITING_REVIEW
def test_edit_refused_while_purge_in_progress(self, client, complete_job, auth_headers):
complete_job.state_data["storage_purge_in_progress"] = datetime.now(UTC).isoformat()
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
assert response.status_code == 409
@@ -0,0 +1,246 @@
"""Encoding worker self-heal (backend/services/gce_encoding/self_heal.py).
Incident 2026-10-06: the primary booted before its network was up, fell back to a
startup script that omitted ENCODING_API_KEY and GCE_METADATA_MTLS_MODE=none, and
then failed every job with CERTIFICATE_VERIFY_FAILED until restarted by hand.
"""
import threading
import pytest
from backend.services.gce_encoding import self_heal
INFRA_ERROR = (
"Failed to retrieve https://metadata.google.internal/computeMetadata/v1/instance/"
"service-accounts/default/?recursive=true from the Google Compute Engine metadata "
"service. Compute Engine Metadata server unavailable."
)
@pytest.fixture
def on_worker_vm(monkeypatch):
monkeypatch.setattr(self_heal, "running_on_worker_vm", lambda: True)
@pytest.fixture(autouse=True)
def reset_restart_flag():
self_heal._restart_pending = False
yield
self_heal._restart_pending = False
class TestRunningOnWorkerVm:
def test_requires_systemd_and_bootstrap(self, monkeypatch, tmp_path):
bootstrap = tmp_path / "bootstrap.sh"
monkeypatch.setattr(self_heal, "BOOTSTRAP_PATH", str(bootstrap))
monkeypatch.setenv("INVOCATION_ID", "abc")
assert self_heal.running_on_worker_vm() is False # no bootstrap.sh (e.g. CI runner)
bootstrap.touch()
assert self_heal.running_on_worker_vm() is True
monkeypatch.delenv("INVOCATION_ID")
assert self_heal.running_on_worker_vm() is False
class TestProbeCredentials:
def test_healthy(self):
assert self_heal.probe_credentials(refresh=lambda: None) is None
def test_retries_then_succeeds(self):
calls = {"n": 0}
def refresh():
calls["n"] += 1
if calls["n"] < 3:
raise RuntimeError("blip")
assert self_heal.probe_credentials(attempts=3, retry_seconds=0, refresh=refresh) is None
assert calls["n"] == 3
def test_returns_last_error_when_always_failing(self):
def refresh():
raise RuntimeError(INFRA_ERROR)
assert self_heal.probe_credentials(attempts=2, retry_seconds=0, refresh=refresh) == INFRA_ERROR
class TestBootHealthProblem:
def test_off_vm_never_reports(self, monkeypatch):
monkeypatch.setattr(self_heal, "running_on_worker_vm", lambda: False)
monkeypatch.delenv("ENCODING_API_KEY", raising=False)
assert self_heal.boot_health_problem(probe=lambda: "broken") is None
def test_healthy_boot(self, on_worker_vm, monkeypatch):
monkeypatch.setenv("ENCODING_API_KEY", "k")
assert self_heal.boot_health_problem(probe=lambda: None) is None
def test_missing_api_key(self, on_worker_vm, monkeypatch):
monkeypatch.delenv("ENCODING_API_KEY", raising=False)
problem = self_heal.boot_health_problem(probe=lambda: None)
assert "ENCODING_API_KEY" in problem
def test_credentials_failing(self, on_worker_vm, monkeypatch):
monkeypatch.setenv("ENCODING_API_KEY", "k")
problem = self_heal.boot_health_problem(probe=lambda: INFRA_ERROR)
assert "cannot obtain GCP credentials" in problem
def _wait_for(event, timeout=5):
assert event.wait(timeout), "self-heal thread did not finish"
class TestScheduleRestart:
def test_ignores_non_infra_errors(self, on_worker_vm):
exited = []
assert not self_heal.schedule_restart_if_unhealthy(
"ffmpeg: invalid codec", lambda: False, delay_seconds=0,
probe=lambda: INFRA_ERROR, exit_process=exited.append,
)
assert exited == []
def test_off_vm_does_nothing(self, monkeypatch):
monkeypatch.setattr(self_heal, "running_on_worker_vm", lambda: False)
assert not self_heal.schedule_restart_if_unhealthy(
INFRA_ERROR, lambda: False, delay_seconds=0,
probe=lambda: INFRA_ERROR, exit_process=lambda code: None,
)
def test_exits_when_still_broken_and_idle(self, on_worker_vm):
done = threading.Event()
exited = []
def exit_process(code):
exited.append(code)
done.set()
assert self_heal.schedule_restart_if_unhealthy(
INFRA_ERROR, lambda: False, delay_seconds=0,
probe=lambda: INFRA_ERROR, exit_process=exit_process,
)
_wait_for(done)
assert exited == [1]
def test_no_exit_when_credentials_recover(self, on_worker_vm):
done = threading.Event()
exited = []
def probe():
done.set()
return None
assert self_heal.schedule_restart_if_unhealthy(
INFRA_ERROR, lambda: False, delay_seconds=0,
probe=probe, exit_process=exited.append,
)
_wait_for(done)
# Let the thread finish and release the pending flag.
for _ in range(100):
if not self_heal._restart_pending:
break
threading.Event().wait(0.01)
assert exited == []
assert self_heal._restart_pending is False
def test_waits_for_in_flight_jobs_before_exiting(self, on_worker_vm):
done = threading.Event()
exited = []
active = iter([True, True, False])
def exit_process(code):
exited.append(code)
done.set()
self_heal.schedule_restart_if_unhealthy(
INFRA_ERROR, lambda: next(active), delay_seconds=0,
probe=lambda: INFRA_ERROR, exit_process=exit_process,
)
_wait_for(done)
assert exited == [1]
def test_only_one_check_at_a_time(self, on_worker_vm):
release = threading.Event()
def probe():
release.wait(5)
return None
assert self_heal.schedule_restart_if_unhealthy(
INFRA_ERROR, lambda: False, delay_seconds=0, probe=probe, exit_process=lambda c: None,
)
assert not self_heal.schedule_restart_if_unhealthy(
INFRA_ERROR, lambda: False, delay_seconds=0, probe=probe, exit_process=lambda c: None,
)
release.set()
# ---------------------------------------------------------------------------
# Wiring in gce_encoding/main.py
# ---------------------------------------------------------------------------
import asyncio
import os
import sys
from unittest.mock import MagicMock, patch
@pytest.fixture
def worker_module():
with patch.dict(os.environ, {}, clear=False):
os.environ.pop("GCE_METADATA_MTLS_MODE", None)
with patch("google.cloud.storage.Client", return_value=MagicMock()):
sys.modules.pop("backend.services.gce_encoding.main", None)
import backend.services.gce_encoding.main as m
yield m
sys.modules.pop("backend.services.gce_encoding.main", None)
def test_import_defaults_metadata_mtls_off(worker_module):
assert os.environ["GCE_METADATA_MTLS_MODE"] == "none"
def test_import_keeps_explicit_mtls_mode():
with patch.dict(os.environ, {"GCE_METADATA_MTLS_MODE": "strict"}, clear=False):
with patch("google.cloud.storage.Client", return_value=MagicMock()):
sys.modules.pop("backend.services.gce_encoding.main", None)
import backend.services.gce_encoding.main # noqa: F401
sys.modules.pop("backend.services.gce_encoding.main", None)
assert os.environ["GCE_METADATA_MTLS_MODE"] == "strict"
def _run_lifespan(m):
async def go():
async with m.lifespan(m.app):
pass
asyncio.run(go())
def test_lifespan_refuses_to_start_when_boot_unhealthy(worker_module, monkeypatch):
monkeypatch.setattr(worker_module.self_heal, "boot_health_problem", lambda: "no API key")
with pytest.raises(RuntimeError, match="booted unhealthy: no API key"):
_run_lifespan(worker_module)
def test_lifespan_starts_when_healthy(worker_module, monkeypatch):
monkeypatch.setattr(worker_module.self_heal, "boot_health_problem", lambda: None)
monkeypatch.setattr(worker_module.persister, "mark_orphans_failed_on_startup", lambda jobs: 0)
_run_lifespan(worker_module)
def test_failed_job_schedules_self_heal(worker_module, monkeypatch):
seen = []
monkeypatch.setattr(
worker_module.self_heal, "schedule_restart_if_unhealthy",
lambda error_text, has_active: seen.append((error_text, has_active())),
)
worker_module.jobs.clear()
worker_module._self_heal_after_failure(RuntimeError(INFRA_ERROR))
assert seen == [(INFRA_ERROR, False)]
def test_self_heal_scheduling_errors_never_propagate(worker_module, monkeypatch):
def boom(*a, **k):
raise RuntimeError("thread start failed")
monkeypatch.setattr(worker_module.self_heal, "schedule_restart_if_unhealthy", boom)
worker_module._self_heal_after_failure(RuntimeError(INFRA_ERROR)) # must not raise
@@ -0,0 +1,371 @@
"""The heavy steps of the screens worker / stale-review cron must not block the loop.
Prod (2026-10-03 analysis): these ran synchronously on the single uvicorn event
loop and froze every request on the instance for 20-45s, surfacing as the
"servers unavailable" banner. Each test patches the heavy sync call with a
``time.sleep`` and asserts a concurrent ticker keeps ticking meanwhile — i.e.
the work really runs in a worker thread.
"""
import asyncio
import time
from unittest.mock import MagicMock, patch
import pytest
BLOCK_S = 0.4
async def _ticks_during(coro) -> int:
"""Run coro while counting 20ms ticks; a blocked loop yields ~0 ticks."""
ticks = 0
done = asyncio.Event()
async def ticker():
nonlocal ticks
while not done.is_set():
await asyncio.sleep(0.02)
ticks += 1
t = asyncio.create_task(ticker())
try:
await coro
finally:
done.set()
await t
return ticks
def _sleep(*_a, **_kw):
time.sleep(BLOCK_S)
return {}
# Blocked for BLOCK_S → ~0-1 ticks; offloaded → ~BLOCK_S/0.02 = 20 ticks.
MIN_TICKS = 8
@pytest.mark.asyncio
async def test_upload_screens_runs_off_loop(tmp_path):
from backend.workers import screens_worker
title = tmp_path / "t.png"
end = tmp_path / "e.png"
title.write_bytes(b"x")
end.write_bytes(b"x")
storage = MagicMock()
storage.upload_file.side_effect = _sleep
ticks = await _ticks_during(
screens_worker._upload_screens("j1", MagicMock(), storage, str(title), str(end))
)
assert storage.upload_file.call_count == 2
assert ticks >= MIN_TICKS
@pytest.mark.asyncio
async def test_review_audio_transcode_runs_off_loop():
from backend.workers import screens_worker
jm = MagicMock()
job = MagicMock()
job.file_urls = {}
job.input_media_gcs_path = None
jm.get_job.return_value = job
with patch("backend.services.audio_transcoding_service.AudioTranscodingService") as svc, \
patch("backend.utils.stems.vocals_stem_path", return_value=None):
svc.return_value.prepare_review_audio_for_job.side_effect = _sleep
ticks = await _ticks_during(
screens_worker._transcode_review_audio("j1", jm, MagicMock())
)
svc.return_value.prepare_review_audio_for_job.assert_called_once()
assert ticks >= MIN_TICKS
@pytest.mark.asyncio
async def test_title_screen_render_runs_off_loop(tmp_path):
from backend.workers import screens_worker
gen = MagicMock()
gen.create_title_video.side_effect = _sleep
style = MagicMock()
style.get_intro_format.return_value = {}
job = MagicMock(artist="A", title="B")
ticks = await _ticks_during(
screens_worker._generate_title_screen("j1", job, gen, style, str(tmp_path))
)
gen.create_title_video.assert_called_once()
assert ticks >= MIN_TICKS
@pytest.mark.asyncio
async def test_style_config_load_runs_off_loop(tmp_path):
from backend.workers import style_helper
job = MagicMock(job_id="j1", style_assets={}, style_params_gcs_path=None)
def slow_load(**_kw):
time.sleep(BLOCK_S)
return (None, {})
with patch.object(style_helper, "load_styles_from_gcs", side_effect=slow_load):
cfg = style_helper.StyleConfig(job, MagicMock(), str(tmp_path))
ticks = await _ticks_during(cfg.load())
assert ticks >= MIN_TICKS
@pytest.mark.asyncio
async def test_stale_review_cron_runs_off_loop():
from backend.workers import stale_review_processor
with patch.object(stale_review_processor, "process_stale_reviews_sync", side_effect=_sleep):
ticks = await _ticks_during(stale_review_processor.process_stale_reviews())
assert ticks >= MIN_TICKS
@pytest.mark.asyncio
async def test_health_encoding_status_builds_service_off_loop():
"""A cold get_encoding_service() (imports compute_v1, ~10s) must not block the loop."""
from backend.api.routes import health
def slow_build():
time.sleep(BLOCK_S)
svc = MagicMock()
svc.is_enabled = False
return svc
with patch.object(health, "get_encoding_service", side_effect=slow_build):
ticks = await _ticks_during(health.check_encoding_worker_status())
assert ticks >= MIN_TICKS
def test_get_encoding_service_builds_once_under_concurrency():
import threading
from backend.services import encoding_service as es
builds = []
class FakeService:
def __init__(self):
builds.append(1)
time.sleep(0.05)
def set_worker_manager(self, m):
pass
with patch.object(es, "_encoding_service", None), patch.object(es, "EncodingService", FakeService):
results = []
threads = [threading.Thread(target=lambda: results.append(es.get_encoding_service())) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
assert len(builds) == 1
assert len({id(r) for r in results}) == 1
# --- 2026-10-08: routes/cron stalls traced by the loop watchdog ---------------
# complete_review's corrections upload (21s), create_job_from_search's theme prep
# (5-9s), recover_stuck_jobs' Firestore scans (~260 stalls/week), the YouTube
# queue processor and upload-duration validation all ran sync I/O on the loop.
def test_run_on_loop_runs_coroutine_on_the_given_loop():
from backend.utils.loop_bridge import run_on_loop
async def main():
loop = asyncio.get_running_loop()
seen = {}
async def coro():
seen["loop"] = asyncio.get_running_loop()
return 42
result = await asyncio.to_thread(run_on_loop, loop, coro())
assert result == 42
assert seen["loop"] is loop
asyncio.run(main())
def test_run_on_loop_propagates_exceptions():
from backend.utils.loop_bridge import run_on_loop
async def main():
loop = asyncio.get_running_loop()
async def boom():
raise ValueError("nope")
with pytest.raises(ValueError, match="nope"):
await asyncio.to_thread(run_on_loop, loop, boom())
asyncio.run(main())
def test_run_on_loop_times_out_and_cancels():
from backend.utils.loop_bridge import run_on_loop
import concurrent.futures
async def main():
loop = asyncio.get_running_loop()
cancelled = asyncio.Event()
async def hangs():
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
cancelled.set()
raise
with pytest.raises(concurrent.futures.TimeoutError):
await asyncio.to_thread(run_on_loop, loop, hangs(), 0.05)
await asyncio.wait_for(cancelled.wait(), 1)
asyncio.run(main())
def test_run_in_body_thread_copies_context_and_uses_own_pool():
import contextvars
import threading
from backend.utils.loop_bridge import run_in_body_thread
var = contextvars.ContextVar("v", default=None)
def body():
return var.get(), threading.current_thread().name
async def main():
var.set("request-ctx")
return await run_in_body_thread(body)
value, thread_name = asyncio.run(main())
assert value == "request-ctx"
assert thread_name.startswith("route-body")
@pytest.mark.asyncio
async def test_complete_review_saves_off_loop_and_triggers_render():
from unittest.mock import AsyncMock
from backend.api.routes import review
from backend.models.job import JobStatus
job = MagicMock()
job.status = JobStatus.AWAITING_REVIEW
job.file_urls = {}
job.existing_instrumental_gcs_path = None
job.state_data = {}
jm = MagicMock()
jm.get_job.return_value = job
jm.delete_state_data_keys.return_value = []
storage = MagicMock()
storage.upload_json.side_effect = _sleep
with patch.object(review, "JobManager", return_value=jm), \
patch.object(review, "StorageService", return_value=storage), \
patch("backend.services.worker_service.get_worker_service") as ws:
ws.return_value.trigger_render_video_worker = AsyncMock(return_value=True)
result = {}
async def call():
result.update(await review.complete_review(
job_id="j1",
updated_data={"corrections": [], "instrumental_selection": "clean"},
auth_info=("u@example.com", "job_owner"),
))
ticks = await _ticks_during(call())
storage.upload_json.assert_called_once()
ws.return_value.trigger_render_video_worker.assert_awaited_once_with("j1")
assert result == {"status": "success", "instrumental_selection": "clean"}
assert ticks >= MIN_TICKS
@pytest.mark.asyncio
async def test_create_job_from_search_runs_off_loop():
from backend.api.routes import jobs
with patch.object(jobs, "_create_job_from_search_sync", side_effect=_sleep) as body:
ticks = await _ticks_during(
jobs.create_job_from_search(MagicMock(), MagicMock(), MagicMock(), MagicMock())
)
body.assert_called_once()
assert isinstance(body.call_args.args[-1], asyncio.AbstractEventLoop)
assert ticks >= MIN_TICKS
@pytest.mark.asyncio
@pytest.mark.parametrize("route, body", [
("recover_stuck_jobs", "_recover_stuck_jobs_sync"),
("retry_pending_render_jobs", "_retry_pending_render_jobs_sync"),
])
async def test_internal_crons_run_off_loop(route, body):
from backend.api.routes import internal
with patch.object(internal, body, side_effect=_sleep) as mock_body:
ticks = await _ticks_during(getattr(internal, route)(MagicMock(), MagicMock()))
mock_body.assert_called_once()
assert ticks >= MIN_TICKS
@pytest.mark.asyncio
async def test_upload_duration_validation_runs_off_loop():
from backend.api.routes import file_upload
with patch.object(file_upload, "_validate_audio_durations_sync", side_effect=_sleep):
ticks = await _ticks_during(file_upload._validate_audio_durations(MagicMock(), "a.flac", "i.flac"))
assert ticks >= MIN_TICKS
@pytest.mark.asyncio
async def test_youtube_queue_single_upload_runs_off_loop():
from backend.workers import youtube_queue_processor as qp
with patch.object(qp, "_process_single_upload_sync", side_effect=_sleep):
ticks = await _ticks_during(qp._process_single_upload("j1", {}, MagicMock(), MagicMock()))
assert ticks >= MIN_TICKS
@pytest.mark.asyncio
async def test_youtube_queue_quota_and_queue_reads_run_off_loop():
from backend.workers import youtube_queue_processor as qp
quota = MagicMock()
quota.check_quota_available.side_effect = lambda: (_sleep(), (True, 100, "ok"))[1]
queue = MagicMock()
queue.get_queued_uploads.side_effect = lambda **_kw: (_sleep(), [])[1]
with patch.object(qp, "get_youtube_quota_service", return_value=quota), \
patch.object(qp, "get_youtube_upload_queue_service", return_value=queue):
ticks = await _ticks_during(qp.process_youtube_upload_queue())
# 2 x BLOCK_S of blocking work; offloaded it ticks through both.
assert ticks >= 2 * MIN_TICKS
@pytest.mark.asyncio
async def test_cloud_run_job_dispatch_runs_off_loop():
from backend.services.worker_service import WorkerService
client = MagicMock()
client.run_job.side_effect = _sleep
ws = WorkerService.__new__(WorkerService)
ticks = await _ticks_during(ws._run_job_with_retry(client, MagicMock(), log_prefix="[t]"))
client.run_job.assert_called_once()
assert ticks >= MIN_TICKS
@pytest.mark.asyncio
async def test_render_trigger_bumps_generation_off_loop():
from unittest.mock import AsyncMock
from backend.services.worker_service import WorkerService
ws = WorkerService.__new__(WorkerService)
ws._use_cloud_tasks = False
ws.settings = MagicMock(use_cloud_run_jobs_for_render=False)
with patch.object(WorkerService, "_bump_worker_generation", side_effect=_sleep), \
patch.object(WorkerService, "_start_encoding_worker_warmup"), \
patch.object(WorkerService, "trigger_worker", new=AsyncMock(return_value=True)):
ticks = await _ticks_during(ws.trigger_render_video_worker("j1"))
assert ticks >= MIN_TICKS
+1 -2
View File
@@ -1373,8 +1373,7 @@ class TestValidateJobUrlEndpoint:
req = MagicMock()
req.headers = {}
with patch("backend.api.routes.file_upload.get_locale_from_request", return_value="en"):
return asyncio.run(
validate_job_url(
return (validate_job_url(
request=req,
body=ValidateUrlRequest(url=url),
auth_result=MagicMock(),
@@ -0,0 +1,151 @@
"""
Instrumental resolution fixes (storage-retention work, 2026-10-03):
- the GCE encoder's with-backing / clean lookups fail loudly instead of
silently falling back to another instrumental;
- a user-supplied ("existing") instrumental recorded under uploads/ (7-day
lifecycle) resolves to its kept job-root copy, repointing the job.
"""
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
from backend.services.gce_encoding.main import resolve_instrumental
from backend.utils.existing_instrumental import persistent_instrumental_path, resolve_existing_instrumental
def _touch(root: Path, *names):
for name in names:
path = root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b"x")
class TestEncoderLookupIsStrict:
def test_with_backing_found(self, tmp_path):
_touch(tmp_path, "stems/instrumental_clean.flac", "stems/instrumental_with_backing.flac")
assert resolve_instrumental(tmp_path, {"instrumental_selection": "with_backing"}).name == \
"instrumental_with_backing.flac"
def test_with_backing_missing_does_not_fall_back_to_clean(self, tmp_path):
_touch(tmp_path, "stems/instrumental_clean.flac", "custom_instrumental.flac")
assert resolve_instrumental(tmp_path, {"instrumental_selection": "with_backing"}) is None
def test_legacy_named_backing_file_still_found(self, tmp_path):
_touch(tmp_path, "Artist - Title (Instrumental Backing).flac")
assert resolve_instrumental(tmp_path, {"instrumental_selection": "with_backing"}) is not None
def test_clean_found(self, tmp_path):
_touch(tmp_path, "stems/instrumental_clean.flac", "stems/instrumental_with_backing.flac")
assert resolve_instrumental(tmp_path, {"instrumental_selection": "clean"}).name == "instrumental_clean.flac"
@pytest.mark.parametrize("other", [
"stems/instrumental_with_backing.flac", "custom_instrumental.flac", "stems/custom_instrumental.flac",
])
def test_clean_missing_does_not_fall_back(self, tmp_path, other):
_touch(tmp_path, other)
assert resolve_instrumental(tmp_path, {"instrumental_selection": "clean"}) is None
def test_legacy_named_clean_file_still_found(self, tmp_path):
_touch(tmp_path, "Artist - Title (Instrumental Clean).flac")
assert resolve_instrumental(tmp_path, {"instrumental_selection": "clean"}) is not None
class TestExistingInstrumentalResolution:
def _job(self, path="uploads/job1/audio/existing_instrumental.wav"):
return SimpleNamespace(job_id="job1", existing_instrumental_gcs_path=path)
def test_persistent_path(self):
assert persistent_instrumental_path("job1", "uploads/job1/audio/existing_instrumental.wav") == \
"jobs/job1/custom_instrumental.wav"
assert persistent_instrumental_path("job1", "uploads/job1/conformed/existing_instrumental.flac") == \
"jobs/job1/custom_instrumental.flac"
def test_recorded_path_used_when_present(self):
storage = MagicMock()
storage.file_exists.return_value = True
jm = MagicMock()
assert resolve_existing_instrumental(self._job(), storage, jm) == "uploads/job1/audio/existing_instrumental.wav"
jm.update_job.assert_not_called()
def test_expired_upload_falls_back_to_staged_copy_and_repoints(self):
storage = MagicMock()
storage.file_exists.return_value = False
storage.list_files.return_value = [
"jobs/job1/input/song.flac", "jobs/job1/stems/custom_instrumental.flac",
"jobs/job1/custom_instrumental.wav",
]
jm, log = MagicMock(), MagicMock()
assert resolve_existing_instrumental(self._job(), storage, jm, log) == "jobs/job1/custom_instrumental.wav"
jm.update_job.assert_called_once_with("job1", {"existing_instrumental_gcs_path": "jobs/job1/custom_instrumental.wav"})
log.warning.assert_called_once()
def test_legacy_existing_instrumental_staged_name(self):
storage = MagicMock()
storage.file_exists.return_value = False
storage.list_files.return_value = ["jobs/job1/existing_instrumental.mp3"]
assert resolve_existing_instrumental(self._job(), storage) == "jobs/job1/existing_instrumental.mp3"
def test_nothing_staged_keeps_recorded_path(self):
storage = MagicMock()
storage.file_exists.return_value = False
storage.list_files.return_value = ["jobs/job1/stems/custom_instrumental.flac"]
jm = MagicMock()
assert resolve_existing_instrumental(self._job(), storage, jm) == "uploads/job1/audio/existing_instrumental.wav"
jm.update_job.assert_not_called()
def test_no_existing_instrumental(self):
assert resolve_existing_instrumental(self._job(path=None), MagicMock()) is None
class TestOrchestratorStagingRepoints:
@pytest.mark.asyncio
async def test_staging_from_uploads_repoints_job(self):
from backend.workers.video_worker_orchestrator import OrchestratorConfig, VideoWorkerOrchestrator
config = OrchestratorConfig(
job_id="job1", artist="A", title="T", title_video_path="", karaoke_video_path="",
instrumental_audio_path="", existing_instrumental_gcs_path="uploads/job1/audio/existing_instrumental.wav",
)
jm, storage = MagicMock(), MagicMock()
orch = VideoWorkerOrchestrator(config=config, job_manager=jm, storage=storage)
backend = MagicMock()
backend.name = "gce"
backend.encode = MagicMock(side_effect=RuntimeError("stop after staging"))
orch._get_encoding_backend = MagicMock(return_value=backend)
async def boom(*args, **kwargs):
raise RuntimeError("stop after staging")
from unittest.mock import patch
with patch("backend.services.encoding_service.run_with_lost_job_resubmit", side_effect=boom):
with pytest.raises(RuntimeError):
await orch._run_encoding()
storage.copy_blob.assert_called_once_with(
"uploads/job1/audio/existing_instrumental.wav", "jobs/job1/custom_instrumental.wav")
jm.update_job.assert_any_call("job1", {"existing_instrumental_gcs_path": "jobs/job1/custom_instrumental.wav"})
@pytest.mark.asyncio
async def test_already_persisted_path_is_not_recopied(self):
from unittest.mock import patch
from backend.workers.video_worker_orchestrator import OrchestratorConfig, VideoWorkerOrchestrator
config = OrchestratorConfig(
job_id="job1", artist="A", title="T", title_video_path="", karaoke_video_path="",
instrumental_audio_path="", existing_instrumental_gcs_path="jobs/job1/custom_instrumental.wav",
)
jm, storage = MagicMock(), MagicMock()
orch = VideoWorkerOrchestrator(config=config, job_manager=jm, storage=storage)
backend = MagicMock()
backend.name = "gce"
orch._get_encoding_backend = MagicMock(return_value=backend)
async def boom(*args, **kwargs):
raise RuntimeError("stop")
with patch("backend.services.encoding_service.run_with_lost_job_resubmit", side_effect=boom):
with pytest.raises(RuntimeError):
await orch._run_encoding()
storage.copy_blob.assert_not_called()
+54
View File
@@ -167,6 +167,60 @@ class TestScreensWorkerEndpoint:
assert response.status_code == 401
class TestScreensWorkerInlineInCloudTasksMode:
"""Prod (Cloud Tasks) runs screens INLINE so CPU stays allocated and the
heavy steps run in worker threads instead of a post-response BackgroundTask."""
def _settings(self, enable_cloud_tasks):
s = MagicMock()
s.enable_cloud_tasks = enable_cloud_tasks
return s
def test_cloud_tasks_mode_awaits_worker_inline(self, client, auth_headers):
import backend.api.routes.internal as internal_mod
with patch('backend.config.get_settings', return_value=self._settings(True)):
internal_mod.generate_screens.reset_mock()
internal_mod.generate_screens.return_value = True
response = client.post(
"/api/internal/workers/screens", headers=auth_headers, json={"job_id": "test123"}
)
assert response.status_code == 200
assert response.json()["status"] == "completed"
internal_mod.generate_screens.assert_awaited_once_with("test123")
def test_cloud_tasks_mode_worker_failure_still_200(self, client, auth_headers):
"""A handled failure must not return non-2xx (Cloud Tasks would re-run it)."""
import backend.api.routes.internal as internal_mod
with patch('backend.config.get_settings', return_value=self._settings(True)):
internal_mod.generate_screens.return_value = False
response = client.post(
"/api/internal/workers/screens", headers=auth_headers, json={"job_id": "test123"}
)
assert response.status_code == 200
assert response.json()["status"] == "failed"
def test_cloud_tasks_mode_worker_exception_still_200(self, client, auth_headers):
import backend.api.routes.internal as internal_mod
with patch('backend.config.get_settings', return_value=self._settings(True)):
internal_mod.generate_screens.side_effect = RuntimeError("boom")
try:
response = client.post(
"/api/internal/workers/screens", headers=auth_headers, json={"job_id": "test123"}
)
finally:
internal_mod.generate_screens.side_effect = None
assert response.status_code == 200
assert response.json()["status"] == "failed"
def test_direct_http_mode_keeps_background_task(self, client, auth_headers):
with patch('backend.config.get_settings', return_value=self._settings(False)):
response = client.post(
"/api/internal/workers/screens", headers=auth_headers, json={"job_id": "test123"}
)
assert response.status_code == 200
assert response.json()["status"] == "started"
class TestVideoWorkerEndpoint:
"""Tests for POST /api/internal/workers/video."""
+68
View File
@@ -0,0 +1,68 @@
"""Per-key locks restore per-instance serialization for threadpool route handlers."""
import threading
import time
from unittest.mock import MagicMock
from backend.utils.keyed_lock import KeyedLocks
def test_same_key_serializes_different_keys_dont():
locks = KeyedLocks()
order = []
def worker(key, tag):
with locks.hold(key):
order.append(f"{tag}-in")
time.sleep(0.1)
order.append(f"{tag}-out")
t1 = threading.Thread(target=worker, args=("job1", "a"))
t2 = threading.Thread(target=worker, args=("job1", "b"))
t1.start(); time.sleep(0.02); t2.start()
t1.join(); t2.join()
assert order == ["a-in", "a-out", "b-in", "b-out"]
start = time.monotonic()
t3 = threading.Thread(target=worker, args=("x", "c"))
t4 = threading.Thread(target=worker, args=("y", "d"))
t3.start(); t4.start(); t3.join(); t4.join()
assert time.monotonic() - start < 0.18 # ran in parallel
def test_reentrant_and_cleans_up():
locks = KeyedLocks()
with locks.hold("k"):
with locks.hold("k"):
pass
assert locks._locks == {} and locks._refs == {}
def test_concurrent_cancel_refunds_once():
"""Two threads cancelling the same job: the second must see CANCELLED and no-op."""
from backend.models.job import JobStatus
from backend.services import job_manager as jm_mod
state = {"status": JobStatus.AWAITING_REVIEW}
jm = jm_mod.JobManager.__new__(jm_mod.JobManager)
def get_job(_id):
time.sleep(0.05) # widen the check-then-write window
job = MagicMock()
job.status = state["status"]
return job
def update_job_status(job_id, status, message):
state["status"] = status
jm.get_job = get_job
jm.update_job_status = update_job_status
jm._refund_credit_for_job = MagicMock()
results = []
threads = [threading.Thread(target=lambda: results.append(jm.cancel_job("j1"))) for _ in range(2)]
for t in threads:
t.start()
for t in threads:
t.join()
assert sorted(results) == [False, True]
jm._refund_credit_for_job.assert_called_once()
@@ -44,7 +44,7 @@ async def _call_summary(auth: AuthResult):
patch("backend.api.routes.jobs.job_manager") as mock_jm:
# Return a fresh copy each call so pruning doesn't mutate shared state.
mock_jm.list_jobs_summary.return_value = [dict(j) for j in JOBS]
return await list_jobs(request, fields="summary", auth_result=auth)
return list_jobs(request, fields="summary", auth_result=auth)
@pytest.mark.asyncio
+292
View File
@@ -0,0 +1,292 @@
"""Tests for the event-loop stall watchdog (backend/services/loop_watchdog.py)."""
import asyncio
import logging
import time
import pytest
from unittest.mock import patch
from backend.services.loop_watchdog import LoopWatchdog, _format_stack
def _blocking_culprit_function(seconds: float) -> None:
time.sleep(seconds) # deliberately blocks the event loop
class FakeClock:
def __init__(self):
self.t = 1000.0
def __call__(self):
return self.t
class TestCheckStateMachine:
"""Drive check() with a fake clock — no threads, fully deterministic."""
def _wd(self, **kw):
clock = FakeClock()
recorded = []
# cpu_clock tracks wall time: the process was running (not throttled) between checks.
kw.setdefault("cpu_clock", clock)
wd = LoopWatchdog(clock=clock, recorder=recorded.append, **kw)
wd._loop_thread_id = None # no real frames in these tests
return wd, clock, recorded
def test_no_stall_when_ticking(self, caplog):
wd, clock, recorded = self._wd()
for _ in range(10):
clock.t += 0.25
wd._last_tick = clock.t
wd.check()
assert not wd._in_stall
assert recorded == []
assert "EVENT_LOOP_STALL" not in caplog.text
def test_short_stall_logged_not_recorded(self, caplog):
caplog.set_level(logging.WARNING)
wd, clock, recorded = self._wd()
wd._last_tick = clock.t
clock.t += 2.0
wd.check()
assert wd._in_stall
clock.t += 0.25
wd._last_tick = clock.t # heartbeat resumes
wd.check()
assert not wd._in_stall
assert "EVENT_LOOP_STALL ended duration_ms=2000" in caplog.text
assert recorded == [] # below 5s record threshold
ended = [r for r in caplog.records if "ended" in r.getMessage()]
assert ended[0].levelno == logging.WARNING
def test_long_stall_recorded_and_error(self, caplog):
caplog.set_level(logging.WARNING)
wd, clock, recorded = self._wd()
wd._last_tick = clock.t
for step in (1.0, 5.0, 12.0):
clock.t = 1000.0 + step
wd.check()
clock.t = 1000.0 + 12.25
wd._last_tick = clock.t
wd.check()
assert len(recorded) == 1
assert recorded[0]["duration_ms"] == 12000
ended = [r for r in caplog.records if "ended" in r.getMessage()]
assert ended[0].levelno == logging.ERROR
def test_sub_threshold_gap_ignored(self, caplog):
wd, clock, recorded = self._wd()
wd._last_tick = clock.t
clock.t += 0.9
wd.check()
assert not wd._in_stall
class TestRealLoop:
"""End-to-end: a real blocking call on the loop is detected with its stack."""
@pytest.mark.asyncio
async def test_detects_blocking_call_with_stack(self, caplog):
caplog.set_level(logging.WARNING, logger="backend.services.loop_watchdog")
recorded = []
wd = LoopWatchdog(
tick_s=0.05,
stall_threshold_s=0.3,
record_threshold_s=0.5,
error_threshold_s=5.0,
sample_at_s=(0.3,),
recorder=recorded.append,
)
wd.start()
try:
await asyncio.sleep(0.15) # let the heartbeat run
_blocking_culprit_function(0.8)
await asyncio.sleep(0.3) # let the loop resume and the thread notice
finally:
await wd.stop()
assert "_blocking_culprit_function" in caplog.text
assert len(recorded) == 1
assert recorded[0]["duration_ms"] >= 500
assert "_blocking_culprit_function" in recorded[0]["culprit"]
@pytest.mark.asyncio
async def test_quiet_when_loop_stays_responsive(self, caplog):
caplog.set_level(logging.WARNING, logger="backend.services.loop_watchdog")
wd = LoopWatchdog(tick_s=0.05, stall_threshold_s=0.3)
wd.start()
try:
await asyncio.to_thread(time.sleep, 0.6) # offloaded — loop free
finally:
await wd.stop()
assert "EVENT_LOOP_STALL" not in caplog.text
def test_format_stack_none():
assert _format_stack(None) == ("", "")
class TestIdleGapSuppression:
"""CPU-throttled idle instances: the watchdog thread can wake before the
heartbeat, see a big gap, but the loop is parked in select() — not blocked."""
def _run_gap(self, idle: bool, caplog):
caplog.set_level(logging.DEBUG, logger="backend.services.loop_watchdog")
clock = FakeClock()
recorded = []
wd = LoopWatchdog(clock=clock, recorder=recorded.append, cpu_clock=clock)
wd._loop_thread_id = 12345
with patch("backend.services.loop_watchdog._is_idle_frame", return_value=idle), \
patch("backend.services.loop_watchdog.sys._current_frames", return_value={12345: None}):
wd._last_tick = clock.t
for step in (1.0, 5.0, 15.0, 40.0):
clock.t = 1000.0 + step
wd.check()
clock.t = 1000.0 + 40.25
wd._last_tick = clock.t
wd.check()
return recorded
def test_all_idle_samples_are_not_a_stall(self, caplog):
recorded = self._run_gap(idle=True, caplog=caplog)
assert recorded == []
assert "EVENT_LOOP_STALL ended" not in caplog.text
assert "ignored idle gap" in caplog.text
def test_non_idle_samples_are_a_stall(self, caplog):
recorded = self._run_gap(idle=False, caplog=caplog)
assert len(recorded) == 1
assert "EVENT_LOOP_STALL ended" in caplog.text
class TestThrottledProcessFreeze:
"""Cloud Run CPU throttling freezes every thread: the watchdog oversleeps and the
process burns ~no CPU. That gap is not a loop stall (2026-10-08 false alert:
30s "stall" in asyncio get_debug with no request in flight)."""
def _wd(self):
clock = FakeClock()
cpu = FakeClock() # advances only when the test says the process ran
recorded = []
wd = LoopWatchdog(clock=clock, cpu_clock=cpu, recorder=recorded.append)
wd._loop_thread_id = 12345
return wd, clock, cpu, recorded
def _check(self, wd):
with patch("backend.services.loop_watchdog._is_idle_frame", return_value=False), \
patch("backend.services.loop_watchdog.sys._current_frames", return_value={12345: None}):
wd.check()
def test_frozen_gap_is_not_reported(self, caplog):
caplog.set_level(logging.DEBUG, logger="backend.services.loop_watchdog")
wd, clock, cpu, recorded = self._wd()
wd._last_tick = clock.t
self._check(wd) # baseline check
clock.t += 30.0 # whole process frozen 30s, no CPU used
self._check(wd)
clock.t += 0.25
cpu.t += 0.01
wd._last_tick = clock.t # thawed: heartbeat resumes
self._check(wd)
assert recorded == []
assert "EVENT_LOOP_STALL" not in caplog.text
assert "discounted 30000ms of process freeze" in caplog.text
def test_short_partial_throttle_freeze_is_not_reported(self, caplog):
"""Partial throttling: the watchdog gets a slice every ~1.5s, burning ~no CPU."""
caplog.set_level(logging.WARNING)
wd, clock, cpu, recorded = self._wd()
wd._last_tick = clock.t
self._check(wd)
for _ in range(2): # 2 x 1.5s sparse wake-ups, loop never ticks
clock.t += 1.5
cpu.t += 0.002
self._check(wd)
clock.t += 0.25
cpu.t += 0.01
wd._last_tick = clock.t
self._check(wd)
assert recorded == []
assert "EVENT_LOOP_STALL" not in caplog.text
def test_blocking_io_stall_still_reported(self, caplog):
"""Blocking I/O on the loop: the watchdog keeps waking on time (GIL released)."""
caplog.set_level(logging.WARNING)
wd, clock, cpu, recorded = self._wd()
wd._last_tick = clock.t
self._check(wd)
for _ in range(int(12 / 0.25)): # 12s stall, watchdog wakes every tick
clock.t += 0.25
cpu.t += 0.001
self._check(wd)
clock.t += 0.25
wd._last_tick = clock.t
self._check(wd)
assert len(recorded) == 1
assert "EVENT_LOOP_STALL ended duration_ms=12000" in caplog.text
def test_cpu_bound_gil_hog_still_reported(self, caplog):
"""GIL-holding CPU work also starves the watchdog, but the process burns CPU."""
caplog.set_level(logging.WARNING)
wd, clock, cpu, recorded = self._wd()
wd._last_tick = clock.t
self._check(wd)
clock.t += 20.0
cpu.t += 19.5
self._check(wd)
clock.t += 0.25
wd._last_tick = clock.t
self._check(wd)
assert len(recorded) == 1
assert "EVENT_LOOP_STALL ended duration_ms=20000" in caplog.text
def test_freeze_inside_real_stall_is_subtracted(self, caplog):
"""8s of real blocking then a 30s freeze reports ~8s, not 38s."""
caplog.set_level(logging.WARNING)
wd, clock, cpu, recorded = self._wd()
wd._last_tick = clock.t
self._check(wd)
for _ in range(int(8 / 0.25)):
clock.t += 0.25
cpu.t += 0.001
self._check(wd)
clock.t += 30.0 # frozen
self._check(wd)
clock.t += 0.25
wd._last_tick = clock.t
self._check(wd)
assert "EVENT_LOOP_STALL ended duration_ms=8000" in caplog.text
assert recorded[0]["duration_ms"] == 8000
def test_is_idle_frame_detects_parked_selector():
"""A thread blocked in selectors' select() is classified idle; a busy one isn't."""
import selectors
import socket
import sys
import threading
from backend.services.loop_watchdog import _is_idle_frame
a, b = socket.socketpair()
sel = selectors.DefaultSelector()
sel.register(a, selectors.EVENT_READ)
started = threading.Event()
def park():
started.set()
sel.select(timeout=2)
t = threading.Thread(target=park)
t.start()
started.wait()
time.sleep(0.2)
try:
assert _is_idle_frame(sys._current_frames()[t.ident]) is True
assert _is_idle_frame(sys._current_frames()[threading.get_ident()]) is False
finally:
b.send(b"x")
t.join()
sel.close()
a.close()
b.close()
+44
View File
@@ -67,3 +67,47 @@ def test_lifespan_starts_warmup_thread_without_blocking_readiness():
assert not warmup_release.is_set()
finally:
warmup_release.set()
def test_lazy_route_modules_import_before_readiness_off_loop():
"""httpx & co. are imported in a worker thread during lifespan startup, before
the first request (cold-start importlib stalls, 2026-10-08)."""
import importlib
seen = []
real_import = importlib.import_module
def tracking_import(name, *a, **kw):
if name in main_module._LAZY_ROUTE_IMPORTS:
seen.append((name, threading.current_thread().name))
return real_import(name, *a, **kw)
with patch.object(main_module, "_run_background_warmup"), \
patch.object(importlib, "import_module", side_effect=tracking_import):
with TestClient(main_module.app):
pass
assert [name for name, _ in seen] == list(main_module._LAZY_ROUTE_IMPORTS)
# asyncio.to_thread's default-executor workers, i.e. not the event-loop thread.
assert all(thread.startswith("asyncio_") for _, thread in seen), seen
def test_lazy_route_import_failure_is_non_fatal():
import importlib
with patch.object(importlib, "import_module", side_effect=ImportError("nope")):
main_module._import_lazy_route_modules() # logs, doesn't raise
def test_slow_lazy_route_import_does_not_block_startup(caplog):
import logging
import time
caplog.set_level(logging.ERROR)
with patch.object(main_module, "_run_background_warmup"), \
patch.object(main_module, "LAZY_ROUTE_IMPORT_TIMEOUT_S", 0.05), \
patch.object(main_module, "_import_lazy_route_modules", side_effect=lambda: time.sleep(0.5)):
with TestClient(main_module.app):
pass
assert "exceeded 0.05s; continuing startup" in caplog.text
@@ -0,0 +1,281 @@
"""Guard: no FastAPI route may be ``async def`` without awaiting anything.
The API runs one uvicorn process with one event loop per Cloud Run instance.
An ``async def`` handler runs ON that loop, so every sync Firestore / GCS /
HTTP / email / LLM call inside it freezes every other request on the instance
(users see the "Reconnecting" / "servers unavailable" banner). A plain ``def``
handler is run by FastAPI in its threadpool instead. On 2026-10-03, 168
handlers were async-without-await; 161 were converted (trivial no-call ones like health checks stay async) and this test keeps it
that way.
Fix a failure by making the handler a plain ``def`` (FastAPI then runs it in
the threadpool), or, if it genuinely needs to be async, ``await`` its blocking
work via ``asyncio.to_thread(...)``.
"""
import ast
from pathlib import Path
BACKEND = Path(__file__).resolve().parents[1]
ROUTE_FILES = sorted((BACKEND / "api" / "routes").glob("*.py")) + [BACKEND / "main.py"]
HTTP_VERBS = {"get", "post", "put", "patch", "delete", "head", "options", "api_route"}
def _awaits_directly(fn: ast.AsyncFunctionDef) -> bool:
"""True if fn's own body (excluding nested function scopes) awaits."""
stack = list(fn.body)
while stack:
node = stack.pop()
if isinstance(node, (ast.Await, ast.AsyncFor, ast.AsyncWith)):
return True
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)):
continue
stack.extend(ast.iter_child_nodes(node))
return False
_LOOP_APIS = {"create_task", "ensure_future", "get_running_loop", "get_event_loop"}
def _uses_loop_api(fn) -> bool:
"""True if fn's own body calls a running-loop API (asyncio.create_task etc.).
Such a handler genuinely needs to run ON the loop: in FastAPI's threadpool
there is no running loop, so create_task raises (or, if the RuntimeError is
swallowed, the work is silently dropped).
"""
stack = list(fn.body)
while stack:
node = stack.pop()
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)):
continue
if isinstance(node, ast.Attribute) and node.attr in _LOOP_APIS:
return True
stack.extend(ast.iter_child_nodes(node))
return False
def _is_route(fn) -> bool:
return any(
isinstance(d, ast.Call)
and isinstance(d.func, ast.Attribute)
and d.func.attr in HTTP_VERBS
for d in fn.decorator_list
)
def _is_trivial(fn) -> bool:
"""No calls at all in the body (e.g. a health check returning a literal dict) —
can't block, and keeping it async means it never waits for a threadpool slot."""
return not any(isinstance(c, ast.Call) for stmt in fn.body for c in ast.walk(stmt))
def find_offenders(source: str) -> list[str]:
"""async routes that never await (and don't need the loop, and aren't trivial)."""
tree = ast.parse(source)
return [
n.name
for n in ast.walk(tree)
if isinstance(n, ast.AsyncFunctionDef)
and _is_route(n)
and not _awaits_directly(n)
and not _uses_loop_api(n)
and not _is_trivial(n)
]
def find_loopless_sync_routes(source: str) -> list[str]:
"""Plain-def routes that call a running-loop API — broken in the threadpool."""
tree = ast.parse(source)
return [
n.name
for n in ast.walk(tree)
if isinstance(n, ast.FunctionDef) and _is_route(n) and _uses_loop_api(n)
]
def test_no_async_route_without_await():
offenders = []
for path in ROUTE_FILES:
for name in find_offenders(path.read_text()):
offenders.append(f"{path.relative_to(BACKEND.parent)}::{name}")
assert not offenders, (
"These routes are `async def` but never await, so their sync work blocks the "
"event loop for every request. Make them plain `def` (FastAPI runs them in "
"its threadpool) or await blocking work via asyncio.to_thread:\n "
+ "\n ".join(offenders)
)
def test_no_sync_route_uses_running_loop_apis():
offenders = []
for path in ROUTE_FILES:
for name in find_loopless_sync_routes(path.read_text()):
offenders.append(f"{path.relative_to(BACKEND.parent)}::{name}")
assert not offenders, (
"These plain-`def` routes call asyncio.create_task/get_running_loop, which "
"fails (or silently no-ops) in FastAPI's threadpool. Keep them `async def`:\n "
+ "\n ".join(offenders)
)
def find_awaited_sync_routes(source: str) -> list[str]:
"""`await some_sync_route(...)` within the same module — a TypeError at runtime
(awaiting the return value), usually swallowed by a broad except."""
tree = ast.parse(source)
sync_routes = {
n.name for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and _is_route(n)
}
hits = []
for node in ast.walk(tree):
if isinstance(node, ast.Await) and isinstance(node.value, ast.Call):
fn = node.value.func
# Bare names only: `await svc.health_check()` is a different object's
# (async) method that merely shares a route's name.
if isinstance(fn, ast.Name) and fn.id in sync_routes:
hits.append(fn.id)
return hits
def test_no_await_of_sync_route_handlers():
offenders = []
for path in ROUTE_FILES:
for name in find_awaited_sync_routes(path.read_text()):
offenders.append(f"{path.relative_to(BACKEND.parent)}::await {name}(...)")
assert not offenders, (
"These code paths `await` a plain-`def` route handler (TypeError at runtime). "
"Call it via `await asyncio.to_thread(handler, ...)` instead:\n "
+ "\n ".join(offenders)
)
def test_detector_flags_and_allows_correctly():
src = '''
@router.get("/a")
async def bad(): return db.get()
@router.get("/b")
async def good():
return await asyncio.to_thread(db.get)
@router.post("/c")
def sync_ok(): return db.get()
@router.get("/health")
async def trivial(): return {"status": "ok"}
@router.post("/d")
async def nested_only():
async def _bg():
await x()
tasks.add_task(_bg)
async def not_a_route(): return 1
@router.post("/e")
async def spawns_task():
async def _bg():
await x()
asyncio.create_task(_bg())
@router.post("/f")
def sync_spawns_task():
asyncio.get_running_loop().create_task(x())
'''
assert sorted(find_offenders(src)) == ["bad", "nested_only"]
assert find_loopless_sync_routes(src) == ["sync_spawns_task"]
caller = src + '''
async def helper():
await sync_ok()
await asyncio.to_thread(sync_ok)
await client.sync_ok()
'''
assert find_awaited_sync_routes(caller) == ["sync_ok"]
# Known-blocking calls (network / Secret Manager I/O) that awaiting *something else*
# in the same handler doesn't excuse. On 2026-10-07 the routes below awaited
# request.json() etc. (so test_no_async_route_without_await passed) yet froze the
# loop 5-16s: a Dropbox token refresh (HTTP + Secret Manager write) inside
# check_dropbox_credentials, and the GDrive validator's OIDC fetch + POST.
# Pass these to asyncio.to_thread(fn, ...) — a reference, not a call — instead.
BLOCKING_CALLS = {
"check_youtube_credentials",
"check_dropbox_credentials",
"check_gdrive_credentials",
"check_all_credentials",
"trigger_gdrive_validation",
}
_BLOCKING_MODULE_CALLS = {("requests", "get"), ("requests", "post"), ("requests", "put"),
("requests", "delete"), ("requests", "request"), ("time", "sleep")}
def _blocking_call_name(call: ast.Call) -> str | None:
fn = call.func
if isinstance(fn, ast.Name) and fn.id in BLOCKING_CALLS:
return fn.id
if isinstance(fn, ast.Attribute):
if fn.attr in BLOCKING_CALLS:
return fn.attr
if isinstance(fn.value, ast.Name) and (fn.value.id, fn.attr) in _BLOCKING_MODULE_CALLS:
return f"{fn.value.id}.{fn.attr}"
return None
def find_blocking_calls_in_async_routes(source: str) -> list[str]:
"""`async def` routes that directly call a known-blocking function (excluding
nested sync helpers, which are presumably run via to_thread)."""
tree = ast.parse(source)
hits = []
for fn in ast.walk(tree):
if not (isinstance(fn, ast.AsyncFunctionDef) and _is_route(fn)):
continue
stack = list(fn.body)
while stack:
node = stack.pop()
if isinstance(node, (ast.FunctionDef, ast.Lambda, ast.ClassDef)):
continue
if isinstance(node, ast.Call) and (name := _blocking_call_name(node)):
hits.append(f"{fn.name}: {name}() line {node.lineno}")
stack.extend(ast.iter_child_nodes(node))
return hits
def test_no_known_blocking_calls_in_async_routes():
offenders = []
for path in ROUTE_FILES:
for hit in find_blocking_calls_in_async_routes(path.read_text()):
offenders.append(f"{path.relative_to(BACKEND.parent)}::{hit}")
assert not offenders, (
"These `async def` routes call known-blocking functions directly on the event "
"loop. Use `await asyncio.to_thread(fn, ...)`:\n " + "\n ".join(sorted(offenders))
)
def test_blocking_call_detector():
src = '''
@router.post("/a")
async def bad(request):
await request.json()
cm.check_dropbox_credentials()
requests.post(url)
@router.post("/b")
async def good(request):
await request.json()
await asyncio.to_thread(cm.check_dropbox_credentials)
await asyncio.to_thread(trigger_gdrive_validation, brand_code="X")
@router.post("/c")
def sync_ok():
cm.check_dropbox_credentials()
@router.post("/d")
async def helper_ok():
def _work():
return trigger_gdrive_validation()
await asyncio.to_thread(_work)
'''
hits = find_blocking_calls_in_async_routes(src)
assert sorted(h.split(" line")[0] for h in hits) == [
"bad: check_dropbox_credentials()", "bad: requests.post()"]
@@ -69,10 +69,11 @@ def _mock_jm(*, downloading=None, pending=None, rendering=None, review_complete=
where.stream.side_effect = [
iter(downloading or []), iter(rendering or []), iter(review_complete or []),
]
# Two .limit().stream() calls in order: download_pending_retry, then downloading
# (lost-screens-trigger sweep, bounded by SCREENS_RECOVERY_SCAN_LIMIT)
# Three .limit().stream() calls in order: download_pending_retry, then downloading
# (lost-screens-trigger sweep, bounded by SCREENS_RECOVERY_SCAN_LIMIT), then
# lyrics_complete (stalled storage-retention stems restore)
where.limit.return_value.stream.side_effect = [
iter(pending or []), iter(downloading_prep or []),
iter(pending or []), iter(downloading_prep or []), iter([]),
]
mock_jm.get_job.side_effect = lambda jid: (jobs or {}).get(jid)
mock_jm.transition_to_state.return_value = True
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,101 @@
"""The "waiting for encoding server" marker is cleared once a retried render really runs.
Incident 2026-10-06 (job ebfe4344): after the encoding worker was fixed, the
retried render ran normally but the job card still said "(waiting for encoding
server availability)" because state_data.render_pending_capacity from the earlier
parked attempts was never removed.
"""
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from backend.models.job import JobStatus
def _job(state_data, status=JobStatus.REVIEW_COMPLETE):
job = MagicMock()
job.artist = "Randy Vild"
job.title = "We'll Never Die"
job.input_media_gcs_path = "jobs/test/audio.flac"
job.style_assets = {}
job.style_params_gcs_path = None
job.subtitle_offset_ms = 0
job.prep_only = False
job.state_data = {"worker_generation": 1, "is_duet": False, **state_data}
job.file_urls = {}
job.status = status
return job
async def _run(state_data, ticks):
from backend.workers import render_video_worker as rvw
job_start = _job(state_data)
job_after = _job(state_data, status=JobStatus.RENDERING_VIDEO)
jm = MagicMock()
calls = {"n": 0}
def _get_job(_job_id):
calls["n"] += 1
return job_start if calls["n"] == 1 else job_after
jm.get_job.side_effect = _get_job
jm.transition_to_state.return_value = True
async def _render(_job_id, _config, progress_callback=None):
for tick in ticks:
progress_callback(tick)
return {"output_files": ["gs://b/jobs/test/videos/with_vocals.mkv"], "metadata": {}}
encoding_service = MagicMock()
encoding_service.is_enabled = True
encoding_service.render_video_on_gce = AsyncMock(side_effect=_render)
storage = MagicMock()
storage.file_exists.return_value = False
with patch.object(rvw, "JobManager", return_value=jm), \
patch.object(rvw, "StorageService", return_value=storage), \
patch.object(rvw, "get_settings"), \
patch.object(rvw, "create_job_logger", return_value=MagicMock()), \
patch.object(rvw, "setup_job_logging", return_value=MagicMock()), \
patch.object(rvw, "validate_worker_can_run", return_value=None), \
patch.object(rvw, "get_encoding_service", return_value=encoding_service):
result = await rvw.process_render_video("ebfe4344")
return result, jm
PENDING = {"render_pending_capacity": {"attempt_count": 7, "last_code": "worker_infra_failure"}}
@pytest.mark.asyncio
async def test_marker_cleared_once_on_first_real_progress():
result, jm = await _run(PENDING, ticks=[10, 50, 100])
assert result is True
clears = [
c for c in jm.delete_state_data_key.call_args_list
if c.args == ("ebfe4344", "render_pending_capacity")
]
assert len(clears) == 1
@pytest.mark.asyncio
async def test_marker_kept_until_worker_reports_progress():
# A zero-progress tick (queued on the worker) is not proof the render is running.
_, jm = await _run(PENDING, ticks=[0])
assert not any(
c.args == ("ebfe4344", "render_pending_capacity")
for c in jm.delete_state_data_key.call_args_list
)
@pytest.mark.asyncio
async def test_no_delete_when_job_was_never_parked():
_, jm = await _run({}, ticks=[10, 50])
assert not any(
c.args == ("ebfe4344", "render_pending_capacity")
for c in jm.delete_state_data_key.call_args_list
)
@@ -291,3 +291,30 @@ async def test_worker_skips_job_already_rendering():
mock_job_manager.transition_to_state.assert_not_called()
mock_job_manager.fail_job.assert_not_called()
assert worker_registry.get_active_workers() == {}
@pytest.mark.asyncio
@pytest.mark.parametrize("diverted, error, expected", [(True, None, True), (False, RuntimeError("x"), False)])
async def test_worker_hands_theme_stale_job_to_screens_worker(diverted, error, expected):
"""Theme edited after the screens were made: the worker diverts to the screens
worker (which re-triggers it) instead of rendering; a failed hand-off fails the job."""
from backend.workers import render_video_worker as rvw
mock_job_manager = MagicMock()
mock_job_manager.get_job.return_value = _build_minimal_job(JobStatus.REVIEW_COMPLETE)
divert = AsyncMock(return_value=diverted, side_effect=error)
with patch.object(rvw, "JobManager", return_value=mock_job_manager), \
patch.object(rvw, "StorageService"), \
patch.object(rvw, "get_settings"), \
patch.object(rvw, "create_job_logger", return_value=MagicMock()), \
patch.object(rvw, "setup_job_logging", return_value=MagicMock()), \
patch("backend.services.theme_change_service.divert_for_stale_screens", divert), \
patch.object(rvw, "get_encoding_service") as enc:
result = await rvw.process_render_video("stale-job")
assert result is expected
enc.assert_not_called() # never started rendering
mock_job_manager.transition_to_state.assert_not_called()
assert mock_job_manager.mark_job_failed.called is (error is not None)
assert worker_registry.get_active_workers() == {}
+3 -3
View File
@@ -1087,7 +1087,7 @@ class TestCorrectionsDuetFlag:
mock_request.headers = {}
async def _run():
return await submit_corrections(
return submit_corrections(
job_id=mock_job.job_id,
submission=submission,
http_request=mock_request,
@@ -1219,7 +1219,7 @@ class TestCorrectionsFirestoreDocSize:
mock_request.headers = {}
async def _run():
return await submit_corrections(
return submit_corrections(
job_id=mock_job.job_id,
submission=submission,
http_request=mock_request,
@@ -1307,7 +1307,7 @@ class TestCompleteReviewSegmentGuard:
mock_request.headers = {}
async def _run():
return await complete_review(
return complete_review(
job_id=job.job_id,
body=None,
request=mock_request,
+2 -2
View File
@@ -1401,7 +1401,7 @@ class TestGetPreviewVideoRedirect:
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(
return (get_preview_video(
job_id=job_id,
preview_hash=preview_hash,
auth_info=("user@test.com", "job_owner"),
@@ -1789,7 +1789,7 @@ class TestPreviewVideoStatusEndpoint:
import asyncio
from backend.api.routes.review import get_preview_video_status
with patch("backend.api.routes.review.StorageService", return_value=mock_storage):
return asyncio.run(get_preview_video_status(
return (get_preview_video_status(
job_id=job_id,
preview_hash=preview_hash,
auth_info=("user@test.com", "job_owner"),
+892
View File
@@ -0,0 +1,892 @@
"""
Tests for the storage-retention purge (backend/services/storage_retention.py).
Covers the per-file policy (keep list, purge list, 720p keep, user
instrumentals, finalise-only sources, unknown files), job eligibility
(age, job types, in-flight markers, tenants), per-job planning (input must be
recoverable, bring-your-own-instrumental keeps stems, never outside
jobs/{id}/), file_urls cleanup, and the service: dry-run writes only a report,
real runs delete + record markers/manifest, scoping, batching + cursor,
idempotency and the eligibility re-check at claim time.
"""
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from google.cloud.firestore_v1 import DELETE_FIELD
from backend.services import storage_retention as sr
from backend.services.storage_retention import (
KEEP,
PURGE,
StorageRetentionService,
classify_file,
completed_at,
file_url_deletions,
job_skip_reason,
plan_job,
purge_in_progress,
)
NOW = datetime(2026, 10, 3, 12, 0, tzinfo=timezone.utc)
OLD = (NOW - timedelta(days=45)).isoformat()
# --- classify_file ----------------------------------------------------------------
class TestClassifyFile:
@pytest.mark.parametrize("rel", [
"input/Artist - Title.flac",
"input/edited.flac",
"lyrics/corrections.json",
"lyrics/karaoke.lrc",
"style/style_params.json",
"review_sessions/abc.json",
"audio_edit/session1/stack.json",
"audio_edit_sessions/x.json",
"uploads/custom_instrumental_source.wav",
"packages/cdg_zip.zip",
"packages/txt_zip.zip",
"screens/title.png",
"screens/end.jpg",
"analysis/backing_vocals_waveform.png",
"stems/custom_instrumental.flac",
"stems/custom_instrumental.mp3",
"stems/vocals_derived.flac",
"custom_instrumental.mp3",
"custom_instrumental.wav",
"existing_instrumental.flac",
"quick/lyrics.json",
"something_new/file.bin",
"random_root_file.txt",
])
def test_kept(self, rel):
assert classify_file(rel)[0] == KEEP
@pytest.mark.parametrize("rel, category", [
("finals/lossless_4k_mp4.mp4", "finals"),
("finals/lossless_4k_mkv.mkv", "finals"),
("finals/lossy_4k_mp4.mp4", "finals"),
("finals/with_vocals_mp4.mp4", "finals"),
("finals/portrait_1080x1920.mp4", "finals"),
("finals/title_mov.mov", "finals"),
("finals/Artist - Title (Final Karaoke Lossless 4k).mp4", "finals"),
("finals/Artist - Title (Final Karaoke Lossy 4k).mp4", "finals"),
("finals/Artist - Title (Karaoke).mp4", "finals"),
("finals/Artist - Title (With Vocals).mp4", "finals"),
("finals/Artist - Title (Title).mov", "finals"),
("videos/with_vocals.mkv", "videos"),
("previews/f9d280ecd095.mp4", "previews"),
("previews/f9d280ecd095.ass", "previews"),
("encoded/out.mp4", "encoded"),
("quick/video.mp4", "quick"),
("screens/title.mov", "screens_mov"),
("screens/end.mov", "screens_mov"),
("review-audio/instrumental_clean.ogg", "review_audio"),
("review-audio/waveform_review_500.json", "review_audio"),
("stems/instrumental_clean.flac", "stems"),
("stems/instrumental_with_backing.flac", "stems"),
("stems/vocals_clean.flac", "stems"),
("stems/lead_vocals.flac", "stems"),
("stems/backing_vocals.flac", "stems"),
])
def test_purged(self, rel, category):
assert classify_file(rel) == (PURGE, category)
@pytest.mark.parametrize("rel", [
"finals/lossy_720p_mp4.mp4",
"finals/Artist - Title (Final Karaoke Lossy 720p).mp4",
# artist/title containing format words must not confuse the 720p keep
"finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 720p).mp4",
])
def test_720p_final_is_kept(self, rel):
assert classify_file(rel) == (KEEP, "final_720p")
def test_720p_lookalike_title_is_still_purged(self):
# "720p" in the title but the format tag says 4K
assert classify_file("finals/720p Song - X (Final Karaoke Lossy 4k).mp4")[0] == PURGE
@pytest.mark.parametrize("rel", [
"videos/with_vocals.mkv",
"videos/with_vocals.mov",
"screens/title.mov",
"screens/end.mov",
"stems/instrumental_clean.flac",
"stems/instrumental_with_backing.flac",
])
def test_finalise_only_sources_are_kept(self, rel):
assert classify_file(rel, finalise_only=True)[0] == KEEP
def test_finalise_only_still_purges_regenerable_finals(self):
assert classify_file("finals/lossy_4k_mp4.mp4", finalise_only=True)[0] == PURGE
def test_unrecoverable_stems_are_kept(self):
assert classify_file("stems/instrumental_clean.flac", stems_purgeable=False) == (KEEP, "stems_unrecoverable")
# --- completed_at / eligibility ---------------------------------------------------
def _job(**overrides):
job = {
"job_id": "job1",
"status": "complete",
"timeline": [
{"status": "encoding", "timestamp": (NOW - timedelta(days=46)).isoformat()},
{"status": "complete", "timestamp": OLD},
],
"input_media_gcs_path": "jobs/job1/input/song.flac",
"state_data": {"instrumental_selection": "clean"},
"file_urls": {"lyrics": {"corrections": "jobs/job1/lyrics/corrections.json"}},
"theme_id": "nomad",
"tenant_id": "",
}
job.update(overrides)
return job
class TestEligibility:
def test_completed_at_uses_latest_complete_entry(self):
later = (NOW - timedelta(days=3)).isoformat()
job = _job(timeline=[{"status": "complete", "timestamp": OLD},
{"status": "complete", "timestamp": later}])
assert completed_at(job) == datetime.fromisoformat(later)
def test_completed_at_falls_back_to_updated_at(self):
assert completed_at(_job(timeline=[], updated_at=NOW)) == NOW
def test_naive_timestamps_are_utc(self):
assert completed_at(_job(timeline=[{"status": "complete", "timestamp": "2026-08-01T10:00:00"}])).tzinfo
def test_old_complete_job_is_candidate(self):
assert job_skip_reason(_job(), NOW, 30) is None
@pytest.mark.parametrize("overrides, reason", [
({"status": "failed"}, "not_complete"),
({"status": "in_review"}, "not_complete"),
({"finalise_only": True}, "finalise_only"),
({"prep_only": True}, "prep_only"),
({"outputs_deleted_at": NOW}, "outputs_deleted"),
({"state_data": {"visibility_change_in_progress": True}}, "active_visibility_change_in_progress"),
({"state_data": {"admin_rerender": {"brand_code": "X"}}}, "active_admin_rerender"),
({"state_data": {"theme_rerender": {"theme_id": "t"}}}, "active_theme_rerender"),
({"state_data": {"regenerate": {"source": "customer"}}}, "active_regenerate"),
({"state_data": {"youtube_upload_queued": True}}, "youtube_upload_queued"),
({"state_data": {"storage_purge_in_progress": NOW.isoformat()}}, "purge_in_progress"),
({"timeline": [{"status": "complete", "timestamp": (NOW - timedelta(days=29)).isoformat()}]}, "too_recent"),
({"timeline": [], "updated_at": None}, "no_completion_time"),
# only purge what a regenerate could rebuild
({"state_data": {}}, "not_regenerable_no_instrumental_selection"),
({"file_urls": {}}, "not_regenerable_no_reviewed_lyrics"),
({"theme_id": None}, "not_regenerable_no_theme"),
])
def test_skip_reasons(self, overrides, reason):
assert job_skip_reason(_job(**overrides), NOW, 30) == reason
def test_stale_purge_claim_does_not_block(self):
stale = (NOW - timedelta(hours=2)).isoformat()
job = _job(state_data={"storage_purge_in_progress": stale, "instrumental_selection": "clean"})
assert job_skip_reason(job, NOW, 30) is None
def test_excluded_tenant(self):
assert job_skip_reason(_job(tenant_id="vocalstar"), NOW, 30, ["vocalstar"]) == "excluded_tenant"
def test_tenant_jobs_follow_the_same_policy_by_default(self):
assert job_skip_reason(_job(tenant_id="randy-vild"), NOW, 30) is None
def test_purge_in_progress_helper_accepts_models_and_dicts(self):
recent = datetime.now(timezone.utc).isoformat()
assert purge_in_progress({"state_data": {"storage_purge_in_progress": recent}})
assert purge_in_progress(SimpleNamespace(state_data={"storage_purge_in_progress": recent}))
assert not purge_in_progress(SimpleNamespace(state_data={}))
assert not purge_in_progress(SimpleNamespace(state_data=None))
# --- plan_job -----------------------------------------------------------------------
def _listing(job_id="job1", extra=()):
files = [
("input/song.flac", 30_000_000),
("lyrics/corrections.json", 200_000),
("finals/lossless_4k_mp4.mp4", 60_000_000),
("finals/lossy_4k_mp4.mp4", 30_000_000),
("finals/lossy_720p_mp4.mp4", 29_000_000),
("finals/Artist - Title (Final Karaoke Lossy 720p).mp4", 29_000_000),
("finals/Artist - Title (Karaoke).mp4", 140_000_000),
("videos/with_vocals.mkv", 150_000_000),
("previews/abc.mp4", 3_000_000),
("review-audio/instrumental_clean.ogg", 3_000_000),
("screens/title.png", 3_000_000),
("screens/title.mov", 300_000),
("packages/cdg_zip.zip", 4_000_000),
("stems/instrumental_clean.flac", 23_000_000),
("stems/vocals_clean.flac", 14_000_000),
*extra,
]
return [(f"jobs/{job_id}/{rel}", size) for rel, size in files]
class TestPlanJob:
def test_purges_regenerables_and_keeps_the_rest(self):
plan = plan_job(_job(), _listing())
purged = {p.split("/", 2)[2] for p, _, _ in plan.purge}
assert purged == {
"finals/lossless_4k_mp4.mp4", "finals/lossy_4k_mp4.mp4",
"finals/Artist - Title (Karaoke).mp4", "videos/with_vocals.mkv",
"previews/abc.mp4", "review-audio/instrumental_clean.ogg",
"screens/title.mov", "stems/instrumental_clean.flac", "stems/vocals_clean.flac",
}
assert plan.purges_renders and plan.purges_stems
assert plan.bytes_by_category()["stems"] == 37_000_000
assert plan.kept_bytes == 30_000_000 + 200_000 + 29_000_000 * 2 + 3_000_000 + 4_000_000
def test_custom_instrumental_is_never_purged(self):
extra = [("stems/custom_instrumental.flac", 40_000_000), ("custom_instrumental.mp3", 9_000_000)]
plan = plan_job(_job(state_data={"instrumental_selection": "custom"}), _listing(extra=extra))
purged = {p for p, _, _ in plan.purge}
assert "jobs/job1/stems/custom_instrumental.flac" not in purged
assert "jobs/job1/custom_instrumental.mp3" not in purged
# the separated stems still go (re-separated on demand)
assert "jobs/job1/stems/instrumental_clean.flac" in purged
def test_input_unavailable_keeps_everything(self):
plan = plan_job(_job(input_media_gcs_path="uploads/job1/audio/song.flac"), _listing())
assert plan.skip_reason == "input_unavailable" and not plan.purge
def test_input_missing_from_listing_keeps_everything(self):
listing = [x for x in _listing() if "/input/" not in x[0]]
assert plan_job(_job(), listing).skip_reason == "input_unavailable"
def test_input_only_from_input_media_gcs_path(self):
# regenerate/separation/render read input_media_gcs_path only
job = _job(input_media_gcs_path=None, file_urls={"input": {"audio": "jobs/job1/input/song.flac"}})
assert plan_job(job, _listing()).skip_reason == "input_unavailable"
def test_existing_instrumental_job_keeps_stems(self):
plan = plan_job(_job(existing_instrumental_gcs_path="jobs/job1/custom_instrumental.flac"), _listing())
assert not plan.purges_stems and plan.purges_renders
assert plan.stems_note == "existing_instrumental"
def test_finalise_only_sources_kept_by_plan(self):
plan = plan_job(_job(finalise_only=True), _listing())
purged = {p for p, _, _ in plan.purge}
assert "jobs/job1/videos/with_vocals.mkv" not in purged
assert "jobs/job1/screens/title.mov" not in purged
assert "jobs/job1/stems/instrumental_clean.flac" not in purged
def test_never_plans_outside_the_job_prefix(self):
listing = _listing() + [("jobs/job10/finals/lossy_4k_mp4.mp4", 1), ("uploads/job1/x.mp4", 1)]
plan = plan_job(_job(), listing)
assert all(p.startswith("jobs/job1/") for p, _, _ in plan.purge)
def test_tenant_job_planned_like_any_other(self):
plan = plan_job(_job(tenant_id="randy-vild"), _listing())
assert plan.purges_renders and plan.purges_stems
class TestFileUrlDeletions:
def test_only_purged_entries_are_dropped(self):
file_urls = {
"finals": {"lossy_4k_mp4": "jobs/job1/finals/lossy_4k_mp4.mp4",
"lossy_720p_mp4": "jobs/job1/finals/lossy_720p_mp4.mp4"},
"stems": {"instrumental_clean": "gs://bucket/jobs/job1/stems/instrumental_clean.flac",
"custom_instrumental": "jobs/job1/stems/custom_instrumental.flac"},
"videos": {"with_vocals": "jobs/job1/videos/with_vocals.mkv"},
"input": "jobs/job1/input/song.flac",
}
purged = ["jobs/job1/finals/lossy_4k_mp4.mp4", "jobs/job1/stems/instrumental_clean.flac",
"jobs/job1/videos/with_vocals.mkv"]
assert sorted(file_url_deletions(file_urls, purged)) == [
"file_urls.finals.lossy_4k_mp4",
"file_urls.stems.instrumental_clean",
"file_urls.videos.with_vocals",
]
def test_unsafe_keys_are_never_written(self):
file_urls = {"finals": {"weird.key": "jobs/job1/finals/a.mp4"}}
assert file_url_deletions(file_urls, ["jobs/job1/finals/a.mp4"]) == []
# --- Service ----------------------------------------------------------------------
class FakeStorage:
def __init__(self, files, updated=None):
self.files = dict(files)
self.updated = dict(updated or {})
self.deleted = []
self.reports = {}
self.texts = {}
self.delete_generations = {}
def list_files_with_sizes(self, prefix):
return [(k, v) for k, v in sorted(self.files.items()) if k.startswith(prefix)]
def list_blob_meta(self, prefix):
old = datetime(2026, 1, 1, tzinfo=timezone.utc)
return [{"name": k, "size": v, "generation": 1000 + i, "updated": self.updated.get(k, old)}
for i, (k, v) in enumerate(sorted(self.files.items())) if k.startswith(prefix)]
def delete_file(self, path, ignore_missing=False, if_generation_match=None):
self.deleted.append(path)
self.delete_generations[path] = if_generation_match
self.files.pop(path, None)
return True
def upload_json(self, path, data):
self.reports[path] = data
return path
def upload_text(self, path, text, content_type="text/plain"):
self.texts[path] = text
return path
class FakeDoc:
def __init__(self, db, doc_id):
self.db, self.id = db, doc_id
def get(self, transaction=None):
data = self.db.data.get(self.id)
return SimpleNamespace(exists=data is not None, id=self.id, to_dict=lambda: _copy(data))
def update(self, payload):
self.db.updates.append((self.id, payload))
_apply(self.db.data.setdefault(self.id, {}), payload)
def set(self, payload, merge=False):
self.db.data.setdefault(self.id, {}).update(payload)
def _copy(data):
import copy
return copy.deepcopy(data) if data is not None else None
def _apply(doc, payload):
import sys
# The service imports DELETE_FIELD at call time; other suites stub
# google.cloud.firestore_v1, so compare against whatever is live now.
delete_sentinels = {id(DELETE_FIELD), id(getattr(sys.modules.get("google.cloud.firestore_v1"), "DELETE_FIELD", DELETE_FIELD))}
for key, value in payload.items():
parts = key.split(".")
target = doc
for part in parts[:-1]:
target = target.setdefault(part, {})
if id(value) in delete_sentinels:
target.pop(parts[-1], None)
else:
target[parts[-1]] = value
class FakeQuery:
def __init__(self, db, docs):
self.db, self.docs = db, docs
self._limit, self._after = None, None
def where(self, filter=None):
return FakeQuery(self.db, [d for d in self.docs if self.db.data[d].get("status") == "complete"])
def order_by(self, *_):
q = FakeQuery(self.db, sorted(self.docs)); q._limit, q._after = self._limit, self._after
return q
def select(self, _):
return self
def limit(self, n):
self._limit = n
return self
def start_after(self, cursor):
self._after = cursor["__name__"].id
return self
def stream(self):
docs = [d for d in self.docs if self._after is None or d > self._after]
if self._limit:
docs = docs[: self._limit]
return [SimpleNamespace(id=d, to_dict=(lambda d=d: _copy(self.db.data[d]))) for d in docs]
class FakeCollection:
def __init__(self, db, name):
self.db, self.name = db, name
def document(self, doc_id):
if self.name == "storage_retention":
return self.db.state_doc
return FakeDoc(self.db, doc_id)
def where(self, filter=None):
return FakeQuery(self.db, list(self.db.data)).where(filter)
def select(self, fields):
return FakeQuery(self.db, list(self.db.data))
class FakeDb:
def __init__(self, jobs):
self.data = {j["job_id"]: j for j in jobs}
self.updates = []
self.state = {}
state = self
class StateDoc:
def get(self_inner):
return SimpleNamespace(exists=bool(state.state), to_dict=lambda: dict(state.state))
def set(self_inner, payload, merge=False):
state.state.update(payload)
self.state_doc = StateDoc()
def collection(self, name):
return FakeCollection(self, name)
def transaction(self):
class FakeTransaction:
def update(self_inner, ref, payload):
ref.update(payload)
return FakeTransaction()
def _settings(**overrides):
values = dict(
storage_retention_dry_run=True, storage_retention_min_age_days=30,
storage_retention_max_jobs_per_run=50, storage_retention_excluded_tenants="",
firestore_collection="jobs", gcs_bucket_name="bucket",
)
values.update(overrides)
return SimpleNamespace(**values)
@pytest.fixture(autouse=True)
def _no_transactions():
with patch.object(sr, "_run_in_transaction", lambda db, fn: fn(db.transaction())), \
patch("backend.services.firestore_service.log_to_job"):
yield
def _service(jobs, files=None, **settings):
files = files if files is not None else {k: v for j in jobs for k, v in _listing(j["job_id"])}
for j in jobs:
j.setdefault("input_media_gcs_path", f"jobs/{j['job_id']}/input/song.flac")
j["input_media_gcs_path"] = f"jobs/{j['job_id']}/input/song.flac"
db, storage = FakeDb(jobs), FakeStorage(files)
return StorageRetentionService(db=db, storage=storage, settings=_settings(**settings)), db, storage
class TestServiceDryRun:
def test_dry_run_reports_without_touching_anything(self):
svc, db, storage = _service([_job(job_id="a"), _job(job_id="b", status="failed")])
report = svc.run(now=NOW)
assert report["dry_run"] is True
assert storage.deleted == [] and db.updates == []
assert [j["job_id"] for j in report["jobs"]] == ["a"]
assert report["summary"]["jobs_to_purge"] == 1
cats = report["summary"]["bytes_by_category"]
assert cats["finals"] == 60_000_000 + 30_000_000 + 140_000_000
assert cats["stems"] == 37_000_000
assert "final_720p" not in cats
# only completed jobs are walked at all
assert report["skipped"] == {} and report["summary"]["jobs_scanned"] == 1
# report written to GCS
assert report["report_path"] in storage.reports
assert report["report_path"].startswith("storage-retention/reports/") and "dry-run" in report["report_path"]
def test_default_comes_from_settings(self):
svc, db, storage = _service([_job(job_id="a")], storage_retention_dry_run=True)
assert svc.run(now=NOW)["dry_run"] is True
def test_dry_run_scans_everything_without_cursor(self):
jobs = [_job(job_id=f"j{i:03d}") for i in range(5)]
svc, db, storage = _service(jobs)
report = svc.run(now=NOW)
assert report["summary"]["jobs_to_purge"] == 5
assert db.state == {} # cursor untouched
class TestServiceRealRun:
def test_real_run_deletes_and_records(self):
job = _job(job_id="a", file_urls={
"lyrics": {"corrections": "jobs/a/lyrics/corrections.json"},
"finals": {"lossy_4k_mp4": "jobs/a/finals/lossy_4k_mp4.mp4",
"lossy_720p_mp4": "jobs/a/finals/lossy_720p_mp4.mp4"},
"stems": {"instrumental_clean": "jobs/a/stems/instrumental_clean.flac"},
"videos": {"with_vocals": "jobs/a/videos/with_vocals.mkv"},
"packages": {"cdg_zip": "jobs/a/packages/cdg_zip.zip"},
})
svc, db, storage = _service([job])
report = svc.run(dry_run=False, now=NOW)
assert report["summary"]["jobs_purged"] == 1
assert "jobs/a/finals/lossy_720p_mp4.mp4" not in storage.deleted
assert "jobs/a/input/song.flac" not in storage.deleted
assert "jobs/a/packages/cdg_zip.zip" not in storage.deleted
assert "jobs/a/stems/instrumental_clean.flac" in storage.deleted
doc = db.data["a"]
assert doc["renders_purged_at"] == NOW and doc["stems_purged_at"] == NOW
assert doc["file_urls"]["finals"] == {"lossy_720p_mp4": "jobs/a/finals/lossy_720p_mp4.mp4"}
assert "instrumental_clean" not in doc["file_urls"]["stems"]
assert "with_vocals" not in doc["file_urls"]["videos"]
assert doc["file_urls"]["packages"] == {"cdg_zip": "jobs/a/packages/cdg_zip.zip"}
manifest = doc["storage_purge"]
assert manifest["status"] == "complete"
assert manifest["bytes"] == sum(f["bytes"] for f in manifest["files"])
assert {f["path"] for f in manifest["files"]} == set(storage.deleted)
# the claim marker is cleared
assert "storage_purge_in_progress" not in doc["state_data"]
assert "run" in report["report_path"] and "dry-run" not in report["report_path"]
def test_second_run_is_idempotent(self):
svc, db, storage = _service([_job(job_id="a")])
svc.run(dry_run=False, now=NOW)
deleted = list(storage.deleted)
report = svc.run(dry_run=False, now=NOW + timedelta(days=1))
assert storage.deleted == deleted
assert report["skipped"] == {"already_purged": 1}
def test_regenerated_job_becomes_eligible_again_after_its_window(self):
svc, db, storage = _service([_job(job_id="a")])
svc.run(dry_run=False, now=NOW)
# regenerate: files come back, a new completion is recorded
regenerated_at = NOW + timedelta(days=1)
db.data["a"]["timeline"].append({"status": "complete", "timestamp": regenerated_at.isoformat()})
db.data["a"]["renders_purged_at"] = None
db.data["a"]["stems_purged_at"] = None
storage.files.update({k: v for k, v in _listing("a")})
assert svc.run(dry_run=True, now=NOW + timedelta(days=10))["skipped"] == {"too_recent": 1}
later = svc.run(dry_run=True, now=regenerated_at + timedelta(days=31))
assert later["summary"]["jobs_to_purge"] == 1
def test_custom_instrumental_job(self):
files = {k: v for k, v in _listing("a", extra=[("stems/custom_instrumental.flac", 1),
("custom_instrumental.mp3", 1)])}
svc, db, storage = _service([_job(job_id="a", state_data={"instrumental_selection": "custom"})], files)
svc.run(dry_run=False, now=NOW)
assert "jobs/a/stems/custom_instrumental.flac" in storage.files
assert "jobs/a/custom_instrumental.mp3" in storage.files
assert "jobs/a/finals/lossy_720p_mp4.mp4" in storage.files
def test_finalise_only_job_untouched(self):
svc, db, storage = _service([_job(job_id="a", finalise_only=True)])
report = svc.run(dry_run=False, now=NOW)
assert storage.deleted == [] and report["skipped"] == {"finalise_only": 1}
def test_tenant_job_purged_unless_excluded(self):
svc, db, storage = _service([_job(job_id="a", tenant_id="vocalstar")])
assert svc.run(dry_run=True, now=NOW)["summary"]["jobs_to_purge"] == 1
svc, db, storage = _service([_job(job_id="a", tenant_id="vocalstar")],
storage_retention_excluded_tenants="vocalstar, singa")
assert svc.run(dry_run=False, now=NOW)["skipped"] == {"excluded_tenant": 1}
assert storage.deleted == []
def test_claim_rechecks_live_doc(self):
svc, db, storage = _service([_job(job_id="a")])
original_plan = sr.plan_job
def plan_then_race(job, listing):
# a regenerate claims the job between planning and deletion
db.data["a"]["state_data"]["regenerate"] = {"source": "customer"}
return original_plan(job, listing)
with patch.object(sr, "plan_job", side_effect=plan_then_race):
report = svc.run(dry_run=False, now=NOW)
assert storage.deleted == []
assert report["jobs"][0]["result"] == {"status": "skipped", "reason": "no_longer_eligible"}
assert report["summary"]["jobs_purged"] == 0
def test_delete_failures_are_recorded_not_fatal(self):
svc, db, storage = _service([_job(job_id="a")])
real_delete = storage.delete_file
def flaky(path, ignore_missing=False, if_generation_match=None):
if path.endswith("lossy_4k_mp4.mp4"):
raise RuntimeError("boom")
return real_delete(path, ignore_missing, if_generation_match)
storage.delete_file = flaky
svc.run(dry_run=False, now=NOW)
manifest = db.data["a"]["storage_purge"]
assert manifest["failures"][0]["path"].endswith("lossy_4k_mp4.mp4")
assert db.data["a"]["renders_purged_at"] == NOW
def test_batch_limit_and_resumable_cursor(self):
jobs = [_job(job_id=f"j{i}") for i in range(5)]
svc, db, storage = _service(jobs)
first = svc.run(dry_run=False, max_jobs=2, now=NOW)
assert first["summary"]["jobs_purged"] == 2
assert db.state["cursor_job_id"] == "j1"
second = svc.run(dry_run=False, max_jobs=2, now=NOW)
assert [j["job_id"] for j in second["jobs"]] == ["j2", "j3"]
third = svc.run(dry_run=False, max_jobs=2, now=NOW)
assert [j["job_id"] for j in third["jobs"]] == ["j4"]
assert db.state["cursor_job_id"] is None # wrapped
def test_real_run_uses_settings_batch_size(self):
jobs = [_job(job_id=f"j{i}") for i in range(3)]
svc, db, storage = _service(jobs, storage_retention_max_jobs_per_run=1)
assert svc.run(dry_run=False, now=NOW)["summary"]["jobs_purged"] == 1
def test_scoped_run_only_touches_listed_jobs(self):
svc, db, storage = _service([_job(job_id="a"), _job(job_id="b")])
report = svc.run(dry_run=False, job_ids=["b"], now=NOW)
assert [j["job_id"] for j in report["jobs"]] == ["b"]
assert all(p.startswith("jobs/b/") for p in storage.deleted)
assert db.state == {}
def test_scoped_min_age_override(self):
recent = _job(job_id="a", timeline=[{"status": "complete", "timestamp": NOW.isoformat()}])
svc, db, storage = _service([recent])
assert svc.run(dry_run=True, job_ids=["a"], now=NOW)["skipped"] == {"too_recent": 1}
assert svc.run(dry_run=True, job_ids=["a"], min_age_days=0, now=NOW)["summary"]["jobs_to_purge"] == 1
def test_orphans_section(self):
files = {k: v for k, v in _listing("a")}
files["jobs/ghost/finals/x.mp4"] = 2**30
svc, db, storage = _service([_job(job_id="a")], files)
report = svc.run(dry_run=True, include_orphans=True, now=NOW)
assert report["orphans"]["folders"] == 1
assert report["orphans"]["largest"][0]["job_id"] == "ghost"
class TestInterruptedPurge:
def test_markers_are_set_before_any_delete(self):
svc, db, storage = _service([_job(job_id="a")])
seen = {}
def delete(path, ignore_missing=False, if_generation_match=None):
# at the first delete the job must already say what's being purged
if not seen:
doc = db.data["a"]
seen.update(renders=doc.get("renders_purged_at"), stems=doc.get("stems_purged_at"),
status=(doc.get("storage_purge") or {}).get("status"))
storage.files.pop(path, None)
storage.deleted.append(path)
return True
storage.delete_file = delete
svc.run(dry_run=False, now=NOW)
assert seen == {"renders": NOW, "stems": NOW, "status": "pending"}
def test_interrupted_purge_is_finished_by_next_pass(self):
svc, db, storage = _service([_job(job_id="a")])
calls = {"n": 0}
real = storage.delete_file
def dies_after_two(path, ignore_missing=False, if_generation_match=None):
calls["n"] += 1
if calls["n"] > 2:
raise SystemExit("instance killed")
return real(path, ignore_missing, if_generation_match)
storage.delete_file = dies_after_two
with pytest.raises(SystemExit):
svc.run(dry_run=False, now=NOW)
doc = db.data["a"]
assert doc["storage_purge"]["status"] == "pending"
assert doc["stems_purged_at"] == NOW # regenerate will re-separate
storage.delete_file = real
db.data["a"]["state_data"].pop("storage_purge_in_progress", None) # stale claim
report = svc.run(dry_run=False, now=NOW + timedelta(hours=1))
assert report["summary"]["jobs_purged"] == 1
assert db.data["a"]["storage_purge"]["status"] == "complete"
# --- Deletion audit log -------------------------------------------------------------
import json as _json
def _log_lines(storage, path):
return [_json.loads(line) for line in storage.texts[path].splitlines() if line]
class TestDeletionLog:
def test_real_run_logs_every_deleted_object_with_generation(self):
svc, db, storage = _service([_job(job_id="a")])
report = svc.run(dry_run=False, now=NOW)
log_path = report["deletion_log"]
assert log_path == "storage-retention/deletion-logs/20261003T120000Z-job_purge.jsonl"
lines = _log_lines(storage, log_path)
assert {l["path"] for l in lines} == set(storage.deleted)
assert all(l["result"] == "deleted" and l["mode"] == "job_purge" and l["job_id"] == "a" for l in lines)
assert all(l["generation"] is not None for l in lines)
cats = {l["category"] for l in lines}
assert {"finals", "videos", "stems", "review-audio", "previews", "screens-mov"} == cats
# deletes are generation-pinned to exactly the logged version
for l in lines:
assert str(storage.delete_generations[l["path"]]) == l["generation"]
summary = storage.reports[report["deletion_summary"]]
assert summary["objects_deleted"] == len(lines)
assert summary["bytes_deleted"] == sum(l["size_bytes"] for l in lines)
assert summary["jobs"] == 1 and summary["failures"] == 0
# manifest on the job doc carries generations + log path
manifest = db.data["a"]["storage_purge"]
assert manifest["deletion_log"] == log_path
assert all(f["generation"] for f in manifest["files"])
def test_dry_run_writes_no_deletion_log(self):
svc, db, storage = _service([_job(job_id="a")])
report = svc.run(dry_run=True, now=NOW)
assert "deletion_log" not in report and storage.texts == {}
def test_failures_are_logged(self):
svc, db, storage = _service([_job(job_id="a")])
real = storage.delete_file
def flaky(path, ignore_missing=False, if_generation_match=None):
if path.endswith("lossy_4k_mp4.mp4"):
raise RuntimeError("412 precondition failed")
return real(path, ignore_missing, if_generation_match)
storage.delete_file = flaky
report = svc.run(dry_run=False, now=NOW)
failed = [l for l in _log_lines(storage, report["deletion_log"]) if l["result"] == "failed"]
assert len(failed) == 1 and "precondition" in failed[0]["error"]
assert storage.reports[report["deletion_summary"]]["failures"] == 1
def test_log_is_flushed_per_job_so_a_crash_keeps_the_record(self):
jobs = [_job(job_id="a"), _job(job_id="b")]
svc, db, storage = _service(jobs)
real = storage.delete_file
def die_on_b(path, ignore_missing=False, if_generation_match=None):
if path.startswith("jobs/b/"):
raise SystemExit("killed")
return real(path, ignore_missing, if_generation_match)
storage.delete_file = die_on_b
with pytest.raises(SystemExit):
svc.run(dry_run=False, now=NOW)
path = "storage-retention/deletion-logs/20261003T120000Z-job_purge.jsonl"
lines = _log_lines(storage, path)
assert lines and {l["job_id"] for l in lines} == {"a"}
assert {l["path"] for l in lines} == {p for p in storage.deleted if p.startswith("jobs/a/")}
@pytest.mark.parametrize("path", [
"storage-retention/deletion-logs/x.jsonl", "uploads/a/x.flac", "jobs/", "jobs//x", "temp/x",
])
def test_guard_refuses_paths_outside_job_folders(self, path):
with pytest.raises(ValueError):
sr.assert_deletable(path)
def test_guard_allows_job_files(self):
sr.assert_deletable("jobs/a/finals/x.mp4")
# --- Orphan folders ----------------------------------------------------------------
def _orphan_service(files, updated=None, records=None):
db = FakeDb([_job(job_id="live")])
for coll, ids in (records or {}).items():
db.extra = getattr(db, "extra", {})
db.extra.update({(coll, i): True for i in ids})
real_collection = db.collection
def collection(name):
if name in ("jobs-dev", "youtube_upload_queue"):
extra = getattr(db, "extra", {})
return SimpleNamespace(document=lambda i: SimpleNamespace(
get=lambda: SimpleNamespace(exists=extra.get((name, i), False))))
return real_collection(name)
db.collection = collection
storage = FakeStorage(files, updated)
return StorageRetentionService(db=db, storage=storage, settings=_settings()), db, storage
ORPHAN_FILES = {
"jobs/live/finals/lossy_4k_mp4.mp4": 10,
"jobs/ghost/input/song.flac": 100,
"jobs/ghost/finals/lossy_720p_mp4.mp4": 30,
"jobs/ghost/videos/with_vocals.mkv": 200,
"jobs/ghost/stems/custom_instrumental.flac": 40,
"jobs/ghost/custom_instrumental.mp3": 9,
"jobs/fresh/finals/x.mp4": 50,
"jobs/queued/finals/x.mp4": 70,
"jobs/_preview123/review-audio/mixed.ogg": 4,
"storage-retention/deletion-logs/old.jsonl": 1,
"uploads/ghost/audio/x.flac": 5,
}
class TestOrphans:
def _svc(self):
updated = {"jobs/fresh/finals/x.mp4": NOW - timedelta(days=2)}
return _orphan_service(ORPHAN_FILES, updated, records={"youtube_upload_queue": ["queued"]})
def test_plan_keeps_only_input(self):
objs = [{"name": k, "size": v, "updated": NOW - timedelta(days=90)}
for k, v in ORPHAN_FILES.items() if k.startswith("jobs/ghost/")]
plan = sr.plan_orphan_folder("ghost", objs, NOW)
assert [m["name"] for m in plan["keep"]] == ["jobs/ghost/input/song.flac"]
assert plan["purge_bytes"] == 30 + 200 + 40 + 9 and plan["skip_reason"] is None
def test_recent_folder_is_skipped(self):
plan = sr.plan_orphan_folder("x", [{"name": "jobs/x/a.mp4", "size": 1, "updated": NOW - timedelta(days=29)}], NOW)
assert plan["skip_reason"] == "recently_modified"
def test_dry_run_reports_without_deleting(self):
svc, db, storage = self._svc()
report = svc.purge_orphans(dry_run=True, now=NOW)
assert storage.deleted == [] and storage.texts == {}
assert report["candidates"] == 4 # ghost, fresh, queued, _preview123 (never "live")
assert sorted(f["job_id"] for f in report["folders"]) == ["_preview123", "ghost"]
assert report["skipped"] == {"recently_modified": 1, "has_record": 1}
assert report["not_orphans"] == [{"job_id": "queued", "collection": "youtube_upload_queue"}]
assert report["summary"]["gib_input_kept"] == round(100 / 2**30, 2)
assert report["report_path"].endswith("-orphans-dry-run.json")
def test_real_run_deletes_non_input_and_logs(self):
svc, db, storage = self._svc()
report = svc.purge_orphans(dry_run=False, now=NOW)
assert sorted(storage.deleted) == sorted([
"jobs/ghost/finals/lossy_720p_mp4.mp4", "jobs/ghost/videos/with_vocals.mkv",
"jobs/ghost/stems/custom_instrumental.flac", "jobs/ghost/custom_instrumental.mp3",
"jobs/_preview123/review-audio/mixed.ogg",
])
for kept in ("jobs/ghost/input/song.flac", "jobs/live/finals/lossy_4k_mp4.mp4",
"jobs/fresh/finals/x.mp4", "jobs/queued/finals/x.mp4",
"storage-retention/deletion-logs/old.jsonl", "uploads/ghost/audio/x.flac"):
assert kept in storage.files
lines = _log_lines(storage, report["deletion_log"])
assert report["deletion_log"].endswith("-orphan.jsonl")
assert {l["category"] for l in lines} == {"orphan-nonInput"} and {l["mode"] for l in lines} == {"orphan"}
assert storage.reports[report["deletion_summary"]]["objects_deleted"] == 5
def test_record_created_after_listing_is_respected(self):
svc, db, storage = self._svc()
db.extra = {("jobs-dev", "ghost"): True}
svc.purge_orphans(dry_run=False, now=NOW)
assert not any(p.startswith("jobs/ghost/") for p in storage.deleted)
def test_batch_limit(self):
svc, db, storage = self._svc()
report = svc.purge_orphans(dry_run=False, max_folders=1, now=NOW)
assert len(report["folders"]) == 1 and report["skipped"]["batch_limit"] == 3
class TestDeletionLogFlushFailure:
def test_run_stops_deleting_when_log_cannot_be_written(self):
svc, db, storage = _service([_job(job_id="a"), _job(job_id="b")])
def broken(path, text, content_type="text/plain"):
raise RuntimeError("gcs write denied")
storage.upload_text = broken
report = svc.run(dry_run=False, now=NOW)
assert not any(p.startswith("jobs/b/") for p in storage.deleted)
assert report["errors"] and "deletion log not persisted" in report["errors"][0]["error"]
assert storage.reports[report["deletion_summary"]]["log_flush_error"] == "gcs write denied"
def test_orphan_run_stops_too(self):
files = {"jobs/g1/finals/a.mp4": 1, "jobs/g2/finals/b.mp4": 1}
svc, db, storage = _orphan_service(files)
storage.upload_text = lambda *a, **k: (_ for _ in ()).throw(RuntimeError("denied"))
report = svc.purge_orphans(dry_run=False, now=NOW)
assert storage.deleted == ["jobs/g1/finals/a.mp4"]
assert "deletion log not persisted" in report["errors"][0]["error"]
+11 -11
View File
@@ -120,7 +120,7 @@ class TestGetStyleUploadUrls:
)
])
result = await get_style_upload_urls("job-abc", body, admin_auth)
result = get_style_upload_urls("job-abc", body, admin_auth)
assert result["status"] == "success"
assert len(result["upload_urls"]) == 1
@@ -143,7 +143,7 @@ class TestGetStyleUploadUrls:
from fastapi import HTTPException
with pytest.raises(HTTPException) as exc_info:
await get_style_upload_urls("job-abc", body, admin_auth)
get_style_upload_urls("job-abc", body, admin_auth)
assert exc_info.value.status_code == 400
assert "Invalid file_type for style upload" in str(exc_info.value.detail)
@@ -163,7 +163,7 @@ class TestGetStyleUploadUrls:
from fastapi import HTTPException
with pytest.raises(HTTPException) as exc_info:
await get_style_upload_urls("nonexistent", body, admin_auth)
get_style_upload_urls("nonexistent", body, admin_auth)
assert exc_info.value.status_code == 404
@pytest.mark.asyncio
@@ -183,7 +183,7 @@ class TestGetStyleUploadUrls:
from fastapi import HTTPException
with pytest.raises(HTTPException) as exc_info:
await get_style_upload_urls("job-abc", body, admin_auth)
get_style_upload_urls("job-abc", body, admin_auth)
assert exc_info.value.status_code == 400
assert "cutoff" in str(exc_info.value.detail).lower()
@@ -204,7 +204,7 @@ class TestGetStyleUploadUrls:
from fastapi import HTTPException
with pytest.raises(HTTPException) as exc_info:
await get_style_upload_urls("job-abc", body, user_auth)
get_style_upload_urls("job-abc", body, user_auth)
assert exc_info.value.status_code == 403
@pytest.mark.asyncio
@@ -223,7 +223,7 @@ class TestGetStyleUploadUrls:
from fastapi import HTTPException
with pytest.raises(HTTPException) as exc_info:
await get_style_upload_urls("job-abc", body, admin_auth)
get_style_upload_urls("job-abc", body, admin_auth)
assert exc_info.value.status_code == 400
assert "extension" in str(exc_info.value.detail).lower()
@@ -239,7 +239,7 @@ class TestGetStyleUploadUrls:
FileUploadRequest(filename="introimg.jpg", content_type="image/jpeg", file_type="style_intro_background"),
])
result = await get_style_upload_urls("job-abc", body, admin_auth)
result = get_style_upload_urls("job-abc", body, admin_auth)
assert len(result["upload_urls"]) == 2
@@ -269,7 +269,7 @@ class TestCompleteStyleUploads:
uploaded_files=["style_karaoke_background"],
)
result = await complete_style_uploads("job-abc", body, admin_auth)
result = complete_style_uploads("job-abc", body, admin_auth)
assert result["status"] == "success"
assert "karaoke_background" in result["assets_updated"]
@@ -310,7 +310,7 @@ class TestCompleteStyleUploads:
color_overrides={"artist_color": "#ff0000"},
)
result = await complete_style_uploads("job-abc", body, admin_auth)
result = complete_style_uploads("job-abc", body, admin_auth)
assert result["status"] == "success"
mock_ts.apply_color_overrides.assert_called_once()
@@ -330,7 +330,7 @@ class TestCompleteStyleUploads:
from fastapi import HTTPException
with pytest.raises(HTTPException) as exc_info:
await complete_style_uploads("job-abc", body, admin_auth)
complete_style_uploads("job-abc", body, admin_auth)
assert exc_info.value.status_code == 400
assert "not uploaded" in str(exc_info.value.detail).lower()
@@ -345,5 +345,5 @@ class TestCompleteStyleUploads:
from fastapi import HTTPException
with pytest.raises(HTTPException) as exc_info:
await complete_style_uploads("job-abc", body, admin_auth)
complete_style_uploads("job-abc", body, admin_auth)
assert exc_info.value.status_code == 400
+1 -1
View File
@@ -228,4 +228,4 @@ class TestAudioSeparatorStatus:
from backend.api.routes.health import check_audio_separator_status
assert await audio_separator_health() == check_audio_separator_status()
assert audio_separator_health() == check_audio_separator_status()
+14 -1
View File
@@ -99,9 +99,20 @@ def test_preview_returns_data_urls(client_for):
assert resp.status_code == 200
body = resp.json()
assert body["title_card"].startswith("data:image/jpeg;base64,")
assert body["end_screen"] is None # not rendered (e.g. the theme omits it)
assert render.call_args.kwargs["artist"] == "Randy Vild"
def test_preview_returns_end_screen_and_null_for_omitted_title(client_for):
with patch.object(tenant_theme, "prepare_preview_styles", return_value={"intro": {}}), \
patch.object(tenant_theme, "render_theme_preview", return_value=PreviewImages(None, b"k", b"e")):
resp = client_for().post("/api/tenant/theme/preview", json={"style_params": {"intro": {}}})
assert resp.status_code == 200
body = resp.json()
assert body["title_card"] is None
assert body["end_screen"].startswith("data:image/jpeg;base64,")
def test_preview_validation_and_render_errors(client_for):
client = client_for()
with patch.object(tenant_theme, "prepare_preview_styles", side_effect=TenantValidationError("bad path")):
@@ -116,7 +127,9 @@ def test_preview_validation_and_render_errors(client_for):
def test_save_and_upload(client_for):
client = client_for()
with patch.object(tenant_theme, "save_tenant_theme") as save, \
patch.object(tenant_theme, "get_theme_for_editor", return_value=THEME):
patch.object(tenant_theme, "get_theme_for_editor", return_value=THEME), \
patch.object(tenant_theme, "refresh_inflight_jobs", return_value={"updated": 0, "failed": 0}), \
patch.object(tenant_theme, "outdated_jobs", return_value={"job_ids": []}):
resp = client.put("/api/tenant/theme", json={"style_params": {"intro": {"title_color": "#ffffff"}}})
assert resp.status_code == 200
assert save.call_args.args[0].id == "randy-vild"
@@ -264,3 +264,15 @@ def test_missing_theme_file_is_not_found():
storage.download_json = lambda path: (_ for _ in ()).throw(FileNotFoundError(path))
with pytest.raises(tts.ThemeNotFoundError):
tts.get_theme_for_editor(_config(), storage=storage)
@pytest.mark.parametrize("section", ["intro", "end"])
def test_screen_enabled_flag_must_be_boolean(section):
style = _style()
style[section]["enabled"] = False
styles, _ = tts.sanitize_style_params(style, available_assets=ASSETS)
assert styles[section]["enabled"] is False
style[section]["enabled"] = "no"
with pytest.raises(TenantValidationError, match=f"{section}.enabled"):
tts.sanitize_style_params(style, available_assets=ASSETS)
+378
View File
@@ -0,0 +1,378 @@
"""
Tests for keeping a tenant's tracks in step with its theme after a theme edit.
Covers the in-progress refresh on save (re-snapshot + stale-screens flag), the
render-worker divert that regenerates stale screens before rendering, outdated
finished-track detection, Edit picking up the current theme, the quiet bulk
re-render, and the /api/tenant/theme save / outdated-jobs / rerender-outdated
routes.
"""
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi.testclient import TestClient
from google.cloud.firestore_v1 import DELETE_FIELD
from backend.models.job import JobStatus
from backend.services import theme_change_service as svc
T0 = datetime(2026, 9, 29, 23, 0, tzinfo=timezone.utc)
THEME_SAVED = datetime(2026, 10, 6, 14, 35, tzinfo=timezone.utc)
def _job(job_id="job1", status=JobStatus.AWAITING_REVIEW, **overrides):
fields = dict(
job_id=job_id, status=status, tenant_id="randy-vild", theme_id="randy-vild",
user_email="randy@example.com", color_overrides={}, created_at=T0,
theme_applied_at=None, state_data={},
)
fields.update(overrides)
return SimpleNamespace(**fields)
def _passthrough_transactional(fn):
return fn
def _job_manager(claim_status=None):
"""JobManager whose Firestore transaction sees ``claim_status`` (None = job's own)."""
jm = MagicMock()
doc_ref = MagicMock()
jm.firestore.db.collection.return_value.document.return_value = doc_ref
jm._doc_ref = doc_ref
jm._claim_status = claim_status
return jm
def _set_claim_status(jm, status):
snap = MagicMock(exists=True)
snap.to_dict.return_value = {"status": status}
jm._doc_ref.get.return_value = snap
@pytest.fixture
def prepare():
fn = MagicMock(return_value=("jobs/x/style/style_params.json", {"intro_background": "themes/t/bg.jpg"}, None))
with patch("backend.api.routes.file_upload._prepare_theme_for_job", fn), \
patch("backend.services.theme_rerender_service.firestore.transactional", _passthrough_transactional):
yield fn
class TestRefreshInflightJobs:
def _run(self, jobs, prepare, claim_status_for=None):
jm = _job_manager()
jm.list_jobs.return_value = jobs
# The transactional claim re-reads the job's status: return the job's own.
statuses = iter([claim_status_for or j.status.value for j in jobs
if j.status in svc.REFRESHABLE_STATUSES and j.theme_id == "randy-vild"])
def get(transaction=None):
snap = MagicMock(exists=True)
snap.to_dict.return_value = {"status": next(statuses)}
return snap
jm._doc_ref.get.side_effect = get
result = svc.refresh_inflight_jobs("randy-vild", "randy-vild", job_manager=jm)
updates = [c.args[1] for c in jm.firestore.db.transaction.return_value.update.call_args_list]
return result, updates
def test_review_stage_job_resnapshotted_and_flagged(self, prepare):
result, updates = self._run([_job(status=JobStatus.IN_REVIEW)], prepare)
assert result == {"updated": 1, "failed": 0}
update = updates[0]
assert update["style_params_gcs_path"] == "jobs/x/style/style_params.json"
assert update["style_assets"] == {"intro_background": "themes/t/bg.jpg"}
assert update["state_data.theme_screens_stale"] is True
assert isinstance(update["theme_applied_at"], datetime)
prepare.assert_called_once_with("job1", "randy-vild", None)
def test_pre_screens_job_resnapshotted_without_flag(self, prepare):
_, updates = self._run([_job(status=JobStatus.TRANSCRIBING)], prepare)
assert "state_data.theme_screens_stale" not in updates[0]
assert updates[0]["style_params_gcs_path"]
def test_render_pending_capacity_is_flagged(self, prepare):
"""RVILD-0003 sat here while the theme was edited — it must pick up the change."""
_, updates = self._run([_job(status=JobStatus.RENDER_PENDING_CAPACITY)], prepare)
assert updates[0]["state_data.theme_screens_stale"] is True
@pytest.mark.parametrize("status", [
JobStatus.REVIEW_COMPLETE, JobStatus.RENDERING_VIDEO, JobStatus.ENCODING,
JobStatus.COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED,
])
def test_rendering_and_terminal_jobs_untouched(self, prepare, status):
result, updates = self._run([_job(status=status)], prepare)
assert result == {"updated": 0, "failed": 0}
assert updates == []
prepare.assert_not_called()
def test_job_on_another_theme_untouched(self, prepare):
result, _ = self._run([_job(theme_id="nomad")], prepare)
assert result["updated"] == 0
prepare.assert_not_called()
def test_job_that_moved_on_is_skipped(self, prepare):
result, updates = self._run([_job(status=JobStatus.IN_REVIEW)], prepare, claim_status_for="rendering_video")
assert result == {"updated": 0, "failed": 0}
assert updates == []
def test_one_failure_does_not_block_others(self, prepare):
prepare.side_effect = [RuntimeError("gcs down"), ("p", {}, None)]
result, updates = self._run([_job("a"), _job("b")], prepare)
assert result == {"updated": 1, "failed": 1}
assert len(updates) == 1
class TestDivertForStaleScreens:
def _jm(self, status="review_complete"):
jm = _job_manager()
_set_claim_status(jm, status)
return jm
@pytest.mark.asyncio
async def test_no_flag_renders_normally(self):
jm = self._jm()
job = _job(status=JobStatus.REVIEW_COMPLETE)
assert await svc.divert_for_stale_screens(job, jm, MagicMock()) is False
jm.firestore.db.transaction.assert_not_called()
@pytest.mark.asyncio
async def test_flag_ignored_outside_review_complete(self):
job = _job(status=JobStatus.IN_REVIEW, state_data={"theme_screens_stale": True})
assert await svc.divert_for_stale_screens(job, self._jm(), MagicMock()) is False
@pytest.mark.asyncio
async def test_stale_screens_regenerated_before_render(self):
jm = self._jm()
storage = MagicMock()
storage.list_files.return_value = ["jobs/job1/finals/A - B (Title).mov", "jobs/job1/finals/x.mp4"]
worker_service = MagicMock(trigger_screens_worker=AsyncMock(return_value=True))
job = _job(status=JobStatus.REVIEW_COMPLETE, state_data={"theme_screens_stale": True})
with patch("backend.services.theme_rerender_service.firestore.transactional", _passthrough_transactional), \
patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
assert await svc.divert_for_stale_screens(job, jm, storage) is True
update = jm.firestore.db.transaction.return_value.update.call_args.args[1]
assert update["status"] == "lyrics_complete"
assert update["state_data.regen_restore_status"] == "review_complete"
assert update["state_data.theme_screens_stale"] is DELETE_FIELD
assert update["file_urls.screens"] is DELETE_FIELD
deleted = {c.args[0] for c in storage.delete_file.call_args_list}
assert "jobs/job1/screens/title.png" in deleted
assert "jobs/job1/finals/A - B (Title).mov" in deleted
assert "jobs/job1/finals/x.mp4" not in deleted
worker_service.trigger_screens_worker.assert_awaited_once_with("job1")
@pytest.mark.asyncio
async def test_already_diverted_by_duplicate_trigger_skips_render(self):
jm = self._jm(status="generating_screens")
job = _job(status=JobStatus.REVIEW_COMPLETE, state_data={"theme_screens_stale": True})
with patch("backend.services.theme_rerender_service.firestore.transactional", _passthrough_transactional):
assert await svc.divert_for_stale_screens(job, jm, MagicMock()) is True
jm.firestore.db.transaction.return_value.update.assert_not_called()
@pytest.mark.asyncio
async def test_trigger_failure_restores_and_raises(self):
jm = self._jm()
worker_service = MagicMock(trigger_screens_worker=AsyncMock(return_value=False))
job = _job(status=JobStatus.REVIEW_COMPLETE, state_data={"theme_screens_stale": True})
with patch("backend.services.theme_rerender_service.firestore.transactional", _passthrough_transactional), \
patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
with pytest.raises(RuntimeError):
await svc.divert_for_stale_screens(job, jm, MagicMock())
restore = jm.update_job.call_args.args[1]
assert restore["status"] == "review_complete"
assert restore["state_data.theme_screens_stale"] is True # a retry diverts again
class TestOutdatedJobs:
def _run(self, jobs, updated_at=THEME_SAVED, user_email=None):
jm = MagicMock()
jm.list_jobs.return_value = jobs
with patch.object(svc, "theme_updated_at", return_value=updated_at), \
patch("backend.services.theme_rerender_service.validate_rerender",
side_effect=lambda j: "nope" if j.job_id == "invalid" else None):
result = svc.outdated_jobs("randy-vild", "randy-vild", user_email, job_manager=jm)
return result, jm
def test_lists_finished_tracks_made_before_the_theme_save(self):
jobs = [
_job("old", status=JobStatus.COMPLETE),
_job("rerendered", status=JobStatus.COMPLETE, theme_applied_at=THEME_SAVED + timedelta(minutes=5)),
_job("new", status=JobStatus.COMPLETE, created_at=THEME_SAVED + timedelta(hours=1)),
_job("inreview", status=JobStatus.IN_REVIEW),
_job("othertheme", status=JobStatus.COMPLETE, theme_id="nomad"),
_job("invalid", status=JobStatus.COMPLETE),
]
result, _ = self._run(jobs)
assert result["job_ids"] == ["old"]
assert result["theme_updated_at"] == THEME_SAVED.isoformat()
def test_scoped_to_owner(self):
_, jm = self._run([], user_email="randy@example.com")
assert jm.list_jobs.call_args.kwargs["user_email"] == "randy@example.com"
assert jm.list_jobs.call_args.kwargs["tenant_id"] == "randy-vild"
def test_unknown_theme_time_means_nothing_outdated(self):
result, jm = self._run([_job(status=JobStatus.COMPLETE)], updated_at=None)
assert result["job_ids"] == []
jm.list_jobs.assert_not_called()
def test_string_and_naive_timestamps(self):
assert svc._as_utc("2026-10-06T14:35:00Z") == THEME_SAVED
assert svc._as_utc(datetime(2026, 10, 6, 14, 35)) == THEME_SAVED
assert svc._as_utc("garbage") is None
class TestThemeUpdatedAt:
def test_reads_style_blob_time(self):
storage = MagicMock()
storage.bucket.get_blob.return_value = SimpleNamespace(updated=THEME_SAVED)
assert svc.theme_updated_at("randy-vild", storage) == THEME_SAVED
storage.bucket.get_blob.assert_called_once_with("themes/randy-vild/style_params.json")
def test_missing_blob_or_error(self):
storage = MagicMock()
storage.bucket.get_blob.return_value = None
assert svc.theme_updated_at("t", storage) is None
storage.bucket.get_blob.side_effect = RuntimeError("boom")
assert svc.theme_updated_at("t", storage) is None
class TestEditThemeUpdate:
def _run(self, job, updated_at=THEME_SAVED, screens_regenerating=False, tenant_theme="randy-vild"):
config = SimpleNamespace(defaults=SimpleNamespace(locked_theme=tenant_theme, theme_id=tenant_theme), id="randy-vild")
with patch("backend.services.tenant_service.get_tenant_service") as gts, \
patch.object(svc, "theme_updated_at", return_value=updated_at):
gts.return_value.get_tenant_config.return_value = config
return svc.edit_theme_update(job, screens_regenerating=screens_regenerating)
def test_outdated_track_gets_current_theme_and_stale_flag(self, prepare):
update = self._run(_job(status=JobStatus.COMPLETE))
assert update["style_params_gcs_path"] == "jobs/x/style/style_params.json"
assert update["state_data.theme_screens_stale"] is True
def test_no_flag_when_edit_already_regenerates_screens(self, prepare):
update = self._run(_job(status=JobStatus.COMPLETE), screens_regenerating=True)
assert update["style_params_gcs_path"]
assert "state_data.theme_screens_stale" not in update
def test_current_track_unchanged(self, prepare):
job = _job(status=JobStatus.COMPLETE, theme_applied_at=THEME_SAVED + timedelta(minutes=1))
assert self._run(job) == {}
prepare.assert_not_called()
def test_non_tenant_and_theme_switched_jobs_unchanged(self, prepare):
assert self._run(_job(tenant_id="")) == {}
assert self._run(_job(), tenant_theme="other") == {}
prepare.assert_not_called()
class TestQuietBulkRerender:
def test_quiet_theme_rerender_suppresses_notifications(self):
from backend.services.admin_rerender_service import suppress_customer_notifications
quiet = SimpleNamespace(state_data={"theme_rerender": {"theme_id": "t", "notify_customer": False}})
loud = SimpleNamespace(state_data={"theme_rerender": {"theme_id": "t", "notify_customer": True}})
legacy = SimpleNamespace(state_data={"theme_rerender": {"theme_id": "t"}})
assert suppress_customer_notifications(quiet) is True
assert suppress_customer_notifications(loud) is False
assert suppress_customer_notifications(legacy) is False
@pytest.mark.asyncio
async def test_marker_records_notify_choice_and_clears_stale_flag(self, prepare):
from backend.services.theme_rerender_service import ThemeRerenderService
jm = _job_manager()
_set_claim_status(jm, "complete")
worker_service = MagicMock(trigger_screens_worker=AsyncMock(return_value=True))
job = SimpleNamespace(
job_id="job1", status="complete", tenant_id="randy-vild", theme_id="randy-vild",
color_overrides={}, outputs_deleted_at=None, prep_only=False, finalise_only=False,
state_data={"instrumental_selection": "custom"},
file_urls={"lyrics": {"corrections": "c.json"}}, progress=100,
)
with patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
await ThemeRerenderService(job_manager=jm, storage=MagicMock()).start(
job, theme_id="randy-vild", requested_by="x", notify_customer=False)
update = jm.firestore.db.transaction.return_value.update.call_args.args[1]
assert update["state_data.theme_rerender"]["notify_customer"] is False
assert update["state_data.theme_screens_stale"] is DELETE_FIELD
assert isinstance(update["theme_applied_at"], datetime)
# --- Routes ------------------------------------------------------------------
from backend.api.routes import tenant_theme # noqa: E402
from backend.tests.test_tenant_theme_route import RANDY, THEME, app, client_for # noqa: E402,F401
def test_save_reports_refreshed_and_outdated(client_for):
client = client_for()
with patch.object(tenant_theme, "save_tenant_theme"), \
patch.object(tenant_theme, "get_theme_for_editor", return_value=THEME), \
patch.object(tenant_theme, "refresh_inflight_jobs", return_value={"updated": 3, "failed": 0}) as refresh, \
patch.object(tenant_theme, "outdated_jobs", return_value={"job_ids": ["a", "b"]}) as outdated:
resp = client.put("/api/tenant/theme", json={"style_params": {}})
assert resp.status_code == 200
body = resp.json()
assert body["refreshed_jobs"] == 3 and body["outdated_job_ids"] == ["a", "b"]
assert body["theme_id"] == "randy-vild"
refresh.assert_called_once_with("randy-vild", "randy-vild")
assert outdated.call_args.args == ("randy-vild", "randy-vild", "randyvild@gmail.com")
def test_save_succeeds_even_if_follow_up_work_fails(client_for):
client = client_for()
with patch.object(tenant_theme, "save_tenant_theme"), \
patch.object(tenant_theme, "get_theme_for_editor", return_value=THEME), \
patch.object(tenant_theme, "refresh_inflight_jobs", side_effect=RuntimeError("x")), \
patch.object(tenant_theme, "outdated_jobs", side_effect=RuntimeError("y")):
resp = client.put("/api/tenant/theme", json={"style_params": {}})
assert resp.status_code == 200
assert resp.json()["refreshed_jobs"] == 0 and resp.json()["outdated_job_ids"] == []
def test_outdated_jobs_scope_member_vs_admin(client_for):
with patch.object(tenant_theme, "outdated_jobs", return_value={"theme_updated_at": None, "job_ids": ["a"]}) as od:
assert client_for().get("/api/tenant/theme/outdated-jobs").json()["job_ids"] == ["a"]
assert od.call_args.args[2] == "randyvild@gmail.com"
client_for(email="andrew@nomadkaraoke.com").get("/api/tenant/theme/outdated-jobs")
assert od.call_args.args[2] is None
def test_rerender_outdated_is_quiet_and_reports_failures(client_for):
from backend.services.theme_rerender_service import RerenderError
service = MagicMock()
service.start = AsyncMock(side_effect=[None, RerenderError("published"), None])
jm = MagicMock()
jm.get_job.side_effect = lambda jid: None if jid == "gone" else SimpleNamespace(job_id=jid)
with patch.object(tenant_theme, "outdated_jobs", return_value={"job_ids": ["a", "b", "gone", "c"]}), \
patch("backend.services.job_manager.JobManager", return_value=jm), \
patch("backend.services.theme_rerender_service.ThemeRerenderService", return_value=service):
resp = client_for().post("/api/tenant/theme/rerender-outdated")
assert resp.status_code == 200
assert resp.json() == {"started": ["a", "c"], "failed": {"b": "published"}, "remaining": []}
assert all(c.kwargs["notify_customer"] is False for c in service.start.call_args_list)
def test_new_endpoints_reject_non_members(client_for):
client = client_for(email="stranger@example.com")
assert client.get("/api/tenant/theme/outdated-jobs").status_code == 403
assert client.post("/api/tenant/theme/rerender-outdated").status_code == 403
def test_rerender_outdated_caps_each_call(client_for):
"""Bounded per request; the rest come back as ``remaining`` for the UI to offer again."""
service = MagicMock()
service.start = AsyncMock(return_value=None)
jm = MagicMock()
jm.get_job.side_effect = lambda jid: SimpleNamespace(job_id=jid)
ids = [f"j{i}" for i in range(tenant_theme.MAX_BULK_RERENDER + 3)]
with patch.object(tenant_theme, "outdated_jobs", return_value={"job_ids": ids}), \
patch("backend.services.job_manager.JobManager", return_value=jm), \
patch("backend.services.theme_rerender_service.ThemeRerenderService", return_value=service):
body = client_for().post("/api/tenant/theme/rerender-outdated").json()
assert body["started"] == ids[:tenant_theme.MAX_BULK_RERENDER]
assert body["remaining"] == ids[tenant_theme.MAX_BULK_RERENDER:]
assert service.start.await_count == tenant_theme.MAX_BULK_RERENDER
@@ -139,3 +139,59 @@ def test_failed_download_leaves_no_partial_cache_file(tmp_path, monkeypatch):
with pytest.raises(IOError):
tps._local_theme_asset(Storage, "t1", "bg.jpg")
assert not any(f.is_file() for f in tmp_path.rglob("*"))
def _with_end(theme, **end):
theme["end"] = {
"background_color": "#301020",
"background_image": None,
"font": "AvenirNext-Bold.ttf",
"title_color": "#ffffff",
"artist_color": "#ffdf6b",
"title_region": "370,900,3100,350",
"artist_region": "370,1450,3100,200",
"extra_text": "THANK YOU FOR SINGING!",
"extra_text_color": "#ff7acc",
"extra_text_region": "370,400,3100,400",
**end,
}
return theme
def test_renders_the_end_screen_with_its_own_background_and_layout():
tps._CACHE.clear()
result = tps.render_theme_preview("t1", _with_end(_theme()), artist="Randy Vild", storage=_NoGcsAssets())
end = _img(result.end_screen)
assert end.size == (1280, 720)
r, g, b = end.getpixel((8, 8)) # the end section's own #301020, not the title card's
assert abs(r - 0x30) <= 6 and abs(g - 0x10) <= 6 and abs(b - 0x20) <= 6
assert result.as_data_urls()["end_screen"].startswith("data:image/jpeg;base64,")
def test_end_screen_text_size_changes_only_the_end_screen():
"""Randy Vild's report: the end screen's text size is its own setting."""
tps._CACHE.clear()
big = tps.render_theme_preview("t1", _with_end(_theme()), storage=_NoGcsAssets())
small = tps.render_theme_preview(
"t1", _with_end(_theme(), title_region="370,900,3100,120", extra_text_region="370,400,3100,120"),
storage=_NoGcsAssets(),
)
assert big.title_card == small.title_card
assert big.end_screen != small.end_screen
def text_pixels(data):
return sum(1 for r, g, b in _img(data).getdata() if r > 200 and g > 200 and b > 200)
assert text_pixels(small.end_screen) < text_pixels(big.end_screen) * 0.6
def test_omitted_screens_are_not_rendered():
tps._CACHE.clear()
theme = _with_end(_theme())
theme["intro"]["enabled"] = False
theme["end"]["enabled"] = False
result = tps.render_theme_preview("t1", theme, storage=_NoGcsAssets())
assert result.title_card is None and result.end_screen is None
assert _img(result.karaoke_frame).size == (1280, 720)
urls = result.as_data_urls()
assert urls["title_card"] is None and urls["end_screen"] is None
+331
View File
@@ -0,0 +1,331 @@
"""
Themes can leave the title and/or end screen out of rendered videos
(``intro.enabled`` / ``end.enabled`` = false).
Covers the cloud pipeline end to end: the screens worker records which screens
it made (``state_data.screens_included``), the render prerequisites and /retry
ladder accept a missing omitted screen, the orchestrator/encoding config carry
explicit include flags, and the encoders (GCE worker + LocalEncodingService)
concatenate only the included segments, without rebuilding an omitted screen
from a theme background PNG that the encoder's loose globs would match.
"""
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from backend.workers.style_helper import SCREENS_INCLUDED_KEY, screen_included
# --- marker helper --------------------------------------------------------------
def test_screen_included_defaults_to_true_for_older_jobs():
assert screen_included({}, "title") and screen_included(None, "end")
assert screen_included({SCREENS_INCLUDED_KEY: {"title": True}}, "end")
assert not screen_included({SCREENS_INCLUDED_KEY: {"title": False, "end": True}}, "title")
# --- screens worker -------------------------------------------------------------
@pytest.mark.asyncio
@pytest.mark.parametrize("include_title,include_end", [(False, True), (True, False), (False, False), (True, True)])
async def test_screens_worker_skips_omitted_screens_and_records_them(tmp_path, include_title, include_end):
from datetime import datetime, timezone
from backend.models.job import Job, JobStatus
from backend.workers import screens_worker as sw
job = Job(
job_id="j1", artist="A", title="T", status=JobStatus.DOWNLOADING,
created_at=datetime.now(timezone.utc), updated_at=datetime.now(timezone.utc),
state_data={"lyrics_complete": True, "audio_complete": True},
)
jm = MagicMock()
jm.get_job.return_value = job
jm.transition_to_state.return_value = True
style_config = MagicMock(include_title_screen=include_title, include_end_screen=include_end)
async def load_style(*args, **kwargs):
return style_config
async def make_png(name):
png = tmp_path / f"{name}.png"
png.write_bytes(b"png")
return str(png)
async def noop(*args, **kwargs):
return {}
title_gen = MagicMock(side_effect=lambda **kw: make_png("title"))
end_gen = MagicMock(side_effect=lambda **kw: make_png("end"))
upload = MagicMock(side_effect=noop)
with patch.object(sw, "JobManager", return_value=jm), \
patch.object(sw, "StorageService"), \
patch.object(sw, "get_settings"), \
patch.object(sw, "create_job_logger"), \
patch.object(sw, "setup_job_logging"), \
patch.object(sw, "_validate_prerequisites", return_value=True), \
patch("backend.services.stems_restore.maybe_start_stems_restore", return_value="not_needed"), \
patch.object(sw, "load_style_config", side_effect=load_style), \
patch.object(sw, "_create_video_generator"), \
patch.object(sw, "_generate_title_screen", title_gen), \
patch.object(sw, "_generate_end_screen", end_gen), \
patch.object(sw, "_upload_screens", upload), \
patch.object(sw, "_apply_countdown_padding_if_needed", side_effect=noop), \
patch.object(sw, "_transcode_review_audio", side_effect=noop), \
patch("backend.services.auto_approval.executor.maybe_auto_complete_review", side_effect=noop), \
patch("backend.services.auto_approval.pre_apply.ensure_and_pre_apply", side_effect=noop):
result = await sw.generate_screens("j1")
assert result is True, jm.mark_job_failed.call_args
assert title_gen.called is include_title
assert end_gen.called is include_end
kwargs = upload.call_args.kwargs
assert (kwargs["title_screen_path"] is not None) is include_title
assert (kwargs["end_screen_path"] is not None) is include_end
jm.update_state_data.assert_any_call("j1", SCREENS_INCLUDED_KEY, {"title": include_title, "end": include_end})
def test_upload_screens_skips_an_omitted_screen(tmp_path):
from backend.workers.screens_worker import _upload_screens_sync
(tmp_path / "End.png").write_bytes(b"png")
(tmp_path / "End.jpg").write_bytes(b"jpg")
storage, jm = MagicMock(), MagicMock()
storage.upload_file.side_effect = lambda local, gcs: f"gs://b/{gcs}"
_upload_screens_sync("j1", jm, storage, None, str(tmp_path / "End.png"))
assert [c.args[1] for c in storage.upload_file.call_args_list] == ["jobs/j1/screens/end.png", "jobs/j1/screens/end.jpg"]
jm.update_file_url.assert_any_call("j1", "screens", "end_png", "gs://b/jobs/j1/screens/end.png")
jm.update_file_url.assert_any_call("j1", "screens", "end_jpg", "gs://b/jobs/j1/screens/end.jpg")
# --- render prerequisites + retry ladder -----------------------------------------
def _video_job(screens, included=None):
state = {"instrumental_selection": "clean"}
if included is not None:
state[SCREENS_INCLUDED_KEY] = included
return SimpleNamespace(
job_id="j1",
state_data=state,
file_urls={"screens": screens, "videos": {"with_vocals": "gs://v"}, "stems": {"instrumental_clean": "gs://i"}},
)
@pytest.mark.parametrize(
"screens,included,ok",
[
({"title_png": "x", "end_png": "y"}, None, True),
({"end_png": "y"}, None, False), # older job: a missing title is still an error
({"end_png": "y"}, {"title": False, "end": True}, True),
({"title_png": "x"}, {"title": True, "end": False}, True),
({}, {"title": False, "end": False}, True),
({}, {"title": True, "end": False}, False),
],
)
def test_video_prerequisites_accept_omitted_screens(screens, included, ok):
from backend.workers import video_worker
with patch.object(video_worker, "validate_worker_can_run", return_value=None):
assert video_worker._validate_prerequisites(_video_job(screens, included)) is ok
@pytest.mark.parametrize(
"file_urls,state_data,expected",
[
({"screens": {"title_jpg": "x"}}, {}, True),
({"screens": {}}, {}, False),
# Title omitted by the theme and the screens worker finished
({"screens": {"end_png": "y"}}, {SCREENS_INCLUDED_KEY: {"title": False}, "screens_progress": {"stage": "complete"}}, True),
# ...but a re-render cleared screens_progress: the stale marker alone isn't enough
({"screens": {}}, {SCREENS_INCLUDED_KEY: {"title": False}}, False),
],
)
def test_retry_screens_check_understands_omitted_title(file_urls, state_data, expected):
from backend.api.routes.jobs import _has_title_screen
assert _has_title_screen(file_urls, state_data) is expected
# --- orchestrator + encoding config ---------------------------------------------
def _orch_job(included):
return SimpleNamespace(
job_id="j1", artist="A", title="T",
state_data={"instrumental_selection": "clean", SCREENS_INCLUDED_KEY: included},
file_urls={"screens": {"end_png": "gs://b/jobs/j1/screens/end.png"}, "videos": {"with_vocals": "gs://b/v.mkv"}},
)
def test_orchestrator_config_drops_omitted_screen_paths(tmp_path):
from backend.workers import video_worker_orchestrator as vwo
dist = MagicMock(enable_youtube_upload=False, brand_prefix=None, discord_webhook_url=None,
youtube_description=None, dropbox_path=None, gdrive_folder_id=None)
with patch("backend.services.job_defaults_service.get_effective_distribution_for_job", return_value=dist):
config = vwo.create_orchestrator_config_from_job(_orch_job({"title": False, "end": True}), str(tmp_path))
assert config.title_video_path is None
assert config.end_video_path.endswith("A - T (End).png")
assert config.include_title_screen is False and config.include_end_screen is True
@pytest.mark.asyncio
async def test_orchestrator_passes_include_flags_to_the_encoder():
from backend.workers.video_worker_orchestrator import OrchestratorConfig, VideoWorkerOrchestrator
config = OrchestratorConfig(
job_id="j1", artist="A", title="T", title_video_path=None, karaoke_video_path="k.mkv",
instrumental_audio_path="i.flac", include_title_screen=False, include_end_screen=True,
)
orch = VideoWorkerOrchestrator(config=config, job_manager=MagicMock(), storage=MagicMock())
backend = MagicMock()
backend.name = "local"
backend.encode = MagicMock(side_effect=RuntimeError("stop"))
orch._get_encoding_backend = MagicMock(return_value=backend)
with pytest.raises(RuntimeError, match="stop"):
await orch._run_encoding()
encoding_input = backend.encode.call_args.args[0]
assert encoding_input.title_video_path is None
assert encoding_input.options["include_title_screen"] is False
assert encoding_input.options["include_end_screen"] is True
@pytest.mark.asyncio
async def test_original_vocals_guide_has_no_intro_offset_without_a_title_card():
from backend.workers.video_worker_orchestrator import OrchestratorConfig, VideoWorkerOrchestrator
config = OrchestratorConfig(
job_id="j1", artist="A", title="T", title_video_path=None, karaoke_video_path="k",
instrumental_audio_path="i", include_title_screen=False,
)
orch = VideoWorkerOrchestrator(config=config, job_manager=MagicMock(), storage=MagicMock())
assert await orch._resolve_intro_seconds() == 0.0
@pytest.mark.asyncio
async def test_gce_backend_sends_include_flags_only_when_a_screen_is_omitted():
from backend.services.encoding_interface import EncodingInput, GCEEncodingBackend
def make_input(**flags):
return EncodingInput(
title_video_path=None, karaoke_video_path="k", instrumental_audio_path="i", artist="A", title="T",
options={"job_id": "j1", "input_gcs_path": "gs://b/in/", "output_gcs_path": "gs://b/out/", **flags},
)
sent = []
async def encode_videos(job_id, input_gcs_path, output_gcs_path, encoding_config, **kwargs):
sent.append(encoding_config)
raise RuntimeError("stop")
gce = GCEEncodingBackend()
service = MagicMock()
service.is_enabled = True
service.encode_videos = encode_videos
gce._service = service
with patch.object(GCEEncodingBackend, "_get_service", return_value=service):
await gce.encode(make_input(include_title_screen=False, include_end_screen=True))
await gce.encode(make_input(include_title_screen=True, include_end_screen=True))
assert sent[0]["include_title_screen"] is False and "include_end_screen" not in sent[0]
assert "include_title_screen" not in sent[1] and "include_end_screen" not in sent[1]
# --- encoders -------------------------------------------------------------------
@pytest.mark.parametrize(
"with_title,with_end,n",
[(True, True, 3), (False, True, 2), (True, False, 2), (False, False, 1)],
)
def test_lossless_concat_includes_only_present_segments(tmp_path, with_title, with_end, n):
from backend.services.local_encoding_service import LocalEncodingService
end = tmp_path / "end.mov"
end.write_bytes(b"x")
service = LocalEncodingService(logger=MagicMock())
with patch.object(service, "_execute_command_with_fallback", return_value=True) as run:
assert service.encode_lossless_mp4(
str(tmp_path / "title.mov") if with_title else None,
str(tmp_path / "karaoke.mkv"),
str(tmp_path / "out.mp4"),
str(end) if with_end else None,
)
gpu, cpu = run.call_args.args[:2]
for cmd in (gpu, cpu):
assert f"concat=n={n}:v=1:a=1" in cmd
assert cmd.count(" -i ") == n
assert ("title.mov" in cmd) is with_title
assert ("end.mov" in cmd) is with_end
assert "karaoke.mkv" in cmd
# Segment order: title, karaoke, end
assert cpu.index("karaoke.mkv") > (cpu.index("title.mov") if with_title else -1)
if with_end:
assert cpu.index("end.mov") > cpu.index("karaoke.mkv")
def _gce_work_dir(tmp_path: Path) -> Path:
work = tmp_path / "work"
(work / "style").mkdir(parents=True)
(work / "videos").mkdir()
(work / "stems").mkdir()
# Theme assets the encoder's loose "*title*.png" / "*end*.png" globs would match
(work / "style" / "cdg_title_background.png").write_bytes(b"png" * 1000)
(work / "style" / "end_background.png").write_bytes(b"png" * 1000)
(work / "videos" / "with_vocals.mkv").write_bytes(b"mkv" * 1000)
(work / "stems" / "instrumental_clean.flac").write_bytes(b"flac" * 1000)
return work
@pytest.mark.parametrize("include_title,include_end", [(False, False), (False, True), (True, False)])
def test_gce_worker_never_rebuilds_an_omitted_screen_from_theme_pngs(tmp_path, include_title, include_end):
from backend.services.gce_encoding import main
work = _gce_work_dir(tmp_path)
(work / "screens").mkdir()
for screen, included in (("title", include_title), ("end", include_end)):
if included:
(work / "screens" / f"{screen}.png").write_bytes(b"png" * 1000)
made = []
def fake_mov(png, mov, duration=5):
made.append(png.name)
mov.write_bytes(b"mov" * 1000)
return mov
service = MagicMock()
service.encode_all_formats.return_value = MagicMock(success=True)
main.jobs["j1"] = {"status": "pending", "progress": 0}
with patch.object(main, "generate_mov_from_png", side_effect=fake_mov), \
patch.object(main, "render_portrait_into_outputs"), \
patch.object(main, "_persist"), \
patch("backend.services.local_encoding_service.LocalEncodingService", return_value=service):
main.run_encoding("j1", work, {
"artist": "A", "title": "T",
"include_title_screen": include_title, "include_end_screen": include_end,
})
config = service.encode_all_formats.call_args.args[0]
assert (config.title_video is not None) is include_title
assert (config.end_video is not None) is include_end
assert sorted(made) == sorted(f"{s}.png" for s, inc in (("title", include_title), ("end", include_end)) if inc)
staged = sorted(p.name for p in (work / "outputs").glob("*.mov"))
assert ("A - T (Title).mov" in staged) is include_title
assert ("A - T (End).mov" in staged) is include_end
def test_gce_worker_still_requires_a_title_when_included(tmp_path):
from backend.services.gce_encoding import main
work = _gce_work_dir(tmp_path)
(work / "style" / "cdg_title_background.png").unlink()
main.jobs["j2"] = {"status": "pending", "progress": 0}
with patch.object(main, "_persist"), \
patch.object(main, "generate_mov_from_png", side_effect=lambda png, mov, duration=5: mov), \
patch("backend.services.local_encoding_service.LocalEncodingService"):
with pytest.raises(Exception, match="No title video"):
main.run_encoding("j2", work, {"artist": "A", "title": "T"})
@@ -1311,6 +1311,60 @@ class TestVideoWorkerOrchestratorDistribution:
assert orchestrator.result.youtube_url is None
def _youtube_orchestrator(self, temp_dir):
video_file = os.path.join(temp_dir, "test.mp4")
with open(video_file, "w") as f:
f.write("dummy video")
config = OrchestratorConfig(
job_id="test-job",
artist="Eli",
title="The Comeback",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_youtube_upload=True,
youtube_credentials={"token": "test"},
)
orchestrator = VideoWorkerOrchestrator(config)
orchestrator.result.final_video_lossy = video_file
return orchestrator
@pytest.mark.asyncio
async def test_upload_to_youtube_failure_is_queued_for_retry(self):
"""A failed (non-quota) upload goes to the deferred queue instead of being lost."""
with tempfile.TemporaryDirectory() as temp_dir:
orchestrator = self._youtube_orchestrator(temp_dir)
with patch.object(orchestrator, "_get_youtube_service") as mock_get, \
patch("backend.services.youtube_upload_queue_service.get_youtube_upload_queue_service") as mock_queue_get:
mock_get.return_value.upload_video.side_effect = Exception('<HttpError 410 returned "Gone">')
await orchestrator._upload_to_youtube()
queue_kwargs = mock_queue_get.return_value.queue_upload.call_args.kwargs
assert queue_kwargs["job_id"] == "test-job"
assert queue_kwargs["reason"] == "upload_error"
assert orchestrator.result.youtube_upload_queued is True
assert orchestrator.result.youtube_url is None
assert len(orchestrator.result.distribution_warnings) == 1
assert "queued for automatic retry" in orchestrator.result.distribution_warnings[0]
@pytest.mark.asyncio
async def test_upload_to_youtube_failure_and_queue_failure_warns(self):
"""If queueing also fails, the warning names the upload error (not quota)."""
with tempfile.TemporaryDirectory() as temp_dir:
orchestrator = self._youtube_orchestrator(temp_dir)
with patch.object(orchestrator, "_get_youtube_service") as mock_get, \
patch("backend.services.youtube_upload_queue_service.get_youtube_upload_queue_service") as mock_queue_get:
mock_get.return_value.upload_video.side_effect = Exception("Gone")
mock_queue_get.return_value.queue_upload.side_effect = Exception("firestore down")
await orchestrator._upload_to_youtube()
assert orchestrator.result.youtube_upload_queued is False
assert orchestrator.result.distribution_warnings == [
"YouTube upload skipped (upload failed: Gone) and failed to queue: firestore down"
]
class TestVideoWorkerOrchestratorNotifications:
"""Test notifications stage."""
@@ -566,3 +566,64 @@ class TestGetYouTubeUploadService:
assert service is not None
assert service.client_secrets_file == "/path/to/secrets.json"
class TestYouTubeUploadSessionRestart:
"""A lost resumable session (404/410) restarts the upload; other errors don't."""
@staticmethod
def _http_error(status):
from googleapiclient.errors import HttpError
resp = MagicMock()
resp.status = status
resp.reason = "Gone"
return HttpError(resp, b'{"error": {"message": "Gone"}}', uri="https://youtube.googleapis.com/upload")
def _service(self, insert_execute_side_effect):
service = YouTubeUploadService(credentials={"token": "t"}, non_interactive=True, server_side_mode=True)
youtube = MagicMock()
youtube.videos.return_value.insert.return_value.execute.side_effect = insert_execute_side_effect
service._youtube_service = youtube
return service, youtube
@patch("time.sleep")
@patch("googleapiclient.http.MediaFileUpload")
def test_410_restarts_with_fresh_session(self, mock_media, mock_sleep):
service, youtube = self._service([self._http_error(410), {"id": "VID"}])
with patch.object(service, "check_duplicate", return_value=(False, None, None)):
video_id, video_url = service.upload_video(video_path="/v.mkv", title="A - B (Karaoke)", description="d")
assert video_id == "VID"
assert youtube.videos.return_value.insert.call_count == 2
assert mock_media.call_count == 2 # new MediaFileUpload per session
youtube.videos.return_value.insert.return_value.execute.assert_called_with(
num_retries=YouTubeUploadService.UPLOAD_NUM_RETRIES
)
mock_sleep.assert_called_once()
@patch("time.sleep")
@patch("googleapiclient.http.MediaFileUpload")
def test_410_on_every_attempt_raises(self, mock_media, mock_sleep):
attempts = YouTubeUploadService.UPLOAD_SESSION_ATTEMPTS
service, youtube = self._service([self._http_error(410)] * attempts)
with patch.object(service, "check_duplicate", return_value=(False, None, None)):
with pytest.raises(Exception, match="410"):
service.upload_video(video_path="/v.mkv", title="A - B (Karaoke)", description="d")
assert youtube.videos.return_value.insert.call_count == attempts
assert mock_sleep.call_count == attempts - 1
@patch("time.sleep")
@patch("googleapiclient.http.MediaFileUpload")
def test_quota_403_is_not_restarted(self, mock_media, mock_sleep):
service, youtube = self._service([self._http_error(403)])
with patch.object(service, "check_duplicate", return_value=(False, None, None)):
with pytest.raises(Exception, match="403"):
service.upload_video(video_path="/v.mkv", title="A - B (Karaoke)", description="d")
assert youtube.videos.return_value.insert.call_count == 1
mock_sleep.assert_not_called()
+75
View File
@@ -0,0 +1,75 @@
"""
Resolve a job's user-supplied ("existing") instrumental to a path that exists.
``existing_instrumental_gcs_path`` was recorded under ``uploads/{job_id}/...``,
which the bucket lifecycle deletes after 7 days — so any re-render, regenerate
or edit of an older bring-your-own-instrumental job lost its instrumental. The
video pipeline stages a copy at the job root (``jobs/{id}/custom_instrumental.<ext>``,
see video_worker_orchestrator._run_encoding), which is kept forever.
New uploads are persisted to that root path at upload time (file_upload); for
older jobs this resolver falls back to the staged copy and (best-effort)
repoints the job at it, so the fix migrates jobs lazily as they're used.
"""
import logging
import os
from typing import Optional
logger = logging.getLogger(__name__)
STAGED_STEMS = ("custom_instrumental", "existing_instrumental")
def persistent_instrumental_path(job_id: str, source_path: str) -> str:
"""The job-root path a user instrumental is kept at (same name the encoder globs)."""
ext = os.path.splitext(source_path or "")[1].lower() or ".mp3"
return f"jobs/{job_id}/custom_instrumental{ext}"
def _staged_copy(job_id: str, storage) -> Optional[str]:
try:
names = storage.list_files(f"jobs/{job_id}/")
except Exception as e: # noqa: BLE001
logger.warning(f"[job:{job_id}] Couldn't list job files for staged instrumental: {e}")
return None
prefix = f"jobs/{job_id}/"
for stem in STAGED_STEMS:
for name in sorted(names):
rel = name[len(prefix):]
if "/" not in rel and os.path.splitext(rel)[0] == stem:
return name
return None
def resolve_existing_instrumental(job, storage, job_manager=None, log=None) -> Optional[str]:
"""Return a GCS path for the job's existing instrumental that actually exists.
- the recorded path, if it exists;
- else the staged job-root copy (and repoint the job at it, best-effort);
- else the recorded path unchanged (the caller fails loudly as before).
"""
recorded = getattr(job, "existing_instrumental_gcs_path", None)
if not recorded:
return recorded
job_id = job.job_id
try:
if storage.file_exists(recorded):
return recorded
except Exception as e: # noqa: BLE001
logger.warning(f"[job:{job_id}] Couldn't check existing instrumental {recorded}: {e}")
return recorded
staged = _staged_copy(job_id, storage)
if not staged:
logger.error(f"[job:{job_id}] Existing instrumental {recorded} is gone and no staged copy exists")
return recorded
message = f"Existing instrumental {recorded} expired; using staged copy {staged}"
logger.warning(f"[job:{job_id}] {message}")
if log is not None:
log.warning(message)
if job_manager is not None:
try:
job_manager.update_job(job_id, {"existing_instrumental_gcs_path": staged})
except Exception as e: # noqa: BLE001
logger.warning(f"[job:{job_id}] Couldn't repoint existing_instrumental_gcs_path: {e}")
return staged
+57
View File
@@ -0,0 +1,57 @@
"""Per-key re-entrant locks (in-process).
Route handlers now run in FastAPI's threadpool (plain ``def``), so two requests
for the same job/user on one instance can interleave inside non-transactional
check-then-write code (e.g. a double-clicked Cancel refunding twice). When those
handlers were never-awaiting ``async def``s they ran start-to-finish on the
event loop, which serialized them per instance; these locks restore exactly
that per-instance guarantee. They do NOT coordinate across Cloud Run instances
(nothing did before either) — that would need Firestore transactions.
Usage::
with job_lock(job_id):
...check status, then write...
"""
from __future__ import annotations
import threading
from contextlib import contextmanager
from typing import Dict, Iterator
class KeyedLocks:
def __init__(self) -> None:
self._guard = threading.Lock()
self._locks: Dict[str, threading.RLock] = {}
self._refs: Dict[str, int] = {}
@contextmanager
def hold(self, key: str) -> Iterator[None]:
with self._guard:
lock = self._locks.get(key)
if lock is None:
lock = self._locks[key] = threading.RLock()
self._refs[key] = self._refs.get(key, 0) + 1
try:
with lock:
yield
finally:
with self._guard:
self._refs[key] -= 1
if self._refs[key] == 0:
# Nobody holds or waits on it — drop it so the map stays small.
del self._refs[key]
del self._locks[key]
_job_locks = KeyedLocks()
_user_locks = KeyedLocks()
def job_lock(job_id: str):
return _job_locks.hold(job_id or "")
def user_lock(email: str):
return _user_locks.hold((email or "").lower())
+58
View File
@@ -0,0 +1,58 @@
"""Run a blocking route body in a worker thread while its coroutines still run on the loop.
The API has one event loop per Cloud Run instance, so sync Firestore / GCS calls
inside an ``async def`` route freeze every request on the instance (see
``backend/services/loop_watchdog.py``). Routes that are mostly sync I/O but must
await a few coroutines (worker triggers) do::
return await run_in_body_thread(_do_work_sync, ..., asyncio.get_running_loop())
and, inside ``_do_work_sync``, ``run_on_loop(loop, worker_service.trigger_x(job_id))``.
The coroutine runs on the API loop (so loop APIs like ``create_task`` inside it
keep working) while the worker thread waits for its result.
"""
import asyncio
import concurrent.futures
import contextvars
import functools
from typing import Any, Callable, Coroutine, TypeVar
T = TypeVar("T")
# Route bodies block in run_on_loop while the coroutine they dispatched may itself
# need asyncio.to_thread (the loop's default executor). Running the bodies on
# their own pool means they can never use up the threads those coroutines wait for.
_BODY_EXECUTOR = concurrent.futures.ThreadPoolExecutor(max_workers=16, thread_name_prefix="route-body")
# Worker triggers finish in seconds (bounded run_job retries); anything this slow
# is hung, and the cron/route should fail rather than hold its thread forever.
RUN_ON_LOOP_TIMEOUT_SECONDS = 120
async def run_in_body_thread(func: Callable[..., T], *args: Any) -> T:
"""Run a sync route body on the dedicated route-body pool and await its result.
Like ``asyncio.to_thread``, the caller's contextvars (trace / tenant / request
context) are copied into the thread.
"""
loop = asyncio.get_running_loop()
ctx = contextvars.copy_context()
return await loop.run_in_executor(_BODY_EXECUTOR, functools.partial(ctx.run, func, *args))
def run_on_loop(
loop: asyncio.AbstractEventLoop,
coro: Coroutine[Any, Any, T],
timeout: float = RUN_ON_LOOP_TIMEOUT_SECONDS,
) -> T:
"""From a worker thread, run ``coro`` on ``loop`` and return (or raise) its result."""
try:
future = asyncio.run_coroutine_threadsafe(coro, loop)
except Exception:
coro.close() # loop closed (instance shutdown) — don't leak a never-awaited coroutine
raise
try:
return future.result(timeout=timeout)
except concurrent.futures.TimeoutError:
future.cancel()
raise
+21 -2
View File
@@ -193,6 +193,15 @@ async def process_audio_separation(job_id: str) -> bool:
quick_render = None
# Restore mode: storage retention purged this completed job's stems and the
# screens worker asked for them back (backend/services/stems_restore.py).
# Separate + upload as usual, then hand back to the screens worker; skip the
# first-run-only steps (quick version, prep-phase advance, auto-approval).
from backend.services.stems_restore import complete_stems_restore, is_restore_run, mark_restore_failed
restore_mode = is_restore_run(job)
if restore_mode:
job_log.info("RESTORE MODE: re-separating stems purged by storage retention")
# Create temporary working directory
temp_dir = tempfile.mkdtemp(prefix=f"karaoke_{job_id}_")
job_log.info(f"Created temp directory: {temp_dir}")
@@ -240,7 +249,7 @@ async def process_audio_separation(job_id: str) -> bool:
# kjbox make-it jobs: a quick single-model separation on the warm
# GPU, then a background render of a scrolling-lyrics draft video
# while the ensemble below runs. Never raises; joined in `finally`.
if model_dir:
if model_dir and not restore_mode:
quick_render = start_quick_version(
job, audio_path, temp_dir, model_dir, job_manager, storage, job_log
)
@@ -364,7 +373,7 @@ async def process_audio_separation(job_id: str) -> bool:
# Store processing metadata for separation provenance
duration = time.time() - start_time
job_manager.update_processing_metadata(job_id, "separation", {
job_manager.update_processing_metadata(job_id, "separation_restore" if restore_mode else "separation", {
"provider": "local_gpu" if model_dir else "remote_api",
"clean_model": effective_model_names['clean_instrumental_model'],
"backing_models": effective_model_names['backing_vocals_models'],
@@ -383,6 +392,12 @@ async def process_audio_separation(job_id: str) -> bool:
except Exception as e:
logger.warning(f"[job:{job_id}] Backing vocals analysis failed (non-fatal): {e}")
if restore_mode:
await complete_stems_restore(job_id, job_manager)
duration = time.time() - start_time
logger.info(f"[job:{job_id}] WORKER_END worker=audio mode=restore status=success duration={duration:.1f}s")
return True
# Mark audio processing complete
job_manager.mark_audio_complete(job_id)
@@ -413,6 +428,8 @@ async def process_audio_separation(job_id: str) -> bool:
except DownloadError as e:
duration = time.time() - start_time
logger.error(f"[job:{job_id}] WORKER_END worker=audio status=error duration={duration:.1f}s error={e}", exc_info=True)
if restore_mode:
mark_restore_failed(job_id, job_manager)
job_manager.mark_job_failed(
job_id=job_id,
error_message=f"Audio download failed: {str(e)}",
@@ -423,6 +440,8 @@ async def process_audio_separation(job_id: str) -> bool:
except Exception as e:
duration = time.time() - start_time
logger.error(f"[job:{job_id}] WORKER_END worker=audio status=error duration={duration:.1f}s error={e}", exc_info=True)
if restore_mode:
mark_restore_failed(job_id, job_manager)
job_manager.mark_job_failed(
job_id=job_id,
error_message=f"Audio separation failed: {str(e)}",
+28
View File
@@ -170,6 +170,25 @@ async def process_render_video(job_id: str) -> bool:
await worker_registry.unregister(job_id, "render-video")
return False
# The tenant edited its theme after this job's screens were made: regenerate
# them first (the screens worker re-triggers this worker when done).
from backend.services.theme_change_service import divert_for_stale_screens
try:
diverted = await divert_for_stale_screens(job, job_manager, storage)
except Exception as e:
logger.error(f"[job:{job_id}] WORKER_END worker=render-video status=error error={e}")
job_manager.mark_job_failed(
job_id=job_id,
error_message=f"Screen regeneration for the updated theme failed: {e}",
error_details={"stage": "render_video", "error": str(e)},
)
await worker_registry.unregister(job_id, "render-video")
return False
if diverted:
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=skipped reason=theme_screens_regen")
await worker_registry.unregister(job_id, "render-video")
return True
# Capture the supersession fence at start. If an admin reset (or a newer
# render trigger) advances the generation while we render, our result is
# stale and must be discarded instead of overwriting fresh outputs or
@@ -262,6 +281,8 @@ async def process_render_video(job_id: str) -> bool:
for k, v in job.style_assets.items()
}
capacity_marker_cleared = [False]
def progress_callback(progress: int):
# Update progress in place — the job is already in
# RENDERING_VIDEO when this fires, and going through
@@ -285,6 +306,13 @@ async def process_render_video(job_id: str) -> bool:
'progress': scaled,
'updated_at': datetime.now(UTC),
})
# The worker is really rendering now, so drop the marker from
# earlier parked attempts; otherwise the job card keeps saying
# "waiting for encoding server availability" for the whole render.
if progress and not capacity_marker_cleared[0]:
capacity_marker_cleared[0] = True
if (job.state_data or {}).get('render_pending_capacity'):
job_manager.delete_state_data_key(job_id, 'render_pending_capacity')
with job_span("gce-render-video", job_id) as render_span:
render_start = time.time()
+103 -58
View File
@@ -36,7 +36,7 @@ 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
from backend.config import get_settings
from backend.workers.style_helper import load_style_config, StyleConfig
from backend.workers.style_helper import SCREENS_INCLUDED_KEY, load_style_config, StyleConfig
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
from backend.services.tracing import job_span, add_span_event, add_span_attribute
@@ -117,6 +117,14 @@ async def generate_screens(job_id: str) -> bool:
logger.error(f"[job:{job_id}] Prerequisites not met for screen generation")
return False
# Storage retention purged this job's separated stems: re-run audio
# separation first (the audio worker re-triggers this worker when done), so
# review / render / encode find the stems where they always were.
from backend.services.stems_restore import NOT_NEEDED, FAILED as RESTORE_FAILED, maybe_start_stems_restore
restore = await maybe_start_stems_restore(job, job_manager, job_log)
if restore != NOT_NEEDED:
return restore != RESTORE_FAILED
# Set up log capture for VideoGenerator and style_helper (after the guards above
# so their early returns don't leak handlers).
log_handler = setup_job_logging(job_id, "screens", *SCREENS_WORKER_LOGGERS)
@@ -179,38 +187,49 @@ async def generate_screens(job_id: str) -> bool:
# Initialize video generator
video_generator = _create_video_generator(temp_dir)
# A theme may leave either screen out of its videos (intro/end.enabled=false).
include_title = style_config.include_title_screen
include_end = style_config.include_end_screen
title_screen_path = end_screen_path = None
# Generate title screen with style config
with job_span("generate-title-screen", job_id):
job_log.info("Generating title screen...")
title_screen_path = await _generate_title_screen(
job_id=job_id,
job=job,
video_generator=video_generator,
style_config=style_config,
temp_dir=temp_dir,
job_log=job_log
)
if not title_screen_path:
raise Exception("Title screen generation failed")
job_log.info(f"Title screen generated: {title_screen_path}")
if include_title:
with job_span("generate-title-screen", job_id):
job_log.info("Generating title screen...")
title_screen_path = await _generate_title_screen(
job_id=job_id,
job=job,
video_generator=video_generator,
style_config=style_config,
temp_dir=temp_dir,
job_log=job_log
)
if not title_screen_path:
raise Exception("Title screen generation failed")
job_log.info(f"Title screen generated: {title_screen_path}")
else:
job_log.info("Theme omits the title screen — skipping it")
# Generate end screen with style config
with job_span("generate-end-screen", job_id):
job_log.info("Generating end screen...")
end_screen_path = await _generate_end_screen(
job_id=job_id,
job=job,
video_generator=video_generator,
style_config=style_config,
temp_dir=temp_dir,
job_log=job_log
)
if not end_screen_path:
raise Exception("End screen generation failed")
job_log.info(f"End screen generated: {end_screen_path}")
if include_end:
with job_span("generate-end-screen", job_id):
job_log.info("Generating end screen...")
end_screen_path = await _generate_end_screen(
job_id=job_id,
job=job,
video_generator=video_generator,
style_config=style_config,
temp_dir=temp_dir,
job_log=job_log
)
if not end_screen_path:
raise Exception("End screen generation failed")
job_log.info(f"End screen generated: {end_screen_path}")
else:
job_log.info("Theme omits the end screen — skipping it")
# Upload screens to GCS
with job_span("upload-screens", job_id):
await _upload_screens(
@@ -220,7 +239,12 @@ async def generate_screens(job_id: str) -> bool:
title_screen_path=title_screen_path,
end_screen_path=end_screen_path
)
# Read by the render/encode stages (which run before the style is
# loaded) so an omitted screen isn't treated as missing.
job_manager.update_state_data(
job_id, SCREENS_INCLUDED_KEY, {"title": include_title, "end": include_end}
)
# Apply countdown padding if needed
await _apply_countdown_padding_if_needed(job_id, job_manager, job)
@@ -462,7 +486,10 @@ async def _generate_title_screen(
# Generate title screen images only (MOV video is generated on GCE encoding worker)
# Pass duration=0 to skip FFmpeg video creation — Cloud Run doesn't have enough
# memory for 4K H.264 encoding after right-sizing to 2Gi (PR #640).
video_generator.create_title_video(
# 4K PIL render + PNG/JPG encode is seconds of CPU — keep it off the
# event loop (it froze every request on the instance; 2026-10-03).
await asyncio.to_thread(
video_generator.create_title_video,
artist=job.artist,
title=job.title,
format=title_format,
@@ -537,7 +564,10 @@ async def _generate_end_screen(
# Generate end screen images only (MOV video is generated on GCE encoding worker)
# Pass duration=0 to skip FFmpeg video creation — Cloud Run doesn't have enough
# memory for 4K H.264 encoding after right-sizing to 2Gi (PR #640).
video_generator.create_end_video(
# 4K PIL render + PNG/JPG encode is seconds of CPU — keep it off the
# event loop (it froze every request on the instance; 2026-10-03).
await asyncio.to_thread(
video_generator.create_end_video,
artist=job.artist,
title=job.title,
format=end_format,
@@ -564,11 +594,11 @@ async def _upload_screens(
job_id: str,
job_manager: JobManager,
storage: StorageService,
title_screen_path: str,
end_screen_path: str
title_screen_path: Optional[str],
end_screen_path: Optional[str]
) -> None:
"""
Upload title and end screen images to GCS.
Upload title and end screen images to GCS (None = screen omitted by the theme).
Single Responsibility: Only handles uploads.
@@ -583,25 +613,31 @@ async def _upload_screens(
title_screen_path: Path to title screen image (.png)
end_screen_path: Path to end screen image (.png)
"""
# Upload title screen images (.png and .jpg)
title_base = title_screen_path.replace('.png', '')
for ext, key in [('.png', 'title_png'), ('.jpg', 'title_jpg')]:
image_path = f"{title_base}{ext}"
if os.path.exists(image_path):
gcs_path = f"jobs/{job_id}/screens/title{ext}"
url = storage.upload_file(image_path, gcs_path)
job_manager.update_file_url(job_id, 'screens', key, url)
logger.info(f"Job {job_id}: Uploaded title screen image ({ext})")
# Sync GCS uploads (multi-MB 4K PNGs) + Firestore writes — off the loop.
await asyncio.to_thread(
_upload_screens_sync, job_id, job_manager, storage, title_screen_path, end_screen_path
)
# Upload end screen images (.png and .jpg)
end_base = end_screen_path.replace('.png', '')
for ext, key in [('.png', 'end_png'), ('.jpg', 'end_jpg')]:
image_path = f"{end_base}{ext}"
if os.path.exists(image_path):
gcs_path = f"jobs/{job_id}/screens/end{ext}"
url = storage.upload_file(image_path, gcs_path)
job_manager.update_file_url(job_id, 'screens', key, url)
logger.info(f"Job {job_id}: Uploaded end screen image ({ext})")
def _upload_screens_sync(
job_id: str,
job_manager: JobManager,
storage: StorageService,
title_screen_path: Optional[str],
end_screen_path: Optional[str]
) -> None:
for screen, path in (("title", title_screen_path), ("end", end_screen_path)):
if not path:
continue
# Upload the screen's images (.png and .jpg)
base = path.replace('.png', '')
for ext in ('.png', '.jpg'):
image_path = f"{base}{ext}"
if os.path.exists(image_path):
gcs_path = f"jobs/{job_id}/screens/{screen}{ext}"
url = storage.upload_file(image_path, gcs_path)
job_manager.update_file_url(job_id, 'screens', f"{screen}_{ext[1:]}", url)
logger.info(f"Job {job_id}: Uploaded {screen} screen image ({ext})")
async def _analyze_backing_vocals(
@@ -757,13 +793,16 @@ async def _transcode_review_audio(
from backend.services.audio_transcoding_service import AudioTranscodingService
try:
job = job_manager.get_job(job_id)
job = await asyncio.to_thread(job_manager.get_job, job_id)
if not job:
job_log.warning(f"Could not get job {job_id} for review audio transcoding")
return
# GCS download of up to 4 ~35MB FLACs + an ffmpeg transcode each (7-15s
# apiece) — this ran ON the event loop and froze the whole instance for
# 10-45s per job (2026-10-03 analysis). Run it in a worker thread.
transcoding = AudioTranscodingService()
transcoded = transcoding.prepare_review_audio_for_job(job)
transcoded = await asyncio.to_thread(transcoding.prepare_review_audio_for_job, job)
job_log.info(f"Review audio transcoding complete: {len(transcoded)} files")
@@ -771,7 +810,13 @@ async def _transcode_review_audio(
# /waveform-data endpoint is a pure GCS-cache read when the user opens
# review (a miss there decodes a whole stem — seconds of CPU on the
# API instance, which is what wedged it under concurrent load).
from backend.services.audio_analysis_service import AudioAnalysisService
# The first import pulls in numpy/pydub/matplotlib (seconds of CPU on a
# fresh instance) — import it in a worker thread, not on the loop.
def _import_audio_analysis():
from backend.services.audio_analysis_service import AudioAnalysisService
return AudioAnalysisService
AudioAnalysisService = await asyncio.to_thread(_import_audio_analysis)
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
waveform_source = stems.get("backing_vocals") or job.input_media_gcs_path
+12
View File
@@ -8,6 +8,7 @@ confirmation (awaiting_duration_confirm) and takes action:
Called by Cloud Scheduler via an internal endpoint (hourly).
"""
import asyncio
import logging
from datetime import datetime, timezone
from typing import Any, Dict
@@ -33,6 +34,17 @@ _DURATION_CONFIRM_STATUSES = {JobStatus.AWAITING_DURATION_CONFIRM}
async def process_stale_reviews() -> Dict[str, Any]:
"""Async entry point: run the (entirely synchronous) processor in a worker thread.
The body does up to ~1500 Firestore job reads, credit refunds and email
sends (Postmark API → SMTP fallback, up to ~15s each). It used to be an
``async def`` with no awaits, so the hourly cron froze every request on the
API instance for its whole duration (2026-10-03 analysis).
"""
return await asyncio.to_thread(process_stale_reviews_sync)
def process_stale_reviews_sync() -> Dict[str, Any]:
"""
Query for stale review / duration-confirm jobs and take action.
@@ -0,0 +1,54 @@
"""
Storage-retention pass as a Cloud Run Job (``storage-retention-job``).
The API endpoint ``POST /api/internal/storage-retention/run`` (Cloud Scheduler,
daily) starts this job instead of doing the work itself: the backend service
throttles CPU outside requests and requests through Cloudflare time out after
100s, while a full pass takes minutes. See backend/services/storage_retention.py.
Usage:
python -m backend.workers.storage_retention_worker --dry-run true \\
[--max-jobs N] [--include-orphans] [--report-path storage-retention/reports/x.json]
"""
import argparse
import logging
import sys
def _bool(value: str) -> bool:
return str(value).strip().lower() not in ("false", "0", "no")
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description="Storage-retention pass")
parser.add_argument("--dry-run", type=_bool, default=True)
parser.add_argument("--max-jobs", type=int, default=None)
parser.add_argument("--include-orphans", action="store_true")
parser.add_argument("--report-path", default=None)
parser.add_argument("--mode", choices=["job_purge", "orphans"], default="job_purge")
parser.add_argument("--max-folders", type=int, default=None)
args = parser.parse_args(argv)
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
from backend.services.storage_retention import StorageRetentionService
try:
if args.mode == "orphans":
report = StorageRetentionService().purge_orphans(
dry_run=args.dry_run, max_folders=args.max_folders, report_path=args.report_path,
)
else:
report = StorageRetentionService().run(
dry_run=args.dry_run, max_jobs=args.max_jobs,
include_orphans=args.include_orphans, report_path=args.report_path,
)
except Exception:
logging.getLogger(__name__).exception("STORAGE_RETENTION job crashed")
return 1
# Non-zero exit marks the Cloud Run execution failed (visible in the
# console/alerts) when the report couldn't be written or any job errored.
return 1 if (report.get("report_write_error") or report.get("errors")) else 0
if __name__ == "__main__":
sys.exit(main())
+27 -1
View File
@@ -8,6 +8,7 @@ This module uses the unified style_loader from karaoke_gen for
consistent style handling across local CLI and cloud backend.
"""
import json
import asyncio
import logging
import os
from pathlib import Path
@@ -30,11 +31,23 @@ from karaoke_gen.style_loader import (
get_end_format,
get_karaoke_format,
get_cdg_format,
screen_enabled,
)
logger = logging.getLogger(__name__)
# state_data key the screens worker writes: {"title": bool, "end": bool} — which
# screens the job's theme includes. Absent (jobs screened before themes could omit
# screens) means both were made.
SCREENS_INCLUDED_KEY = "screens_included"
def screen_included(state_data: Optional[Dict[str, Any]], screen: str) -> bool:
"""Whether the job's videos include its "title" or "end" screen."""
included = (state_data or {}).get(SCREENS_INCLUDED_KEY) or {}
return included.get(screen, True) is not False
# Re-export defaults for backwards compatibility with existing code
DEFAULT_INTRO_FORMAT = DEFAULT_INTRO_STYLE
@@ -101,7 +114,10 @@ class StyleConfig:
self._has_custom_styles = bool(style_params_gcs_path)
# Use the unified style loader
self._styles_path, self._style_params = load_styles_from_gcs(
# Sync GCS downloads (theme JSON, 4K backgrounds, fonts) — run off the
# event loop so they can't freeze the API instance (2026-10-03).
self._styles_path, self._style_params = await asyncio.to_thread(
load_styles_from_gcs,
style_params_gcs_path=style_params_gcs_path,
style_assets=style_assets,
temp_dir=self.temp_dir,
@@ -185,6 +201,16 @@ class StyleConfig:
"""Check if custom styles were provided (not using defaults)."""
return self._has_custom_styles
@property
def include_title_screen(self) -> bool:
"""Whether the theme puts a title screen at the start of the video."""
return screen_enabled(self._style_params, "intro")
@property
def include_end_screen(self) -> bool:
"""Whether the theme puts an end screen at the end of the video."""
return screen_enabled(self._style_params, "end")
@property
def intro_video_duration(self) -> int:
"""
+108 -37
View File
@@ -42,13 +42,15 @@ from backend.services.admin_rerender_service import (
admin_rerender_kept_outputs,
suppress_customer_notifications,
)
from backend.services.regenerate_service import active_regenerate
from backend.utils.existing_instrumental import resolve_existing_instrumental
from backend.services.job_health_service import validate_worker_can_run
from backend.services.rclone_service import get_rclone_service
from backend.services.youtube_service import get_youtube_service
from backend.services.youtube_description import translated_language_name
from backend.services.encoding_service import get_encoding_service, run_with_lost_job_resubmit
from backend.config import get_settings
from backend.workers.style_helper import load_style_config
from backend.workers.style_helper import load_style_config, screen_included
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
from backend.services.tracing import job_span, add_span_event, add_span_attribute
@@ -136,6 +138,9 @@ async def _encode_via_gce(
"base_name": base_name,
"instrumental_selection": instrumental_selection,
"existing_instrumental": existing_instrumental,
# Screens the theme leaves out (the encoder must not rebuild them from other PNGs).
"include_title_screen": screen_included(job.state_data, "title"),
"include_end_screen": screen_included(job.state_data, "end"),
# NOTE: intentionally no "ffmpeg_threads" — finalization ffmpeg commands in
# LocalEncodingService carry no -threads flag, so x264 uses its all-core auto
# default (measured ~66-78% of a 32-vCPU worker busy during the heavy libx264
@@ -269,6 +274,17 @@ async def generate_video_orchestrated(job_id: str) -> bool:
job_log.warning(status_error)
return False
# A user-supplied instrumental recorded under uploads/ expires after 7 days;
# fall back to (and repoint the job at) its staged copy under jobs/{id}/.
if getattr(job, 'existing_instrumental_gcs_path', None):
job.existing_instrumental_gcs_path = resolve_existing_instrumental(
job, storage, job_manager=job_manager, log=job_log,
)
# Storage-retention regenerate: GCS outputs only (snapshot taken at worker
# start — the marker is cleared with the COMPLETE transition below).
regenerate = active_regenerate(job)
# Create temporary working directory
temp_dir = tempfile.mkdtemp(prefix=f"karaoke_video_{job_id}_")
original_cwd = os.getcwd()
@@ -346,26 +362,30 @@ async def generate_video_orchestrated(job_id: str) -> bool:
if not result.success:
raise Exception(result.error_message or "Orchestrator failed")
# Prepare distribution directory for native uploads
with job_span("distribution", job_id):
await _handle_native_distribution(
job_id=job_id,
job=job,
job_log=job_log,
job_manager=job_manager,
temp_dir=temp_dir,
result={
'brand_code': result.brand_code,
'youtube_url': result.youtube_url,
'final_video': result.final_video,
'final_video_lossy': result.final_video_lossy,
'final_video_720p': result.final_video_720p,
'final_karaoke_cdg_zip': result.final_karaoke_cdg_zip,
'dropbox_link': result.dropbox_link,
'gdrive_files': result.gdrive_files,
},
storage=storage,
)
# Prepare distribution directory for native uploads. A GCS-only
# regenerate publishes nothing.
if regenerate:
job_log.info("GCS-only regenerate: skipping native distribution")
else:
with job_span("distribution", job_id):
await _handle_native_distribution(
job_id=job_id,
job=job,
job_log=job_log,
job_manager=job_manager,
temp_dir=temp_dir,
result={
'brand_code': result.brand_code,
'youtube_url': result.youtube_url,
'final_video': result.final_video,
'final_video_lossy': result.final_video_lossy,
'final_video_720p': result.final_video_720p,
'final_karaoke_cdg_zip': result.final_karaoke_cdg_zip,
'dropbox_link': result.dropbox_link,
'gdrive_files': result.gdrive_files,
},
storage=storage,
)
# Upload generated files to GCS
# Note: State transition to PACKAGING is handled by the orchestrator in _run_distribution()
@@ -394,12 +414,22 @@ async def generate_video_orchestrated(job_id: str) -> bool:
# An admin re-render leaves outputs it doesn't re-publish in place
# (e.g. YouTube now disabled) — keep their links.
kept_outputs = admin_rerender_kept_outputs(job)
state_updates: Dict[str, Any] = {
'state_data.brand_code': result.brand_code,
'state_data.youtube_url': result.youtube_url or kept_outputs.get('youtube_url'),
'state_data.youtube_upload_queued': result.youtube_upload_queued,
'state_data.dropbox_link': result.dropbox_link or kept_outputs.get('dropbox_link'),
'state_data.gdrive_files': result.gdrive_files or kept_outputs.get('gdrive_files'),
if regenerate:
# GCS-only regenerate: nothing was published, so the job's
# existing brand code / YouTube / Dropbox / Drive links stand.
state_updates: Dict[str, Any] = {}
else:
state_updates = {
'state_data.brand_code': result.brand_code,
'state_data.youtube_url': result.youtube_url or kept_outputs.get('youtube_url'),
'state_data.youtube_upload_queued': result.youtube_upload_queued,
'state_data.dropbox_link': result.dropbox_link or kept_outputs.get('dropbox_link'),
'state_data.gdrive_files': result.gdrive_files or kept_outputs.get('gdrive_files'),
}
state_updates.update({
# Fresh renders were just uploaded, so a storage-retention purge
# marker is stale (the stems marker is cleared by the restore).
'renders_purged_at': None,
# Clear the visibility-change guard flag (previously popped from the map).
'state_data.visibility_change_in_progress': DELETE_FIELD,
# Fresh finals were just uploaded, so any earlier "outputs deleted"
@@ -410,9 +440,12 @@ async def generate_video_orchestrated(job_id: str) -> bool:
# A theme/admin re-render (if any) finished; only a FAILED
# re-render keeps its marker (it lets the retry re-run it).
'state_data.theme_rerender': DELETE_FIELD,
# The admin re-render marker is cleared atomically WITH the
# COMPLETE transition below, so a failed transition keeps it.
}
# The admin re-render / regenerate markers are cleared atomically
# WITH the COMPLETE transition below, so a failed transition keeps them.
})
if regenerate and regenerate.get('after') == 'change_to_private':
# The chained visibility change sets its own guard right away.
state_updates.pop('state_data.visibility_change_in_progress', None)
if result.distribution_warnings:
state_updates['state_data.distribution_warnings'] = result.distribution_warnings
job_manager.update_job(job_id, state_updates)
@@ -451,20 +484,34 @@ async def generate_video_orchestrated(job_id: str) -> bool:
if is_admin_rerender:
completion_metadata["admin_rerender"] = True
completion_metadata["customer_notified"] = notify_customer
if regenerate:
completion_metadata["regenerate"] = True
completion_metadata["customer_notified"] = notify_customer
completion_metadata["regenerate_source"] = regenerate.get("source")
if not notify_customer:
job_log.info("Admin re-render: completion email/push suppressed (notify_customer=False)")
job_log.info("Re-render/regenerate: completion email/push suppressed (notify_customer=False)")
extra_updates = {'state_data.admin_rerender': DELETE_FIELD}
if regenerate:
from datetime import datetime as _dt, timezone as _tz
extra_updates['state_data.regenerate'] = DELETE_FIELD
extra_updates['renders_regenerated_at'] = _dt.now(_tz.utc)
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.COMPLETE,
progress=100,
message="Karaoke generation complete!",
message="Karaoke generation complete!" if not regenerate else "Video regenerated",
timeline_metadata=completion_metadata,
notify=notify_customer,
extra_updates={'state_data.admin_rerender': DELETE_FIELD},
# An admin re-render isn't a newly completed job for the user.
count_completion=not is_admin_rerender,
extra_updates=extra_updates,
# An admin re-render / regenerate isn't a newly completed job for the user.
count_completion=not (is_admin_rerender or regenerate),
)
# A regenerate started by a public->private visibility change (the
# redistribution needs the full finals set): run that change now.
if regenerate and regenerate.get('after') == 'change_to_private':
await _run_chained_change_to_private(job_id, job_manager, regenerate, job_log)
# If this was a requests-board community pick published directly here
# (i.e. not deferred to the youtube_upload_queue), advance its request
# to `published` and fan out "your track is live" voter emails. The
@@ -532,6 +579,25 @@ async def generate_video_orchestrated(job_id: str) -> bool:
logger.debug(f"Cleaned up temp directory: {temp_dir}")
async def _run_chained_change_to_private(job_id: str, job_manager: JobManager, regenerate: Dict[str, Any], job_log) -> None:
"""Finish a public->private visibility change that waited for a regenerate."""
from backend.services.visibility_change_service import VisibilityChangeService
requested_by = regenerate.get('requested_by') or 'unknown'
try:
fresh = job_manager.get_job(job_id)
await VisibilityChangeService(job_manager).change_to_private(
job_id, fresh, requested_by, regenerate_if_missing=False,
)
job_log.info("Regenerated finals redistributed: visibility changed to private")
except Exception as e: # noqa: BLE001 - the regenerate itself succeeded
job_log.error(f"Visibility change to private after regenerate failed: {e}")
logger.exception(f"[job:{job_id}] Chained change_to_private failed")
try:
job_manager.update_job(job_id, {'state_data.visibility_change_in_progress': DELETE_FIELD})
except Exception: # noqa: BLE001
pass
async def redistribute_video(job_id: str) -> bool:
"""
Redistribute existing finals for a completed job (no re-encoding).
@@ -1234,9 +1300,13 @@ async def _handle_native_distribution(
job_log.info(f"Uploading to Dropbox folder: {remote_folder}")
from backend.services.dropbox_service import dropbox_skip_suffixes_for
# The orchestrator already uploaded this folder minus stems/ and
# lyrics/ (prepared just above) — only send what's new or changed
# instead of re-uploading every file a second time.
dropbox.upload_folder(
temp_dir, remote_folder,
exclude_suffixes=dropbox_skip_suffixes_for(dropbox_path),
skip_unchanged=True,
)
# Create sharing link
@@ -1438,8 +1508,9 @@ def _validate_prerequisites(job) -> bool:
# Check screens exist (MOV or PNG — MOV is no longer uploaded, PNG is the new default)
screens = job.file_urls.get('screens', {})
has_title = screens.get('title') or screens.get('title_png')
has_end = screens.get('end') or screens.get('end_png')
# A screen the theme omits (state_data.screens_included) isn't needed.
has_title = screens.get('title') or screens.get('title_png') or not screen_included(job.state_data, 'title')
has_end = screens.get('end') or screens.get('end_png') or not screen_included(job.state_data, 'end')
if not has_title or not has_end:
logger.error(f"Job {job.job_id}: Missing title or end screen")
return False
+75 -22
View File
@@ -32,6 +32,7 @@ from backend.services.tracing import job_span, add_span_event
from backend.workers.supersede import capture_generation, encoding_worker_job_id
from backend.services.theme_rerender_service import rerender_brand_code
from backend.services.admin_rerender_service import suppress_customer_notifications
from backend.services.regenerate_service import is_gcs_only_run
from backend.services.original_audio import (
original_audio_gcs_path,
original_audio_output_filename,
@@ -48,14 +49,18 @@ class OrchestratorConfig:
artist: str
title: str
# Input file paths (in temp_dir)
title_video_path: str
# Input file paths (in temp_dir). None = the theme leaves that screen out.
title_video_path: Optional[str]
karaoke_video_path: str
instrumental_audio_path: str
end_video_path: Optional[str] = None
lrc_file_path: Optional[str] = None
title_jpg_path: Optional[str] = None
# Whether the theme includes the title / end screen (state_data.screens_included)
include_title_screen: bool = True
include_end_screen: bool = True
# Output directory
output_dir: str = ""
@@ -133,6 +138,12 @@ class OrchestratorConfig:
# transitions that would otherwise abort the redistribution.
redistribute_mode: bool = False
# GCS-only regenerate (storage retention, backend/services/regenerate_service.py):
# rebuild the finals/packages in GCS but skip brand-code allocation, every
# distribution upload (YouTube/Dropbox/GDrive), the Discord post and the
# GDrive validation — the published outputs are left exactly as they are.
gcs_only: bool = False
@dataclass
class OrchestratorResult:
@@ -333,19 +344,27 @@ class VideoWorkerOrchestrator:
# Stage 2: Encoding
await self._run_encoding()
# Stage 3: Organization (brand code)
await self._run_organization()
if self.config.gcs_only:
# Regenerate: GCS outputs only. Keep the existing brand code
# (never allocate one) and publish nowhere.
self.result.brand_code = self.config.keep_brand_code
self.job_log.info(
"GCS-only regenerate: skipping organization, distribution and notifications"
)
else:
# Stage 3: Organization (brand code)
await self._run_organization()
# Stage 4: Distribution (YouTube, Dropbox, GDrive)
await self._run_distribution()
# Stage 4: Distribution (YouTube, Dropbox, GDrive)
await self._run_distribution()
# Stage 5: Notifications (Discord)
await self._run_notifications()
# Stage 5: Notifications (Discord)
await self._run_notifications()
# Stage 6: Post-distribution GDrive validation
# Only for jobs that uploaded to the public share (non-private)
if self.config.gdrive_folder_id:
await self._trigger_gdrive_validation()
# Stage 6: Post-distribution GDrive validation
# Only for jobs that uploaded to the public share (non-private)
if self.config.gdrive_folder_id:
await self._trigger_gdrive_validation()
self.result.success = True
self.result.total_time_seconds = time.time() - start_time
@@ -506,6 +525,8 @@ class VideoWorkerOrchestrator:
"output_gcs_path": output_gcs_path,
"countdown_padding_seconds": self.config.countdown_padding_seconds,
"existing_instrumental": self.config.existing_instrumental_gcs_path,
"include_title_screen": self.config.include_title_screen,
"include_end_screen": self.config.include_end_screen,
},
)
@@ -533,8 +554,16 @@ class VideoWorkerOrchestrator:
if src:
ext = os.path.splitext(src)[1].lower() or ".mp3"
dest = f"jobs/{self.config.job_id}/custom_instrumental{ext}"
self.storage.copy_blob(src, dest)
self.job_log.info(f"Staged custom instrumental for GCE encoder: {dest}")
if src != dest:
self.storage.copy_blob(src, dest)
self.job_log.info(f"Staged custom instrumental for GCE encoder: {dest}")
# uploads/ expires after 7 days: point the job at the
# kept job-root copy for future re-renders/regenerates.
if src.startswith("uploads/") and self.job_manager:
self.job_manager.update_job(
self.config.job_id, {"existing_instrumental_gcs_path": dest}
)
self.config.existing_instrumental_gcs_path = dest
except Exception as e:
self.job_log.warning(f"Failed to stage custom instrumental for GCE encoder: {e}")
@@ -869,12 +898,19 @@ class VideoWorkerOrchestrator:
self._queue_youtube_upload(user_email, reason="quota_exceeded_api")
return
self.job_log.error(f"YouTube upload failed: {e}")
self.result.distribution_warnings.append(f"YouTube upload failed: {e}")
# Transient failures (e.g. a dropped resumable session that outlived the
# in-process restarts) must not lose the upload: hand it to the deferred
# queue, which retries from the GCS finals (bounded by max_attempts).
self.job_log.error(f"YouTube upload failed, queueing for retry: {e}")
self._queue_youtube_upload(user_email, reason="upload_error", error=error_str)
if self.result.youtube_upload_queued:
self.result.distribution_warnings.append(
f"YouTube upload failed, queued for automatic retry: {e}"
)
# Don't fail the pipeline - YouTube is optional
def _queue_youtube_upload(self, user_email: str, reason: str = "quota_exceeded"):
"""Queue a YouTube upload for later processing when quota is insufficient."""
def _queue_youtube_upload(self, user_email: str, reason: str = "quota_exceeded", error: Optional[str] = None):
"""Queue a YouTube upload for later processing (insufficient quota or a failed upload)."""
try:
from backend.services.youtube_upload_queue_service import get_youtube_upload_queue_service
queue_service = get_youtube_upload_queue_service()
@@ -891,8 +927,9 @@ class VideoWorkerOrchestrator:
self.job_log.info(f"YouTube upload queued for later processing (reason: {reason})")
except Exception as e:
self.job_log.error(f"Failed to queue YouTube upload: {e}")
cause = f"upload failed: {error}" if error else "quota exceeded"
self.result.distribution_warnings.append(
f"YouTube upload skipped (quota exceeded) and failed to queue: {e}"
f"YouTube upload skipped ({cause}) and failed to queue: {e}"
)
def _stage_original_audio_for_upload(self):
@@ -1065,7 +1102,10 @@ class VideoWorkerOrchestrator:
async def _resolve_intro_seconds(self) -> float:
"""The master's silent title-card length = the job's style intro ``video_duration``
(default 5s). Read the *actual* value — long-intro styles exist. Falls back to 5s
(``get_intro_format`` raises when no theme is loaded — that's the fallback path)."""
(``get_intro_format`` raises when no theme is loaded — that's the fallback path).
0 when the theme leaves the title card out (the master starts with the song)."""
if not self.config.include_title_screen:
return 0.0
try:
from backend.workers.style_helper import load_style_config
import tempfile
@@ -1223,6 +1263,12 @@ def create_orchestrator_config_from_job(
duet_corrections_json_path = candidate
break
# Screens the theme leaves out (recorded by the screens worker).
from backend.workers.style_helper import screen_included
include_title = screen_included(job.state_data, "title")
include_end = screen_included(job.state_data, "end")
return OrchestratorConfig(
worker_generation=capture_generation(job),
job_id=job.job_id,
@@ -1230,11 +1276,15 @@ def create_orchestrator_config_from_job(
title=job.title,
# Input files — use actual extension from GCS (PNG for new jobs, MOV for legacy)
title_video_path=os.path.join(temp_dir, f"{base_name} (Title){_screen_ext(job, 'title')}"),
title_video_path=(
os.path.join(temp_dir, f"{base_name} (Title){_screen_ext(job, 'title')}") if include_title else None
),
# Use actual extension from GCS path (typically .mkv) instead of hardcoding .mov
karaoke_video_path=os.path.join(temp_dir, f"{base_name} (With Vocals){os.path.splitext(job.file_urls.get('videos', {}).get('with_vocals', '.mkv'))[1] or '.mkv'}"),
instrumental_audio_path=instrumental_path,
end_video_path=os.path.join(temp_dir, f"{base_name} (End){_screen_ext(job, 'end')}"),
end_video_path=os.path.join(temp_dir, f"{base_name} (End){_screen_ext(job, 'end')}") if include_end else None,
include_title_screen=include_title,
include_end_screen=include_end,
lrc_file_path=os.path.join(temp_dir, f"{base_name} (Karaoke).lrc"),
title_jpg_path=os.path.join(temp_dir, f"{base_name} (Title).jpg"),
@@ -1280,6 +1330,9 @@ def create_orchestrator_config_from_job(
is_duet=is_duet,
duet_corrections_json_path=duet_corrections_json_path,
# GCS-only regenerate (storage retention): no distribution at all
gcs_only=is_gcs_only_run(job),
# Encoding backend - auto selects GCE if available
encoding_backend="auto",
Loaded 100 of 194 files, more files were not shown because too many files have changed in this diff. Show more