Compare commits

..
27 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 5.5 055a5d3f73 feat(youtube): enable comment auto-reply in prod + one-time backfill (v0.280.2) (#1207)
## Summary

Switches on the YouTube comment auto-reply bot from #1205 in prod
(Andrew authorised go-live after the 6-month replay sign-off):

- `YOUTUBE_COMMENT_AUTOREPLY_ENABLED=true`
- `YOUTUBE_COMMENT_AUTOREPLY_START=2026-04-22T00:00:00Z`. This is used
on the first run only, as a one-time backfill (Andrew: "yes please, will
be a good test of the system working once in prod"). The replay predicts
3 replies: Fightmaster "Nobody's Baby", Bear Ghost "Tiny Hitman", Playa
Fly "N God We Trust". Threads already answered by hand are skipped.

Already verified in prod before this PR:
- The endpoint returns `disabled` while the flag is off.
- A `?dry_run=true` run loads secret `youtube-comment-bot-credentials`,
builds the channel index and reads comments with no errors.
- The Cloud Scheduler job `youtube-comment-autoreply-hourly` and the
secret were applied through Pulumi in #1205.

## Testing

Config-only change; the code and tests are in #1205.


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

https://claude.ai/code/session_016E3ibN2EcKxnGQvEf6T4V8

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 02:41:15 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 53bed95e76 feat(local-stack): kjbox partner secret + fake quick version (v0.280.1) (#1206)
## Summary
Local-stack only (no prod impact). For mobile Phase 5 "Tonight": the
kjbox local stack points at gen's local stack for make-it.
- `scripts/local-stack.sh`: `KJBOX_PARTNER_SECRET` and
`DECIDE_GEN_PARTNER_SECRET` default to `local-stack-secret`, external
values win.
- Fake workers emit a quick version (`state_data.quick_version` ready +
`file_urls.quick.video_mp4`) for kjbox-sourced jobs, using prod's
`should_build_quick_version` gate and quick-version helpers.
`FAKE_WORKERS` is still refused in production.
- docs/TESTING.md § Local stack updated.

## Testing
`test_kjbox_partner_api.py`, `test_fake_workers.py`,
`test_kjbox_resolve_partner.py`, `test_fake_match_judge.py`: all pass.
Reviewed by a task reviewer (1 fix round).

@coderabbitai ignore

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

https://claude.ai/code/session_013Bkasn6trBadg1Zb39vSVR

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 02:06:01 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 6c53f0471a feat(youtube): auto-reply to song requests in YouTube comments with requests-board links (v0.280.0) (#1205)
## Summary

Backlog Frog #6 (YouTube channel → gen funnel). Andrew's spec: *"we
could probably also solve that by building some automation to detect
youtube comments asking for songs and auto-reply with a link to the
requests board"*.

An hourly bot reads new top-level comments on the Nomad Karaoke channel
and, when someone asks for a song:
- **Song already on the channel:** replies with that video's link.
- **Otherwise:** adds the song to the requests board (or finds the
existing request) and replies with a link straight to it, e.g. `Added
"Tiny Hitman" by Bear Ghost to our requests board 🥳 upvote it here and
we'll email you when it's made: <link>`.
- **Vague asks** ("more Johnnie please") get a generic board link.
- **Non-English comments** get a translated reply, which falls back to
English if a URL doesn't survive translation.

The reply promotes only the board, not gen (Andrew's call). The goal is
turning anonymous YouTubers into board users with an email address.

**Andrew signed this off on a 6-month local replay**
(`scripts/youtube-comments/replay.py`, read-only):
- 265 threads, 33 song requests.
- It flagged all 29 requests Andrew had answered by hand, and all 7
vague asks.
- It posted no replies to non-requests.
- His calls on borderline cases became prompt rules: yes to Playa Fly,
no to "Joe Cuervo Karaoke 🎤" on an unrelated video.

## Changes

- **Decision core:** `backend/services/youtube_comment_bot.py`, a pure
module with injectable ports (Gemini classifier/translator, board,
channel index), shared by the replay and the worker.
- **Worker:** `backend/workers/youtube_comment_bot_worker.py`, called
through `POST /api/internal/youtube-comments/run` (`?dry_run=true`).
- Creates a create-only action doc per comment **before** posting, so
nothing gets a double reply.
- Keeps a high-water mark with a 6h overlap. A Gemini error causes a
retry, not a permanent skip.
  - Per-run cap and quota coordination.
  - Posts to #noise per reply; failures go to #alerts, throttled.
- **Kill switch:** `YOUTUBE_COMMENT_AUTOREPLY_ENABLED` defaults to
**false**, and this PR leaves it off. A follow-up PR switches it on
after a prod dry run. `YOUTUBE_COMMENT_AUTOREPLY_START` enables a
one-time backfill of unanswered requests.
- **Requests board:**
- New `source="youtube_comment"`; bot-added requests are owned by the
placeholder `youtube-comment@nomadkaraoke.com` with no votes.
- The **first real up-voter claims the request**, inside the vote
transaction. The daily picker skips unclaimed requests, so a free credit
never goes to the placeholder.
- Frontend `?request=<id>` deep link: highlight, scroll, banner (33
locales).
- Signing in from the link uses purpose `requests_board:<id>`, so the
magic link returns to the request with `&upvote=1` and the upvote is
cast once.
- **OAuth:** the bot uses its **own** Desktop OAuth client and secret
`youtube-comment-bot-credentials` (`youtube` + `youtube.force-ssl`),
because Google refuses `force-ssl` in the device flow. The upload token
is untouched.
- **Infra (Pulumi, already applied locally):** secret container + Cloud
Scheduler `youtube-comment-autoreply-hourly`.
- **Description template:** a make-your-own line moves above YouTube's
"...more" fold (`utm_campaign=make_cta_top`). The daily backfill
re-drains the channel over about 11 days.
- **Docs:** `docs/REQUESTS-BOARD.md` § YouTube comment auto-reply,
API.md, README.md, plus the plan in
`docs/archive/2026-10-22-youtube-comment-autoreply-plan.md`.

## Testing

- `backend/tests/test_youtube_comment_bot.py` (33): skips, routing,
vague asks, translation fallback, malformed classifier output, API
helpers.
- `backend/tests/test_youtube_comment_bot_worker.py` (12): kill switch,
dry run, idempotency (second run and concurrent claim), go-live start,
cap, quota, missing scope, post failure, classifier-error retry.
- `backend/tests/emulator/test_song_request_service.py`: bot add/dedupe,
claim on first upvote, downvote doesn't claim, picker skips unclaimed,
human resubmit claims, `find_published_by_key`.
- `backend/tests/test_admin_login_link.py`: `requests_board:<id>`
redirect and purpose helper.
- `frontend/e2e/regression/requests-board-deep-link.spec.ts` (3):
highlight + sign-in purpose, upvote-once on return + param dropped, no
toggle-off when already upvoted.
- Full `make test`: backend 6584 passed; the only failures are the
local-environment `test_emulator_integration` cases, which fail
identically on `origin/main` (port 8080 is held by another session's
emulator). Frontend Jest: 1760 passed.
- Behavioural acceptance: the 6-month replay above.

@coderabbitai ignore

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

https://claude.ai/code/session_016E3ibN2EcKxnGQvEf6T4V8

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 01:51:15 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 714ac74324 fix(resolve): keep Gemini SDK deadline >= 10 s (v0.279.7) — hotfix for #1203 (#1204)
## Problem
#1203 (v0.279.6) set the Gemini SDK timeout for free-text resolve to 7
s. The Gemini API rejects that:

```
resolve_free_text attempt 1/2 failed: 400 INVALID_ARGUMENT. 'Manually set deadline 7s is too short. Minimum allowed deadline is 10s.'
```

So since the 21:16 UTC deploy, every uncached "Describe the song" /
kjbox resolve answers kind `none` (seen on prod for 6 new descriptions
at 21:20).

## Fix
- The SDK timeout goes back to `match_judge_timeout_ms` (12 s), with a
floor of 10 s (`GEMINI_MIN_DEADLINE_MS`).
- The per-attempt cap (now 8 s) is client-side only
(`asyncio.wait_for`). Worst case is still about 20 s, and decide waits
25 s.
- 4xx errors other than 429 are no longer retried.
- Tests: the SDK deadline respects the API minimum, and a client error
is not retried.

Urgent hotfix: no local CodeRabbit run, so this PR is left open for the
bot review.

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

https://claude.ai/code/session_01G81fc5sBB8GwG5Xhz2UMgc

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

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

## Summary by CodeRabbit

- **Bug Fixes**
- Improved AI-powered match judgments by handling timeouts and temporary
service failures more reliably.
- Prevented unnecessary retries for invalid requests, allowing
unavailable results to be returned faster.
- Improved timeout handling to reduce premature failures during AI
evaluations.

- **Chores**
  - Updated the application version to 0.279.7.

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 17:36:33 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 2172306a21 fix(resolve): bound free-text resolve so a first-time description answers in time (v0.279.6) (#1203)
## Problem
Prod 2026-10-20: mobile "Describe the song" returned "we couldn't work
out…" on the first ask of every new description; repeating worked.

Evidence (Cloud Logging, `karaoke-backend`):
- `/api/kjbox/catalog/resolve` from decide: 12.1 s, 12.7 s, 17.2 s, 10.6
s.
- 20:28:41 "The song from Titanic": Gemini call at :41.6, then `Failed
to search tracks from karaoke-decide` at :53.7 — the catalog tidy waited
10 s on decide's `/api/catalog/tracks`, which took 37.6 s (cold start;
it routinely takes 35-44 s cold).
- 20:32:44: `resolve_free_text failed: 504 DEADLINE_EXCEEDED` after 10.5
s (one stalled Gemini call; a fresh call answered in ~2 s).
- decide's 12 s upstream timeout fired first → `{}`; gen finished and
cached → second ask worked.

## Fix (`match_judge/free_text.py`)
- Gemini: 7 s per attempt (SDK + `asyncio.wait_for`), one retry on
transient failures; quota/billing errors are not retried. Same
provider/model/config as before.
- Catalog tidy: 4 s cap. On timeout, answer with the AI verdict
(`reason: unavailable`, so not cached) and let the shielded catalog
search finish in the background, warming decide and the catalog proxy's
cache.
- Worst case ~18-20 s; decide now waits 25 s (karaoke-decide#163).

Tests: retry on a stalled call, retry-then-give-up, no retry on quota,
slow catalog tidy answers with the AI verdict while the search finishes
in the background.

CodeRabbit (local): 2 findings. Fixed the minor one (hold the task from
creation). Skipped the suggestion to coalesce concurrent catalog
searches: the route already rate-limits per partner and the catalog
proxy caches results, so it isn't worth the extra complexity here.

@coderabbitai ignore

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

https://claude.ai/code/session_01G81fc5sBB8GwG5Xhz2UMgc

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 17:01:20 -04:00
Andrew Beveridge ☄️andClaude Sonnet 5.5 83e097fa3b feat(local-stack): fake review fixtures and knobs for mobile native review (v0.279.5) (#1202)
## Summary
Local-stack (FAKE_WORKERS=1) support for nomad-mobile Phase 2, which is
the native lyrics and instrumental review. Maestro can now drive every
review state against the real review endpoints. Nothing changes in prod:
all hooks are gated on `fake_workers_enabled()`.

## Changes
- **New per-user `FakeConfig` knobs:**
- `review_fixture` (`default` / `corrections` / `duet` / `rtl` /
`large`). The fixtures are built from the real `CorrectionResult` types:
AI spans with `undo_info`, an untimed word, an evidenced vocal gap with
synced reference lines, duet singers, Hebrew/Arabic lines, and 300
lines.
  - `backing_vocals` (`silent` / `audible`)
  - `stems_delay_seconds` (stems land after review opens)
- `review_mode` and `auto_approval` (writes
`processing_metadata.auto_approval`, so the confident and skipped-step
states can be reached)
  - `review_complete_fail_once`
- **Fake media gets an amplitude envelope**, so waveforms aren't flat.
There is also an audible backing stem variant.
- **`/api/review/{id}/audio` dev-proxy branch** now uses
`_ranged_response` (Range → 206), so seeking works on iOS. The prod
signed-URL path is untouched.
- **`GET /api/test/jobs/{id}/review-result`** returns the submitted
review (selection, `is_duet`, corrected lines) for Maestro assertions.
- `docs/TESTING.md` § Local stack documents the knobs.

## Testing
- `make test`: backend 2184 + 6532 + 163 passed, frontend 1760 passed.
- 29 new tests in `backend/tests/fake_workers/test_review_fixtures.py`.
- Smoke-tested on the local stack: every fixture loads; `with_backing`
analysis; Range 206; 503 then 200 on complete; `review-result`;
`auto_approval` states; late stems.

Reviewed locally (CodeRabbit CLI, 1 finding fixed).

@coderabbitai ignore

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

https://claude.ai/code/session_01G81fc5sBB8GwG5Xhz2UMgc

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 00:20:38 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 e050cb8b3d fix: rescue repetitive-song reference lyrics the relevance filter undercounts (v0.279.4) (#1201)
@coderabbitai ignore

## Why
Andrew: job 5c1d24eb loaded no reference lyrics. LRCLIB and Genius both
returned the correct song, but the relevance filter scored them 26% and
25%, below its 30% threshold. Anchor coverage credits a repeated phrase
only once, so chorus-heavy songs undercount. The transcription was
decent, with a few consistent mishearings.

## What
`filter_irrelevant_sources(..., transcribed_text=)` now does a second,
**additive** check. A source the anchor filter rejects is kept when its
word-trigram overlap with the transcription clears four guards:
- **≥ 25%** of reference trigrams matched, repeats counted;
- **≥ 20** reference trigrams, so tiny references can't score by chance;
- **≥ 10** matches;
- **≥ 15 distinct** matched trigrams, so a shared refrain alone can't
pass.

Trigrams must contain three distinct words, so "na na na" and "oh oh oh"
don't count. Tokens are NFC-normalized and keep combining marks.

Both call sites pass the transcription: the corrector, which also serves
the review UI's lyrics search and add-source flow, and the controller's
uncorrected path. Without `transcribed_text`, behaviour is unchanged.
The rescue **never rejects** a source the anchor filter keeps. The
serialized `rejected_sources` metadata is unchanged.

## Calibration (459 recent production jobs; per-job reference txt vs
`(Lyrics Uncorrected).txt`)
- **Wrong-song baseline:** 491k cross-job pairs, excluding pairs with
the same title.
  - Worst genuine pair: 9.4%; p99.99: 5.5%.
- The only cross-job pairs that pass are one job whose audio is another
job's song under a wrong title. Their transcriptions overlap 45%, where
unrelated songs score under 10%.
- A naive n-gram rule would have admitted a wrong song at 41% through
shared "na na" filler. Requiring three distinct words removes it.
- **Rescued:** 22 sources that are currently rejected, **all the correct
song**, scoring 26–88%. Examples: the 5c1d24eb song, Deacon Blue, UB40,
Atomic Kitten, Sezen Aksu, Grateful Dead, Etherwood, Sub Focus, Terry
Allen.
- **Left rejected by the distinct-trigram guard:** one refrain-only drum
& bass track (8 distinct matches; it's the right song but has the risk
profile). This was a deliberate, cautious choice.
- No lyrics text is committed; the tests use invented lyrics.

## Testing
- `tests/correction/test_relevance.py`, 17 passed (8 new):
  - a repetitive correct song is rescued;
  - no transcription means unchanged behaviour;
  - a wrong song is still rejected;
  - filler doesn't count;
  - a tiny reference isn't rescued;
  - a source the anchor filter keeps is never rejected;
  - a shared refrain alone can't rescue;
  - combining marks are kept.
- `tests/unit`: 2184 passed. Running `tests/unit`, `tests/correction`
and the backend review tests together gives the same 12 order-dependent
failures on untouched main; they pass separately, as CI runs them.
- Local CodeRabbit: 2 cycles. Fixed the combining-marks and
distinct-trigram findings.

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

https://claude.ai/code/session_01Jw21syo4HizJJjYw2mg2Vp

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 00:08:38 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 b67b273056 feat(kjbox): decide partner secret for catalog resolve + fake judge + error monitor for decide search (v0.278.10) (#1190)
## ⚠️ Merge prerequisite (do BEFORE merging)

The Secret Manager secret `decide-gen-partner-secret` must have a
version before this merges, otherwise the CI deploy's `--set-secrets
...DECIDE_GEN_PARTNER_SECRET=decide-gen-partner-secret:latest` fails.

```
gcloud auth login admin@nomadkaraoke.com
cd ~/Projects/nomadkaraoke/karaoke-gen-decide-partner-resolve/infrastructure
GOOGLE_OAUTH_ACCESS_TOKEN=$(gcloud auth print-access-token) pulumi up     # review: should only add the decide-gen-partner-secret Secret
openssl rand -hex 32 | tr -d '\n' | gcloud secrets versions add decide-gen-partner-secret --project=nomadkaraoke --data-file=-
```

No extra IAM grant needed: gen's API runs as `karaoke-backend@`, which
already has project-level `secretmanager.secretAccessor`.

## Summary
- `POST /api/kjbox/catalog/resolve` now also accepts karaoke-decide via
header `X-Partner-Secret` (new setting `decide_partner_secret` / env
`DECIDE_GEN_PARTNER_SECRET`). Other kjbox endpoints stay
`X-Kjbox-Secret` only. decide gets its own AI-call budget (60/min) so
kjbox nights are never starved; the verdict cache is shared.
- Fake match judge / resolve for the local E2E stack (`FAKE_WORKERS`):
`judge_kind` / `judge_canonical_*` knobs; no Gemini or catalog calls.
- Error monitor now watches decide's new `karaoke-decide-search` service
and `song-index-build` job.
- Pulumi: declares the `decide-gen-partner-secret` Secret (value added
manually); CI deploy mounts it.
- Version 0.278.10.

## Testing
- [x] Changed-module + kjbox/catalog/error-monitor/fake-worker backend
tests pass (133 passed). Full `backend/tests` suite exceeds 10 min
locally, so left to CI.

## Review
- CodeRabbit CLI failed twice (WebSocket closed / connection error), so
no local CodeRabbit review completed; I did a manual diff review instead
(no issues found). Deliberately NO `@coderabbitai ignore`, so the GitHub
bot reviews this PR.

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

https://claude.ai/code/session_01VsLw9cTTMBab1tiRxCsYrm

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 21:42:27 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 4286d98dbe fix: LRCLIB as a registered server-side app; honour Retry-After, retry 5xx (v0.279.2) (#1200)
@coderabbitai ignore

## Why
LRCLIB now applies stricter rate limits to unregistered clients
(https://lrclib.net/docs#implementation-requirements-rate-limiting), and
Cloud Run shares egress IPs. On 10-19, prod jobs got intermittent 503s,
and job 80e7ffdf lost its LRCLIB lyrics. LRCLIB is our only free source;
it supplied lyrics for 165 of 220 jobs in 30 days. Andrew registered a
server-side app.

## What
- **`karaoke_gen/lyrics_transcriber/lyrics/lrclib_client.py`** (new):
- Sends `Lrclib-App-Id` + `Lrclib-Api-Key` from `LRCLIB_APP_ID` /
`LRCLIB_SECRET_KEY`.
- Applies LRCLIB's rules: every 429 sets a **process-wide cooldown** of
`Retry-After` plus up to 30% jitter. The wait is never shortened, and
overlapping 429s keep the latest expiry. Nothing is sent until the
cooldown has passed. It waits and retries once only when the wait is
≤30s.
  - Retries 5xx after 1s/2s, honouring a 5xx `Retry-After`.
- A **401 on our credentials** logs a WARNING and drops to anonymous
access for the process, so a revoked key degrades instead of losing
LRCLIB.
- `LRCLIBProvider` (both `get` and `search`) uses it. The
`quick_version` renderer uses it with `retry=False`, so the fast path
gets the auth and the cooldown but never blocks.
- **Infra:**
  - Pulumi secrets `lrclib-app-id` / `lrclib-api-key`.
  - Env vars on the `lyrics-transcription-job`.
- The backend service deploy's `--set-secrets` (`ci.yml`). The
karaoke-backend SA already has project-wide `secretAccessor`.

## Deploy order (do NOT merge before steps 1–2)
1. `pulumi up` to create the two secrets and the job env. Needs
`/gcp-admin`.
2. Add the secret versions from Andrew's `.envrc` values.
3. Merge. The CI backend deploy references the secrets.

## Testing
- New `tests/unit/test_lrclib_client.py` (14 tests): headers; anonymous
use; Retry-After with jitter; a long Retry-After is not shortened and
blocks further calls; no-retry mode; a second 429; 5xx backoff; 5xx
Retry-After; 401 fallback; overlap merge (mutation-checked); provider
routes through the client.
- 164 passed across the client, `quick_version` and `search_lyrics`
tests.
- **Live** with the real app key: Dar Williams - Iowa and Wolfmother -
Where Eagles Have Been were found. One 503 was recovered by the retry.
- Local CodeRabbit, 3 cycles. I fixed the Retry-After cap, the cooldown
after a final 429, the `quick_version` 401 path, the overlap merge and
5xx Retry-After. I skipped one false positive about the tests' fake
clock (the retry path sleeps, then sends without re-checking the clock).

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

https://claude.ai/code/session_01Jw21syo4HizJJjYw2mg2Vp

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 17:33:19 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 653801cd04 fix: Musixmatch provider uses the RapidAPI v2 /lyrics?artist=&title= endpoint (v0.279.1) (#1199)
@coderabbitai ignore

## Why
BACKLOG "Musixmatch lyrics provider dead for 30+ days (0/287 requests
succeed)". We're still paying for the RapidAPI listing
(`cavsn/musixmatch-song-lyrics-api`, Pro $14.99/mo, active), but the old
`GET /lyrics/{artist}/{title}/` path now 404s for every song. I checked
the listing's playground (via Andrew's RapidAPI login). The API moved to
`GET /lyrics?artist=&title=` (optional `trackId`, `translate`) and
returns a flat `data` object.

## What
- `MusixmatchProvider._fetch_data_from_source` calls the new endpoint
with query params. A miss comes back as **HTTP 200 with `data.error`**,
or with empty `lyrics`. Both are now treated as not-found and logged at
INFO, so they don't alert.
- `_convert_result_format` reads `trackName` / `artistName` / `trackId`
/ `lyrics`. Raw cache entries in the old `macro_calls` shape still
convert.

## Testing
- New `tests/unit/test_musixmatch_provider.py` uses real response shapes
captured today: endpoint and params, the 200 miss logged with no ERROR,
empty lyrics, no key, v2 conversion, legacy conversion.
- 47 passed across the provider, base provider and `search_lyrics`
tests.
- **Live check** with the production key: Queen - Bohemian Rhapsody 47
lines, Adele - Hello 48 lines. The upstream misses some songs (piri -
dog; Taylor Swift - Shake It Off), so coverage is partial but no longer
zero.
- Local CodeRabbit: 0 findings.

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

https://claude.ai/code/session_01Jw21syo4HizJJjYw2mg2Vp

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 16:34:13 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 867617626a feat: requests board picks the visitor's language + header language switcher (#1198)
## Summary
Follow-up to #1193. `requests.nomadkaraoke.com` always served the
English board (the old redirect was also hard-coded to `/en/requests`).

- **Worker (`requests-host`, already deployed):** `/` serves
`/{locale}/requests/`. The locale comes from the `nk_requests_locale`
cookie, else `Accept-Language` (primary-subtag match like gen's
`LocaleRedirect`, so `pt-BR` → `pt` and `nn` → `nb`), else `en`.
`/{locale}/` (e.g. `/es/`) forces a language. Responses send `Vary:
Accept-Language, Cookie`.
- **Board header:** gen's `LanguageSwitcher` sits top-right. On the
vanity host it sets the cookie and reloads `/`, so the copyable URL
stays bare. On gen it behaves as before (`router.replace` to
`/{locale}/requests`).
- **`LanguageSwitcher`:** new optional `onSelectLocale` prop that
replaces the default navigation.

## Testing
- Worker: `node --test infrastructure/cloudflare/requests-host/`, 10
pass. This includes a check that the Worker's locale list matches
`frontend/i18n/routing.ts`.
- New `components/__tests__/LanguageSwitcher.test.tsx` (2 tests); the
703 component tests pass.
- Live checks against the deployed Worker: `es`, `ja`, `pt-BR`, `en-US`
each get the translated board, and the cookie beats `Accept-Language`.
- Mobile (390px) screenshot of a local build: the switcher shows as a
compact flag top-right and the dropdown fits the screen.
- Prod E2E spec extended with a browser-language check and a switcher
round-trip. It will run after deploy.

Local CodeRabbit review: no findings.

@coderabbitai ignore

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

https://claude.ai/code/session_016FYpoNVXzJzqKFaowqpwxr

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 16:15:08 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 37b4f5126a fix: serialise translation-preview renders and keep them in GCS (OOM SIGKILLs) (v0.278.17) (#1197)
@coderabbitai ignore

## Why
BACKLOG "translation-preview renders get the API instance SIGKILLed
(OOM)" (#alerts msgs 1557981404242116608, 1560563690053439628). On 10-09
and 10-16, two concurrent `GET /api/themes/translation-preview` renders
for **different** languages, each a 4K ffmpeg frame taking about 20s,
were followed by `Container terminated on signal 9`. Every in-flight
request got a 503, including a real user's `create-from-search` on
10-09. The existing per-key lock only prevented duplicate renders of the
*same* language.

## What
- `_render_slot = BoundedSemaphore(1)`: one render at a time per
instance.
- **Persistent cache:** rendered frames go to GCS at
`themes/_translation_previews/<theme>/<lang>-<sha256(style_params +
sample)[:16]>.jpg`. Each language renders once per theme change rather
than once per cold instance, so very few requests ever wait on the slot.
A theme edit changes the digest, so stale frames are never served. Cache
reads and writes are best-effort: failures log a WARNING and fall back
to rendering. They use the bucket directly, so a cache miss isn't logged
as a "not found".
- **Fixed an existing test blind spot:** this module's autouse
`no_sleep` fixture stubs the global `time.sleep`. As a result
`test_concurrent_cold_previews_render_once` passed without any threads
overlapping, and so did my first version of the new concurrency test.
Both now wait on `threading.Event().wait()`.

## Testing
- New: a GCS hit serves without rendering; a theme change gets a new
key; four languages never render concurrently. Mutation-checked: with
`BoundedSemaphore(8)` it fails with `assert 4 == 1`.
- `test_lyrics_translation.py`: 33 passed. Local CodeRabbit: 0 findings.

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

https://claude.ai/code/session_01Jw21syo4HizJJjYw2mg2Vp

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:38:28 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 acb02e138a fix: un-pin audio-separator to 0.47.1 with RoFormer overlap=2 (v0.278.16) (#1196)
@coderabbitai ignore

## Why
BACKLOG "audio-separator 0.45–0.47 regression: mel-band RoFormer karaoke
models 3–5× slower on L4". The root cause is **python-audio-separator
#299 (0.47.0)**, not #298. #299 made RoFormer `overlap` a *window count*
that defaults to each model YAML's `num_overlap`. Before that, `overlap`
was effectively an 8-second step, which meant almost no overlap. The
karaoke models' YAMLs set `num_overlap` 4/8, so a 3-minute track went
from 23 forward passes to 87 (aufr33) and 124 (gabox_v2, becruily). That
matches the measured 25→75s, 26→149s and 27→157s. 0.45.0 and 0.46.0
still had the old step formula.

python-audio-separator #313 (released as **0.47.1**) keeps #299. It adds
a per-model forward-pass budget test on every PR and a GPU per-pass
timing test (T4: 1.21 s/pass), plus a README note. Andrew chose
overlap=2 for gen: smoother chunk seams than 0.44's no-overlap, at about
1.5× the 0.44 compute instead of 4–6×.

## What
- `karaoke_gen/audio_processor.py`: `SEPARATOR_MDXC_PARAMS` (overlap=2)
goes to all four `Separator(...)` constructions (stage 1, stage 2
karaoke ensemble, single-model paths) **only when audio-separator ≥
0.47**. On older versions `overlap=2` meant a 2-second step, which is 4×
slower, so they keep their defaults. Ensembles load each model through
`load_model`, so the param reaches every model in the preset.
- `backend/Dockerfile.gpu-base`: `AUDIO_SEPARATOR_VERSION=0.47.1`, with
the comment rewritten to explain the root cause. 0.47.1 needs
`torch>=2.3` on Linux, so the pre-installed `torch==2.6.0+cu126`
(required by the L4 driver) is kept.
- The poetry lock stays on 0.44.1. The version-aware params keep CI and
CPU images on the old semantics, and there's no torch churn.

## Expected cost per ~3-min track (forward passes)
| model | 0.44.2 | 0.47 YAML default | 0.47 + overlap=2 |
|---|---|---|---|
| karaoke_aufr33 | 23 | 87 | 44 |
| karaoke_gabox_v2 | 23 | 124 | 32 |
| karaoke_becruily | 23 | 124 | 32 |
| instrumental fv7z / resurrection | 23 | 32 / 21 | 32 / 21 |

## Verification plan (before /backlog-finish)
After the deploy, time the separation of the daily E2E or a real job on
the audio-separation-job logs. I expect roughly 1.5× the 0.44.2
karaoke-stage times (~40–50s per karaoke model rather than 75–157s). If
it's worse, revert the pin to 0.44.2. That's one line.

## Testing
- `tests/unit/test_audio_processor_local_gpu.py`: version gating
(0.47.x/0.48/1.0 → overlap 2; 0.44/0.46 → defaults; unknown → defaults;
fresh copy), and both stages' constructors receive `mdxc_params.overlap
== 2`.
- `make test`: the backend unit suite passes. The only failures are 8
`test_emulator_integration.py` tests, caused by my local environment:
another session's emulator setup is on :8080/:4443, and they fail
identically on untouched main. CI is green on main.
- Local CodeRabbit: 0 findings.

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

https://claude.ai/code/session_01Jw21syo4HizJJjYw2mg2Vp

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:09:41 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 92fd647203 fix: preview with untimed in-browser edits fills timings or 422s, not a KeyError 500 (v0.278.15) (#1195)
@coderabbitai ignore

## Why
BACKLOG "Lyrics preview 500 `KeyError 'end_time'` on unsaved edits"
(#alerts msg 1559340473439617117). On 10-12 a paying user's review
preview failed 3× (job 16792df7). Both the GCE and the local fallback
failed with `'end_time'`. `JSON.stringify` drops `undefined`, so a word
or line edited in the browser can arrive without its timing keys, and
`CorrectionOperations.update_correction_result_with_data` indexes
`w["end_time"]` / `s["end_time"]`.

## What
- `timing_sanitizer.sanitize_corrections`: a segment with missing or
non-finite bounds now gets them from its words' timings, or else from
the neighbouring lines' gap. It used to be skipped. The existing word
clamp then fills untimed words inside that window.
- New `find_missing_timings()` returns the text of a line that still has
no usable timing.
- `POST /api/review/{id}/preview-video` now sanitizes the payload up
front, as review submit already did. If a line can't be recovered, it
returns **422** `The line "…" has a word with no timing. Sync that line,
then try the preview again.` (en/es/de) instead of a 500.
- The frontend payload is unchanged. The backend now treats a missing
key and a null value the same way, so a frontend change would add
nothing.

## Testing
- `test_timing_sanitizer.py`: bounds from words, missing `end_time`
**key** (the 16792df7 shape), untimed line filled from its neighbours'
gap, unrecoverable line reported. The old "non-finite segment bounds
left untouched" test is replaced, because that is the behaviour this PR
changes.
- `test_routes_review.py::TestPreviewVideoMissingTimings`: a 422 naming
the line, with no render attempted; fillable gaps reach the renderer
filled.
- 131 passed across review routes, sanitizer, and submit-corrections
tests. Local CodeRabbit: 0 findings.

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

https://claude.ai/code/session_01Jw21syo4HizJJjYw2mg2Vp

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:57:13 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 3bbf397dc4 fix: keep auth, tenant lookup and job-log writes off the API event loop (v0.278.14) (#1194)
@coderabbitai ignore

## Why
The residual event-loop freezes BACKLOG item. Seven days of
`EVENT_LOOP_STALL in progress` stacks (2026-10-12→19, 355 samples),
grouped by their outermost app frame, ranked the app-level loop
blockers:

| Source | Samples | Max |
|---|---|---|
| in-process screens worker → job-log handler → sync Firestore write per
log line | 30 | 2.2s |
| `require_auth` → `validate_token_full` (session read on **every**
authed request) | 19 | 1.9s |
| preview encodes
(`_run_preview_encode`/`_encode_preview_in_background`) → job-log write
| 15 | 2.4s |
| `change_visibility` → sync Dropbox/GCS deletes | 6 | 1.2s |
| tenant middleware → `get_tenant_config` (GCS on cache miss) | 5 | 1.2s
|
| `require_review_auth` → `get_job` | 5 | 2.2s |
| `auto_correct_worker._run_suggest` → `get_job` (the only stall since
#1192) | 1 | 1.2s |

(The render/video in-process stalls stopped with #1192.)

## What
- **`backend/services/log_write_offload.py`**: when a job-log write is
made on a running event loop in the API process, it goes to one
background writer thread. The queue is bounded at 5000 and a drop is
logged at WARNING, rate-limited; `atexit` drains the queue. Writes stay
inline in threads and Cloud Run Jobs, so the worker code paths behave
exactly as before. Logs are read back ordered by their own `timestamp`,
so the hand-off doesn't reorder them.
- **`asyncio.to_thread`** for
`require_auth`/`require_auth_legacy`/`require_review_auth`, the tenant
middleware, `rerender_with_current_theme`'s tenant lookup,
`auto_correct._run_suggest`, and `change_visibility`'s `get_job`.
- **Visibility change:** `_delete_*_outputs` are now plain `def`, and
the sync steps run in one worker thread. Moving them off the loop
removed the implicit serialisation, so both directions now **claim
`visibility_change_in_progress` atomically** before touching anything.
They use the new `FirestoreService.try_set_job_state_flag`, a
transactional test-and-set. A lost claim returns 409. The
regenerate→private continuation passes `holds_claim=True`, because its
regenerate already set the flag. The claim is released if the reset
fails, and a raising screens trigger rolls back like a `False` one.
- **Guard (`test_no_blocking_async_routes.py`):** `BLOCKING_CALLS` gains
`validate_token(_full)`, `validate_session`, `get_tenant_config`,
`append_log_to_subcollection` and `append_worker_log`. Every `async def`
in `api/dependencies.py` and `middleware/` is now checked, not just
decorated routes. Mutation-checked: reverting `require_auth` fails the
guard.
- `docs/LESSONS-LEARNED.md` entry. About 70 direct
`get_job`/`update_job` calls in async routes remain. They're single
round-trips that rarely show in the watchdog, and the doc says to move
them when one does.

## Testing
- New: `test_log_write_offload.py` (inline vs offloaded, Cloud Run Job
inline, ordering, full-queue drop, Firestore append off the loop
thread), claim tests in `test_change_visibility.py` (lost claim, release
on failure, chained continuation, trigger exception, route 409), and
emulator `test_try_set_job_state_flag.py` (once-only, already set,
missing job, one winner among 4 concurrent callers).
- Backend: 6478 passed. The 8 failures are
`test_emulator_integration.py`, caused by my local environment: another
session's emulator setup has an `ssh` forward on :4443 instead of
fake-GCS, and they fail identically on untouched main. CI's emulator job
covers them and the new emulator test.
- Local CodeRabbit: 3 cycles. I fixed the claim race (two findings),
trigger-exception rollback, and the guarded claim release. I skipped two
minor nitpicks on the pre-existing trigger-failure rollback.

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

https://claude.ai/code/session_01Jw21syo4HizJJjYw2mg2Vp

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:41:34 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 b02cce3cc7 feat: serve the requests board on requests.nomadkaraoke.com itself (#1193)
## Summary
`requests.nomadkaraoke.com` used to 302 to
`gen.nomadkaraoke.com/en/requests`, so the short link couldn't be copied
out of a mobile address bar (Andrew pastes it into YouTube comment
replies). Now the board is served on the vanity host itself.

- **New Worker `requests-host`**
(`infrastructure/cloudflare/requests-host/`): `/` serves gen's
`/en/requests/` (query kept), paths with an extension are proxied from
gen, and every other path 302s to the same path on gen.
- **Pulumi (already applied):** Worker route
`requests.nomadkaraoke.com/*`; old redirect rule removed; DNS comment
updated.
- **Tenant detection:** `requests` added to the non-tenant subdomains.
The browser and Pages Function now share one list
(`frontend/lib/edge/nonTenantSubdomains.ts`); the browser copy had
drifted and was missing `requests`. Backend list updated to match.
- **Board "Make it yourself"** goes to `gen.nomadkaraoke.com/app` when
on the vanity host.
- **Docs:** runbook rewritten, including why a Pages custom domain
didn't work. Attaching the domain bypassed zone redirect rules and
served the gen homepage for ~3 min before rollback.

## Testing
- `node --test infrastructure/cloudflare/requests-host/`: 4 pass
- Jest tenant + new non-tenant list tests: pass. Backend
`test_tenant_middleware.py`: 36 pass
- `make test`: 6465 pass. 8 fail in `test_emulator_integration.py`, and
the same 8 fail on a clean `origin/main` checkout (pre-existing,
env-related)
- New prod E2E `e2e/production/requests-vanity-host.spec.ts`: board at
`/` with no redirect and the API working, other paths 302 to gen. The
pass/fail status of the "not a tenant" check (still sends `X-Tenant-ID:
requests` until this frontend deploys) is listed below.
- Manual browser check on prod: URL stays
`requests.nomadkaraoke.com/?utm_source=…`, board renders, no console
errors

| Prod E2E check | Before this deploy |
|---|---|
| serves board at `/` | ✅ |
| other paths → gen | ✅ |
| not treated as tenant | ❌ expected, fixed by this PR |

Local CodeRabbit review done (1 minor doc finding, fixed).

@coderabbitai ignore

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

https://claude.ai/code/session_016FYpoNVXzJzqKFaowqpwxr

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:18:57 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 1344a086da fix: worker Cloud Run Jobs never dispatch video/render into the API process (v0.278.12) (#1192)
## Problem: a regression from #1191, caught by #alerts triage
At 07:03 UTC on 2026-10-19, two new freeze alerts fired: **52s with 29
requests affected** (culprit
`firestore_service.append_log_to_subcollection`, during CDG packaging)
and **81s with 33 requests** (culprit `dropbox_service.upload_file`).
The stacks show `video_worker.generate_video` running **inside
karaoke-backend**.

Cause: in today's daily E2E run (job 5a5e5181), #1191's park/resume
worked as designed (parked 06:55:04, resumed 06:57:50). But the resume
runs in `audio-separation-job`, which doesn't set
`USE_CLOUD_RUN_JOBS_FOR_VIDEO`. So `trigger_video_worker` fell back to
Cloud Tasks, which runs it as a `BackgroundTask` on the API, putting the
whole video worker on the API's event loop. The same latent bug already
applied to the audio worker's auto-approval → render trigger.

## Fix
- `backend/config.py`: inside a Cloud Run Job (`CLOUD_RUN_JOB` is set by
the platform), `use_cloud_run_jobs_for_video` and
`use_cloud_run_jobs_for_render` default to **true**. An explicit env
value still wins. This covers every worker job (audio, lyrics, download,
...) with no infra change, through the normal image deploy.
- Error monitor normalizer: `requests_affected=N` →
`requests_affected=<N>`, so a stall culprit is one alert pattern instead
of one per request count.

## Testing
- New `backend/tests/test_config_cloud_run_job_dispatch.py`: inside a
job → true; outside → unchanged; explicit env wins.
- New normalizer test.
- `backend/tests` + `tests/unit/services/error_monitor`: 6871 passed.
- Local CodeRabbit review: 0 findings.

## Verify after deploy
The next parked-then-resumed job logs `Started Cloud Run Job
video-encoding-job` from audio-separation-job, and there are no
`EVENT_LOOP_STALL` lines on karaoke-backend with `video_worker` in the
stack.

@coderabbitai ignore

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

https://claude.ai/code/session_019pmG2XAgtUguEJWLFpkKHN

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:17:49 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 0d0605d7b5 fix: final encode waits for stem separation instead of stranding the job; pin audio-separator 0.44.2 (v0.278.11) (#1191)
## Problem
The daily E2E Stage 2 failed on 2026-10-17 (run #216) and 2026-10-18
(#217). When a customer finishes review **before** stem separation does,
`video-encoding-job` fails its prerequisites (`Missing instrumental:
instrumental_clean`) 3× within seconds. The job then sits at
`instrumental_selected` ("Starting final encode") forever: it's never
marked failed, nothing alerts, and separation finishing doesn't
re-trigger the encode.

The race became common when the GPU image's unpinned `pip install
"audio-separator[gpu]"` picked up **0.47.0** on the 10-17 rebuild. On
L4, the mel-band RoFormer **karaoke** models run 3–5× slower than on
0.44.2, so total separation went from ~5 to ~10–16 min:

| model (~3-min track) | 0.44.2 | 0.47.0 |
|---|---|---|
| karaoke_aufr33_viperx | ~25s | 75s |
| karaoke_gabox_v2 | ~26s | 149s |
| karaoke_becruily | ~27s | 157s |
| instrumental fv7z / resurrection | ~50–60s | ~62s |

The model YAMLs still say `num_overlap: 8, batch_size: 1`, so this isn't
the #299 YAML-defaults change; the cause is somewhere in 0.45–0.47's
RoFormer inference changes. That root cause is tracked separately.

## Fix
- **Pin** `audio-separator[gpu]==0.44.2` in
`backend/Dockerfile.gpu-base` (`ARG AUDIO_SEPARATOR_VERSION`). Changing
this file triggers the GPU base image rebuild in CI.
- **Video worker parks instead of failing.** When the selected stem is
missing *and* separation is still running (`audio_complete` false, valid
status), it sets `state_data.video_waiting_for_stems`, puts a
user-visible message ("Waiting for audio separation to finish; the final
video starts automatically") and exits 0, so Cloud Run doesn't retry. It
re-checks after parking, and an atomic Firestore test-and-clear
(`claim_job_state_flag`) means exactly one of the video worker and the
audio worker proceeds if the stems land mid-park.
- **Audio worker resumes it.** After `mark_audio_complete`,
`resume_video_if_waiting_for_stems` re-triggers a parked encode. The
fake-workers pipeline does the same, so the local stack matches prod.
- **Backstop in `recover_stuck_jobs`.** `instrumental_selected` for more
than 10 min with the stem present → re-trigger the video worker (covers
a lost resume or lost dispatch). More than 60 min with separation never
finishing → `mark_job_failed` (`stage=video_waiting_for_stems`), so the
job fails loudly. Jobs older than 24h are never revived. (No jobs are in
`instrumental_selected` in prod right now.)

## Testing
- New `backend/tests/test_video_waits_for_stems.py` (16 tests): pending
detection (including that a wrong status never parks), park / continue /
claim-race outcomes, and resume (flag claimed / no flag / job moved on).
- `test_recover_stuck_jobs_repark.py`: 5 new sweep tests (re-trigger,
fresh, still separating, never-ready → fail, >24h ignored).
- Full `backend/tests` (excluding emulator): 6455 passed.
- Local CodeRabbit review: 0 findings.

## Verify after deploy
- The GPU job logs `Separator version 0.44.2`, and karaoke-model
separation is back to ~20–30s.
- The next daily E2E Stage 2 passes.

@coderabbitai ignore

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

https://claude.ai/code/session_019pmG2XAgtUguEJWLFpkKHN

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 02:21:52 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 70b2f4279a feat(alerts): collapse error bursts, suppress link previews, de-noise #alerts (v0.278.9) (#1188)
Andrew's goal: "I'd like to make sure that our alerts channel only has
alerts in it that are actionable and important, or are just signal and
not noise." This follows #1186 (#noise routing).

## Changes
1. **Burst collapse** (`error_monitor/monitor.py`, `discord.py`,
`config.py`). When a run has more than 3 new patterns for one service,
including leftover un-alerted ones, the monitor sends ONE #alerts
message. It has the count, total occurrences, the top 5 by count,
first/last seen, and a `scripts/query-error-patterns.py --service X
--status new` pointer. All of those patterns are marked alerted. The
grouping is deterministic, since LLM grouping is off in prod. The
10-messages-per-run cap still applies, and unsent patterns are picked up
again next run. Evidence: on 2026-10-07/08, one mb-refresh run produced
73 separate alerts.
2. **No link previews.** Every error-monitor post (`_post`) and every
`ops_alerts` post now sets `flags: 4` (SUPPRESS_EMBEDS), through a new
`suppress_embeds` kwarg on `DiscordNotificationService.post_message`.
The YouTube "New upload" post keeps its embed.
3. **Loop watchdog.** `EVENT_LOOP_STALL in progress` is now always
WARNING. The `ended` line keeps the existing ERROR rule. In the last two
weeks there were 24 "in progress" pattern alerts on top of 15 "ended"
ones. I checked `infrastructure/modules/monitoring.py`
`EVENT_LOOP_STALL_LOG_FILTER`: it keys on `"EVENT_LOOP_STALL ended"` +
`severity>=ERROR`, so this needs no Pulumi change.
4. **Frontend chunk-load errors** (`frontend_ingestion.py`,
`firestore_adapter.py`). Reports matching `isChunkLoadError` collapse
into one pattern per build with `alert_min_hourly_count=10`. The monitor
holds that pattern un-alerted until more than 10 arrive within an hour,
which means a broken deploy. Separately, Safari/Firefox stacks now get
the message prepended before hashing (a pattern was named
`@https://gen.nomadkaraoke.com`). Chrome hashes are unchanged. Existing
Safari/Firefox patterns will re-key once, and burst collapse groups
them.
5. **known_issues.** Added a service-scoped ignore for
`github-runner-manager` "no available instance" aborts during scale-up
(seen 09-20, 09-23, 09-27, 10-08). The same message from other services
still alerts.
6. **divebar-mirror schedulers.** Added `attempt_deadline="600s"` on
both `divebar-mirror-daily` and `divebar-mirror-refresh`; the function
timeout is 540s. With the 180s default, Cloud Scheduler retried syncs
that were still running, and the overlapping runs hit OOM (4x in 30
days).

## ⚠️ Pulumi
`infrastructure/modules/divebar_mirror.py` changed, so **this needs
`pulumi up` by Andrew before merge**. Auto-merge is NOT enabled.

## Testing
- New and updated unit tests in
`tests/unit/services/error_monitor/{test_monitor,test_discord,test_frontend_ingestion,test_firestore_adapter,test_known_issues}.py`,
`backend/tests/{test_loop_watchdog,test_discord_service,test_ops_alerts}.py`,
and `tests/unit/test_divebar_mirror_scheduler.py` (an AST guard:
deadline > function timeout).
- `pytest backend/tests --ignore=backend/tests/emulator`: 6421 passed,
36 skipped.
- `tests/unit/services/error_monitor`: all pass.
- Local CodeRabbit review (`--committed`) completed with 0 findings.

@coderabbitai ignore

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

https://claude.ai/code/session_019pmG2XAgtUguEJWLFpkKHN

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 05:13:13 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 9af5c8224e docs(medley): recommend backing_vocals_db -8, not -14 (#1189)
The customer reported that -14 dB made the backing singers inaudible
(about 25 dB under the band). -8 dB leaves them about 18 dB under: quiet
but present. This updates the MEDLEYS.md spec-table example and adds the
guidance. Docs only, so no version bump.

@coderabbitai ignore

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

https://claude.ai/code/session_01QV2TQwyC7pwVkGPCk98Bqg

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 23:58:23 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 0e507852af fix(alerts): demote expected conditions off ERROR + Payment Link webhook fix (v0.278.9) (#1187)
## Summary

Alert hygiene, part of keeping Discord #alerts to actionable signal
only. ERROR is page-worthy: the error monitor turns every new ERROR
pattern into an #alerts message. This PR moves expected conditions down
to INFO/WARNING and fixes the one real bug among them, which was a
Payment Link checkout crashing the Stripe webhook. It covers the BACKLOG
items "Payment Link checkouts crash the Stripe webhook" and part of
"Alert-hygiene bundle".

## Changes

1. **Stripe webhook, non-gen checkouts** (`users.py`,
`stripe_service.py`, `stripe_admin_service.py`)
- A session that gen didn't create (a Stripe Payment Link:
`payment_link` is set, there's no gen metadata, and
`customer_email=None`) used to log ERROR "No user email in checkout
session". `store_payment` then crashed on `None.lower()`, so the payment
never reached `stripe_payments` or revenue.
- New `StripeService.is_gen_checkout()`. A non-gen checkout now logs
INFO "non-gen checkout (payment link ...)" and grants no credits. It is
marked processed for idempotency and is still stored, with
`customer_details.email`, `order_type="payment_link"`, `payment_link_id`
and the line-item description.
- `store_payment` now handles None for metadata, customer_details,
total_details and payment-method fields.
- **Not backfilled:** session `cs_live_a1ENsua3w6mDH04PPc…` (2026-10-13,
a $36 tip, no customer action needed). It could be backfilled through an
admin path that calls `store_payment` on the expanded session. GCP
writes from agents are restricted, so this PR doesn't do it.
2. **Lyrics providers** (`base_lyrics_provider._log_request_exception`):
a 404 means "no lyrics for this track" and now logs INFO. 429 moves to
WARNING alongside 5xx, connection errors and timeouts. Auth errors and
other 4xx stay ERROR. After 5 404s from one provider in a process, it
logs a single WARNING saying the provider may be dead (TODO points at
the Musixmatch backlog item).
3. **research_audio** (`audio_search.py`): no more
`AWAITING_AUDIO_SELECTION -> SEARCHING_AUDIO ->
AWAITING_AUDIO_SELECTION` transitions, which were invalid and logged 2
ERRORs per re-search. The job stays in AWAITING_AUDIO_SELECTION with no
status writes, so a crashed request can't strand it. After the search
the job is re-read. If a selection landed in the meantime, the fresh
results are discarded with a 409 instead of replacing the results that
selection indexed into.
4. **audio-download-job on a deleted job** (`audio_download_worker.py`):
if `get_job()` returns None at the start or after the download, or a
failure happens and a fresh read confirms the doc is gone, the worker
logs INFO and returns success, so it exits 0. That means no `fail_job`,
no further writes, no worker triggers and no Cloud Run retry. A GCS
NotFound on a job that still exists stays an ERROR. Seen with job
6ffe88ad on 2026-10-14.
5. **Loop watchdog**: "Failed to record loop stall (non-fatal)" now logs
WARNING with exc_info. Only that line changed, to keep the conflict with
feat/alert-noise-monitor trivial.
6. **Job-list queries** (`firestore_service.list_jobs`,
`list_jobs_summary`, `list_jobs_by_batch_id`): `query.stream()` now gets
`retry=` and `timeout=` of 30s. The client default is 300s for both,
which caused the "Error listing jobs summary: Timeout of 300.0s
exceeded" errors.

Version 0.278.9 (0.278.8 is taken by the still-open #1186).

## Testing

- New/updated unit tests:
- `test_stripe_webhook_non_gen_checkout.py`: webhook stores the payment,
logs INFO, logs nothing at ERROR, and marks the session processed.
- `test_stripe_admin_service.py`: Payment Link session and null fields.
- `tests/unit/test_base_lyrics_provider.py`: log levels for 404, 429 and
401, plus the dead-provider WARNING.
- `test_audio_search_research_attach.py`: no status writes, and a
selection made mid-search gets a 409.
- `test_audio_download_worker.py`: job deleted at start, mid-download,
or with NotFound on write.
  - `test_loop_watchdog.py`: recorder failure logs WARNING.
- `test_firestore_list_query_timeout.py`: bounded retry/timeout on all
three list queries.
- `pytest backend/tests --ignore=backend/tests/emulator`: 6434 passed.
`pytest tests/unit`: 2108 passed.
- Local CodeRabbit review: cycle 1 raised 2 findings (non-gen session
idempotency, re-search race), both fixed. Cycle 2 was clean.

@coderabbitai ignore

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

https://claude.ai/code/session_019pmG2XAgtUguEJWLFpkKHN

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 02:58:58 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 a6d4163d2e feat(alerts): route non-signal Discord posts to #noise (v0.278.8) (#1186)
## Summary
Andrew asked for #alerts to carry only real problems. Routine and
informational posts now go to the new **#noise** channel. The GitHub org
PR webhook was already moved to #noise separately.

| Message | Before | After |
|---|---|---|
| Error monitor: New Error Pattern / Spike / Incident | #alerts |
#alerts |
| Error monitor: ✅ Patterns Auto-Resolved | #alerts | **#noise** |
| Error monitor: 📊 Daily Error Digest | #alerts | **#noise** |
| Nightly Backup Report (clean run) | #alerts | **#noise** |
| Nightly backup failed/partial (title is now "🚨 Nightly Backup FAILED")
| #alerts | #alerts |
| ✅ E2E Daily Test PASSED | #alerts | **#noise** |
| 🩹 E2E self-healed Stripe (auto-merge PR opened) | #alerts | **#noise**
|
| 🩹 self-heal PR needs CI approval click / could not open | #alerts |
#alerts |
| E2E / Tenant E2E failures, DR freshness stale, Job failed, Publish
completeness SHADOW, Gemini unavailable, OAuth credential alerts,
quarterly DR drill reminder | #alerts | #alerts (unchanged) |

## How the noise webhook is resolved
- **Backend / error monitor and the backup function** read it at
runtime: env `DISCORD_NOISE_WEBHOOK_URL` first, then the Secret Manager
secret `discord-noise-webhook` (the name can be overridden with
`DISCORD_NOISE_WEBHOOK_SECRET_NAME`). No Pulumi change is needed,
because both service accounts already have project-wide
`secretAccessor`.
- **GitHub Actions** uses `secrets.DISCORD_NOISE_WEBHOOK_URL ||
secrets.DISCORD_ALERT_WEBHOOK_URL`.
- **Nothing is silently dropped.** If the noise webhook can't be
resolved, or a post to it fails, the message goes to #alerts instead. In
the workflow this uses `curl -fsS` with a retry on the alert webhook.
- The error monitor now rate-limits each channel separately (10 per run
each), so noise can't use up the alert budget during an incident.

## Deploy notes
- **Backup Cloud Function:** CI doesn't deploy its source. Run
`infrastructure/functions/backup_to_aws/deploy.sh` after merge.
- **Error monitor job:** runs `karaoke-backend:latest`, so it picks up
the change once CI pushes the image.
- **No `pulumi up` needed.**

## Testing
- `tests/unit/services/error_monitor`: 376 passed. New tests cover noise
vs alert routing, fallback when the noise webhook is missing or fails,
separate rate limits, and secret resolution.
- `backend/tests` (excluding emulator): 6418 passed, 36 skipped.
- `infrastructure/functions/backup_to_aws`: 60 passed, including the new
`test_discord_alert.py` and routing tests in `test_main.py`. These were
run in a scratch venv because `functions_framework` isn't in the conda
env, which was already the case before this change.
- `actionlint` on `e2e-daily.yml`: no new findings. The only findings
are info-level shellcheck notes that were already there.

@coderabbitai ignore

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

https://claude.ai/code/session_019pmG2XAgtUguEJWLFpkKHN

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 02:46:50 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 290f927175 fix(backend): move remaining event-loop blockers off the loop (v0.278.7) (#1185)
## Summary
Found while triaging Discord #alerts and 14 days of freeze telemetry
(2026-10-18). The event-loop watchdog still caught real freezes that hit
users:

- **151s freeze, 32 requests affected (2026-10-17 20:10 UTC).** `POST
/api/review/{id}/custom-lyrics/generate` called
`CustomLyricsService.generate` (a sync Gemini call) on the loop. Every
user on the instance saw "server unavailable". It now runs via
`asyncio.to_thread`.
- **14.9s freeze, 7 requests (2026-10-16).** The first `from
google.cloud import run_v2` in
`worker_service._trigger_worker_cloud_run_job` ran on the loop.
`google.cloud.run_v2` and `httpcore` (imported lazily by httpx) are now
in the startup `_LAZY_ROUTE_IMPORTS`, so they are imported off-loop
before readiness.
- **GCS on the loop in async routes.** `_prepare_theme_for_job` ran on
the loop in `upload_and_create_job`, `create_job_with_upload_urls`,
`create_job_from_url` and audio-search `search_audio`;
`submit_audio_edit` also uploaded `edit_log.json` on the loop. These now
go through `to_thread`.
- **Guard.** `upload_json`, `_prepare_theme_for_job` and `generate` are
added to the `BLOCKING_CALLS` denylist in
`test_no_blocking_async_routes.py`. The denylist caught the two extra
routes above.

## Testing
- `pytest backend/tests --ignore=backend/tests/emulator`: 6418 passed,
36 skipped.
- `test_audio_search` source check updated to accept the
`to_thread(_prepare_theme_for_job, …)` form.
- Local CodeRabbit review: 0 findings.

## Verify after deploy
No new `EVENT_LOOP_STALL ended … requests_affected>0` lines with
culprits `_call_gemini`, `run_v2` or `upload_json`.

@coderabbitai ignore

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

https://claude.ai/code/session_019pmG2XAgtUguEJWLFpkKHN

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 01:56:13 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 9d6aa3df7d feat(medley): per-section backing_vocals_db for the karaoke track (v0.278.6) (#1184)
## Summary
The Fiverr medley customer said the backing singers in two songs were
too loud to sing over in tune, and asked for them as a faint background.

- **New option:** a per-section `backing_vocals_db` in the medley spec.
For the karaoke track only, the section is rebuilt from the clean
instrumental plus the backing-vocal stem at that level, e.g. `-14` for a
faint background. The rest of the karaoke track, the clean instrumental
and the guide are unchanged.
- **Cached mix:** the mix is cached per job/level, written to a
`.partial.flac` and renamed, so an interrupted run never leaves a
truncated mix to be reused. If the job has no backing stem, it stops
with a clear error.
- **Docs:** `docs/MEDLEYS.md` spec table.

## Testing
- `test_make_medley.py`: parsing, the ffmpeg graph, only the karaoke
variant changing, the atomic write and the cache. 20 + chord-chart tests
pass.
- Real data: the customer's medley with `-14` on Remember When and On
the Other Hand.
- Only those two sections change; the others differ by ≤ -43 dB, which
is crossfade overlap.
  - Overall section loudness is unchanged.
- A local CodeRabbit review found 1 issue (stale or partial cache). It
is fixed.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 15:04:43 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 03ee693f28 feat(medley): customer chord charts + static-gain master (v0.278.5) (#1183)
## Summary
Two follow-ups on the medley tooling, both from the Fiverr medley
customer's feedback.

- **Fixes the robotic artifact at the start of the karaoke audio.** The
final single-pass `loudnorm` ran in dynamic mode. On a song that opens a
cappella (HSLHT sings from 0.4s, band at 3s), the instrumental's first
3s is near-silent separation residue at -70 dB, and `loudnorm` boosted
it by about 50 dB into a loud warble. The master is now one static gain
to -14 LUFS plus a 4×-oversampled limiter at -1 dB (`master_filter`).
After the fix, the first 3s measure -61 dB (were -15 dB). Sync is
sample-identical and true peak is -0.9 dB.
- **Imports the customer's own chord chart.**
`scripts/medley/chord_chart.py` plus a new `make_medley.py chart` step
read a chords-over-lyrics chart (.txt or .docx in Courier, capo shapes,
`Capo N` / `Key change Capo 1` lines). They align it word-by-word to the
reviewed lyrics, so chords come out timed on the words the chart puts
them on. Detected chords fill intros, breaks and spoken verses,
transposed into the capo shapes.
- **Shows the capo in the chord box.** New `ChordChange.capo` field,
shown as "capo N" under the chord.
- **Docs:** `docs/MEDLEYS.md` gets a new section on importing a customer
chart, and the mastering guidance now says never to use single-pass
`loudnorm`. `docs/README.md` has an entry.

## Testing
- Unit tests:
  - New: `tests/unit/test_chord_chart.py` (9).
- Added: capo tests in `test_guitar_chords.py`, plus master and capo
tests in `test_make_medley.py`.
- Full `tests/unit` suite: 2100 passed, 65 skipped (run before the last
CodeRabbit fix; only the 9 chord-chart tests were re-run after it).
- Real data: the customer's 4-song chart against the medley. The
lyrics-with-chords output matched the chart line by line, and 4K frames
rendered with capo labels.
- A local CodeRabbit review found 1 issue (two chord groups after the
same word could come out in the wrong order). It is fixed and has a
test.

@coderabbitai ignore

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

https://claude.ai/code/session_01QV2TQwyC7pwVkGPCk98Bqg

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 14:24:45 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 9a44a30368 fix(review): idempotent correction-data review transition (v0.278.4) (#1182)
## Summary
The same race as #1181, on the other door into review. `GET
/api/review/{job_id}/correction-data` moves `AWAITING_REVIEW` to
`IN_REVIEW`. When two loads arrive concurrently, both see
`AWAITING_REVIEW`, so the second transition raises `in_review ->
in_review`. That returns a 500 and the review page shows "Failed to load
lyrics". The iOS in-app browser hits this every time; mobile E2E caught
it.

**Fix:** a shared `ensure_in_review()` helper in
`backend/services/review_state.py`, now used by both `correction-data`
and `start-review`.
- An already-`IN_REVIEW` job does not transition again.
- A lost race re-reads the job and carries on.
- Any other invalid transition still errors.
- `record_review_started` runs only for the winning transition.

Version 0.278.4.

## Testing
- 4 new `TestCorrectionDataReviewTransitionIdempotent` cases.
- 493 review and correction backend tests pass.
- Local CodeRabbit found nothing.
- Verified against the local stack via the mobile Maestro review-bridge
flow.

@coderabbitai ignore

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

https://claude.ai/code/session_011yLH4kWXMqjeKfZUG3ZiWZ

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 12:07:03 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 072f85cad9 fix(review): idempotent start-review (no more in_review -> in_review error) (v0.278.3) (#1181)
## Summary
Opening a lyrics review could fail with `Invalid state transition
in_review -> in_review`.

`POST /api/jobs/{job_id}/start-review` always called
`transition_to_state(IN_REVIEW)` and never checked for `in_review`. So
any second open failed: a duplicate request, a double-mount, a second
tab, or the mobile app's in-app browser opening the review again. Mobile
E2E found this, and a screenshot captured gen's error page.

The endpoint is now idempotent:
- If the job is already `in_review`, it returns `{"status": "success",
"job_status": "in_review"}`.
- If the transition raises because a concurrent call won the race, it
re-reads the job. If the job is now `in_review`, it returns the same
success.
- Any other invalid transition still raises.
- `record_review_started` runs only for the winning `awaiting_review →
in_review` transition.

Version 0.278.3.

## Testing
- 4 new `TestStartReview` cases in `backend/tests/test_jobs_api.py`.
- The review-related backend tests pass: 452.
- Local CodeRabbit found nothing.

@coderabbitai ignore

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

https://claude.ai/code/session_011yLH4kWXMqjeKfZUG3ZiWZ

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 10:20:58 -04:00
219 changed files with 9327 additions and 637 deletions

No files matched your search

+2 -2
View File
@@ -2175,8 +2175,8 @@ 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,STORAGE_RETENTION_DRY_RUN=false,STORAGE_RETENTION_MAX_JOBS_PER_RUN=50,CONVERSION_EMAILS_ENABLED=true,REVIEW_LAST_CHANCE_ENABLED=true,CONVERSION_OFFER_PERCENT=25,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"
--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,CONVERSION_EMAILS_ENABLED=true,REVIEW_LAST_CHANCE_ENABLED=true,CONVERSION_OFFER_PERCENT=25,YOUTUBE_COMMENT_AUTOREPLY_ENABLED=true,YOUTUBE_COMMENT_AUTOREPLY_START=2026-04-22T00:00:00Z,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,LRCLIB_APP_ID=lrclib-app-id:latest,LRCLIB_SECRET_KEY=lrclib-api-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,DECIDE_GEN_PARTNER_SECRET=decide-gen-partner-secret:latest"
# R3/R4 — smoke the tagged candidate revision BEFORE it serves any traffic.
- name: Smoke candidate revision
+20 -6
View File
@@ -411,22 +411,31 @@ jobs:
if: always() && steps.pr.outputs.unchanged != 'true'
run: |
PR="${{ steps.pr.outputs.pr_url }}"
# #alerts = needs a human; #noise = informational (auto-merge handles it).
# Noise falls back to the alert webhook if its secret is unset.
ALERT_WEBHOOK="${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
NOISE_WEBHOOK="${{ secrets.DISCORD_NOISE_WEBHOOK_URL || secrets.DISCORD_ALERT_WEBHOOK_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
WEBHOOK="$ALERT_WEBHOOK"
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
WEBHOOK="$NOISE_WEBHOOK"
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
WEBHOOK="$ALERT_WEBHOOK"
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 }}"
PAYLOAD="{\"embeds\": [{\"title\": \"$TITLE\", \"description\": \"$DESC\n\n**Run:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": $COLOR}]}"
# A failed #noise post retries on #alerts so it is never silently lost.
curl -fsS -H "Content-Type: application/json" -d "$PAYLOAD" "$WEBHOOK" \
|| { [ "$WEBHOOK" != "$ALERT_WEBHOOK" ] && curl -s -H "Content-Type: application/json" -d "$PAYLOAD" "$ALERT_WEBHOOK"; } \
|| true
# =========================================================================
# Stage 2: Happy Path (uses credit from Stage 1)
@@ -600,12 +609,17 @@ jobs:
steps:
- name: Discord notification (success)
# Passes are not signal: they go to #noise (fallback: #alerts if the
# noise secret is unset, so nothing is ever silently dropped).
if: needs.e2e-happy-path.result == 'success'
run: |
STAGE1="${{ needs.e2e-credit-purchase.result || 'skipped' }}"
curl -s -H "Content-Type: application/json" \
-d "{\"embeds\": [{\"title\": \"✅ E2E Daily Test PASSED\", \"description\": \"Payment: ${STAGE1} | Happy Path: success\n\n**Run:** #${{ github.run_number }}\", \"color\": 3066993}]}" \
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
ALERT_WEBHOOK="${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
NOISE_WEBHOOK="${{ secrets.DISCORD_NOISE_WEBHOOK_URL || secrets.DISCORD_ALERT_WEBHOOK_URL }}"
PAYLOAD="{\"embeds\": [{\"title\": \"✅ E2E Daily Test PASSED\", \"description\": \"Payment: ${STAGE1} | Happy Path: success\n\n**Run:** #${{ github.run_number }}\", \"color\": 3066993}]}"
curl -fsS -H "Content-Type: application/json" -d "$PAYLOAD" "$NOISE_WEBHOOK" \
|| { [ "$NOISE_WEBHOOK" != "$ALERT_WEBHOOK" ] && curl -s -H "Content-Type: application/json" -d "$PAYLOAD" "$ALERT_WEBHOOK"; } \
|| true
- name: Send email notification
if: github.event_name == 'schedule'
+9 -1
View File
@@ -102,9 +102,17 @@ RUN --mount=type=cache,target=/root/.cache/pip \
# have NVIDIA driver 570 which only supports up to CUDA 12.8. PyTorch cu130
# fails with "NVIDIA driver is too old". PyTorch cu126 works with 12.8 drivers.
# Installing torch first means audio-separator[gpu] sees it as already satisfied.
#
# PINNED to an exact version: an unpinned install silently picked up 0.47.0 on the
# 2026-10-17 rebuild and separation went from ~5 to ~10-16 min. Cause: 0.47 (#299) made
# RoFormer `overlap` a window count defaulting to each model YAML's num_overlap (4-8 for
# the karaoke models = 4-6x the forward passes of 0.44's fixed 8 s step). karaoke_gen's
# audio_processor now passes overlap=2 on >= 0.47 (SEPARATOR_MDXC_PARAMS). Time a real
# job before bumping this, and read the audio-separator release notes for compute changes.
ARG AUDIO_SEPARATOR_VERSION=0.47.1
RUN --mount=type=cache,target=/root/.cache/pip \
pip install torch==2.6.0+cu126 torchvision==0.21.0+cu126 --index-url https://download.pytorch.org/whl/cu126 && \
pip install "audio-separator[gpu]"
pip install "audio-separator[gpu]==${AUDIO_SEPARATOR_VERSION}"
# Now copy actual source code (AFTER deps installed, so code changes don't
# invalidate the expensive pip install layer in registry cache)
+8 -6
View File
@@ -1,6 +1,7 @@
"""
FastAPI dependencies for authentication and authorization.
"""
import asyncio
import logging
import secrets
from datetime import datetime, timedelta, UTC
@@ -89,7 +90,8 @@ async def require_auth(
)
# Validate token using the full method
auth_result = auth_service.validate_token_full(token_str)
# Sync Firestore reads: run off the event loop (every authed request passes here).
auth_result = await asyncio.to_thread(auth_service.validate_token_full, token_str)
# Get request_id from middleware for correlation
request_id = getattr(request.state, "request_id", None)
@@ -122,7 +124,7 @@ async def require_auth(
if not getattr(request.state, "tenant_config", None):
from backend.services.tenant_service import get_tenant_service
tenant_service = get_tenant_service()
tenant_config = tenant_service.get_tenant_config(auth_result.tenant_id)
tenant_config = await asyncio.to_thread(tenant_service.get_tenant_config, auth_result.tenant_id)
if tenant_config and tenant_config.is_active:
request.state.tenant_config = tenant_config
@@ -165,7 +167,7 @@ async def require_auth_legacy(
detail="Authentication required. Provide token via Authorization header or ?token= parameter"
)
is_valid, user_type, remaining_uses, message = auth_service.validate_token(token_str)
is_valid, user_type, remaining_uses, message = await asyncio.to_thread(auth_service.validate_token, token_str)
if not is_valid:
raise HTTPException(
@@ -284,10 +286,10 @@ def require_review_auth_factory(job_id_param: str = "job_id"):
full_token = token
if full_token:
auth_result = auth_service.validate_token_full(full_token)
auth_result = await asyncio.to_thread(auth_service.validate_token_full, full_token)
if auth_result.is_valid:
# For full auth, also verify job ownership
job = job_manager.get_job(job_id)
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")
@@ -319,7 +321,7 @@ def require_review_auth_factory(job_id_param: str = "job_id"):
# Try review token
if review_token:
job = job_manager.get_job(job_id)
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")
+25 -28
View File
@@ -838,8 +838,8 @@ async def search_audio(
if effective_theme_id and not body.style_files:
from backend.api.routes.file_upload import _prepare_theme_for_job
try:
style_params_path, theme_style_assets, youtube_desc = _prepare_theme_for_job(
job_id, effective_theme_id, body.color_overrides
style_params_path, theme_style_assets, youtube_desc = await asyncio.to_thread(
_prepare_theme_for_job, job_id, effective_theme_id, body.color_overrides
)
theme_update = {
'style_params_gcs_path': style_params_path,
@@ -1200,13 +1200,12 @@ async def research_audio(
})
logger.info(f"[job:{job_id}] Re-search with edited terms: {artist} - {title}")
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.SEARCHING_AUDIO,
progress=5,
message=f"Searching for: {artist} - {title}",
raise_on_invalid=False,
)
# No status writes: the job stays in AWAITING_AUDIO_SELECTION for the whole
# re-search. (It used to transition -> SEARCHING_AUDIO and back, which isn't
# a valid transition, so every re-search logged two "Invalid state
# transition" ERRORs. Not writing status also means a crashed request can't
# strand the job in SEARCHING_AUDIO.)
logger.info(f"[job:{job_id}] Re-searching audio: {artist} - {title}")
audio_search_service = get_audio_search_service()
try:
@@ -1214,16 +1213,24 @@ async def research_audio(
except NoResultsError:
search_results = []
except AudioSearchError as e:
# Restore the awaiting state so the job isn't stranded, then surface the error.
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
progress=10,
message="Search failed. Please try again or provide your own audio.",
raise_on_invalid=False,
)
# Job is still awaiting selection (never left it); surface the error.
logger.warning(f"[job:{job_id}] Re-search failed: {e}")
raise HTTPException(status_code=502, detail=f"Search failed: {e}")
# The search can take seconds; a selection may have landed meanwhile. Don't
# swap the cached results out from under it (the download worker indexes
# them by selected_audio_index).
latest = job_manager.get_job(job_id)
if not latest or latest.status != JobStatus.AWAITING_AUDIO_SELECTION:
logger.info(
f"[job:{job_id}] Job left awaiting_audio_selection during re-search "
f"(status={latest.status if latest else 'missing'}); discarding results"
)
raise HTTPException(
status_code=409,
detail="Job is no longer awaiting audio selection",
)
# Replace cached results (empty is fine — the UI offers the manual fallback).
results_dicts = [r.to_dict() for r in search_results]
remote_id = getattr(audio_search_service, "last_remote_search_id", None)
@@ -1234,17 +1241,7 @@ async def research_audio(
'state_data.remote_search_id': remote_id,
})
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
progress=10,
message=(
f"Found {len(results_dicts)} audio sources. Waiting for selection."
if results_dicts else
"No audio sources found. Edit the details and search again, or provide your own audio."
),
raise_on_invalid=False,
)
logger.info(f"[job:{job_id}] Re-search found {len(results_dicts)} audio sources")
return AudioSearchResponse(
status="awaiting_selection",
+6
View File
@@ -210,6 +210,12 @@ async def match_judge(
locale = get_locale_from_request(request)
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
from backend.services.fake_workers import fake_workers_enabled
if fake_workers_enabled():
# Local E2E stack: scripted verdict (per-user fake config), no catalog/Gemini.
from backend.services.fake_workers.judge import fake_match_verdict
return fake_match_verdict(body.artist, body.title, auth_result.user_email, stage=body.stage).to_dict()
from backend.services.match_judge.service import judge_match
verdict = await judge_match(
body.artist, body.title,
+6 -3
View File
@@ -794,7 +794,8 @@ async def upload_and_create_job(
theme_youtube_desc = None
if effective_theme_id and not has_custom_style_files:
try:
theme_style_params_path, theme_style_assets, theme_youtube_desc = _prepare_theme_for_job(
theme_style_params_path, theme_style_assets, theme_youtube_desc = await asyncio.to_thread(
_prepare_theme_for_job,
job_id, effective_theme_id, parsed_color_overrides or None, locale=locale
)
logger.info(f"Applied theme '{effective_theme_id}' to job {job_id}")
@@ -1472,7 +1473,8 @@ async def create_job_with_upload_urls(
# If theme is set and no style_params uploaded, prepare theme style now
if effective_theme_id and not has_style_params_upload:
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
style_params_path, style_assets, youtube_desc = await asyncio.to_thread(
_prepare_theme_for_job,
job_id, effective_theme_id, body.color_overrides, locale=locale
)
# Update job with theme style data
@@ -2175,7 +2177,8 @@ async def create_job_from_url(
# If theme is set, prepare theme style now
if effective_theme_id:
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
style_params_path, style_assets, youtube_desc = await asyncio.to_thread(
_prepare_theme_for_job,
job_id, effective_theme_id, body.color_overrides, locale=locale
)
# Update job with theme style data
+78
View File
@@ -719,6 +719,38 @@ def youtube_backfill_run_endpoint(
}
@router.post("/youtube-comments/run")
def youtube_comments_run_endpoint(
http_request: Request,
background_tasks: BackgroundTasks,
dry_run: bool = False,
max_replies: Optional[int] = None,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
"""
Reply to song requests in new YouTube channel comments (requests-board links).
Called by Cloud Scheduler (hourly). Does nothing unless
YOUTUBE_COMMENT_AUTOREPLY_ENABLED is true, except ``?dry_run=true``, which logs
every reply it would post (YOUTUBE_COMMENT_BOT) and writes nothing.
"""
from backend.config import get_settings
from backend.workers.youtube_comment_bot_worker import run_comment_bot_sync
if not get_settings().youtube_comment_autoreply_enabled and not dry_run:
return {"status": "disabled", "message": "YOUTUBE_COMMENT_AUTOREPLY_ENABLED is false"}
async def _process():
try:
result = await asyncio.to_thread(run_comment_bot_sync, dry_run, max_replies)
logger.info(f"YOUTUBE_COMMENT_BOT complete: {result}")
except Exception as e:
logger.exception(f"YOUTUBE_COMMENT_BOT failed: {e}")
background_tasks.add_task(_process)
return {"status": "started", "dry_run": dry_run}
@router.post("/storage-retention/run")
async def storage_retention_run_endpoint(
dry_run: Optional[bool] = None,
@@ -1362,6 +1394,47 @@ def _recover_stuck_jobs_sync(http_request: Request, loop: asyncio.AbstractEventL
)
stems_restore_failed.append(job_id)
# --- INSTRUMENTAL_SELECTED with no encode running ---
# The video worker moves to GENERATING_VIDEO as soon as it starts, so a job
# still here after 10 min has no encode underway. Either it's parked waiting
# for stem separation (the audio worker resumes it; this catches a lost
# resume) or its video dispatch was lost. Re-trigger once the stems exist;
# if separation never finishes, fail loudly so the job doesn't sit silently
# (the 2026-10-17/18 stuck "Starting final encode" jobs). Bounded to 24h so
# ancient abandoned jobs are never revived.
from backend.services.job_health_service import selected_stem_pending
video_retriggered = []
stems_wait_failed = []
is_query = jobs_ref.where(
filter=FieldFilter("status", "==", JobStatus.INSTRUMENTAL_SELECTED.value)
).limit(SCREENS_RECOVERY_SCAN_LIMIT).stream()
for doc in is_query:
if len(video_retriggered) >= RENDER_RETRIGGERS_PER_TICK:
break
job_id = (doc.to_dict() or {}).get("job_id", doc.id)
job = job_manager.get_job(job_id)
age = _job_updated_age_seconds(job) if job else None
if age is None or not (INSTRUMENTAL_SELECTED_STALL_SECONDS < age < INSTRUMENTAL_SELECTED_MAX_AGE_SECONDS):
continue
if selected_stem_pending(job):
if age > STEMS_WAIT_FAIL_SECONDS:
logger.error(f"[job:{job_id}] Final encode waited >60 min for stem separation that never finished — failing")
job_manager.mark_job_failed(
job_id=job_id,
error_message="Audio separation didn't finish, so the final video couldn't be made. Retry the job to try again.",
error_details={"stage": "video_waiting_for_stems", "reason": "stems_never_ready"},
)
stems_wait_failed.append(job_id)
continue
logger.warning(f"[job:{job_id}] INSTRUMENTAL_SELECTED stalled >10 min with stems ready — re-triggering video worker")
try:
# Clear a parked flag first so a late audio-worker resume can't double-trigger.
job_manager.claim_video_stems_wait(job_id)
if run_on_loop(loop, worker_service.trigger_video_worker(job_id)):
video_retriggered.append(job_id)
except Exception as e: # noqa: BLE001
logger.warning(f"[job:{job_id}] video re-trigger failed: {e}")
logger.info(
f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} "
f"download_parked={len(download_parked)} download_retried={len(download_retried)} "
@@ -1392,6 +1465,8 @@ def _recover_stuck_jobs_sync(http_request: Request, loop: asyncio.AbstractEventL
"screens_retriggered_count": len(screens_retriggered),
"stems_restore_failed_jobs": stems_restore_failed,
"regen_screens_retriggered_jobs": regen_screens_retriggered,
"video_retriggered_jobs": video_retriggered,
"stems_wait_failed_jobs": stems_wait_failed,
}
@@ -1400,6 +1475,9 @@ RENDER_RETRIGGERS_PER_TICK = 10 # bound the blast radius per 5-min tick
PREP_SCREENS_STALL_SECONDS = 10 * 60 # screens normally start within seconds of lyrics done
SCREENS_RETRIGGERS_PER_TICK = 10 # bound the blast radius per 5-min tick
SCREENS_RECOVERY_SCAN_LIMIT = 500 # cap DOWNLOADING docs scanned per tick (transient state)
INSTRUMENTAL_SELECTED_STALL_SECONDS = 10 * 60 # video worker leaves this state within seconds
STEMS_WAIT_FAIL_SECONDS = 60 * 60 # separation normally lands within ~15 min of review
INSTRUMENTAL_SELECTED_MAX_AGE_SECONDS = 24 * 3600 # never revive ancient abandoned jobs
def _job_updated_age_seconds(job):
+15 -12
View File
@@ -21,6 +21,7 @@ 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.services.review_state import ensure_in_review
from backend.models.job import Job, JobCreate, JobResponse, JobStatus
from backend.models.requests import (
URLSubmissionRequest,
@@ -46,7 +47,7 @@ from backend.services.metrics import metrics
from backend.i18n import t, get_locale_from_request, get_full_locale_from_request
from backend.middleware.tenant import get_tenant_from_request
from backend.utils.test_data import is_test_email
from backend.exceptions import InsufficientCreditsError
from backend.exceptions import InsufficientCreditsError, InvalidStateTransitionError
from backend.services.firestore_service import FirestoreService, log_to_job
from backend.models.requests import ChangeVisibilityRequest, ChangeVisibilityResponse
from backend.services.user_service import get_user_service
@@ -1097,20 +1098,20 @@ def start_review(
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
# Idempotent: concurrent/duplicate opens (React double-mount, double-tap, two
# tabs) must not fail with "in_review -> in_review". Already in review == success,
# and the one-time side effects (record_review_started) are not repeated.
was_awaiting = job.status == JobStatus.AWAITING_REVIEW
success = job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.IN_REVIEW,
message="User started reviewing lyrics"
result = ensure_in_review(
job_manager, job_id, job.status, "User started reviewing lyrics"
)
if not success:
if result == "refused":
raise HTTPException(status_code=400, detail=t(locale, "jobs.reviewCannotStart"))
if was_awaiting:
if result == "started" and was_awaiting:
job_manager.record_review_started(
job_id, getattr(job, "user_email", None), auth_result.user_email, auth_result.is_admin
)
return {"status": "success", "job_status": "in_review"}
@@ -3092,14 +3093,14 @@ async def change_visibility(
"""
locale = get_locale_from_request(http_request)
job_manager = JobManager()
job = job_manager.get_job(job_id)
job = await asyncio.to_thread(job_manager.get_job, job_id)
if not job:
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
user_email = auth_result.user_email or "unknown"
is_admin = auth_result.is_admin
from backend.services.visibility_change_service import VisibilityChangeService
from backend.services.visibility_change_service import VisibilityChangeInProgress, VisibilityChangeService
service = VisibilityChangeService(job_manager)
# Validate (skip job-exists check since we already handled it)
@@ -3129,6 +3130,8 @@ async def change_visibility(
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 VisibilityChangeInProgress as e:
raise HTTPException(status_code=409, 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)}")
@@ -3247,7 +3250,7 @@ async def rerender_with_current_theme(
if reason:
raise HTTPException(status_code=400, detail=reason)
tenant = get_tenant_service().get_tenant_config(job.tenant_id)
tenant = await asyncio.to_thread(get_tenant_service().get_tenant_config, job.tenant_id)
if tenant is None or not tenant.is_active:
raise HTTPException(status_code=400, detail="This track's portal is no longer active.")
# Re-rendering is free work, so (like tenant billing) require the caller to
+41 -9
View File
@@ -74,6 +74,27 @@ def require_kjbox_partner(x_kjbox_secret: Optional[str] = Header(default=None))
return secret
def require_resolve_partner(
x_kjbox_secret: Optional[str] = Header(default=None),
x_partner_secret: Optional[str] = Header(default=None),
) -> str:
"""Gate for ``catalog/resolve``: kjbox (``X-Kjbox-Secret``) or karaoke-decide
(``X-Partner-Secret``). Returns the partner name ("kjbox" / "decide"), which
picks the rate-budget bucket. 503 when neither secret is configured."""
settings = get_settings()
kjbox_secret = settings.kjbox_partner_secret
decide_secret = getattr(settings, "decide_partner_secret", "")
if not kjbox_secret and not decide_secret:
raise HTTPException(status_code=503, detail="not configured")
if kjbox_secret and x_kjbox_secret and hmac.compare_digest(
x_kjbox_secret.encode(), kjbox_secret.encode()):
return "kjbox"
if decide_secret and x_partner_secret and hmac.compare_digest(
x_partner_secret.encode(), decide_secret.encode()):
return "decide"
raise HTTPException(status_code=403, detail="forbidden")
def get_kjbox_service(
secret: str = Depends(require_kjbox_partner),
user_service: UserService = Depends(get_user_service),
@@ -433,25 +454,31 @@ class ResolveRequest(BaseModel):
_RESOLVE_CACHE_MAX = 2000
_RESOLVE_PER_MINUTE = 120
_resolve_cache: "dict[str, dict]" = {}
_RESOLVE_DECIDE_PER_MINUTE = 60 # karaoke-decide's own bucket, so kjbox nights are never starved
_resolve_calls: "list[float]" = []
_resolve_calls_decide: "list[float]" = []
_resolve_lock = threading.Lock()
def _resolve_budget_ok() -> bool:
"""Partner-wide in-process cap on AI calls (cache hits are free)."""
def _resolve_budget_ok(partner: str = "kjbox") -> bool:
"""Per-partner in-process cap on AI calls (cache hits are free)."""
import time
now = time.monotonic()
if partner == "decide":
calls, limit = _resolve_calls_decide, _RESOLVE_DECIDE_PER_MINUTE
else:
calls, limit = _resolve_calls, _RESOLVE_PER_MINUTE
with _resolve_lock:
while _resolve_calls and _resolve_calls[0] < now - 60:
_resolve_calls.pop(0)
if len(_resolve_calls) >= _RESOLVE_PER_MINUTE:
while calls and calls[0] < now - 60:
calls.pop(0)
if len(calls) >= limit:
return False
_resolve_calls.append(now)
calls.append(now)
return True
@router.post("/catalog/resolve")
async def catalog_resolve(body: ResolveRequest, _secret: str = Depends(require_kjbox_partner)):
async def catalog_resolve(body: ResolveRequest, partner: str = Depends(require_resolve_partner)):
"""Split + auto-correct a singer's free-text song search.
kjbox calls this only when its own catalogue search found nothing, then
@@ -467,7 +494,12 @@ async def catalog_resolve(body: ResolveRequest, _secret: str = Depends(require_k
query = " ".join(body.query.split())
if not query:
raise HTTPException(status_code=422, detail="empty_query")
key = query.casefold()
from backend.services.fake_workers import fake_workers_enabled
if fake_workers_enabled(get_settings()):
# Local E2E stack: scripted verdict, no Gemini, no cache/budget (tests change the knobs).
from backend.services.fake_workers.judge import fake_resolve
return fake_resolve(query)
key = query.casefold() # shared by both partners: same query -> same verdict
with _resolve_lock:
hit = _resolve_cache.get(key)
if hit is not None:
@@ -476,7 +508,7 @@ async def catalog_resolve(body: ResolveRequest, _secret: str = Depends(require_k
if not hit.get("typed_artist"):
hit = {**hit, "typed_title": query}
return hit
if not _resolve_budget_ok():
if not _resolve_budget_ok(partner):
raise HTTPException(status_code=429, detail="rate_limited")
verdict = await resolve_and_tidy(query)
if verdict.get("reason") != "unavailable": # don't cache transient failures
+42 -7
View File
@@ -32,6 +32,7 @@ from google.cloud.firestore_v1.field_path import FieldPath
from backend.models.job import JobStatus
from backend.models.review_session import ReviewSession, ReviewSessionSummary
from backend.services.job_manager import JobManager
from backend.services.review_state import ensure_in_review
from backend.services.firestore_service import FirestoreService
from backend.services.storage_service import StorageService
from backend.services.tempo_label import (
@@ -925,11 +926,14 @@ async def get_correction_data(
# Transition to IN_REVIEW if not already (never in replay — read-only)
if not replay and job.status == JobStatus.AWAITING_REVIEW:
started = await asyncio.to_thread(
job_manager.transition_to_state,
job_id=job_id,
new_status=JobStatus.IN_REVIEW,
message="User opened combined review interface",
# Idempotent: iOS/in-app browsers fire two concurrent loads; the loser
# must not 500 on "in_review -> in_review" nor repeat one-time side effects.
started = "started" == await asyncio.to_thread(
ensure_in_review,
job_manager,
job_id,
job.status,
"User opened combined review interface",
)
if started:
# Set by require_review_auth (absent for review-token links).
@@ -1065,6 +1069,9 @@ async def _stream_audio(job_id: str, request: Optional[Request] = None, stem: Li
# 302-redirecting to a signed URL. Prod (flag unset) is unchanged.
audio_bytes, content_type = await transcoding.get_review_audio_bytes_async(audio_gcs_path)
logger.info(f"Job {job_id}: [dev-proxy] streaming {len(audio_bytes)}B input audio")
if request is not None:
# Range support so native players (iOS AVPlayer) can seek the song source.
return _ranged_response(request, audio_bytes, content_type)
return Response(content=audio_bytes, media_type=content_type)
signed_url = await transcoding.get_review_audio_url_async(audio_gcs_path, expiration_minutes=120)
@@ -1285,6 +1292,11 @@ async def complete_review(
After saving, triggers the render video worker which will use the
pre-selected instrumental (no separate instrumental selection step).
"""
# Local stack only (FAKE_WORKERS=1): a one-shot 503 for the finish-failure flows.
from backend.services.fake_workers import fake_workers_enabled
if fake_workers_enabled():
await asyncio.to_thread(_fake_complete_failure_hook, job_id)
# 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.
@@ -1315,6 +1327,15 @@ async def complete_review(
}
def _fake_complete_failure_hook(job_id: str) -> None:
"""Raise a 503 once when the job's user set ``review_complete_fail_once`` (fake workers only)."""
from backend.services.fake_workers.config import consume_review_complete_failure
job = JobManager().get_job(job_id)
if job and consume_review_complete_failure(getattr(job, "user_email", None)):
raise HTTPException(status_code=503, detail="Fake review-complete failure (review_complete_fail_once)")
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.
@@ -1521,7 +1542,10 @@ async def generate_custom_lyrics(
target_segments = await _load_target_segments_for_custom_lyrics(job_id, parsed_lines)
try:
result = service.generate(
# Off the event loop: generate() makes a synchronous Gemini call that can take
# minutes; on the loop it froze the whole instance for 151s (2026-10-17).
result = await asyncio.to_thread(
service.generate,
job_id=job_id,
target_lines=parsed_lines,
target_segments=target_segments,
@@ -1948,6 +1972,17 @@ async def generate_preview_video(
detail=t("en", "review.reviewNotReady", status=job.status)
)
# An in-browser edit can send words/lines without timings (JSON drops undefined),
# which crashed the preview with KeyError 'end_time'. Fill what we can, as review
# submit does, and name the line we can't instead of returning a 500.
from backend.services.timing_sanitizer import find_missing_timings, sanitize_corrections
_, timing_fixes = sanitize_corrections(updated_data)
if timing_fixes:
logger.info(f"Job {job_id}: preview payload had {timing_fixes} missing/out-of-range timings; filled")
untimed_line = find_missing_timings(updated_data)
if untimed_line is not None:
raise HTTPException(status_code=422, detail=t("en", "review.previewMissingTimings", line=untimed_line[:80]))
# Check if GCE preview encoding is enabled
use_gce_preview = encoding_service.is_preview_enabled
@@ -3348,7 +3383,7 @@ async def submit_audio_edit(
edit_log = body.get("edit_log")
if edit_log:
edit_log_path = f"jobs/{job_id}/audio_edit/edit_log.json"
storage.upload_json(edit_log_path, edit_log)
await asyncio.to_thread(storage.upload_json, edit_log_path, edit_log)
logger.info(f"Job {job_id}: Saved audio edit log to {edit_log_path}")
if edit_stack:
+36
View File
@@ -98,6 +98,42 @@ def scenario(body: ScenarioRequest) -> Dict[str, Any]:
raise HTTPException(status_code=422, detail=str(e))
@router.get("/jobs/{job_id}/review-result")
def review_result(job_id: str) -> Dict[str, Any]:
"""What the review submitted: the saved corrected lines plus the instrumental / duet choice.
Lets Maestro assert on a review without going through the review auth.
``lines`` is empty until a review was completed (corrections_updated.json exists).
"""
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
job = JobManager().get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="unknown job")
state = job.state_data or {}
path = ((job.file_urls or {}).get("lyrics") or {}).get("corrections_updated") \
or f"jobs/{job_id}/lyrics/corrections_updated.json"
storage = StorageService()
lines = []
if storage.file_exists(path):
for seg in storage.download_json(path).get("corrected_segments") or []:
lines.append({
"text": seg.get("text"),
"singer": seg.get("singer"),
"words": [
{"text": w.get("text"), "start_time": w.get("start_time"), "end_time": w.get("end_time")}
for w in seg.get("words") or []
],
})
return {
"status": getattr(job.status, "value", job.status),
"instrumental_selection": state.get("instrumental_selection"),
"is_duet": bool(state.get("is_duet", False)),
"lines": lines,
}
@router.get("/emails")
def emails(to: Optional[str] = None, limit: int = 20) -> Dict[str, Any]:
return {"emails": list_emails(to, limit=limit)}
+45 -9
View File
@@ -11,6 +11,7 @@ Handles:
import hashlib
import html
import logging
import re
import threading
from dataclasses import dataclass
from datetime import datetime, timezone
@@ -294,7 +295,7 @@ def send_magic_link(
# Board sign-in ("requests_board") is passwordless identity only: no welcome credit,
# and a HIGHER per-IP signup cap (BOARD_MAX_SIGNUPS_PER_IP) so a whole venue on shared
# WiFi can sign in to vote — but still a deterministic ceiling, not an open door.
is_board_signin = request.purpose == "requests_board"
is_board_signin = _is_board_purpose(request.purpose)
# Per-IP and per-fingerprint signup rate limit (only for new users)
device_fingerprint = request.device_fingerprint
@@ -404,16 +405,33 @@ def send_magic_link(
)
_BOARD_REQUEST_ID_RE = re.compile(r"[A-Za-z0-9_-]{4,64}")
def _is_board_purpose(purpose) -> bool:
""""requests_board", or "requests_board:<request_id>" (sign-in from a link to one
request, e.g. the YouTube comment bot's reply) — both are board identity-only."""
return isinstance(purpose, str) and (
purpose == "requests_board" or purpose.startswith("requests_board:")
)
def _magic_link_redirect_path(purpose) -> "Optional[str]":
"""Map a magic-link purpose to a post-login redirect path.
"requests_board" -> the voting board; "job_review:<job_id>" -> straight to
that job's lyrics review (used by outreach one-click links). Unknown or
malformed purposes fall through to None (frontend default: /app).
"requests_board" -> the voting board; "requests_board:<request_id>" -> the board
focused on that request, upvoting it on arrival; "job_review:<job_id>" ->
straight to that job's lyrics review (used by outreach one-click links).
Unknown or malformed purposes fall through to None (frontend default: /app).
"""
import re as _re
if purpose == "requests_board":
return "/requests"
if isinstance(purpose, str) and purpose.startswith("requests_board:"):
request_id = purpose.split(":", 1)[1]
if _BOARD_REQUEST_ID_RE.fullmatch(request_id):
return f"/requests?request={request_id}&upvote=1"
return "/requests"
if isinstance(purpose, str) and purpose.startswith("job_review:"):
job_id = purpose.split(":", 1)[1]
if _re.fullmatch(r"[A-Za-z0-9_-]{4,64}", job_id):
@@ -604,7 +622,7 @@ def verify_magic_link(
email_service=email_service,
is_first_login=is_first_login,
precomputed_eval=precomputed_eval,
grant_welcome_credit=magic_link_purpose != "requests_board" and not magic_link_tenant_id,
grant_welcome_credit=not _is_board_purpose(magic_link_purpose) and not magic_link_tenant_id,
referral_code=referral_code if not magic_link_tenant_id else None,
locale=locale if has_accept_language else None,
ui_locale=get_full_locale_from_request(http_request),
@@ -1581,11 +1599,14 @@ async def stripe_webhook(
if event_type == "checkout.session.completed":
session = event["data"]["object"]
session_id = session.get("id")
metadata = session.get("metadata", {})
metadata = session.get("metadata") or {}
customer_email = (
metadata.get("user_email")
or metadata.get("customer_email")
or session.get("customer_email", "")
or session.get("customer_email")
# Payment Link checkouts only carry the email here
or (session.get("customer_details") or {}).get("email")
or ""
)
# Idempotency check: Skip if this session was already processed
@@ -1602,7 +1623,22 @@ async def stripe_webhook(
return {"status": "received", "type": event_type, "note": "already_processed"}
# Check if this is a made-for-you order
if metadata.get("order_type") == "made_for_you":
if not StripeService.is_gen_checkout(session):
# Not created by gen (e.g. a Stripe Payment Link tip): nothing to
# fulfil, but the payment is still stored below for revenue.
logger.info(
f"non-gen checkout (payment link {session.get('payment_link') or 'none'}) "
f"session {session_id}: ${(session.get('amount_total') or 0) / 100:.2f}; "
f"recording payment only, no credits granted"
)
# Record the session so a redelivered event is skipped by the
# idempotency check (otherwise total_spent below double-counts).
user_service._mark_stripe_session_processed(
stripe_session_id=session_id,
email=customer_email,
amount=0,
)
elif metadata.get("order_type") == "made_for_you":
# Handle made-for-you order - create a job
await _handle_made_for_you_order(
session_id=session_id,
@@ -1651,7 +1687,7 @@ async def stripe_webhook(
logger.error(f"Failed to add credits: {credit_msg}")
# Update user's cached total_spent (non-blocking)
amount_total = session.get("amount_total", 0)
amount_total = session.get("amount_total") or 0
if amount_total > 0 and customer_email:
try:
from google.cloud.firestore_v1 import Increment
+30 -5
View File
@@ -228,7 +228,15 @@ class Settings(BaseSettings):
# When enabled AND enable_cloud_tasks is true, video worker uses Cloud Run Jobs
# instead of Cloud Tasks. This supports encoding times >30 minutes (up to 24 hours).
# Default is false - Cloud Tasks is sufficient for most videos (15-20 min).
use_cloud_run_jobs_for_video: bool = os.getenv("USE_CLOUD_RUN_JOBS_FOR_VIDEO", "false").lower() in ("true", "1", "yes")
# Inside a Cloud Run Job (Cloud Run sets CLOUD_RUN_JOB) both flags default to
# true: a worker job that triggers the next stage (audio worker resuming a
# parked encode, auto-approval starting a render) must never fall back to
# Cloud Tasks -> a BackgroundTask on the API service. That runs the whole
# video worker on the API's event loop (2026-10-19: 52s + 81s freezes,
# ~30 requests each). Explicit env values still win.
use_cloud_run_jobs_for_video: bool = os.getenv(
"USE_CLOUD_RUN_JOBS_FOR_VIDEO", "true" if os.getenv("CLOUD_RUN_JOB") else "false"
).lower() in ("true", "1", "yes")
# When enabled AND enable_cloud_tasks is true, the post-review render worker
# also runs as a Cloud Run Job (reusing video-encoding-job with an args
@@ -237,7 +245,9 @@ class Settings(BaseSettings):
# 10s after SIGTERM, far less than a render takes, so the job froze at
# rendering_video until the 45-min stuck-job sweep (incident 2026-09-13,
# job 41e06b90; same class as incident 2026-03-08 for the video worker).
use_cloud_run_jobs_for_render: bool = os.getenv("USE_CLOUD_RUN_JOBS_FOR_RENDER", "false").lower() in ("true", "1", "yes")
use_cloud_run_jobs_for_render: bool = os.getenv(
"USE_CLOUD_RUN_JOBS_FOR_RENDER", "true" if os.getenv("CLOUD_RUN_JOB") else "false"
).lower() in ("true", "1", "yes")
# GCE Encoding Worker (for high-performance video encoding)
# When enabled, video encoding is offloaded to a dedicated C4 GCE instance
@@ -332,6 +342,9 @@ class Settings(BaseSettings):
# for the karaoke-night "make it" flow. Every endpoint 503s while the secret is
# empty, so deploys are dark until it's wired (Secret Manager: kjbox-partner-secret).
kjbox_partner_secret: str = os.getenv("KJBOX_PARTNER_SECRET", "")
# karaoke-decide's own secret (header X-Partner-Secret) for POST /api/kjbox/catalog/resolve
# only (Secret Manager: decide-gen-partner-secret). Empty = decide is not accepted.
decide_partner_secret: str = os.getenv("DECIDE_GEN_PARTNER_SECRET", "")
# Partner-wide cap on NEW gen accounts created via kjbox per rolling 24h (a venue
# shares one IP, so gen's per-IP signup cap is bypassed for kjbox; this bounds it).
kjbox_signup_cap_per_24h: int = int(os.getenv("KJBOX_SIGNUP_CAP_PER_24H", "100"))
@@ -404,9 +417,10 @@ class Settings(BaseSettings):
# (scripts/youtube-descriptions). Keep those two in sync when editing this.
default_youtube_description: str = os.getenv(
"DEFAULT_YOUTUBE_DESCRIPTION",
'🎤 Sing along to "{title}" by {artist} — a high-quality karaoke version '
"using the original song audio with the lead vocals removed and scrolling "
"lyrics hand-synced to the music.\n\n"
'🎤 Karaoke version of "{title}" by {artist}: original audio, lead vocals '
"removed, hand-synced lyrics.\n"
"▶️ Make a karaoke video of ANY song: "
"https://nomadkaraoke.com/r/youtube?utm_source=youtube&utm_medium=description&utm_campaign=make_cta_top\n\n"
"⬆️ REQUEST THE NEXT NOMAD RELEASE\n"
"Vote for the songs you want us to make next — the most-upvoted requests get "
"made into karaoke videos and published free, right here on this channel. "
@@ -463,6 +477,17 @@ 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")
# YouTube comment auto-reply (backend/workers/youtube_comment_bot_worker.py):
# replies to song requests in channel comments with a requests-board link.
# OFF by default; go-live only after Andrew signs off a local replay
# (scripts/youtube-comments/replay.py). Dry runs work while off.
youtube_comment_autoreply_enabled: bool = os.getenv("YOUTUBE_COMMENT_AUTOREPLY_ENABLED", "false").lower() in ("true", "1", "yes")
youtube_comment_autoreply_max_replies: int = int(os.getenv("YOUTUBE_COMMENT_AUTOREPLY_MAX_REPLIES", "20"))
youtube_comment_autoreply_min_confidence: float = float(os.getenv("YOUTUBE_COMMENT_AUTOREPLY_MIN_CONFIDENCE", "0.8"))
# ISO date/time: on the FIRST run, comments since this are eligible (a one-time
# backfill of requests nobody answered). Empty = only comments after go-live.
youtube_comment_autoreply_start: str = os.getenv("YOUTUBE_COMMENT_AUTOREPLY_START", "")
# 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:
+5
View File
@@ -79,6 +79,11 @@ def validate_credentials_on_startup():
# readiness — a background thread alone would still race the first request.
_LAZY_ROUTE_IMPORTS = (
"httpx",
# Imported lazily by httpx / worker_service on first use; still froze the loop
# after the list above existed (httpcore ~1s; google.cloud.run_v2 14.9s with
# 7 requests in flight, 2026-10-16).
"httpcore",
"google.cloud.run_v2",
"backend.services.worker_service",
"backend.services.flacfetch_client",
"backend.services.catalog_proxy_service",
+6 -3
View File
@@ -13,6 +13,7 @@ The middleware is non-blocking - if no tenant is detected, the request
proceeds as a default Nomad Karaoke request (tenant_id = None).
"""
import asyncio
import logging
import os
from typing import Optional
@@ -36,8 +37,9 @@ IS_PRODUCTION = os.environ.get("ENV", "").lower() == "production" or \
bool(os.environ.get("K_SERVICE"))
# Known non-tenant subdomains that should be treated as default Nomad Karaoke
NON_TENANT_SUBDOMAINS = {"gen", "api", "www", "buy", "admin", "app", "beta"}
# Known non-tenant subdomains that should be treated as default Nomad Karaoke.
# Mirror of frontend/lib/edge/nonTenantSubdomains.ts ("requests" = voting-board host).
NON_TENANT_SUBDOMAINS = {"gen", "api", "www", "buy", "admin", "app", "beta", "requests"}
class TenantMiddleware(BaseHTTPMiddleware):
@@ -65,7 +67,8 @@ class TenantMiddleware(BaseHTTPMiddleware):
tenant_config: Optional[TenantConfig] = None
if tenant_id:
tenant_service = get_tenant_service()
tenant_config = tenant_service.get_tenant_config(tenant_id)
# get_tenant_config can hit GCS on a cache miss: keep it off the event loop.
tenant_config = await asyncio.to_thread(tenant_service.get_tenant_config, tenant_id)
if tenant_config and not tenant_config.is_active:
# Tenant exists but is inactive - treat as default
+16 -2
View File
@@ -24,8 +24,15 @@ RequestStatus = Literal[
]
# Where a request came from. Phase 2's trending-karaoke agent submits with
# source="trending_agent"; everything a human submits is "human".
RequestSource = Literal["human", "trending_agent"]
# source="trending_agent"; everything a human submits is "human"; the YouTube
# comment bot (backend/services/youtube_comment_bot.py) adds "youtube_comment".
RequestSource = Literal["human", "trending_agent", "youtube_comment"]
# submitted_by placeholder for requests the YouTube comment bot adds on a
# commenter's behalf (no email yet). The first real up-voter claims the request
# (becomes submitted_by); until then the daily picker skips it, so a free credit
# can never be granted to this address.
YOUTUBE_COMMENT_SUBMITTER = "youtube-comment@nomadkaraoke.com"
# Existing-community-version review state (set when the daily picker's KaraokeNerds
# check finds an existing community karaoke version for a would-be pick):
@@ -59,6 +66,13 @@ class SongRequest(BaseModel):
created_at: datetime = Field(default_factory=datetime.utcnow)
updated_at: datetime = Field(default_factory=datetime.utcnow)
# YouTube comment bot provenance (source="youtube_comment"): the comment that
# asked for the song, and the commenter's display name (audit only).
youtube_comment_id: Optional[str] = None
youtube_video_id: Optional[str] = None
youtube_author: Optional[str] = None
claimed_at: Optional[datetime] = None
# Phase-2 fields (never set in Phase 1).
job_id: Optional[str] = None
youtube_url: Optional[str] = None
+9
View File
@@ -19,6 +19,10 @@ import requests
logger = logging.getLogger(__name__)
# Discord message flag SUPPRESS_EMBEDS (1 << 2): no link-preview cards.
SUPPRESS_EMBEDS_FLAG = 4
class DiscordNotificationService:
"""
Service for sending Discord webhook notifications.
@@ -75,6 +79,7 @@ class DiscordNotificationService:
self,
message: str,
webhook_url: Optional[str] = None,
suppress_embeds: bool = False,
) -> bool:
"""
Post a message to a Discord channel via webhook.
@@ -82,6 +87,8 @@ class DiscordNotificationService:
Args:
message: The message content to post
webhook_url: Optional webhook URL (uses instance URL if not provided)
suppress_embeds: Send Discord's SUPPRESS_EMBEDS flag so URLs in the
text don't unfurl into link-preview cards (alerts)
Returns:
True if message was posted successfully, False otherwise
@@ -109,6 +116,8 @@ class DiscordNotificationService:
# trigger a Discord ping. (CWE-74 — output injection into a downstream
# component.)
data = {"content": message, "allowed_mentions": {"parse": []}}
if suppress_embeds:
data["flags"] = SUPPRESS_EMBEDS_FLAG
response = requests.post(url, json=data, timeout=30)
response.raise_for_status()
self.logger.info("Message posted to Discord successfully")
+25
View File
@@ -37,6 +37,8 @@ MAX_LOG_ENTRIES: int = 2000
MONITORED_CLOUD_RUN_SERVICES: list[str] = [
"karaoke-backend",
"karaoke-decide",
# karaoke-decide search service (offline song index + search API)
"karaoke-decide-search",
"audio-separator",
# Gen2 Cloud Functions appear as Cloud Run services in logs
"gdrive-validator",
@@ -57,6 +59,8 @@ MONITORED_CLOUD_RUN_JOBS: list[str] = [
"mb-refresh",
# karaoke-decide ListenBrainz statistics dump -> BigQuery refresh
"lb-refresh",
# karaoke-decide song search index build (eval-gated)
"song-index-build",
]
# Gen2 Cloud Functions log as cloud_run_revision, not cloud_function.
@@ -150,6 +154,18 @@ MAX_DISCORD_MESSAGES_PER_RUN: int = 10
#: Discord API hard limit on message length.
DISCORD_MAX_MESSAGE_LENGTH: int = 2000
#: Discord message flag SUPPRESS_EMBEDS (1 << 2). Set on every error-monitor
#: post so quoted URLs (GCP docs links) don't unfurl into large preview cards.
DISCORD_SUPPRESS_EMBEDS_FLAG: int = 4
#: When one run has MORE than this many new patterns for one service, send a
#: single burst summary instead of one message each (2026-10-07/08: one bad
#: mb-refresh run produced 73 "New Error Pattern" messages, 10 an hour).
BURST_COLLAPSE_MIN_PATTERNS: int = 3
#: Number of patterns listed in a burst summary.
BURST_TOP_PATTERNS: int = 5
# ---------------------------------------------------------------------------
# Pattern tracking settings
# ---------------------------------------------------------------------------
@@ -178,6 +194,15 @@ def get_discord_webhook_secret_name() -> str:
return os.environ.get("DISCORD_WEBHOOK_SECRET_NAME", "error-monitor-discord-webhook")
def get_discord_noise_webhook_secret_name() -> str:
"""Return the Secret Manager secret name for the #noise Discord webhook.
#alerts is reserved for real problems (new patterns, spikes, incidents);
informational posts (auto-resolved summaries, the daily digest) go to #noise.
"""
return os.environ.get("DISCORD_NOISE_WEBHOOK_SECRET_NAME", "discord-noise-webhook")
def get_digest_mode() -> bool:
"""Return True if the monitor should run in digest mode (batch alerts instead of immediate).
+112 -21
View File
@@ -14,9 +14,12 @@ Usage:
format_daily_digest,
)
discord = ErrorMonitorDiscord(webhook_url="https://discord.com/api/webhooks/...")
msg = format_new_pattern_alert(...)
discord.send_message(msg)
discord = ErrorMonitorDiscord(
webhook_url="https://discord.com/api/webhooks/...", # #alerts
noise_webhook_url="https://discord.com/api/webhooks/...", # #noise
)
discord.send_message(format_new_pattern_alert(...)) # a real problem
discord.send_noise_message(format_auto_resolved_alert(...)) # informational
"""
import logging
@@ -26,7 +29,9 @@ from zoneinfo import ZoneInfo
import requests
from backend.services.error_monitor.config import (
BURST_TOP_PATTERNS,
DISCORD_MAX_MESSAGE_LENGTH,
DISCORD_SUPPRESS_EMBEDS_FLAG,
MAX_DISCORD_MESSAGES_PER_RUN,
)
@@ -106,6 +111,47 @@ def format_new_pattern_alert(
return _truncate("\n".join(lines))
def format_pattern_burst_alert(service: str, patterns: list[dict]) -> str:
"""Format ONE Discord alert for a burst of new patterns from one service.
One root cause (a bad run, a schema change) often produces dozens of
distinct messages, e.g. one per table. Listing them one message each buried
#alerts, so they collapse into a summary with the top patterns by count and
a pointer to the full list.
Args:
service: The service all the patterns came from.
patterns: Dicts with keys normalized_message, count, first_seen, last_seen.
Returns:
Formatted Discord message string, truncated to 2000 chars.
"""
ranked = sorted(patterns, key=lambda p: p.get("count") or 0, reverse=True)
total = sum(int(p.get("count") or 0) for p in patterns)
first = min((p["first_seen"] for p in patterns if p.get("first_seen")), default="?")
last = max((p["last_seen"] for p in patterns if p.get("last_seen")), default="?")
lines = [
f"🔴 **{len(patterns)} new error patterns from {service}** (one burst, {total} occurrences)",
"",
f"**Service:** {service}",
f"**First seen:** {first}",
f"**Last seen:** {last}",
f"**Alerted at:** {_now_eastern()}",
"",
f"**Top {min(BURST_TOP_PATTERNS, len(ranked))} by count:**",
]
for p in ranked[:BURST_TOP_PATTERNS]:
msg = (p.get("normalized_message") or "").splitlines()[0][:150] if p.get("normalized_message") else ""
lines.append(f"• `{msg}` ×{p.get('count', 0)}")
if len(ranked) > BURST_TOP_PATTERNS:
lines.append(f"…and {len(ranked) - BURST_TOP_PATTERNS} more")
lines += [
"",
f"All patterns: `python scripts/query-error-patterns.py --service {service} --status new`",
]
return _truncate("\n".join(lines))
def format_incident_alert(
title: str,
severity: str,
@@ -272,22 +318,50 @@ def format_daily_digest(
class ErrorMonitorDiscord:
"""Webhook client for sending error monitor alerts to Discord.
"""Webhook client for sending error monitor messages to Discord.
Enforces a per-run rate limit of MAX_DISCORD_MESSAGES_PER_RUN to avoid
flooding the channel during high-volume incident windows.
Two channels:
* **#alerts** (``webhook_url``, :meth:`send_message`) — signal only: real
problems someone should look at (new patterns, spikes, incidents).
* **#noise** (``noise_webhook_url``, :meth:`send_noise_message`) —
informational posts (auto-resolved summaries, daily digest). If no noise
webhook is configured, or a noise post fails, the message falls back to
the alert webhook so it is never silently dropped.
Each channel has its own per-run rate limit of MAX_DISCORD_MESSAGES_PER_RUN,
so noise can never eat the alert budget during an incident window.
Attributes:
webhook_url: The Discord incoming webhook URL.
messages_sent: Counter of messages attempted this run (success or failure).
webhook_url: The #alerts Discord incoming webhook URL.
noise_webhook_url: The #noise webhook URL (None → use webhook_url).
messages_sent: #alerts messages attempted this run (success or failure).
noise_messages_sent: #noise messages attempted this run.
"""
def __init__(self, webhook_url: str) -> None:
def __init__(self, webhook_url: str, noise_webhook_url: str | None = None) -> None:
self.webhook_url = webhook_url
self.noise_webhook_url = noise_webhook_url
self.messages_sent: int = 0
self.noise_messages_sent: int = 0
@staticmethod
def _post(url: str, content: str) -> bool:
try:
response = requests.post(
url,
json={"content": content, "flags": DISCORD_SUPPRESS_EMBEDS_FLAG},
timeout=30,
)
response.raise_for_status()
logger.debug("Discord message sent successfully.")
return True
except Exception as exc:
logger.error("Failed to send Discord message: %s", exc)
return False
def send_message(self, content: str) -> bool:
"""Send a message to the configured Discord webhook.
"""Send a message to the #alerts webhook (real problems only).
Rate-limits: if messages_sent >= MAX_DISCORD_MESSAGES_PER_RUN, the
message is silently skipped and False is returned without incrementing
@@ -308,16 +382,33 @@ class ErrorMonitorDiscord:
return False
try:
response = requests.post(
self.webhook_url,
json={"content": content},
timeout=30,
)
response.raise_for_status()
logger.debug("Discord message sent successfully.")
return True
except Exception as exc:
logger.error("Failed to send Discord message: %s", exc)
return False
return self._post(self.webhook_url, content)
finally:
self.messages_sent += 1
def send_noise_message(self, content: str) -> bool:
"""Send an informational message to the #noise webhook.
Falls back to the #alerts webhook if no noise webhook is configured or
the noise post fails. Rate-limited separately from :meth:`send_message`.
Returns:
True if the message was delivered to either channel.
"""
if self.noise_messages_sent >= MAX_DISCORD_MESSAGES_PER_RUN:
logger.warning(
"Discord noise rate limit reached (%d messages sent this run); skipping message.",
self.noise_messages_sent,
)
return False
try:
noise_url = self.noise_webhook_url or self.webhook_url
if self._post(noise_url, content):
return True
if noise_url != self.webhook_url:
logger.warning("Noise webhook post failed; falling back to the alert webhook.")
return self._post(self.webhook_url, content)
return False
finally:
self.noise_messages_sent += 1
@@ -38,6 +38,9 @@ class PatternData:
sample_message: str
count: int
timestamp: datetime
# Hold the alert until more than this many occurrences land within one hour
# (see is_below_alert_threshold). None = alert on first sight, as usual.
alert_min_hourly_count: int | None = None
@dataclass
@@ -72,6 +75,33 @@ def _utcnow() -> datetime:
return datetime.now(tz=timezone.utc)
def is_below_alert_threshold(pattern: dict, now: datetime | None = None) -> bool:
"""True if a gated pattern hasn't (yet) earned an alert.
A pattern with ``alert_min_hourly_count`` (frontend chunk-load failures)
alerts only once MORE than that many occurrences land within the last hour,
counted from ``rolling_counts``. Until then it stays ``new`` with
``alerted_at=None`` so a later burst can still fire. Ungated patterns are
never held.
"""
threshold = pattern.get("alert_min_hourly_count")
if threshold is None:
return False
now = now or _utcnow()
cutoff = now - timedelta(hours=1)
recent = 0
for entry in pattern.get("rolling_counts") or []:
try:
ts = datetime.fromisoformat(entry["ts"])
except (KeyError, TypeError, ValueError):
continue
if ts.tzinfo is None:
ts = ts.replace(tzinfo=timezone.utc)
if ts >= cutoff:
recent += int(entry.get("count") or 0)
return recent <= threshold
def _iso(dt: datetime) -> str:
"""Serialise a datetime to ISO-8601 string."""
return dt.isoformat()
@@ -181,24 +211,25 @@ class ErrorPatternsAdapter:
if not snap.exists:
# ── brand new pattern ──────────────────────────────────────────
doc_ref.set(
{
"pattern_id": data.pattern_id,
"service": data.service,
"resource_type": data.resource_type,
"normalized_message": data.normalized_message,
"sample_message": data.sample_message,
"status": "new",
"severity": "P3",
"total_count": data.count,
"rolling_counts": [new_rolling_entry],
"first_seen": ts_iso,
"last_seen": ts_iso,
"alerted_at": None,
"created_at": ts_iso,
"updated_at": ts_iso,
}
)
doc = {
"pattern_id": data.pattern_id,
"service": data.service,
"resource_type": data.resource_type,
"normalized_message": data.normalized_message,
"sample_message": data.sample_message,
"status": "new",
"severity": "P3",
"total_count": data.count,
"rolling_counts": [new_rolling_entry],
"first_seen": ts_iso,
"last_seen": ts_iso,
"alerted_at": None,
"created_at": ts_iso,
"updated_at": ts_iso,
}
if data.alert_min_hourly_count is not None:
doc["alert_min_hourly_count"] = data.alert_min_hourly_count
doc_ref.set(doc)
return UpsertResult(pattern_id=data.pattern_id, is_new=True)
# ── existing pattern ───────────────────────────────────────────────
@@ -216,6 +247,8 @@ class ErrorPatternsAdapter:
"sample_message": data.sample_message,
"updated_at": ts_iso,
}
if data.alert_min_hourly_count is not None:
update["alert_min_hourly_count"] = data.alert_min_hourly_count
# Reactivation: pattern was considered resolved/fixed but error recurred
is_new = False
@@ -74,6 +74,23 @@ def is_opaque_script_error(message: str | None, source: str | None = None, extra
return not extra.get("filename") and not extra.get("lineno")
# A chunk-load failure is a tab running an old build after a deploy: the client
# auto-reloads (frontend/lib/version-check.ts), so one report is not actionable.
# Mirrors isChunkLoadError() there. Reports collapse into one pattern per build
# that alerts only above CHUNK_LOAD_ALERT_PER_HOUR in an hour (a broken deploy).
_CHUNK_LOAD_RE = re.compile(
r"ChunkLoadError|Loading chunk [\w-]+ failed|Failed to load chunk"
r"|Failed to fetch dynamically imported module|Importing a module script failed",
re.IGNORECASE,
)
CHUNK_LOAD_ALERT_PER_HOUR = 10
def is_chunk_load_error(message: str | None) -> bool:
"""True for the bundler's "couldn't load a JS chunk" errors."""
return bool(message) and bool(_CHUNK_LOAD_RE.search(message))
@dataclass
class FrontendErrorReport:
"""In-memory representation of an inbound crash report."""
@@ -118,6 +135,13 @@ def _stack_for_hashing(report: FrontendErrorReport) -> str:
Error object, e.g. Firefox "out of memory") hash on message + location.
"""
if report.stack:
# Safari/Firefox stacks are bare frames ("@https://…:1:5749") with no
# "Name: message" header, so without the message every error thrown from
# one frame shares a pattern named after the URL. Chrome stacks already
# start with the message (their hash is unchanged).
message = (report.message or "").strip()
if message and not report.stack.lstrip().startswith(message):
return f"{message}\n{report.stack}"
return report.stack
location = _error_location(report.extra)
if location:
@@ -153,8 +177,16 @@ def build_pattern_data(
if now is None:
now = datetime.now(tz=timezone.utc)
raw = _stack_for_hashing(report)
normalized = normalize_message(raw)
chunk_load = is_chunk_load_error(report.message)
if chunk_load:
# One pattern per build: chunk names, module ids and stacks vary per
# report but share one cause (that build's chunks are gone or broken).
normalized = (
f"Failed to load JS chunk on build {report.release or 'unknown'} "
f"(client auto-reloads; alerts above {CHUNK_LOAD_ALERT_PER_HOUR}/hour)"
)
else:
normalized = normalize_message(_stack_for_hashing(report))
pattern_id = compute_pattern_hash("frontend", normalized)
# sample_message is human-readable context. Keep the error message plus a
@@ -192,6 +224,7 @@ def build_pattern_data(
sample_message=sample_message,
count=1,
timestamp=now,
alert_min_hourly_count=CHUNK_LOAD_ALERT_PER_HOUR if chunk_load else None,
)
+23 -2
View File
@@ -109,11 +109,28 @@ _IGNORE_PATTERNS: list[tuple[str, re.Pattern, str]] = [
]
# Patterns that are noise only for specific services: the same message from a
# customer-facing service is a real problem. (pattern_name, services, regex, reason)
_SERVICE_IGNORE_PATTERNS: list[tuple[str, frozenset[str], re.Pattern, str]] = [
(
"runner_manager_no_available_instance",
frozenset({"github-runner-manager"}),
re.compile(
r"request was aborted because there was no available instance",
re.IGNORECASE,
),
"github-runner-manager scale-up burst: Cloud Run aborts webhook requests "
"while instances start, GitHub redelivers and the runners still dispatch "
"(seen 2026-09-20, 09-23, 09-27, 10-08)",
),
]
def should_ignore(service: str, message: str) -> IgnoreReason | None:
"""Check whether a log entry matches a known infrastructure noise pattern.
The check is purely message-based; ``service`` is accepted for API symmetry
and future service-specific overrides but does not gate any pattern today.
``_IGNORE_PATTERNS`` match on the message alone; ``_SERVICE_IGNORE_PATTERNS``
also require ``service`` to be one of the listed services.
Args:
service: The originating service name (e.g. ``"karaoke-backend"``).
@@ -130,4 +147,8 @@ def should_ignore(service: str, message: str) -> IgnoreReason | None:
if pattern.search(message):
return IgnoreReason(pattern_name=pattern_name, reason=reason)
for pattern_name, services, pattern, reason in _SERVICE_IGNORE_PATTERNS:
if service in services and pattern.search(message):
return IgnoreReason(pattern_name=pattern_name, reason=reason)
return None
+106 -25
View File
@@ -22,6 +22,7 @@ from google.cloud import logging as cloud_logging
from google.cloud import secretmanager
from backend.services.error_monitor.config import (
BURST_COLLAPSE_MIN_PATTERNS,
GCP_PROJECT,
LEGACY_ROLLING_WINDOW_MINUTES,
LOOKBACK_MINUTES,
@@ -33,6 +34,7 @@ from backend.services.error_monitor.config import (
SPIKE_MIN_COUNT,
SPIKE_MULTIPLIER,
get_digest_mode,
get_discord_noise_webhook_secret_name,
get_discord_webhook_secret_name,
get_llm_enabled,
)
@@ -42,12 +44,14 @@ from backend.services.error_monitor.discord import (
format_daily_digest,
format_incident_alert,
format_new_pattern_alert,
format_pattern_burst_alert,
format_spike_alert,
)
from backend.services.error_monitor.firestore_adapter import (
ErrorPatternsAdapter,
PatternData,
UpsertResult,
is_below_alert_threshold,
)
from backend.services.error_monitor.known_issues import should_ignore
from backend.services.error_monitor.llm_analysis import analyze_patterns, find_duplicate_patterns
@@ -279,7 +283,11 @@ class ErrorMonitor:
def __init__(self) -> None:
self.logging_client = cloud_logging.Client(project=GCP_PROJECT)
self.firestore_adapter = ErrorPatternsAdapter()
self.discord = ErrorMonitorDiscord(webhook_url=self._get_discord_webhook())
alert_webhook = self._get_discord_webhook()
self.discord = ErrorMonitorDiscord(
webhook_url=alert_webhook,
noise_webhook_url=self._get_discord_noise_webhook(alert_webhook),
)
def _get_discord_webhook(self) -> str:
"""Retrieve the Discord webhook URL.
@@ -300,6 +308,33 @@ class ErrorMonitor:
response = client.access_secret_version(name=secret_path)
return response.payload.data.decode("utf-8").strip()
def _get_discord_noise_webhook(self, alert_webhook: str) -> str:
"""Retrieve the #noise Discord webhook URL (informational posts).
``DISCORD_NOISE_WEBHOOK_URL`` env var first, then the Secret Manager
secret ``discord-noise-webhook`` (override the name with
``DISCORD_NOISE_WEBHOOK_SECRET_NAME``). If neither yields a URL, falls
back to ``alert_webhook`` so informational posts are never dropped.
"""
url = (os.environ.get("DISCORD_NOISE_WEBHOOK_URL") or "").strip()
if url:
return url
secret_name = get_discord_noise_webhook_secret_name()
try:
client = secretmanager.SecretManagerServiceClient()
secret_path = f"projects/{GCP_PROJECT}/secrets/{secret_name}/versions/latest"
response = client.access_secret_version(name=secret_path)
url = response.payload.data.decode("utf-8").strip()
except Exception as exc: # noqa: BLE001 - noise channel is optional
logger.warning(
"Could not read %s (%s); informational posts will go to the alert webhook",
secret_name,
exc,
)
return alert_webhook
return url or alert_webhook
# ------------------------------------------------------------------
# Main entry point
# ------------------------------------------------------------------
@@ -414,6 +449,11 @@ class ErrorMonitor:
pid = pattern.get("pattern_id")
if not pid or pid in groups:
continue
if is_below_alert_threshold(pattern, now):
# Gated pattern (e.g. frontend chunk-load failures, which the
# client auto-reloads) that hasn't hit its hourly threshold yet.
# Left unalerted so a later burst still fires.
continue
groups[pid] = {
"service": pattern.get("service", "unknown"),
"resource_type": pattern.get("resource_type", "unknown"),
@@ -536,31 +576,25 @@ class ErrorMonitor:
incident_pattern_ids.update(incident_pids)
# ── Step 6: Individual alerts for new patterns not in incidents ────
# ── Step 6: Alerts for new patterns not in incidents ───────────────
# One root cause often emits many distinct messages (one per table,
# file, step). More than BURST_COLLAPSE_MIN_PATTERNS from one service
# in a run → ONE burst summary; otherwise one alert per pattern. Every
# send still goes through the per-run cap in ErrorMonitorDiscord;
# unsent patterns stay unalerted and are picked up again (and collapse
# with that service's other leftovers) next run.
by_service: dict[str, list[str]] = {}
for pattern_id in new_pattern_ids:
if pattern_id in incident_pattern_ids:
if pattern_id in incident_pattern_ids or pattern_id not in groups:
continue
if pattern_id not in groups:
continue
group = groups[pattern_id]
by_service.setdefault(groups[pattern_id]["service"], []).append(pattern_id)
# Fetch fresh copy to get first_seen timestamp
existing = self.firestore_adapter.get_pattern(pattern_id)
first_seen = existing.get("first_seen", now_iso) if existing else now_iso
msg = format_new_pattern_alert(
service=group["service"],
resource_type=group["resource_type"],
normalized_message=group["normalized"],
sample_message=group["sample_message"],
count=group["count"],
first_seen=first_seen,
)
if self.discord.send_message(msg):
try:
self.firestore_adapter.update_pattern_alerted(pattern_id)
except Exception as exc: # noqa: BLE001
logger.warning("Could not update alerted_at for %s: %s", pattern_id, exc)
for service, pids in by_service.items():
if len(pids) > BURST_COLLAPSE_MIN_PATTERNS:
self._send_burst_alert(service, pids, groups, now_iso)
else:
for pattern_id in pids:
self._send_new_pattern_alert(pattern_id, groups[pattern_id], now_iso)
# ── Step 7: Spike alerts ───────────────────────────────────────────
for spike in spike_patterns:
@@ -575,6 +609,51 @@ class ErrorMonitor:
# ── Step 8: Auto-resolve check ─────────────────────────────────────
self._check_auto_resolve()
# ------------------------------------------------------------------
# New-pattern alert helpers
# ------------------------------------------------------------------
def _mark_alerted(self, pattern_ids: list[str]) -> None:
for pid in pattern_ids:
try:
self.firestore_adapter.update_pattern_alerted(pid)
except Exception as exc: # noqa: BLE001
logger.warning("Could not update alerted_at for %s: %s", pid, exc)
def _send_new_pattern_alert(self, pattern_id: str, group: dict, now_iso: str) -> None:
# Fetch fresh copy to get first_seen timestamp
existing = self.firestore_adapter.get_pattern(pattern_id)
first_seen = existing.get("first_seen", now_iso) if existing else now_iso
msg = format_new_pattern_alert(
service=group["service"],
resource_type=group["resource_type"],
normalized_message=group["normalized"],
sample_message=group["sample_message"],
count=group["count"],
first_seen=first_seen,
)
if self.discord.send_message(msg):
self._mark_alerted([pattern_id])
def _send_burst_alert(
self, service: str, pattern_ids: list[str], groups: dict, now_iso: str
) -> None:
patterns = []
for pid in pattern_ids:
existing = self.firestore_adapter.get_pattern(pid) or {}
patterns.append(
{
"normalized_message": groups[pid]["normalized"],
"count": groups[pid]["count"],
"first_seen": existing.get("first_seen", now_iso),
"last_seen": existing.get("last_seen", now_iso),
}
)
logger.info("Collapsing %d new %s patterns into one burst alert", len(pattern_ids), service)
if self.discord.send_message(format_pattern_burst_alert(service, patterns)):
self._mark_alerted(pattern_ids)
# ------------------------------------------------------------------
# Auto-resolve helper
# ------------------------------------------------------------------
@@ -601,8 +680,9 @@ class ErrorMonitor:
)
if resolved:
# Good news, not a problem → #noise (keeps #alerts pure signal).
msg = format_auto_resolved_alert(resolved)
self.discord.send_message(msg)
self.discord.send_noise_message(msg)
# ------------------------------------------------------------------
# Daily digest
@@ -659,7 +739,8 @@ class ErrorMonitor:
active_patterns=len(active_patterns),
per_service_counts=per_service_counts,
)
self.discord.send_message(msg)
# Informational summary → #noise.
self.discord.send_noise_message(msg)
# ---------------------------------------------------------------------------
+7 -1
View File
@@ -102,7 +102,13 @@ _NORMALIZERS: list[tuple[re.Pattern, str]] = [
re.compile(r"\b(?=[a-fA-F0-9]*[a-fA-F][a-fA-F0-9]*\d|[a-fA-F0-9]*\d[a-fA-F0-9]*[a-fA-F])[a-fA-F0-9]{8,}\b"),
"<ID>",
),
# 12. Large numbers (4+ digits) — must come after epoch/IP/UUID replacements
# 12. Request counts in loop-stall lines (EVENT_LOOP_STALL ... requests_affected=29):
# small numbers that would otherwise make every stall a "new" pattern.
(
re.compile(r"\brequests_affected=\d+"),
"requests_affected=<N>",
),
# 13. Large numbers (4+ digits) — must come after epoch/IP/UUID replacements
(
re.compile(r"\b\d{4,}\b"),
"<NUM>",
+71
View File
@@ -18,6 +18,18 @@ CONFIG_DOC = "fake_config"
WORKER_KINDS = ("audio_download", "audio", "lyrics", "screens", "render_video", "video")
# Values of ``search_confidence`` (fake search shapes → UI tier 1 / 2 / 3).
SEARCH_CONFIDENCES = ("perfect", "recommended", "unsure")
# Values of ``judge_kind`` (the fake match judge / free-text resolve verdict kind).
JUDGE_KINDS = ("none", "cosmetic", "content", "ambiguous")
LARGE_FIXTURE_MIN_SECONDS = 305
# Values of ``review_fixture`` (the shape of the fake lyrics the review UI opens on).
REVIEW_FIXTURES = ("default", "corrections", "duet", "rtl", "large")
# Values of ``backing_vocals`` (silent stem vs one with an audible 10-20 s window).
BACKING_VOCALS = ("silent", "audible")
# Values of ``review_mode`` (what the seeded job asks for) and ``auto_approval``
# (which stored auto-approval verdict the fake screens worker writes).
REVIEW_MODES = ("always_review", "auto")
AUTO_APPROVALS = ("none", "lyrics_confident", "backing_confident", "both_unsure")
@dataclass
@@ -44,6 +56,30 @@ class FakeConfig:
# True: the fake video worker sets state_data.youtube_url (FAKE_YOUTUBE_URL) for
# non-private jobs, like a real YouTube upload. False: tests the "no link" path.
youtube_url_enabled: bool = True
# Fake match judge (POST /api/catalog/match-judge, per-user config) and fake free-text
# resolve (POST /api/kjbox/catalog/resolve, global config: partners have no user).
# judge_kind picks the verdict kind; the canonical values fill it in (defaults if empty).
judge_kind: str = "none"
judge_canonical_artist: str = ""
judge_canonical_title: str = ""
# Review-UI fixtures (per-user, for the mobile review Maestro flows). Defaults keep
# today's behaviour. See docs/TESTING.md § Local stack.
# Shape of the fake lyrics: default | corrections | duet | rtl | large.
review_fixture: str = "default"
# silent: the backing stem is silence (analysis recommends clean). audible: a tone in
# the 10-20 s window, so the analysis recommends with_backing / review.
backing_vocals: str = "silent"
# The fake audio worker uploads its stems this many seconds after it starts, so the
# job reaches awaiting_review first (instrumental-urls audio_complete is false until then).
stems_delay_seconds: float = 0
# What the job scenario asks for: always_review (every screen) or auto (a confident
# stored verdict lets the UI skip a screen).
review_mode: str = "always_review"
# Stored processing_metadata.auto_approval verdict written when the job parks at
# awaiting_review: none | lyrics_confident | backing_confident | both_unsure.
auto_approval: str = "none"
# True: the next POST /api/review/{id}/complete answers 503 once, then this resets to False.
review_complete_fail_once: bool = False
@classmethod
def from_dict(cls, data: Optional[Dict[str, Any]]) -> "FakeConfig":
@@ -64,6 +100,29 @@ class FakeConfig:
raise ValueError("search_result_count must be between 0 and 3")
if self.search_confidence not in SEARCH_CONFIDENCES:
raise ValueError(f"search_confidence must be one of {SEARCH_CONFIDENCES}")
if self.judge_kind not in JUDGE_KINDS:
raise ValueError(f"judge_kind must be one of {JUDGE_KINDS}")
if not isinstance(self.judge_canonical_artist, str) or not isinstance(self.judge_canonical_title, str):
raise ValueError("judge_canonical_artist and judge_canonical_title must be strings")
if self.review_fixture not in REVIEW_FIXTURES:
raise ValueError(f"review_fixture must be one of {REVIEW_FIXTURES}")
if self.review_fixture == "large" and self.audio_duration_seconds < LARGE_FIXTURE_MIN_SECONDS:
# 300 lines at >= 1 s each: shorter audio leaves most lyrics past the end of the song.
raise ValueError(f"review_fixture 'large' needs audio_duration_seconds >= {LARGE_FIXTURE_MIN_SECONDS}")
if self.backing_vocals not in BACKING_VOCALS:
raise ValueError(f"backing_vocals must be one of {BACKING_VOCALS}")
if (
isinstance(self.stems_delay_seconds, bool)
or not isinstance(self.stems_delay_seconds, (int, float))
or not 0 <= self.stems_delay_seconds <= 600
):
raise ValueError("stems_delay_seconds must be a number between 0 and 600")
if self.review_mode not in REVIEW_MODES:
raise ValueError(f"review_mode must be one of {REVIEW_MODES}")
if self.auto_approval not in AUTO_APPROVALS:
raise ValueError(f"auto_approval must be one of {AUTO_APPROVALS}")
if not isinstance(self.review_complete_fail_once, bool):
raise ValueError("review_complete_fail_once must be a boolean")
USER_CONFIG_COLLECTION = "local_stack_user_config"
@@ -124,3 +183,15 @@ def clear_fake_config(db=None) -> None:
_doc(db).delete()
for snap in db.collection(USER_CONFIG_COLLECTION).stream():
snap.reference.delete()
def consume_review_complete_failure(email: Optional[str] = None, db=None) -> bool:
"""True once when ``review_complete_fail_once`` is set for ``email``, then clear it.
Backs the one-shot 503 on ``POST /api/review/{id}/complete`` (finish-step failure/retry flows).
"""
db = db or _default_db()
if not get_fake_config(db, email=email).review_complete_fail_once:
return False
set_fake_config({"review_complete_fail_once": False}, db=db, email=email)
return True
+54
View File
@@ -0,0 +1,54 @@
"""Scripted match-judge / free-text-resolve verdicts for the local E2E stack (never calls Gemini).
``POST /api/catalog/match-judge`` uses the signed-in user's fake config (``email``);
``POST /api/kjbox/catalog/resolve`` is called by partners with no user, so it reads the
GLOBAL config. Knobs: ``judge_kind`` / ``judge_canonical_artist`` / ``judge_canonical_title``
(see config.py and docs/TESTING.md § Local stack).
"""
from __future__ import annotations
from typing import Optional
from backend.services.fake_workers.config import FakeConfig, get_fake_config
from backend.services.match_judge.verdict import KIND_AMBIGUOUS, KIND_NONE, MatchVerdict
DEFAULT_ARTIST = "Fake Artist"
DEFAULT_TITLE = "Fake Title"
def _canonical(cfg: FakeConfig) -> tuple:
return cfg.judge_canonical_artist or DEFAULT_ARTIST, cfg.judge_canonical_title or DEFAULT_TITLE
def verdict_for(cfg: FakeConfig, artist: str, title: str) -> MatchVerdict:
kind = cfg.judge_kind
if kind == KIND_NONE:
return MatchVerdict(KIND_NONE, False, artist, title, engine="ai", reason="fake: none")
ca, ct = _canonical(cfg)
alternatives = []
if kind == KIND_AMBIGUOUS:
alternatives = [{"artist": ca, "title": ct}, {"artist": ca, "title": f"{ct} (Live)"}]
return MatchVerdict(
kind, kind != KIND_AMBIGUOUS, ca, ct, alternatives=alternatives,
engine="ai", reason=f"fake: {kind}",
)
def fake_match_verdict(artist: str, title: str, email: Optional[str] = None, stage: str = "full") -> MatchVerdict:
"""Fake ``judge_match`` verdict from ``email``'s (else global) fake config.
Like the real judge, the ``fast`` (catalog-only) pass only ever settles a tidy (``cosmetic``) or "already
right" (``none``); a ``content`` or ``ambiguous`` verdict is an AI answer, so ``fast`` returns the
``needs_ai`` marker and the client makes the ``full`` call that carries it.
"""
cfg = get_fake_config(email=email)
if stage == "fast" and cfg.judge_kind not in (KIND_NONE, "cosmetic"):
return MatchVerdict(KIND_NONE, False, artist, title, engine="catalog", reason="fake: needs ai", needs_ai=True)
return verdict_for(cfg, artist, title)
def fake_resolve(query: str) -> dict:
"""Fake ``resolve_and_tidy`` response (verdict + typed_artist/typed_title) from the GLOBAL config."""
v = verdict_for(get_fake_config(), "", "").to_dict()
v.pop("needs_ai") # not part of the resolve response shape
return {**v, "typed_artist": "", "typed_title": query}
+206 -12
View File
@@ -6,7 +6,7 @@ anything ``from_dict`` can no longer read).
"""
from __future__ import annotations
from typing import Any, Dict, List
from typing import Any, Dict, List, Optional, Sequence
from karaoke_gen.lyrics_transcriber.types import (
AnchorSequence,
@@ -29,22 +29,65 @@ FAKE_LINES = (
REFERENCE_SOURCE = "lrclib"
LEAD_IN_SECONDS = 2.0
# Right-to-left fixture: Hebrew lines, one of them also carrying Arabic (mixed-script bidi).
RTL_LINES = (
"שיר בדיקה קטן",
"כל מילה מגיעה בזמן",
"שרים יחד עם המערכת המקומית",
"שום דבר כאן לא תומלל أغنية للاختبار",
"העובדים מעמידים פנים והעבודות ממשיכות",
"עד שהסרטון מוכן",
)
def _segments(prefix: str, duration: float) -> List[LyricsSegment]:
"""Spread FAKE_LINES evenly over the song, one word slot per word."""
usable = max(duration - LEAD_IN_SECONDS - 1.0, len(FAKE_LINES))
line_len = usable / len(FAKE_LINES)
# Duet fixture: per-line singer ids cycle 1, 2, 0 (0 = both).
DUET_SINGERS = (1, 2, 0)
LARGE_LINE_COUNT = 300
_LARGE_VOCAB = (
"sing", "along", "with", "the", "local", "stack", "every", "word", "arrives",
"right", "on", "time", "fake", "song", "for", "testing", "workers", "pretend",
)
# The corrections fixture holds one word for longer than the UI's "long word" threshold.
LONG_WORD_SECONDS = 2.2
# A line the transcription missed, only present in the synced reference (the vocal gap).
MISSED_REFERENCE_LINE = "Thanks for singing along tonight"
def _large_lines() -> List[str]:
lines = []
for i in range(LARGE_LINE_COUNT):
count = 6 + (i % 3) # 6-8 words, 7 on average -> 2,100 words
words = [_LARGE_VOCAB[(i * 5 + j) % len(_LARGE_VOCAB)] for j in range(count)]
lines.append(" ".join(words).capitalize())
return lines
def _lines_for(fixture: str) -> Sequence[str]:
if fixture == "rtl":
return RTL_LINES
if fixture == "large":
return _large_lines()
return FAKE_LINES
def _segments(prefix: str, duration: float, lines: Sequence[str] = FAKE_LINES,
singers: Optional[Sequence[int]] = None) -> List[LyricsSegment]:
"""Spread ``lines`` evenly over the song, one word slot per word."""
usable = max(duration - LEAD_IN_SECONDS - 1.0, len(lines))
line_len = usable / len(lines)
segments = []
for i, line in enumerate(FAKE_LINES):
for i, line in enumerate(lines):
words_text = line.split()
start = LEAD_IN_SECONDS + i * line_len
slot = (line_len * 0.9) / len(words_text)
gap = min(0.05, slot * 0.1)
words = [
Word(
id=f"{prefix}w{i}_{j}",
text=text,
start_time=round(start + j * slot, 3),
end_time=round(start + (j + 1) * slot - 0.05, 3),
end_time=round(start + (j + 1) * slot - gap, 3),
confidence=0.99,
)
for j, text in enumerate(words_text)
@@ -56,15 +99,25 @@ def _segments(prefix: str, duration: float) -> List[LyricsSegment]:
words=words,
start_time=words[0].start_time,
end_time=words[-1].end_time,
singer=singers[i % len(singers)] if singers else None,
)
)
return segments
def build_corrections(artist: str, title: str, duration: float) -> Dict[str, Any]:
"""Return a ``CorrectionResult.to_dict()`` whose transcription matches its reference."""
transcribed = _segments("t", duration)
reference = _segments("r", duration)
def build_corrections(artist: str, title: str, duration: float, fixture: str = "default") -> Dict[str, Any]:
"""Return a ``CorrectionResult.to_dict()`` whose transcription matches its reference.
``fixture`` picks the lyrics shape (see ``FakeConfig.review_fixture``). Everything but
``corrections`` is built straight from the real dataclasses; ``corrections`` then edits
the dict into the post-AI-apply state gen's server-side pre-apply produces (extra word
fields the dataclasses don't model), and carries the matching ``vocal_gaps`` block under
a ``vocal_gaps`` key for the lyrics worker to store in ``state_data``.
"""
lines = _lines_for(fixture)
singers = DUET_SINGERS if fixture == "duet" else None
transcribed = _segments("t", duration, lines, singers)
reference = _segments("r", duration, lines, singers)
reference_lyrics = {
REFERENCE_SOURCE: LyricsData(
segments=reference,
@@ -117,7 +170,148 @@ def build_corrections(artist: str, title: str, duration: float) -> Dict[str, Any
word_id_map={},
segment_id_map={},
)
return result.to_dict()
doc = result.to_dict()
if fixture == "duet":
doc["is_duet"] = True
elif fixture == "corrections":
_apply_corrections_fixture(doc, duration)
return doc
def _word_dict(word_id: str, text: str, start: Optional[float], end: Optional[float], **extra: Any) -> Dict[str, Any]:
return {"id": word_id, "text": text, "start_time": start, "end_time": end, "confidence": 1, **extra}
def _apply_corrections_fixture(doc: Dict[str, Any], duration: float) -> None:
"""Turn ``doc`` into the post-AI-apply state: two applied suggestions with undo info,
an untimed word, a long word and an evidenced vocal gap with synced reference lines."""
import copy
from datetime import datetime, timezone
original = doc["original_segments"]
corrected = copy.deepcopy(original)
suggestions: List[Dict[str, Any]] = []
undo_info: Dict[str, Any] = {}
# Segment 1: replace "arrives" (heard as "arrive") -> a single AI-corrected word, real timing.
seg = corrected[1]
idx = next(i for i, w in enumerate(seg["words"]) if w["text"] == "arrives")
old = copy.deepcopy(seg["words"][idx])
original[1]["words"][idx]["text"] = "arrive"
original[1]["text"] = original[1]["text"].replace("arrives", "arrive")
sid = "fake-sug-replace"
new_word = _word_dict(
"fake-ai-arrives", "arrives", old["start_time"], old["end_time"],
created_during_correction=True, ai_corrected=True, timing_estimated=False,
correction_span_id=sid, original_text="arrive",
)
removed = {**old, "text": "arrive"}
seg["words"][idx] = new_word
suggestions.append(_suggestion(sid, "replace", [old["id"]], [seg["id"]], "arrive", "arrives",
"Matches the synced reference", "mishearing"))
undo_info[sid] = {
"op": "replace", "new_word_ids": [new_word["id"]], "removed_words": [removed],
"segment_id": seg["id"], "prev_word_id": seg["words"][idx - 1]["id"] if idx else None,
"removed_segment": None,
}
# Segment 2: one heard word "localstack" -> two words sharing its slot (estimated timing).
seg = corrected[2]
idx = next(i for i, w in enumerate(seg["words"]) if w["text"] == "local")
old = copy.deepcopy(seg["words"][idx])
stack = seg["words"][idx + 1]
span_end = stack["end_time"]
original[2]["words"][idx]["text"] = "localstack"
original[2]["words"][idx]["end_time"] = span_end
del original[2]["words"][idx + 1]
original[2]["text"] = original[2]["text"].replace("local stack", "localstack")
removed_word = {**old, "text": "localstack", "end_time": span_end}
sid2 = "fake-sug-split"
mid = round((old["start_time"] + span_end) / 2, 3)
new_words = [
_word_dict("fake-ai-local", "local", old["start_time"], mid, created_during_correction=True,
ai_corrected=True, timing_estimated=True, correction_span_id=sid2,
original_text="localstack"),
_word_dict("fake-ai-stack", "stack", mid, span_end, created_during_correction=True,
ai_corrected=True, timing_estimated=True, correction_span_id=sid2),
]
seg["words"][idx:idx + 2] = new_words
suggestions.append(_suggestion(sid2, "replace", [old["id"]], [seg["id"]], "localstack", "local stack",
"Two words run together", "mishearing"))
undo_info[sid2] = {
"op": "replace", "new_word_ids": [w["id"] for w in new_words], "removed_words": [removed_word],
"segment_id": seg["id"], "prev_word_id": seg["words"][idx - 1]["id"] if idx else None,
"removed_segment": None,
}
# Segment 3: one word with no timing (the render would crash on it if submitted as-is).
untimed = next(w for w in corrected[3]["words"] if w["text"] == "ever")
untimed["start_time"] = None
untimed["end_time"] = None
# Last segment: first word held for longer than 2 s, the rest squeezed into what remains.
seg = corrected[-1]
first, rest = seg["words"][0], seg["words"][1:]
held_end = round(first["start_time"] + LONG_WORD_SECONDS, 3)
span = seg["words"][-1]["end_time"] - held_end
step = span / len(rest)
first["end_time"] = held_end
for k, w in enumerate(rest):
w["start_time"] = round(held_end + k * step, 3)
w["end_time"] = round(held_end + (k + 1) * step - 0.03, 3)
for segment in corrected:
timed = [w for w in segment["words"] if w["start_time"] is not None]
segment["text"] = " ".join(w["text"] for w in segment["words"])
segment["start_time"] = timed[0]["start_time"]
segment["end_time"] = timed[-1]["end_time"]
doc["corrected_segments"] = corrected
doc["resized_segments"] = copy.deepcopy(corrected)
doc["corrections_made"] = len(suggestions)
doc["metadata"]["auto_approval"] = {
"pre_applied": True,
"applied_suggestion_ids": [s["id"] for s in suggestions],
"rejected_suggestion_ids": [],
"suggestions": suggestions,
"undo_info": undo_info,
"applied_at": datetime.now(timezone.utc).isoformat(),
}
# One evidenced vocal gap after the last line, where only the synced reference has a line.
last_end = corrected[-1]["end_time"]
gap_start = round(last_end + 0.2, 3)
gap_end = round(max(min(last_end + 1.8, duration - 0.1), gap_start + 0.5), 3)
ref = doc["reference_lyrics"][REFERENCE_SOURCE]
ref["segments"].append({
"id": "rs-missed", "text": MISSED_REFERENCE_LINE,
"words": [_word_dict(f"rw-missed-{j}", t, gap_start, gap_end)
for j, t in enumerate(MISSED_REFERENCE_LINE.split())],
"start_time": gap_start, "end_time": gap_end,
})
doc["vocal_gaps"] = {
"version": "fake",
"gaps": [{
"start": gap_start, "end": gap_end, "duration": round(gap_end - gap_start, 3),
"active_fraction": 0.85, "longest_run_s": round(gap_end - gap_start - 0.1, 3),
"reference_lines": {REFERENCE_SOURCE: [MISSED_REFERENCE_LINE]},
"synced_reference_lines": {REFERENCE_SOURCE: [MISSED_REFERENCE_LINE]},
"suspect": True, "evidenced": True,
}],
"suspect_count": 1,
"evidenced_count": 1,
"max_suspect_run_s": round(gap_end - gap_start - 0.1, 3),
}
def _suggestion(sid: str, op: str, word_ids: List[str], segment_ids: List[str], original_text: str,
new_text: str, reason: str, category: str) -> Dict[str, Any]:
return {
"id": sid, "op": op, "word_ids": word_ids, "segment_ids": segment_ids,
"original_text": original_text, "new_text": new_text, "reason": reason,
"category": category, "confidence": 0.95, "models": ["fake-model"],
"consensus": 1, "total_models": 1, "conflict_group": None,
}
def build_lrc(corrections: Dict[str, Any]) -> str:
+41 -16
View File
@@ -15,7 +15,7 @@ import tempfile
import threading
import zipfile
from dataclasses import dataclass
from typing import Dict
from typing import Dict, Tuple
logger = logging.getLogger(__name__)
@@ -23,7 +23,7 @@ SAMPLE_RATE = 22050
VIDEO_SIZE = "320x180"
_lock = threading.Lock()
_cache: Dict[int, "MediaSet"] = {}
_cache: Dict[Tuple[int, str], "MediaSet"] = {}
_root = tempfile.mkdtemp(prefix="fake_worker_media_")
@@ -52,10 +52,29 @@ def _ffmpeg(*args: str) -> None:
subprocess.run(cmd, check=True, capture_output=True, timeout=300)
def _tone(path: str, freq: int, duration: int, volume: float = 0.3) -> None:
# Amplitude shaping so review waveforms aren't solid blocks: a sung-like burst pattern
# (volume swells to full and dips to 30% every second) on the vocal stem, and a slow
# tremolo on the instrumental / full mix.
VOCAL_ENVELOPE = "volume='0.3+0.7*abs(sin(t*PI/2))':eval=frame"
MIX_TREMOLO = "tremolo=f=2:d=0.6"
# Window (seconds) in which the "audible" backing stem sings.
BACKING_WINDOW = (10, 20)
def _tone(path: str, freq: int, duration: int, volume: float = 0.3, shape: str = "") -> None:
chain = f"volume={volume}" + (f",{shape}" if shape else "")
_ffmpeg(
"-f", "lavfi", "-i", f"sine=frequency={freq}:sample_rate={SAMPLE_RATE}:duration={duration}",
"-af", f"volume={volume}", "-ac", "1", path,
"-af", chain, "-ac", "1", path,
)
def _gated_tone(path: str, freq: int, duration: int, window: Tuple[float, float], volume: float = 0.3) -> None:
"""A tone that only sounds inside ``window`` (silent elsewhere)."""
start, end = window
_ffmpeg(
"-f", "lavfi", "-i", f"sine=frequency={freq}:sample_rate={SAMPLE_RATE}:duration={duration}",
"-af", f"volume='if(between(t,{start},{end}),{volume},0)':eval=frame", "-ac", "1", path,
)
@@ -95,16 +114,21 @@ def _zip(path: str, members: Dict[str, bytes]) -> None:
zf.writestr(name, data)
def _build(duration: int) -> MediaSet:
d = os.path.join(_root, str(duration))
def _build(duration: int, backing_vocals: str = "silent") -> MediaSet:
d = os.path.join(_root, f"{duration}-{backing_vocals}")
os.makedirs(d, exist_ok=True)
p = lambda name: os.path.join(d, name) # noqa: E731
# "Instrumental" = low tone, "lead vocals" = high tone, backing vocals = silence,
# so the real backing-vocals analysis recommends the clean instrumental.
_tone(p("instrumental_clean.flac"), 220, duration)
_tone(p("lead_vocals.flac"), 660, duration, volume=0.2)
_silence(p("backing_vocals.flac"), duration)
# "Instrumental" = low tone, "lead vocals" = high tone. Backing vocals = silence
# (the real backing-vocals analysis recommends the clean instrumental) or, for
# backing_vocals="audible", a tone in BACKING_WINDOW (it recommends keeping them).
_tone(p("instrumental_clean.flac"), 220, duration, shape=MIX_TREMOLO)
_tone(p("lead_vocals.flac"), 660, duration, volume=0.2, shape=VOCAL_ENVELOPE)
if backing_vocals == "audible":
window = (min(BACKING_WINDOW[0], duration / 3), min(BACKING_WINDOW[1], duration * 2 / 3))
_gated_tone(p("backing_vocals.flac"), 440, duration, window)
else:
_silence(p("backing_vocals.flac"), duration)
_mix(p("vocals_clean.flac"), p("lead_vocals.flac"), p("backing_vocals.flac"))
_mix(p("instrumental_with_backing.flac"), p("instrumental_clean.flac"), p("backing_vocals.flac"))
_mix(p("input.flac"), p("instrumental_clean.flac"), p("vocals_clean.flac"))
@@ -139,12 +163,13 @@ def _build(duration: int) -> MediaSet:
)
def get_media(duration: int) -> MediaSet:
def get_media(duration: int, backing_vocals: str = "silent") -> MediaSet:
"""Return (building once) the media set for a song of ``duration`` seconds."""
key = (duration, backing_vocals)
with _lock:
media = _cache.get(duration)
media = _cache.get(key)
if media is None:
logger.info(f"fake_workers: generating {duration}s media set in {_root}")
media = _build(duration)
_cache[duration] = media
logger.info(f"fake_workers: generating {duration}s ({backing_vocals} backing) media set in {_root}")
media = _build(duration, backing_vocals)
_cache[key] = media
return media
+71 -3
View File
@@ -23,6 +23,7 @@ from backend.services.fake_workers.config import FakeConfig, get_fake_config
from backend.services.fake_workers.lyrics import build_corrections, build_lrc
from backend.services.fake_workers.media import MediaSet, get_media
from backend.services.job_manager import JobManager
from backend.services.quick_version import service as quick
from backend.services.storage_service import StorageService
logger = logging.getLogger(__name__)
@@ -65,7 +66,32 @@ async def _begin(kind: str, job_id: str) -> FakeConfig:
def _media_for(config: FakeConfig) -> MediaSet:
return get_media(int(config.audio_duration_seconds))
return get_media(int(config.audio_duration_seconds), config.backing_vocals)
# Stored processing_metadata.auto_approval verdicts per FakeConfig.auto_approval value:
# (lyrics verdict, backing verdict, backing non_subjective). The shapes
# auto_approval_summary() reads, so the review UI sees confident / unsure halves.
_AUTO_APPROVAL_VERDICTS = {
"lyrics_confident": ("auto", "review", False),
"backing_confident": ("review", "clean", True),
"both_unsure": ("review", "review", False),
}
def auto_approval_payload(kind: str):
"""The ``processing_metadata.auto_approval`` verdict for ``kind``, or None for "none"."""
verdicts = _AUTO_APPROVAL_VERDICTS.get(kind)
if not verdicts:
return None
lyrics, backing, non_subjective = verdicts
return {
"outcome": "review",
"source": "fake_workers",
"lyrics": {"verdict": lyrics},
"backing": {"verdict": backing, "non_subjective": non_subjective},
"backing_analysis_available": True,
}
# ---------------------------------------------------------------- audio download
@@ -91,6 +117,27 @@ async def run_audio_download(job_id: str) -> bool:
# ---------------------------------------------------------------- audio separation
async def _emit_quick_version(job, job_manager: JobManager, storage: StorageService, media: MediaSet) -> None:
"""kjbox make-it jobs: write the same ``state_data.quick_version`` +
``file_urls.quick.video_mp4`` the real audio worker's quick-version thread does
(``services/quick_version``), using the tiny fixture mp4. Same gate as prod
(``should_build_quick_version``), so non-kjbox jobs are untouched."""
if not quick.should_build_quick_version(job):
return
job_id = job.job_id
quick.set_quick_state(job_manager, job_id, quick.STATUS_SEPARATING, started_at=quick._now_iso())
quick.set_quick_state(job_manager, job_id, quick.STATUS_RENDERING)
gcs_path = f"jobs/{job_id}/quick/quick.mp4"
await asyncio.to_thread(storage.upload_file, media.final_mp4, gcs_path)
job_manager.update_file_url(job_id, quick.FILE_CATEGORY, quick.FILE_KEY, gcs_path)
quick.set_quick_state(
job_manager, job_id, quick.STATUS_READY,
lyrics_tier="fake_workers", line_count=0,
duration_seconds=float(media.duration),
size_bytes=os.path.getsize(media.final_mp4), ready_at=quick._now_iso(),
)
async def run_audio(job_id: str) -> bool:
config = await _begin("audio", job_id)
from backend.workers.audio_worker import _transcode_review_stems, upload_separation_results
@@ -98,11 +145,18 @@ async def run_audio(job_id: str) -> bool:
from backend.workers.worker_logging import create_job_logger
job_manager, storage = JobManager(), StorageService()
if not _job_or_none(job_manager, job_id):
job = _job_or_none(job_manager, job_id)
if not job:
return False
job_log = create_job_logger(job_id, "audio")
media = await asyncio.to_thread(_media_for, config)
try:
await _emit_quick_version(job, job_manager, storage, media)
except Exception as e: # non-fatal, same as the real worker
logger.warning(f"[job:{job_id}] fake audio: quick version failed: {e}")
quick.set_quick_state(job_manager, job_id, quick.STATUS_FAILED, error=str(e)[:500])
job_manager.update_state_data(job_id, "audio_progress", {
"stage": "separating", "progress": 30, "message": "Separating audio (fake)",
})
@@ -117,6 +171,11 @@ async def run_audio(job_id: str) -> bool:
"combined_instrumentals": {"fake_backing_model.ckpt": media.instrumental_with_backing},
}
job_manager.update_state_data(job_id, "model_names", FAKE_MODEL_NAMES)
if config.stems_delay_seconds:
# Late stems: this worker is its own thread/loop, so lyrics -> screens -> awaiting_review
# proceed meanwhile and the review opens with audio_complete still false.
logger.info(f"[job:{job_id}] fake audio: holding stems for {config.stems_delay_seconds}s")
await asyncio.sleep(config.stems_delay_seconds)
await upload_separation_results(job_id, separation_result, storage, job_manager)
await _transcode_review_stems(job_id, job_manager, storage, job_log)
job_manager.update_processing_metadata(job_id, "separation", {
@@ -134,6 +193,8 @@ async def run_audio(job_id: str) -> bool:
job_manager.mark_audio_complete(job_id)
await job_manager.advance_to_screens_if_ready(job_id)
# Same as the real audio worker: resume a final encode parked on these stems.
await job_manager.resume_video_if_waiting_for_stems(job_id)
return True
@@ -147,7 +208,9 @@ async def run_lyrics(job_id: str) -> bool:
return False
corrections = build_corrections(job.artist or "Fake Artist", job.title or "Fake Title",
float(config.audio_duration_seconds))
float(config.audio_duration_seconds), config.review_fixture)
# Not part of corrections.json: gen keeps the vocal-gap analysis in state_data.
vocal_gaps = corrections.pop("vocal_gaps", None)
with tempfile.TemporaryDirectory(prefix=f"fake_lyrics_{job_id}_") as tmp:
corrections_path = os.path.join(tmp, "corrections.json")
with open(corrections_path, "w") as f:
@@ -160,6 +223,8 @@ async def run_lyrics(job_id: str) -> bool:
url = await asyncio.to_thread(storage.upload_file, lrc_path, f"jobs/{job_id}/lyrics/karaoke.lrc")
job_manager.update_file_url(job_id, "lyrics", "lrc", url)
if vocal_gaps:
job_manager.update_state_data(job_id, "vocal_gaps", vocal_gaps)
job_manager.update_state_data(job_id, "lyrics_metadata", {
"segment_count": len(corrections["corrected_segments"]),
"has_corrections": True,
@@ -226,6 +291,9 @@ async def run_screens(job_id: str) -> bool:
await get_worker_service().trigger_render_video_worker(job_id)
else:
verdict = auto_approval_payload(config.auto_approval)
if verdict:
job_manager.update_processing_metadata(job_id, "auto_approval", verdict)
job_manager.transition_to_state(
job_id=job_id, new_status=JobStatus.AWAITING_REVIEW, progress=55,
message="Ready for review. Please review lyrics and select your instrumental.",
+5 -2
View File
@@ -17,7 +17,7 @@ import httpx
from backend.models.job import JobStatus
from backend.services.fake_workers.checkout import public_api_url
from backend.services.fake_workers.config import set_fake_config
from backend.services.fake_workers.config import get_fake_config, set_fake_config
# target -> (per-user fake config overrides, status the job must reach)
JOB_TARGETS: Dict[str, tuple] = {
@@ -76,6 +76,9 @@ def create_job(user: Dict[str, Any], target: str, artist: str = DEFAULT_ARTIST,
raise ScenarioError(f"Unknown job target {target!r}; one of {sorted(JOB_TARGETS)}")
overrides, wanted = JOB_TARGETS[target]
set_fake_config(overrides, email=user["email"])
# The awaiting_review job honours the user's review_mode knob (default always_review),
# so a flow can seed "auto" to reach the confident / skipped-step states.
review_mode = get_fake_config(email=user["email"]).review_mode if target == "awaiting_review" else "auto"
with _api(user["session_token"]) as api:
search = api.post("/api/audio-search/search-standalone", json={"artist": artist, "title": title})
@@ -86,7 +89,7 @@ def create_job(user: Dict[str, Any], target: str, artist: str = DEFAULT_ARTIST,
"selection_index": 0,
"artist": artist,
"title": title,
"review_mode": "always_review" if target == "awaiting_review" else "auto",
"review_mode": review_mode,
})
if created.status_code != 200:
raise ScenarioError(f"create-from-search failed: {created.status_code} {created.text}")
+81 -5
View File
@@ -4,18 +4,43 @@ Firestore database operations for job management.
import logging
from typing import Optional, Dict, Any, List
from datetime import datetime, timezone
from google.api_core import exceptions as core_exceptions
from google.api_core import retry as api_retry
from google.cloud import firestore
from google.cloud.firestore_v1 import FieldFilter
from backend.config import settings
from backend.models.job import Job, JobStatus, TimelineEvent
from backend.models.worker_log import WorkerLogEntry
from backend.services.log_write_offload import submit_or_run
from backend.models.review_session import ReviewSession
from backend.models.audio_edit_session import AudioEditSession
logger = logging.getLogger(__name__)
# Job-list queries back user-facing endpoints (GET /api/jobs). The client's
# default RunQuery retry/timeout is 300s, so a stalled stream used to hold a
# threadpool thread for 5 minutes before failing ("Timeout of 300.0s exceeded").
# Bound them so they fail fast; the frontend just polls again.
LIST_QUERY_TIMEOUT_SECONDS = 30.0
LIST_QUERY_RETRY = api_retry.Retry(
initial=0.1,
maximum=5.0,
multiplier=1.3,
predicate=api_retry.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.InternalServerError,
core_exceptions.ServiceUnavailable,
),
timeout=LIST_QUERY_TIMEOUT_SECONDS,
)
def _bounded_stream(query):
"""query.stream() with the job-list retry/timeout bounds."""
return query.stream(retry=LIST_QUERY_RETRY, timeout=LIST_QUERY_TIMEOUT_SECONDS)
class FirestoreService:
"""Service for Firestore database operations."""
@@ -107,6 +132,47 @@ class FirestoreService:
logger.error(f"Error updating job {job_id}: {e}")
raise
def claim_job_state_flag(self, job_id: str, key: str) -> bool:
"""Atomically test-and-clear ``state_data.<key>``.
Returns True for exactly one caller while the flag is truthy (it is set
to False in the same transaction), so two workers racing to act on the
same flag can't both proceed.
"""
doc_ref = self.db.collection(self.collection).document(job_id)
@firestore.transactional
def _claim(transaction, ref) -> bool:
snapshot = ref.get(transaction=transaction)
if not snapshot.exists:
return False
if not ((snapshot.to_dict() or {}).get("state_data") or {}).get(key):
return False
transaction.update(ref, {f"state_data.{key}": False, "updated_at": datetime.utcnow()})
return True
return _claim(self.db.transaction(), doc_ref)
def try_set_job_state_flag(self, job_id: str, key: str) -> bool:
"""Atomically set ``state_data.<key>`` to True if it isn't already truthy.
The inverse of ``claim_job_state_flag``: returns True for exactly one of
several concurrent callers (a guard flag such as visibility_change_in_progress).
"""
doc_ref = self.db.collection(self.collection).document(job_id)
@firestore.transactional
def _set(transaction, ref) -> bool:
snapshot = ref.get(transaction=transaction)
if not snapshot.exists:
return False
if ((snapshot.to_dict() or {}).get("state_data") or {}).get(key):
return False
transaction.update(ref, {f"state_data.{key}": True, "updated_at": datetime.utcnow()})
return True
return _set(self.db.transaction(), doc_ref)
def update_job_status(
self,
job_id: str,
@@ -227,7 +293,7 @@ class FirestoreService:
query = query.order_by('created_at', direction=firestore.Query.DESCENDING).limit(limit)
docs = query.stream()
docs = _bounded_stream(query)
jobs = [Job(**doc.to_dict()) for doc in docs]
return jobs
@@ -246,7 +312,7 @@ class FirestoreService:
.where(filter=FieldFilter('state_data.batch_id', '==', batch_id))
.limit(limit)
)
return [Job(**doc.to_dict()) for doc in query.stream()]
return [Job(**doc.to_dict()) for doc in _bounded_stream(query)]
except Exception as e:
logger.error(f"Error listing jobs for batch {batch_id}: {e}")
raise
@@ -337,7 +403,7 @@ class FirestoreService:
query = query.order_by('created_at', direction=firestore.Query.DESCENDING).limit(limit)
query = query.select(self.SUMMARY_FIELD_PATHS)
docs = query.stream()
docs = _bounded_stream(query)
results = [doc.to_dict() for doc in docs]
# Apply exclude_statuses filter in Python (see note above)
@@ -489,9 +555,19 @@ class FirestoreService:
# Get subcollection reference
logs_ref = self.db.collection(self.collection).document(job_id).collection("logs")
# Add document with auto-generated ID or use log_entry.id
# Add document with auto-generated ID or use log_entry.id.
# On the API event loop this hands off to a background thread
# (a sync Firestore write there freezes every request on the instance).
doc_ref = logs_ref.document(log_entry.id)
doc_ref.set(log_entry.to_dict())
data = log_entry.to_dict()
def _write():
try:
doc_ref.set(data)
except Exception as e:
logger.debug(f"Error appending log to subcollection for job {job_id}: {e}")
submit_or_run(_write)
# Don't log every append - too spammy
except Exception as e:
+18
View File
@@ -287,3 +287,21 @@ def validate_worker_can_run(worker_name: str, job: Job) -> Optional[str]:
)
return None
def selected_stem_pending(job) -> bool:
"""True when the selected instrumental stem hasn't been produced yet but
stem separation is still running, i.e. the job should wait, not fail.
Review can finish before separation does (audio separation is decoupled from
the lyrics review path), so this is a normal ordering, not an error.
"""
if validate_worker_can_run("video_worker", job):
return False # wrong status (duplicate/late trigger): never park, let the normal checks reject it
selection = (job.state_data or {}).get('instrumental_selection')
if selection not in ('clean', 'with_backing'):
return False # 'custom' uses an uploaded file / mute-region stem
stem_key = 'instrumental_clean' if selection == 'clean' else 'instrumental_with_backing'
if (job.file_urls or {}).get('stems', {}).get(stem_key):
return False
return not (job.state_data or {}).get('audio_complete', False)
+35
View File
@@ -1305,6 +1305,41 @@ class JobManager:
self.update_state_data(job_id, 'audio_complete', True)
logger.info(f"Job {job_id}: Audio processing complete (separation finished)")
# Set by the video worker when review finished before stem separation did
# (the selected instrumental stem doesn't exist yet). The audio worker
# resumes the encode when separation completes; recover_stuck_jobs is the
# backstop. Before this, the video worker just failed its prerequisites 3x
# and the job sat at instrumental_selected forever (2026-10-17/18).
VIDEO_WAITING_FOR_STEMS_KEY = 'video_waiting_for_stems'
def park_video_for_stems(self, job_id: str) -> None:
"""Record that the final encode is waiting for stem separation."""
self.update_job(job_id, {
f'state_data.{self.VIDEO_WAITING_FOR_STEMS_KEY}': True,
'message': 'Waiting for audio separation to finish; the final video starts automatically',
})
def claim_video_stems_wait(self, job_id: str) -> bool:
"""Atomically clear the waiting flag; True for exactly one claimant."""
return self.firestore.claim_job_state_flag(job_id, self.VIDEO_WAITING_FOR_STEMS_KEY)
async def resume_video_if_waiting_for_stems(self, job_id: str) -> bool:
"""Re-trigger the video worker for a job parked waiting on stems.
Called by the audio worker right after ``mark_audio_complete``. No-op
unless the video worker parked the job (flag set) and it's still in a
state the video worker accepts. Returns True iff a dispatch was issued.
"""
if not self.claim_video_stems_wait(job_id):
return False
job = self.get_job(job_id)
if not job or job.status not in (JobStatus.INSTRUMENTAL_SELECTED, JobStatus.REVIEW_COMPLETE):
logger.info(f"Job {job_id}: stems ready but job is {getattr(job, 'status', None)}; not resuming video")
return False
from backend.services.worker_service import get_worker_service
logger.info(f"Job {job_id}: stems ready — resuming parked video worker")
return await get_worker_service().trigger_video_worker(job_id)
def mark_lyrics_complete(self, job_id: str) -> None:
"""
Mark lyrics processing as complete.
+100
View File
@@ -0,0 +1,100 @@
"""
Keep job-log Firestore writes off the API event loop.
Job logs (jobs/{id}/logs/*) are written synchronously by the JobLogHandler /
JobLogger / job_logging handlers. When that code runs on the API's event loop (the
screens worker and preview encodes run as in-process background tasks), every log
line is a 0.1-5s Firestore round-trip that freezes every request on the instance:
the loop watchdog attributed 45 stalls in a week to append_log_to_subcollection.
`submit_or_run` hands the write to one background thread when the caller is on a
running event loop in the API process, and runs it inline everywhere else (worker
threads, Cloud Run Jobs, scripts), so ordering-sensitive callers are unaffected.
Logs are read back ordered by their own timestamp, so the hand-off doesn't reorder
them. The queue is bounded: under a Firestore outage we drop job-log lines rather
than grow memory.
"""
import asyncio
import atexit
import logging
import os
import queue
import threading
import time
from typing import Callable
logger = logging.getLogger(__name__)
_MAX_PENDING = 5000
_DROP_WARNING_INTERVAL_S = 60.0
_queue: "queue.Queue[Callable[[], None]]" = queue.Queue(maxsize=_MAX_PENDING)
_worker: threading.Thread | None = None
_worker_lock = threading.Lock()
_dropped = 0
_last_drop_warning = 0.0
def _on_event_loop() -> bool:
try:
asyncio.get_running_loop()
except RuntimeError:
return False
return True
def _should_offload() -> bool:
# A Cloud Run Job runs a single job; blocking its own loop affects nobody else,
# and a process that exits right after its last log line must not lose it.
return _on_event_loop() and not os.environ.get("CLOUD_RUN_JOB")
def _run_worker() -> None:
while True:
write = _queue.get()
try:
write()
except Exception as e: # the write itself already swallows; belt and braces
logger.debug(f"Offloaded job-log write failed: {e}")
finally:
_queue.task_done()
def _ensure_worker() -> None:
global _worker
if _worker is not None and _worker.is_alive():
return
with _worker_lock:
if _worker is None or not _worker.is_alive():
_worker = threading.Thread(target=_run_worker, name="job-log-writer", daemon=True)
_worker.start()
def submit_or_run(write: Callable[[], None]) -> None:
"""Run `write` on the background writer if called on the API loop, else inline."""
global _dropped, _last_drop_warning
if not _should_offload():
write()
return
_ensure_worker()
try:
_queue.put_nowait(write)
except queue.Full:
_dropped += 1
now = time.monotonic()
if now - _last_drop_warning >= _DROP_WARNING_INTERVAL_S:
_last_drop_warning = now
logger.warning(f"Job-log writer queue full ({_MAX_PENDING}); dropped {_dropped} job-log lines so far")
def drain(timeout: float = 10.0) -> bool:
"""Wait (up to `timeout` s) for queued writes to finish. True if fully drained."""
deadline = time.monotonic() + timeout
while _queue.unfinished_tasks:
if _worker is None or not _worker.is_alive() or time.monotonic() >= deadline:
return False
time.sleep(0.01)
return True
atexit.register(drain)
+8 -15
View File
@@ -13,7 +13,8 @@ This module makes such freezes self-diagnosing:
* 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;
at ``sample_at_s`` so a long freeze shows where it actually spent its time
(``EVENT_LOOP_STALL in progress`` lines, always WARNING);
* 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
@@ -248,19 +249,11 @@ class LoopWatchdog:
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})
# Same impact rule as _finish: an idle instance's stall never logs ERROR.
# (Requests still queued in the socket are invisible until the loop
# resumes, so this can under-call mid-stall; the ended line decides.)
no_impact = self.request_tracker is not None and self._requests_affected() == 0
# Judge severity on blocked time only: frozen (throttled) time is discounted
# from the final duration too, so a post-thaw sample mustn't claim ERROR
# for a block that ends up below the threshold.
blocked = max(0.0, age - self._stall_frozen_s)
level = (
logging.ERROR
if blocked >= self.error_threshold_s and not no_impact
else logging.WARNING
)
# Always WARNING. The "ended" line is the one ERROR per freeze (>=10s
# blocked with a request affected): it's what the backend/event_loop_stalls
# metric counts, and the error monitor turns each ERROR line shape into its
# own #alerts pattern, so an ERROR here too meant two alerts per freeze.
level = logging.WARNING
logger.log(
level,
"EVENT_LOOP_STALL in progress age_ms=%d culprit=%s\n%s",
@@ -408,7 +401,7 @@ class LoopWatchdog:
"requests_affected": affected if tracked else None,
})
except Exception:
logger.exception("Failed to record loop stall (non-fatal)")
logger.warning("Failed to record loop stall (non-fatal)", exc_info=True)
# ----- production recorder ---------------------------------------------------
+67 -12
View File
@@ -29,6 +29,33 @@ Judge = Callable[[str, str], Awaitable[MatchVerdict]]
_VALID_KINDS = {"cosmetic", "content", "ambiguous"}
# Latency budget. A singer (kjbox) or the mobile app's "Describe the song" (via
# decide's /api/search/resolve, which waits 25 s) is waiting on this, so every step
# is bounded and the worst case stays ~20 s:
# Gemini: 2 attempts x 8 s. A low-thinking Flash call answers in ~2 s; the odd
# one stalls until a 504 DEADLINE_EXCEEDED (~10 s), and a fresh attempt is fast.
# The 8 s cap is client-side (asyncio.wait_for): the API rejects request
# deadlines under 10 s with 400 INVALID_ARGUMENT, so the SDK timeout stays at
# match_judge_timeout_ms (>= GEMINI_MIN_DEADLINE_MS).
# Catalog tidy: 4 s. It searches decide's catalog API, whose cold start takes
# 35-45 s; waiting on it (gen's catalog proxy gives up after 10 s) pushed a
# ready AI answer past decide's timeout, so the first ask of a description
# came back empty while gen finished and cached it for the second ask.
GEMINI_ATTEMPT_TIMEOUT_S = 8.0
GEMINI_MIN_DEADLINE_MS = 10000 # the API's minimum request deadline
GEMINI_ATTEMPTS = 2
CATALOG_TIDY_TIMEOUT_S = 4.0
# In-flight catalog searches. One the tidy gave up on keeps running (warming decide and
# the catalog proxy's cache for the next ask); strong refs so it isn't GC'd mid-flight.
_background: set[asyncio.Task] = set()
def _drop_background(task: asyncio.Task) -> None:
_background.discard(task)
if not task.cancelled() and task.exception() is not None:
logger.debug(f"catalog tidy task failed: {task.exception()!r}")
_SYSTEM_PROMPT = (
"You resolve a karaoke singer's free-text song search. The query is one line "
"holding an artist and/or a song title in any order, often lazily typed or "
@@ -134,19 +161,35 @@ def _verdict_from_response(data: object, query: str) -> dict:
}
def _retryable(exc: BaseException) -> bool:
"""Timeouts, 5xx and 429 may pass; any other 4xx (bad request/config) won't."""
code = getattr(exc, "code", None)
return not (isinstance(code, int) and 400 <= code < 500 and code != 429)
async def resolve_free_text(query: str, *, generate: Optional[Generate] = None,
model: Optional[str] = None) -> dict:
"""Split + correct a free-text song query. Never raises: failures → kind 'none'."""
try:
data = await (generate or _default_generate)(
model or _model(), _SYSTEM_PROMPT, f'Singer typed: "{query}"')
except Exception as e:
from backend.services.gemini_client import note_gemini_failure
"""Split + correct a free-text song query. Never raises: failures → kind 'none'.
note_gemini_failure("match_judge_free_text", e)
logger.warning(f"resolve_free_text failed: {e}")
return _none(query, "unavailable")
return verdict_from_response(data, query)
Each Gemini attempt is bounded by GEMINI_ATTEMPT_TIMEOUT_S; a transient failure
(timeout, 5xx) is retried once. Quota/billing/key errors are not retried.
"""
from backend.services.gemini_client import note_gemini_failure
gen = generate or _default_generate
for attempt in range(1, GEMINI_ATTEMPTS + 1):
try:
data = await asyncio.wait_for(
gen(model or _model(), _SYSTEM_PROMPT, f'Singer typed: "{query}"'),
GEMINI_ATTEMPT_TIMEOUT_S)
except Exception as e:
reason = f"timed out after {GEMINI_ATTEMPT_TIMEOUT_S:g}s" if isinstance(e, asyncio.TimeoutError) else str(e)
logger.warning(f"resolve_free_text attempt {attempt}/{GEMINI_ATTEMPTS} failed: {reason}")
if note_gemini_failure("match_judge_free_text", e) or attempt == GEMINI_ATTEMPTS or not _retryable(e):
return _none(query, "unavailable")
continue
return verdict_from_response(data, query)
return _none(query, "unavailable") # pragma: no cover - loop always returns
async def resolve_and_tidy(query: str, *, generate: Optional[Generate] = None,
@@ -168,8 +211,19 @@ async def resolve_and_tidy(query: str, *, generate: Optional[Generate] = None,
artist, title = verdict["typed_artist"], verdict["typed_title"]
else:
return verdict
task = asyncio.ensure_future((judge or _default_judge)(artist, title))
# Held until done even if this request times out or is cancelled (client gone).
_background.add(task)
task.add_done_callback(_drop_background)
try:
cat = await (judge or _default_judge)(artist, title)
# shield: on timeout the search keeps running (warming decide + the catalog
# proxy cache) instead of being cancelled mid-request.
cat = await asyncio.wait_for(asyncio.shield(task), CATALOG_TIDY_TIMEOUT_S)
except asyncio.TimeoutError:
logger.warning(f"resolve_and_tidy catalog pass timed out after {CATALOG_TIDY_TIMEOUT_S:g}s; "
"answering with the AI verdict")
# Transient: the route doesn't cache "unavailable", so a later ask gets the tidy.
return {**verdict, "reason": "unavailable"}
except Exception as e:
logger.warning(f"resolve_and_tidy catalog pass failed: {e}")
# Still answer with the AI verdict, but as a transient result: the
@@ -209,7 +263,8 @@ def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict
from backend.services.gemini_client import get_genai_client
client = get_genai_client(timeout_ms=int(getattr(settings, "match_judge_timeout_ms", 12000)))
timeout_ms = max(int(getattr(settings, "match_judge_timeout_ms", 12000)), GEMINI_MIN_DEADLINE_MS)
client = get_genai_client(timeout_ms=timeout_ms)
response = client.models.generate_content(
model=model,
contents=[user_prompt],
+3 -1
View File
@@ -111,7 +111,9 @@ def send_ops_alert(message: str) -> bool:
from backend.services.discord_service import get_discord_notification_service
service = get_discord_notification_service(webhook_url=webhook)
return service.post_message(message, webhook_url=webhook)
# suppress_embeds: alert text carries error strings with URLs (GCP docs,
# job links) that Discord would otherwise unfurl into big preview cards.
return service.post_message(message, webhook_url=webhook, suppress_embeds=True)
except Exception as exc: # noqa: BLE001 - alerting must never raise
logger.warning("ops_alerts: failed to send alert: %s", exc)
return False
+4 -2
View File
@@ -31,6 +31,8 @@ from typing import List, Optional, Tuple
import requests
from karaoke_gen.lyrics_transcriber.lyrics import lrclib_client
logger = logging.getLogger(__name__)
LRCLIB_BASE = "https://lrclib.net/api"
@@ -124,7 +126,7 @@ def fetch_lrclib_lyrics(
if duration:
params["duration"] = int(round(duration))
try:
r = session.get(f"{LRCLIB_BASE}/get", params=params, timeout=timeout)
r = lrclib_client.get(f"{LRCLIB_BASE}/get", params, user_agent=USER_AGENT, timeout=timeout, session=session, retry=False)
if r.status_code == 200:
got = lyrics_from_lrclib_payload(r.json())
if got and got.kind == "synced":
@@ -137,7 +139,7 @@ def fetch_lrclib_lyrics(
exact_plain = None
try:
r = session.get(f"{LRCLIB_BASE}/search", params={"q": f"{artist} {title}"}, timeout=timeout)
r = lrclib_client.get(f"{LRCLIB_BASE}/search", {"q": f"{artist} {title}"}, user_agent=USER_AGENT, timeout=timeout, session=session, retry=False)
if r.status_code == 200:
hits = r.json() or []
for hit in sorted(hits, key=lambda h: 0 if h.get("syncedLyrics") else 1):
+43
View File
@@ -0,0 +1,43 @@
"""Idempotent "user opened review" transition shared by review entry points.
Both ``POST /api/jobs/{id}/start-review`` and ``GET /api/review/{id}/correction-data``
move a job AWAITING_REVIEW -> IN_REVIEW. Clients fire them concurrently (React
double-mount, iOS in-app browsers, two tabs), so the loser of the race must not
fail with "in_review -> in_review".
"""
from typing import Any, Literal, Optional
from backend.exceptions import InvalidStateTransitionError
from backend.models.job import JobStatus
ReviewOpenResult = Literal["started", "already", "refused"]
def ensure_in_review(
job_manager: Any,
job_id: str,
current_status: Optional[Any],
message: str,
) -> ReviewOpenResult:
"""Move a job to IN_REVIEW exactly once, tolerating concurrent callers.
Returns:
"started": this call performed the transition (do one-time side effects).
"already": job was already IN_REVIEW (or another caller won the race).
"refused": the transition was refused without raising (caller decides).
Raises InvalidStateTransitionError for any invalid transition other than losing
the race to IN_REVIEW. Blocking: call via ``asyncio.to_thread`` from async code.
"""
if current_status == JobStatus.IN_REVIEW:
return "already"
try:
ok = job_manager.transition_to_state(
job_id=job_id, new_status=JobStatus.IN_REVIEW, message=message
)
except InvalidStateTransitionError:
current = job_manager.get_job(job_id)
if current and current.status == JobStatus.IN_REVIEW:
return "already"
raise
return "started" if ok else "refused"
+76 -5
View File
@@ -20,7 +20,12 @@ from google.cloud.firestore_v1 import FieldFilter
from google.api_core import exceptions as gcloud_exceptions
from backend.config import get_settings
from backend.models.song_request import DailyCommunityPick, SongRequest, Vote
from backend.models.song_request import (
YOUTUBE_COMMENT_SUBMITTER,
DailyCommunityPick,
SongRequest,
Vote,
)
from backend.services.match_judge.classifier import normalize_for_match
logger = logging.getLogger(__name__)
@@ -120,6 +125,66 @@ class SongRequestService:
self.cast_vote(email, request.id, "up")
return self.get_request(request.id) or request, False, canonical_artist, canonical_title
def add_from_youtube_comment(
self, artist: str, title: str, *, comment_id: str, video_id: str, author: str
) -> SongRequest:
"""Add a song asked for in a YouTube comment (artist/title already canonical).
Returns the existing open/published request for the same song instead of a
duplicate. A new request belongs to ``YOUTUBE_COMMENT_SUBMITTER`` with no
vote until a real user up-votes (and so claims) it; no daily submission cap.
"""
key = _dedupe_key(artist, title)
existing = self.find_active_by_key(key)
if existing is not None:
return existing
request = SongRequest(
id=str(uuid.uuid4()),
artist=artist,
title=title,
artist_raw=artist,
title_raw=title,
dedupe_key=key,
submitted_by=YOUTUBE_COMMENT_SUBMITTER,
source="youtube_comment",
status="open",
vote_count=0,
youtube_comment_id=comment_id,
youtube_video_id=video_id,
youtube_author=author[:100],
)
self.db.collection(REQUESTS_COLLECTION).document(request.id).set(
request.model_dump(mode="json")
)
logger.info("song request created id=%s from youtube comment=%s key=%s",
request.id, comment_id, key)
return request
def find_active_by_key(self, key: str) -> Optional[SongRequest]:
"""The live request for a song: a votable open one first, then one being made
(queued/in_progress), then a published one. None if only rejected/stalled."""
found: dict = {}
query = self.db.collection(REQUESTS_COLLECTION).where(
filter=FieldFilter("dedupe_key", "==", key)
)
for doc in query.stream():
req = SongRequest(**doc.to_dict())
found.setdefault(req.status, req)
for status in ("open", "queued", "in_progress", "published"):
if status in found:
return found[status]
return None
def find_published_by_key(self, key: str) -> Optional[SongRequest]:
query = self.db.collection(REQUESTS_COLLECTION).where(
filter=FieldFilter("dedupe_key", "==", key)
).limit(10)
for doc in query.stream():
data = doc.to_dict()
if data.get("status") == "published":
return SongRequest(**data)
return None
async def _canonicalize(self, artist: str, title: str) -> Tuple[str, str]:
"""Best-effort artist/title tidy via match_judge; never blocks submission."""
try:
@@ -286,6 +351,8 @@ class SongRequestService:
for req in self.list_active(): # already ranked -vote_count, created_at asc
if req.vote_count < 0:
continue
if req.submitted_by == YOUTUBE_COMMENT_SUBMITTER:
continue # added by the YouTube comment bot, not yet claimed by a real voter
if req.review_state == "pending":
continue
if req.review_state == "snoozed":
@@ -574,10 +641,14 @@ def _cast_vote_txn(transaction, service, vote_ref, target_ref, request_id, email
continue # request gone (e.g. old vote pointed at a closed request)
ref = service.db.collection(REQUESTS_COLLECTION).document(rid)
current = int(snap.to_dict().get("vote_count", 0))
transaction.update(ref, {
"vote_count": current + delta,
"updated_at": now.isoformat(),
})
fields = {"vote_count": current + delta, "updated_at": now.isoformat()}
# The first real up-voter claims a request the YouTube comment bot added
# (usually the commenter, arriving from the bot's reply link).
if (rid == request_id and vote is not None and value > 0
and snap.to_dict().get("submitted_by") == YOUTUBE_COMMENT_SUBMITTER):
fields["submitted_by"] = email
fields["claimed_at"] = now.isoformat()
transaction.update(ref, fields)
return vote
+34 -10
View File
@@ -42,6 +42,16 @@ class StripeAdminService:
# Payment Storage
# =========================================================================
@staticmethod
def _first_line_item_description(session: Dict[str, Any]) -> str:
"""Description of the first expanded line item, or "" if unavailable."""
line_items = session.get("line_items") or {}
data = line_items.get("data") if isinstance(line_items, dict) else None
if data:
first = data[0] or {}
return first.get("description") or ""
return ""
def store_payment(self, session: Dict[str, Any]) -> bool:
"""
Store enriched payment data from a completed Checkout Session.
@@ -55,10 +65,13 @@ class StripeAdminService:
"""
try:
session_id = session.get("id", "")
metadata = session.get("metadata", {})
# Stripe sends explicit nulls, so `or {}` rather than a .get default.
metadata = session.get("metadata") or {}
customer_details = session.get("customer_details") or {}
payment_link_id = session.get("payment_link") or None
# Extract payment intent and charge details
payment_intent = session.get("payment_intent", {})
payment_intent = session.get("payment_intent") or {}
if isinstance(payment_intent, str):
# Not expanded - just store the ID
payment_intent_id = payment_intent
@@ -76,12 +89,18 @@ class StripeAdminService:
balance_txn = bt if isinstance(bt, dict) else {}
# Extract payment method details
payment_method_details = charge_data.get("payment_method_details", {})
payment_method_details = charge_data.get("payment_method_details") or {}
pm_type = payment_method_details.get("type", "unknown")
card_info = payment_method_details.get("card", {})
card_info = payment_method_details.get("card") or {}
# Determine order type
order_type = metadata.get("order_type", "credit_purchase")
# Determine order type. A checkout without gen metadata that came from
# a Stripe Payment Link isn't a credit purchase (no credits granted).
default_order_type = (
"payment_link"
if payment_link_id and not (metadata.get("credits") or metadata.get("user_email"))
else "credit_purchase"
)
order_type = metadata.get("order_type") or default_order_type
package_id = metadata.get("package_id")
credits = 0
try:
@@ -94,13 +113,15 @@ class StripeAdminService:
artist = metadata.get("artist", "")
title = metadata.get("title", "")
product_description = f"Made For You: {artist} - {title}"
elif order_type == "payment_link":
product_description = self._first_line_item_description(session) or "Payment Link"
else:
from backend.services.stripe_service import CREDIT_PACKAGES
pkg = CREDIT_PACKAGES.get(package_id, {})
product_description = pkg.get("name", f"{credits} Credits")
# Extract discount info
total_details = session.get("total_details", {})
total_details = session.get("total_details") or {}
discount_amount = 0
promotion_code = None
if total_details:
@@ -123,10 +144,13 @@ class StripeAdminService:
"customer_email": (
metadata.get("user_email")
or metadata.get("customer_email")
or session.get("customer_email", "")
or session.get("customer_email")
or customer_details.get("email")
or ""
).lower().strip(),
"customer_name": session.get("customer_details", {}).get("name", ""),
"stripe_customer_id": session.get("customer", ""),
"customer_name": customer_details.get("name") or "",
"stripe_customer_id": session.get("customer") or "",
"payment_link_id": payment_link_id,
# Payment method
"payment_method_type": pm_type,
"card_brand": card_info.get("brand", ""),
+16
View File
@@ -333,6 +333,22 @@ class StripeService:
logger.error(f"Error verifying webhook: {e}")
return False, None, str(e)
@staticmethod
def is_gen_checkout(session: Dict) -> bool:
"""True if this checkout was created by gen (credit purchase or made-for-you).
Gen always sets metadata (user_email/credits for credits, order_type for
made-for-you). A session without it came from elsewhere on the Stripe
account, e.g. a Stripe Payment Link (``session.payment_link`` set): it's a
real payment to record, not a credit purchase to fulfil.
"""
metadata = session.get('metadata') or {}
return bool(
metadata.get('order_type')
or metadata.get('user_email')
or metadata.get('credits')
)
def handle_checkout_completed(self, session: Dict) -> Tuple[bool, Optional[str], int, str]:
"""
Handle a completed checkout session.
+55 -5
View File
@@ -3,25 +3,62 @@
Mirrors the frontend sanitizeWordTimings.ts and the render-time
SegmentResizer._sanitize_segment_timings. Operates on the raw corrections dict the
frontend POSTs (Dict[str, Any]); clamps any word whose start/end falls outside its
segment window or is inverted. Segments whose own bounds are non-finite are left
untouched (the editor derives bounds from words elsewhere). Mutates and returns the
same dict for caller convenience, plus the number of fields clamped."""
segment window or is inverted. A segment whose own bounds are missing/non-finite
(JSON.stringify drops `undefined`, so an in-browser edit can arrive without them)
gets them from its words' timings, else from its neighbours; one with no usable
timing anywhere is left untouched (see find_missing_timings). Mutates and returns
the same dict for caller convenience, plus the number of fields changed."""
from __future__ import annotations
import math
from typing import Any, Dict, Tuple
from typing import Any, Dict, List, Optional, Tuple
def _finite(v: Any) -> bool:
return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
def _fill_segment_bounds(segments: List[Any]) -> int:
"""Give segments with missing/non-finite bounds ones derived from their words,
else from the neighbouring segments. Returns the number of fields filled."""
changes = 0
for i, seg in enumerate(segments):
if not isinstance(seg, dict):
continue
start, end = seg.get("start_time"), seg.get("end_time")
if _finite(start) and _finite(end):
continue
words = [w for w in seg.get("words", []) if isinstance(w, dict)]
starts = [w["start_time"] for w in words if _finite(w.get("start_time"))]
ends = [w["end_time"] for w in words if _finite(w.get("end_time"))]
prev_end = next((s.get("end_time") for s in reversed(segments[:i])
if isinstance(s, dict) and _finite(s.get("end_time"))), None)
next_start = next((s.get("start_time") for s in segments[i + 1:]
if isinstance(s, dict) and _finite(s.get("start_time"))), None)
new_start = start if _finite(start) else (min(starts + ends) if starts or ends else prev_end)
new_end = end if _finite(end) else (max(starts + ends) if starts or ends else next_start)
if new_start is None and new_end is None:
continue # no timing anywhere near it: leave it for find_missing_timings
if new_start is None:
new_start = new_end
if new_end is None or new_end < new_start:
new_end = new_start
if new_start != start:
seg["start_time"] = new_start
changes += 1
if new_end != end:
seg["end_time"] = new_end
changes += 1
return changes
def sanitize_corrections(corrections: Dict[str, Any]) -> Tuple[Dict[str, Any], int]:
segments = corrections.get("corrected_segments")
if not isinstance(segments, list):
return corrections, 0
changes = 0
changes = _fill_segment_bounds(segments)
for seg in segments:
if not isinstance(seg, dict):
continue
@@ -62,3 +99,16 @@ def sanitize_corrections(corrections: Dict[str, Any]) -> Tuple[Dict[str, Any], i
prev_end = new_end
return corrections, changes
def find_missing_timings(corrections: Dict[str, Any]) -> Optional[str]:
"""After sanitize_corrections: the text of the first line that still has a word
or segment without a finite start/end time, or None if every timing is usable."""
for seg in corrections.get("corrected_segments") or []:
if not isinstance(seg, dict):
continue
words = [w for w in seg.get("words", []) if isinstance(w, dict)]
fields = [seg] + words
if any(not _finite(f.get("start_time")) or not _finite(f.get("end_time")) for f in fields):
return str(seg.get("text") or " ".join(str(w.get("text", "")) for w in words)).strip()
return None
+50 -4
View File
@@ -4,8 +4,16 @@ Renders one karaoke frame of the default theme (same renderer as production, via
``theme_preview_service``) with sample lyrics and their translation in the chosen
language. Translations come from ``translation_preview_samples`` (generated once,
committed), so the preview never calls the LLM.
Each frame is a 4K ffmpeg render (~20s, ~1 GB peak). Two concurrent renders for
different languages got the API instance OOM-killed (10-09, 10-16), 503ing every
in-flight request. So renders are serialised process-wide, and each rendered frame
is kept in GCS (keyed by a digest of the theme style + sample) so a language is
rendered once per theme change, not once per cold instance.
"""
import base64
import hashlib
import json
import logging
import tempfile
import threading
@@ -24,6 +32,8 @@ _CACHE: "OrderedDict[tuple, str]" = OrderedDict()
_CACHE_MAX = 40
_lock = threading.Lock()
_key_locks: "dict[tuple, threading.Lock]" = {} # bounded: themes x 33 languages
_render_slot = threading.BoundedSemaphore(1) # one 4K render at a time per instance
GCS_PREFIX = "themes/_translation_previews"
def render_translation_preview(language: str, theme_id: Optional[str] = None) -> str:
@@ -48,14 +58,50 @@ def render_translation_preview(language: str, theme_id: Optional[str] = None) ->
return _render_and_cache(key, theme_service, theme_id, code)
def _gcs_path(theme_id: str, code: str, style_params: dict) -> str:
digest = hashlib.sha256(
json.dumps([style_params, SAMPLES[code]], sort_keys=True, default=str).encode()
).hexdigest()[:16]
return f"{GCS_PREFIX}/{theme_id}/{code}-{digest}.jpg"
def _gcs_get(path: str) -> Optional[bytes]:
try:
from google.cloud.exceptions import NotFound
from backend.services.storage_service import StorageService
try:
return StorageService().bucket.blob(path).download_as_bytes()
except NotFound:
return None
except Exception as e: # cache read is best-effort; fall back to rendering
logger.warning(f"Translation preview cache read failed for {path}: {e}")
return None
def _gcs_put(path: str, jpeg: bytes) -> None:
try:
from backend.services.storage_service import StorageService
StorageService().bucket.blob(path).upload_from_string(jpeg, content_type="image/jpeg")
except Exception as e: # best-effort; the next cold instance just renders again
logger.warning(f"Translation preview cache write failed for {path}: {e}")
def _render_and_cache(key: tuple, theme_service, theme_id: str, code: str) -> str:
style_params = theme_service.get_theme_style_params(theme_id)
if style_params is None:
raise ValueError(f"Theme not found: {theme_id}")
styles = resolve_assets(style_params, theme_id)
sample = SAMPLES[code]
with tempfile.TemporaryDirectory(prefix="translation-preview-") as workdir:
jpeg = render_karaoke_frame(styles, sample["lyrics"], workdir, translations=sample["translations"])
path = _gcs_path(theme_id, code, style_params)
jpeg = _gcs_get(path)
if jpeg is None:
styles = resolve_assets(style_params, theme_id)
sample = SAMPLES[code]
with _render_slot:
with tempfile.TemporaryDirectory(prefix="translation-preview-") as workdir:
jpeg = render_karaoke_frame(styles, sample["lyrics"], workdir, translations=sample["translations"])
_gcs_put(path, jpeg)
data_url = "data:image/jpeg;base64," + base64.b64encode(jpeg).decode()
with _lock:
_CACHE[key] = data_url
+73 -29
View File
@@ -5,6 +5,7 @@ Handles changing a job's visibility between public and private:
- Public -> Private: redistribute existing finals to private destination (fast, ~1-2 min)
- Private -> Public: reset styles, regenerate screens, re-render, re-encode (slow, ~15-30 min)
"""
import asyncio
import logging
from datetime import datetime, timezone
from typing import Optional
@@ -18,6 +19,10 @@ from backend.services.storage_service import StorageService
logger = logging.getLogger(__name__)
class VisibilityChangeInProgress(Exception):
"""Another visibility change for this job claimed it first."""
class VisibilityChangeService:
"""Service for changing job visibility after completion."""
@@ -53,7 +58,9 @@ class VisibilityChangeService:
return None
async def change_to_private(self, job_id: str, job, user_email: str, regenerate_if_missing: bool = True) -> dict:
async def change_to_private(
self, job_id: str, job, user_email: str, regenerate_if_missing: bool = True, holds_claim: bool = False,
) -> dict:
"""
Change a public job to private (fast path).
@@ -67,6 +74,9 @@ class VisibilityChangeService:
public may be destroyed until the private archive exists. If redistribution
fails, the job is reverted to public and left fully intact (no partial
deletion, no leaked NOMADNP code — see redistribute_video's failure path).
``holds_claim``: the caller already owns ``visibility_change_in_progress``
(the regenerate-then-private continuation, whose regenerate set it).
"""
logger.info(f"[job:{job_id}] Starting visibility change: public -> private (by {user_email})")
@@ -107,6 +117,14 @@ class VisibilityChangeService:
# destination. Public outputs remain live until the private archive exists.
# No "changed to private" timeline event yet — it is only recorded once the
# move actually succeeds (this is reverted if redistribution fails).
# Claim atomically: two requests that both read the job before either wrote
# the flag must not both redistribute and delete the public outputs.
if not holds_claim:
claimed = await asyncio.to_thread(
self.job_manager.firestore.try_set_job_state_flag, job_id, "visibility_change_in_progress"
)
if not claimed:
raise VisibilityChangeInProgress("A visibility change is already in progress for this job")
job_ref.update({
"state_data.visibility_change_in_progress": True,
"is_private": True,
@@ -141,7 +159,8 @@ class VisibilityChangeService:
# the public outputs + recycling the public NOMAD number is best-effort
# (each failure is logged inside the helper, never raised), so a stray
# orphaned public artifact cannot undo the successful private move.
await self._delete_public_outputs(job_id, public_outputs)
# Sync YouTube/Dropbox/GDrive/GCS deletes: keep them off the API event loop.
await asyncio.to_thread(self._delete_public_outputs, job_id, public_outputs)
# Record the completed move and clear the guard flag. redistribute_video
# already updated state_data with the new private brand_code etc.
@@ -171,12 +190,61 @@ class VisibilityChangeService:
"""
logger.info(f"[job:{job_id}] Starting visibility change: private -> public (by {user_email})")
# Claim the job before any deletes: two concurrent requests that both passed
# validate_change must not both recycle the brand code and re-process.
claimed = await asyncio.to_thread(
self.job_manager.firestore.try_set_job_state_flag, job_id, "visibility_change_in_progress"
)
if not claimed:
raise VisibilityChangeInProgress("A visibility change is already in progress for this job")
db = self.job_manager.firestore.db
job_ref = db.collection("jobs").document(job_id)
try:
# Steps 1-5 are sync YouTube/Dropbox/GDrive/GCS/Firestore I/O: off the event loop.
await asyncio.to_thread(self._reset_job_for_public, job_id, job, user_email, job_ref)
except Exception:
try:
job_ref.update({"state_data.visibility_change_in_progress": DELETE_FIELD})
except Exception:
# The job now refuses every visibility change until the flag is cleared.
logger.exception(f"[job:{job_id}] Failed to release visibility_change_in_progress after a failed reset")
raise
# Step 6: Trigger screens worker
from backend.services.worker_service import get_worker_service
worker_service = get_worker_service()
try:
triggered = await worker_service.trigger_screens_worker(job_id)
except Exception as e:
logger.warning(f"[job:{job_id}] Screens worker trigger raised during visibility change: {e}")
triggered = False
if not triggered:
logger.error(f"[job:{job_id}] Failed to trigger screens worker for visibility change")
# Restore to complete status on failure
job_ref.update({
"status": "complete",
"is_private": True,
"state_data.visibility_change_in_progress": DELETE_FIELD,
"state_data.regen_restore_status": DELETE_FIELD,
})
raise RuntimeError("Failed to trigger screens worker")
logger.info(f"[job:{job_id}] Visibility change to public initiated, screens worker triggered")
return {
"status": "processing",
"message": "Visibility change to public started. The video will be re-rendered "
"with default branding and published publicly. This takes ~15-30 minutes.",
"reprocessing_required": True,
}
def _reset_job_for_public(self, job_id: str, job, user_email: str, job_ref) -> None:
"""Steps 1-5 of change_to_public (all sync I/O; run via asyncio.to_thread)."""
storage = StorageService()
# Step 1: Delete distributed outputs + GCS finals
await self._delete_distributed_outputs(job_id, job, keep_gcs_finals=False)
self._delete_distributed_outputs(job_id, job, keep_gcs_finals=False)
# Step 2: Delete screens and rendered video from GCS
for path in [
@@ -252,31 +320,7 @@ class VisibilityChangeService:
}
job_ref.update(update_payload)
# Step 6: Trigger screens worker
from backend.services.worker_service import get_worker_service
worker_service = get_worker_service()
triggered = await worker_service.trigger_screens_worker(job_id)
if not triggered:
logger.error(f"[job:{job_id}] Failed to trigger screens worker for visibility change")
# Restore to complete status on failure
job_ref.update({
"status": "complete",
"is_private": True,
"state_data.visibility_change_in_progress": DELETE_FIELD,
"state_data.regen_restore_status": DELETE_FIELD,
})
raise RuntimeError("Failed to trigger screens worker")
logger.info(f"[job:{job_id}] Visibility change to public initiated, screens worker triggered")
return {
"status": "processing",
"message": "Visibility change to public started. The video will be re-rendered "
"with default branding and published publicly. This takes ~15-30 minutes.",
"reprocessing_required": True,
}
async def _delete_public_outputs(self, job_id: str, public_outputs: dict):
def _delete_public_outputs(self, job_id: str, public_outputs: dict):
"""Delete the captured PUBLIC outputs and recycle the public NOMAD number.
Used by change_to_private AFTER a successful private redistribution. Operates
@@ -373,7 +417,7 @@ class VisibilityChangeService:
f"public cleanup incomplete (youtube={youtube_ok}, dropbox={dropbox_ok}, gdrive={gdrive_ok})"
)
async def _delete_distributed_outputs(self, job_id: str, job, keep_gcs_finals: bool = False):
def _delete_distributed_outputs(self, job_id: str, job, keep_gcs_finals: bool = False):
"""Delete distributed outputs (YouTube, Dropbox, GDrive) and recycle brand code."""
import re
+537
View File
@@ -0,0 +1,537 @@
"""YouTube comment auto-reply: song requests in channel comments -> requests board.
Viewers often comment "could you make <song>?" on Nomad Karaoke videos. This module
decides, for one top-level comment thread, whether to reply and with what:
- an already-published Nomad video of that song -> link to it;
- otherwise -> add the song to the requests board (or find the existing request)
and link straight to it, so the commenter can sign in with an email and upvote it.
The reply is board-only on purpose (Andrew, 2026-10-22): the goal is turning an
anonymous YouTuber into a requests-board user with a real email address; the
board UI and follow-up emails do the gen conversion later.
Everything here is pure decision logic behind small injectable ports (classifier,
translator, board, channel index), shared by the local replay script
(``scripts/youtube-comments/replay.py``, the go-live gate) and the prod worker
(``backend/workers/youtube_comment_bot_worker.py``). Plan:
``docs/archive/2026-10-22-youtube-comment-autoreply-plan.md``.
"""
from __future__ import annotations
import json
import logging
import re
from dataclasses import dataclass, field
from datetime import datetime
from typing import Callable, Dict, List, Optional, Protocol, Sequence
from urllib.parse import urlencode
from backend.services.match_judge.classifier import normalize_for_match
logger = logging.getLogger(__name__)
NOMAD_CHANNEL_ID = "UCroMk5b4XILdeP7ZCGFicpw"
BOARD_URL = "https://requests.nomadkaraoke.com/"
BOARD_UTM = {
"utm_source": "youtube",
"utm_medium": "comment_reply",
"utm_campaign": "song_request",
}
MAX_SONGS_PER_COMMENT = 3
DEFAULT_MIN_CONFIDENCE = 0.8
def song_key(artist: str, title: str) -> str:
"""Same key shape as the board's ``_dedupe_key`` (artist|title, match-normalized)."""
return f"{normalize_for_match(artist)}|{normalize_for_match(title)}"
def board_link(request_id: Optional[str] = None) -> str:
params = {"request": request_id} if request_id else {}
return f"{BOARD_URL}?{urlencode({**params, **BOARD_UTM})}"
def video_link(video_id: str) -> str:
return f"https://youtu.be/{video_id}"
# ---------------------------------------------------------------------------
# Inputs
# ---------------------------------------------------------------------------
@dataclass
class CommentThread:
"""A top-level comment plus what we know about replies to it."""
thread_id: str
comment_id: str
video_id: str
author: str
author_channel_id: str
text: str
published_at: str # RFC 3339 from the API
total_reply_count: int = 0
# Text of replies written by the channel itself (Andrew answering by hand).
owner_replies: List[str] = field(default_factory=list)
@property
def published(self) -> Optional[datetime]:
try:
return datetime.fromisoformat(self.published_at.replace("Z", "+00:00"))
except (AttributeError, ValueError):
return None
def thread_from_api(item: Dict, channel_id: str = NOMAD_CHANNEL_ID) -> CommentThread:
"""Build a CommentThread from a ``commentThreads.list`` item (part=snippet,replies).
``replies`` holds at most 5 replies; callers that need the full list when
``total_reply_count`` exceeds that fetch them and pass ``owner_replies`` in.
"""
snip = item.get("snippet", {})
top = snip.get("topLevelComment", {})
tsnip = top.get("snippet", {})
owner_replies = [
(r.get("snippet", {}).get("textOriginal") or r.get("snippet", {}).get("textDisplay") or "")
for r in (item.get("replies", {}) or {}).get("comments", []) or []
if (r.get("snippet", {}).get("authorChannelId") or {}).get("value") == channel_id
]
return CommentThread(
thread_id=item.get("id", ""),
comment_id=top.get("id", item.get("id", "")),
video_id=snip.get("videoId") or tsnip.get("videoId") or "",
author=tsnip.get("authorDisplayName", ""),
author_channel_id=(tsnip.get("authorChannelId") or {}).get("value", ""),
text=tsnip.get("textOriginal") or tsnip.get("textDisplay") or "",
published_at=tsnip.get("publishedAt", ""),
total_reply_count=int(snip.get("totalReplyCount", 0) or 0),
owner_replies=owner_replies,
)
# ---------------------------------------------------------------------------
# Classifier (Gemini, injectable)
# ---------------------------------------------------------------------------
@dataclass
class SongAsk:
artist: str
title: str
@dataclass
class Classification:
is_song_request: bool
songs: List[SongAsk]
language: str # ISO 639-1, "en" when unsure
confidence: float
reason: str = ""
is_vague_request: bool = False
# The classifier call itself failed (timeout, 5xx, quota): retry later.
error: bool = False
CLASSIFIER_SYSTEM_PROMPT = """\
You read YouTube comments left on karaoke videos published by the Nomad Karaoke channel.
Decide whether the comment asks the channel to MAKE a karaoke version of one or more
specific songs (a song request).
Counts as a song request:
- "Can you do <song> by <artist>?", "please make <song>", "next do <artist> - <song>",
"would love a karaoke of <song>", or the same in any language.
- A request where the artist is implied but the song title is clear
(e.g. "can you do Yellow next" on a Coldplay video) - fill in the artist when you are sure.
A bare song name with no ask at all ("<song> karaoke 🎤") is a weak signal: count it
only when it clearly relates to the video (same artist, e.g. "<artist> <other song>
karaoke songs" on that artist's video); on an unrelated video give it confidence 0.5.
Does NOT count:
- Praise, thanks, singing reports, jokes, lyric corrections, timing complaints.
- Questions about how the videos are made, software, pricing or downloads.
- Asking for a change to THIS video (key change, backing vocals, slower, duet version).
- Mentions of songs without asking for them to be made.
- Vague asks with no identifiable song ("do more 80s songs", "anything by Queen").
Vague asks get their own flag: set is_vague_request=true (and is_song_request=false,
songs=[]) when the comment asks the channel to make MORE songs without naming a
specific song: "more Johnnie please", "do more from this album", "can you do more
Taylor Swift". Plain praise like "love your channel, keep it up" is NOT vague_request.
If ANY specific song title is identifiable (even lowercase, abbreviated or with the
artist run in, e.g. "playa fly n god we trust karaoke"), it is a song request, not vague.
Return JSON only. confidence is 0..1 that your classification (request, vague
request, or neither) is right.
Give the artist and title as properly capitalised canonical names. List at most 3 songs.
language is the ISO 639-1 code of the comment's language ("en" if unsure)."""
CLASSIFIER_RESPONSE_SCHEMA = {
"type": "OBJECT",
"properties": {
"is_song_request": {"type": "BOOLEAN"},
"is_vague_request": {"type": "BOOLEAN"},
"songs": {
"type": "ARRAY",
"items": {
"type": "OBJECT",
"properties": {
"artist": {"type": "STRING"},
"title": {"type": "STRING"},
},
"required": ["artist", "title"],
},
},
"language": {"type": "STRING"},
"confidence": {"type": "NUMBER"},
"reason": {"type": "STRING"},
},
"required": ["is_song_request", "songs", "language", "confidence"],
}
# (system_prompt, user_prompt, response_schema) -> parsed JSON dict
Generate = Callable[[str, str, Optional[Dict]], Dict]
MAX_NAME_LEN = 100
# Artist/title come from the model reading untrusted comment text and end up in a
# public reply posted as the channel + on the public board: never let a link, an
# @mention, markup or a multi-line blob through.
_UNSAFE_NAME_RE = re.compile(r"https?://|www\.|\.(com|net|org|io|ly|gg|xyz)\b|[@<>\r\n]", re.IGNORECASE)
def _unsafe_name(value: str) -> bool:
return len(value) > MAX_NAME_LEN or bool(_UNSAFE_NAME_RE.search(value))
def parse_classification(data: Dict) -> Classification:
"""Validate the model's JSON; anything malformed becomes a non-request."""
if not isinstance(data, dict):
return Classification(False, [], "en", 0.0, "malformed classifier output")
songs: List[SongAsk] = []
for s in data.get("songs") or []:
if not isinstance(s, dict):
continue
artist = str(s.get("artist") or "").strip()
title = str(s.get("title") or "").strip()
if artist and title and not _unsafe_name(artist) and not _unsafe_name(title):
songs.append(SongAsk(artist, title))
try:
confidence = float(data.get("confidence") or 0.0)
except (TypeError, ValueError):
confidence = 0.0
language = str(data.get("language") or "en").strip().lower()[:5] or "en"
is_request = bool(data.get("is_song_request")) and bool(songs)
return Classification(
is_song_request=is_request,
songs=songs[:MAX_SONGS_PER_COMMENT],
language=language,
confidence=max(0.0, min(1.0, confidence)),
reason=str(data.get("reason") or ""),
is_vague_request=bool(data.get("is_vague_request")) and not is_request,
)
def classify_comment(text: str, video_title: str, generate: Generate) -> Classification:
user_prompt = f"Video title: {video_title or '(unknown)'}\nComment: {text}"
try:
data = generate(CLASSIFIER_SYSTEM_PROMPT, user_prompt, CLASSIFIER_RESPONSE_SCHEMA)
except Exception: # noqa: BLE001 - a classifier failure must never post anything
logger.warning("youtube-comment-bot: classifier call failed", exc_info=True)
return Classification(False, [], "en", 0.0, "classifier error", error=True)
return parse_classification(data)
def gemini_generate(model: Optional[str] = None, timeout_ms: int = 20000) -> Generate:
"""Default Generate backed by the Gemini Developer API (never Vertex)."""
def _generate(system_prompt: str, user_prompt: str, schema: Optional[Dict]) -> Dict:
import copy
from google.genai import types
from backend.config import get_settings
from backend.services.gemini_client import get_genai_client
client = get_genai_client(timeout_ms=timeout_ms)
config = dict(
system_instruction=system_prompt,
temperature=0,
thinking_config=types.ThinkingConfig(thinking_level="low"),
)
if schema is not None:
config["response_mime_type"] = "application/json"
config["response_schema"] = copy.deepcopy(schema)
response = client.models.generate_content(
model=model or get_settings().match_judge_model,
contents=[user_prompt],
config=types.GenerateContentConfig(**config),
)
if schema is None:
return {"text": response.text or ""}
return json.loads(response.text)
return _generate
# ---------------------------------------------------------------------------
# Channel index + board port
# ---------------------------------------------------------------------------
class ChannelIndex:
"""song_key -> video_id for Nomad's own published karaoke videos."""
def __init__(self, by_key: Optional[Dict[str, str]] = None, titles: Optional[Dict[str, str]] = None):
self.by_key: Dict[str, str] = dict(by_key or {})
self.titles: Dict[str, str] = dict(titles or {}) # video_id -> YouTube title
@classmethod
def from_entries(cls, entries: Sequence[Dict]) -> "ChannelIndex":
"""Build from ``youtube_backfill.classify()`` results (high-confidence titles only)."""
idx = cls()
for e in entries:
vid = e.get("video_id")
if vid and e.get("yt_title"):
idx.titles[vid] = e["yt_title"]
if not (vid and e.get("artist") and e.get("song_title")):
continue
if e.get("parse_confidence") != "high" or e.get("translation_language_name"):
continue
idx.by_key.setdefault(song_key(e["artist"], e["song_title"]), vid)
return idx
def find(self, artist: str, title: str) -> Optional[str]:
return self.by_key.get(song_key(artist, title))
@dataclass
class BoardMatch:
request_id: str
artist: str
title: str
status: str # board RequestStatus
youtube_url: Optional[str] = None
class BoardPort(Protocol):
def canonicalize(self, artist: str, title: str) -> "tuple[str, str]": ...
def find_open_or_published(self, artist: str, title: str) -> Optional[BoardMatch]: ...
def add_from_comment(self, artist: str, title: str, thread: CommentThread) -> BoardMatch: ...
# ---------------------------------------------------------------------------
# Decision
# ---------------------------------------------------------------------------
@dataclass
class SongAction:
artist: str
title: str
kind: str # existing_video | board_published | board_existing | board_new
url: str
request_id: Optional[str] = None
video_id: Optional[str] = None
@dataclass
class Decision:
action: str # "reply" | "skip"
reason: str
classification: Optional[Classification] = None
songs: List[SongAction] = field(default_factory=list)
reply_text: str = ""
reply_text_en: str = ""
def _quote(s: SongAction) -> str:
return f'"{s.title}" by {s.artist}'
def render_reply_en(songs: Sequence[SongAction]) -> str:
"""Short, casual, board-only English reply (Andrew's style: brief + emoji)."""
made = [s for s in songs if s.kind in ("existing_video", "board_published")]
board = [s for s in songs if s.kind in ("board_existing", "board_new")]
parts: List[str] = []
if len(made) == 1:
parts.append(f"Already made {_quote(made[0])} 🥳 {made[0].url}")
elif made:
parts.append("Already made these 🥳\n" + "\n".join(f"{_quote(s)}: {s.url}" for s in made))
if len(board) == 1:
s = board[0]
parts.append(f"Added {_quote(s)} to our requests board 🥳 upvote it here and we'll "
f"email you when it's made: {s.url}")
elif board:
parts.append("Added these to our requests board 🥳 upvote them and we'll email you "
"when they're made:\n" + "\n".join(f"{_quote(s)}: {s.url}" for s in board))
return "\n\n".join(parts)
def render_vague_reply_en() -> str:
return f"Request any song you'd like on our requests board 🥳 {board_link()}"
TRANSLATE_SYSTEM_PROMPT = """\
Translate this short YouTube reply from a karaoke channel into the target language.
Keep it warm and casual. Keep every URL, song title and artist name exactly as written.
Return only the translated text."""
_URL_RE = re.compile(r"https?://\S+")
def translate_reply(text_en: str, language: str, generate: Generate) -> str:
"""Translate the reply for non-English comments; English on any doubt."""
if not language or language.startswith("en"):
return text_en
try:
out = generate(TRANSLATE_SYSTEM_PROMPT, f"Target language: {language}\n\n{text_en}", None)
translated = str((out or {}).get("text") or "").strip()
except Exception: # noqa: BLE001
logger.warning("youtube-comment-bot: translation failed; replying in English", exc_info=True)
return text_en
# Every link must survive verbatim, or we fall back to English.
if not translated or sorted(_URL_RE.findall(translated)) != sorted(_URL_RE.findall(text_en)):
return text_en
return translated
def decide(
thread: CommentThread,
*,
video_title: str,
index: ChannelIndex,
board: BoardPort,
generate: Generate,
channel_id: str = NOMAD_CHANNEL_ID,
min_confidence: float = DEFAULT_MIN_CONFIDENCE,
not_before: Optional[datetime] = None,
) -> Decision:
"""Decide what (if anything) to reply to one top-level comment thread.
``board.add_from_comment`` is only called for a confident request, so the
replay's simulated board and the prod board see exactly the same calls.
"""
if thread.author_channel_id == channel_id:
return Decision("skip", "own_comment")
if thread.owner_replies:
return Decision("skip", "already_replied")
if not_before is not None:
published = thread.published
if published is None or published < not_before:
return Decision("skip", "too_old")
if not thread.text.strip():
return Decision("skip", "empty")
classification = classify_comment(thread.text, video_title, generate)
if classification.error:
return Decision("skip", "classifier_error", classification)
if classification.is_vague_request:
if classification.confidence < min_confidence:
return Decision("skip", "low_confidence", classification)
reply_en = render_vague_reply_en()
reply = translate_reply(reply_en, classification.language, generate)
return Decision("reply", "vague_request", classification, [], reply, reply_en)
if not classification.is_song_request:
return Decision("skip", "not_a_request", classification)
if classification.confidence < min_confidence:
return Decision("skip", "low_confidence", classification)
actions: List[SongAction] = []
seen: set = set()
for ask in classification.songs:
artist, title = board.canonicalize(ask.artist, ask.title)
key = song_key(artist, title)
if key in seen:
continue
seen.add(key)
vid = index.find(artist, title) or index.find(ask.artist, ask.title)
if vid:
actions.append(SongAction(artist, title, "existing_video", video_link(vid), video_id=vid))
continue
match = board.find_open_or_published(artist, title)
if match and match.status == "published" and match.youtube_url:
actions.append(SongAction(match.artist, match.title, "board_published",
match.youtube_url, request_id=match.request_id))
continue
if match:
actions.append(SongAction(match.artist, match.title, "board_existing",
board_link(match.request_id), request_id=match.request_id))
continue
created = board.add_from_comment(artist, title, thread)
actions.append(SongAction(created.artist, created.title, "board_new",
board_link(created.request_id), request_id=created.request_id))
if not actions:
return Decision("skip", "no_songs", classification)
reply_en = render_reply_en(actions)
reply = translate_reply(reply_en, classification.language, generate)
return Decision("reply", "song_request", classification, actions, reply, reply_en)
# ---------------------------------------------------------------------------
# YouTube API helpers (shared by the replay script and the worker)
# ---------------------------------------------------------------------------
def iter_comment_threads(youtube, channel_id: str = NOMAD_CHANNEL_ID,
stop_before: Optional[datetime] = None, max_pages: int = 500):
"""Yield ``commentThreads.list`` items for the whole channel, newest first.
1 quota unit per page of 100. Stops once a page's oldest thread is older than
``stop_before`` (order=time is by top-level comment publish time).
"""
token = None
for _ in range(max_pages):
resp = (
youtube.commentThreads()
.list(part="snippet,replies", allThreadsRelatedToChannelId=channel_id,
order="time", maxResults=100, textFormat="plainText", pageToken=token)
.execute()
)
items = resp.get("items", [])
reached_end = False
for item in items:
if stop_before is not None:
published = thread_from_api(item, channel_id).published
if published is not None and published < stop_before:
reached_end = True
break
yield item
token = resp.get("nextPageToken")
if reached_end or not token:
return
def fetch_owner_replies(youtube, parent_id: str, channel_id: str = NOMAD_CHANNEL_ID) -> List[str]:
"""All replies by the channel on a thread (``comments.list``, 1 unit per page)."""
out: List[str] = []
token = None
while True:
resp = (
youtube.comments()
.list(part="snippet", parentId=parent_id, maxResults=100,
textFormat="plainText", pageToken=token)
.execute()
)
for c in resp.get("items", []):
s = c.get("snippet", {})
if (s.get("authorChannelId") or {}).get("value") == channel_id:
out.append(s.get("textOriginal") or s.get("textDisplay") or "")
token = resp.get("nextPageToken")
if not token:
return out
def load_thread(youtube, item: Dict, channel_id: str = NOMAD_CHANNEL_ID) -> CommentThread:
"""thread_from_api, completing owner_replies when the API truncated replies."""
thread = thread_from_api(item, channel_id)
inline = len((item.get("replies", {}) or {}).get("comments", []) or [])
if not thread.owner_replies and thread.total_reply_count > inline:
thread.owner_replies = fetch_owner_replies(youtube, thread.comment_id, channel_id)
return thread
def post_reply(youtube, parent_comment_id: str, text: str) -> str:
"""Post a reply as the channel (needs the youtube.force-ssl scope; 50 units)."""
resp = (
youtube.comments()
.insert(part="snippet", body={"snippet": {"parentId": parent_comment_id, "textOriginal": text}})
.execute()
)
return resp.get("id", "")
@@ -151,6 +151,71 @@ class TestResearch:
if c.args[1].get("title") == "The View from the Afternoon"]
assert applied, "expected edited title applied to job"
def test_research_makes_no_status_writes(self, mock_job_manager):
"""A re-search must not attempt status transitions or status writes.
Regression: research_audio called transition_to_state(SEARCHING_AUDIO)
and back, but AWAITING_AUDIO_SELECTION -> SEARCHING_AUDIO isn't a valid
transition, so every admin re-search logged two "Invalid state
transition" ERRORs (each an #alerts page). The job simply stays in
AWAITING_AUDIO_SELECTION while its cached results are replaced.
"""
from fastapi.testclient import TestClient
from backend.main import app
search = MagicMock()
search.search_async = AsyncMock(return_value=[_result(0)])
search.last_remote_search_id = None
p1, p2 = self._patched(mock_job_manager, search)
with p1, p2:
client = TestClient(app)
resp = client.post("/api/audio-search/park-1/research", json={})
assert resp.status_code == 200, resp.text
mock_job_manager.transition_to_state.assert_not_called()
mock_job_manager.update_job_status.assert_not_called()
for c in mock_job_manager.update_job.call_args_list:
assert "status" not in c.args[1]
def test_research_discards_results_if_selection_landed_mid_search(self, mock_job_manager):
"""A selection made during the search must keep the results it indexed into."""
from fastapi.testclient import TestClient
from backend.main import app
selected = _parked_job(status=JobStatus.DOWNLOADING_AUDIO)
mock_job_manager.get_job.side_effect = [_parked_job(), selected]
search = MagicMock()
search.search_async = AsyncMock(return_value=[_result(0)])
search.last_remote_search_id = None
p1, p2 = self._patched(mock_job_manager, search)
with p1, p2:
client = TestClient(app)
resp = client.post("/api/audio-search/park-1/research", json={})
assert resp.status_code == 409
cached = [c for c in mock_job_manager.update_job.call_args_list
if "state_data.audio_search_results" in c.args[1]]
assert not cached
def test_research_search_error_makes_no_status_writes(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
search = MagicMock()
search.search_async = AsyncMock(side_effect=AudioSearchError("boom"))
p1, p2 = self._patched(mock_job_manager, search)
with p1, p2:
client = TestClient(app)
resp = client.post("/api/audio-search/park-1/research", json={})
assert resp.status_code == 502
mock_job_manager.transition_to_state.assert_not_called()
mock_job_manager.update_job_status.assert_not_called()
def test_research_502_on_search_error(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
@@ -7,6 +7,7 @@ Increment attempt counter, create()-only single-use / idempotency markers,
set(merge=True) preserving the precomputed eval, and the FieldFilter queries
behind the signup / show-credit caps. Run with: scripts/run-emulator-tests.sh
"""
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone
@@ -156,10 +157,17 @@ class TestShowCredit:
prefix = uuid.uuid4().hex
def attempt(i):
try:
return _grant(svc, ref, email, f"{prefix}-{i}", max_per_24h=3).granted
except (kps.ShowCreditCapReached, kps.TransactionContention):
return False
# Retry on contention like a real caller would. Treating contention
# as "not granted" let all 8 lose on the emulator (granted == 0), a
# flake that blocked unrelated PRs (#1191, #1192 on 2026-10-19).
for _ in range(20):
try:
return _grant(svc, ref, email, f"{prefix}-{i}", max_per_24h=3).granted
except kps.ShowCreditCapReached:
return False
except kps.TransactionContention:
time.sleep(0.05)
return False
with ThreadPoolExecutor(max_workers=8) as pool:
results = list(pool.map(attempt, range(8)))
@@ -298,3 +298,82 @@ async def test_snooze_clear_and_reject(service):
r = service.get_request(a.id)
assert r.status == "rejected" and r.review_state is None
assert a.id not in [x.id for x in service.list_active()]
# ---------------------------------------------------------------------------
# YouTube comment bot: bot-added requests + claim on first real upvote
# ---------------------------------------------------------------------------
def _bot_add(service, artist="Glass Harbor", title="Tin Sky", comment_id="c1"):
return service.add_from_youtube_comment(artist, title, comment_id=comment_id, video_id="v1", author="Viewer")
def test_bot_add_creates_unclaimed_request_without_vote(service):
from backend.models.song_request import YOUTUBE_COMMENT_SUBMITTER
req = _bot_add(service)
stored = service.get_request(req.id)
assert stored.source == "youtube_comment"
assert stored.submitted_by == YOUTUBE_COMMENT_SUBMITTER
assert stored.vote_count == 0 and stored.youtube_comment_id == "c1"
def test_bot_add_returns_existing_open_request(service):
a = _bot_add(service, comment_id="c1")
b = _bot_add(service, artist="glass harbor", title="tin sky", comment_id="c2")
assert a.id == b.id
@pytest.mark.asyncio
async def test_bot_add_returns_existing_human_request(service):
human, _, _, _ = await _submit(service, "u1@x.com", "Glass Harbor", "Tin Sky")
assert _bot_add(service).id == human.id
def test_first_upvote_claims_and_second_does_not_steal(service):
req = _bot_add(service)
service.cast_vote("first@x.com", req.id, "up")
service.cast_vote("second@x.com", req.id, "up")
stored = service.get_request(req.id)
assert stored.submitted_by == "first@x.com" and stored.claimed_at is not None
assert stored.vote_count == 2
def test_downvote_does_not_claim(service):
from backend.models.song_request import YOUTUBE_COMMENT_SUBMITTER
req = _bot_add(service)
service.cast_vote("hater@x.com", req.id, "down")
assert service.get_request(req.id).submitted_by == YOUTUBE_COMMENT_SUBMITTER
def test_unclaimed_bot_request_is_not_pickable_until_claimed(service):
req = _bot_add(service)
assert req.id not in [r.id for r in service.list_pick_candidates()]
service.cast_vote("fan@x.com", req.id, "up")
assert req.id in [r.id for r in service.list_pick_candidates()]
@pytest.mark.asyncio
async def test_human_resubmit_of_bot_request_claims_it(service):
req = _bot_add(service)
again, existed, _, _ = await _submit(service, "fan@x.com", "Glass Harbor", "Tin Sky")
assert existed and again.id == req.id
assert service.get_request(req.id).submitted_by == "fan@x.com"
def test_find_published_by_key(service):
req = _bot_add(service)
service.db.collection(srs.REQUESTS_COLLECTION).document(req.id).update(
{"status": "published", "youtube_url": "https://youtu.be/x"})
found = service.find_published_by_key(req.dedupe_key)
assert found and found.id == req.id
def test_bot_add_dedupes_against_request_being_made(service):
req = _bot_add(service, comment_id="c1")
service.transition_status(req.id, "open", "queued")
again = _bot_add(service, comment_id="c2")
assert again.id == req.id and again.status == "queued"
assert service.find_active_by_key(req.dedupe_key).id == req.id
@@ -0,0 +1,78 @@
"""
FirestoreService.try_set_job_state_flag is an atomic test-and-set: of several
concurrent callers exactly one wins. change_to_public relies on it to claim
visibility_change_in_progress before deleting anything.
Run with: scripts/run-emulator-tests.sh
"""
import threading
import uuid
from datetime import datetime, UTC
import pytest
from backend.tests.emulator.conftest import emulators_running
pytestmark = pytest.mark.skipif(
not emulators_running(),
reason="GCP emulators not running. Start with: scripts/start-emulators.sh"
)
if emulators_running():
from backend.models.job import Job, JobStatus
from backend.services.firestore_service import FirestoreService
def _create_job(service, state_data):
job_id = f"tas-{uuid.uuid4().hex[:8]}"
service.create_job(Job(
job_id=job_id,
status=JobStatus.COMPLETE,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Test",
state_data=state_data,
))
return job_id
def test_sets_flag_once():
service = FirestoreService()
job_id = _create_job(service, {})
assert service.try_set_job_state_flag(job_id, "visibility_change_in_progress") is True
assert service.try_set_job_state_flag(job_id, "visibility_change_in_progress") is False
assert service.get_job(job_id).state_data["visibility_change_in_progress"] is True
def test_already_set_flag_is_not_claimed():
service = FirestoreService()
job_id = _create_job(service, {"visibility_change_in_progress": True})
assert service.try_set_job_state_flag(job_id, "visibility_change_in_progress") is False
def test_missing_job_is_not_claimed():
assert FirestoreService().try_set_job_state_flag("no-such-job", "visibility_change_in_progress") is False
def test_exactly_one_concurrent_caller_wins():
service = FirestoreService()
job_id = _create_job(service, {})
barrier = threading.Barrier(4)
results = []
def attempt():
barrier.wait()
try:
results.append(FirestoreService().try_set_job_state_flag(job_id, "visibility_change_in_progress"))
except Exception as e: # contention abort after retries: a loss, never a second winner
results.append(e)
threads = [threading.Thread(target=attempt) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
assert len(results) == 4
assert [r for r in results if r is True] == [True]
Whitespace-only changes.
@@ -0,0 +1,370 @@
"""Fixtures and knobs the fake workers offer the mobile review flows (FakeConfig.review_fixture etc.)."""
import asyncio
import re
import shutil
import threading
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from backend.models.job import JobStatus
from backend.services.fake_workers import config as fw_config
from backend.services.fake_workers.config import FakeConfig, get_fake_config, set_fake_config
from backend.services.fake_workers.lyrics import build_corrections
from backend.tests.test_fake_workers import FakeDB
HEBREW = re.compile("[֐-׿]")
ARABIC = re.compile("[؀-ۿ]")
def _words(doc):
return [w for s in doc["corrected_segments"] for w in s["words"]]
class TestFixtures:
def test_fixture_corrections_shape(self):
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
doc = build_corrections("A", "T", 30, "corrections")
CorrectionResult.from_dict(doc) # still the real schema
words = _words(doc)
replaced = [w for w in words if w.get("ai_corrected") and w.get("original_text")]
assert replaced
assert any(w.get("timing_estimated") for w in words)
assert [w for w in words if w["start_time"] is None] and \
len([w for w in words if w["start_time"] is None]) == 1
assert any(w["start_time"] is not None and w["end_time"] - w["start_time"] > 2 for w in words)
gap = doc["vocal_gaps"]["gaps"][0]
assert gap["evidenced"] is True
assert gap["synced_reference_lines"]["lrclib"]
undo = doc["metadata"]["auto_approval"]["undo_info"]
assert undo["fake-sug-replace"]["removed_words"][0]["text"] == "arrive"
assert undo["fake-sug-replace"]["new_word_ids"] == ["fake-ai-arrives"]
# every undo target exists in the served segments, and the heard text is in original_segments
ids = {w["id"] for w in words}
assert all(set(u["new_word_ids"]) <= ids for u in undo.values())
assert "arrive" in [w["text"] for s in doc["original_segments"] for w in s["words"]]
def test_default_fixture_is_unchanged(self):
doc = build_corrections("A", "T", 30)
assert "vocal_gaps" not in doc and "is_duet" not in doc
assert all(s.get("singer") is None for s in doc["corrected_segments"])
def test_fixture_duet(self):
doc = build_corrections("A", "T", 30, "duet")
assert doc["is_duet"] is True
assert {s["singer"] for s in doc["corrected_segments"]} == {0, 1, 2}
def test_fixture_rtl(self):
doc = build_corrections("A", "T", 30, "rtl")
texts = [s["text"] for s in doc["corrected_segments"]]
assert all(HEBREW.search(t) for t in texts)
assert sum(1 for t in texts if ARABIC.search(t)) == 1
def test_fixture_large(self):
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
doc = build_corrections("A", "T", 30, "large")
assert len(doc["corrected_segments"]) == 300
words = _words(doc)
assert len(words) >= 2000
starts = [w["start_time"] for w in words]
assert starts == sorted(starts) and len(set(starts)) == len(starts)
assert all(w["start_time"] < w["end_time"] for w in words)
CorrectionResult.from_dict(doc)
class TestKnobs:
def test_defaults_keep_todays_behaviour(self):
c = FakeConfig()
assert (c.review_fixture, c.backing_vocals, c.stems_delay_seconds) == ("default", "silent", 0)
assert (c.review_mode, c.auto_approval, c.review_complete_fail_once) == ("always_review", "none", False)
@pytest.mark.parametrize("bad", [
{"review_fixture": "nope"}, {"backing_vocals": "loud"}, {"stems_delay_seconds": -1},
{"stems_delay_seconds": 601}, {"stems_delay_seconds": "2"}, {"review_mode": "manual"},
{"auto_approval": "yes"}, {"review_complete_fail_once": "true"},
{"review_fixture": "large", "audio_duration_seconds": 30},
])
def test_validate_rejects(self, bad):
with pytest.raises(ValueError):
set_fake_config(bad, db=FakeDB(), email="u@example.com")
def test_large_fixture_accepts_long_audio(self):
set_fake_config({"review_fixture": "large", "audio_duration_seconds": 305}, db=FakeDB(), email="u@example.com")
def test_consume_review_complete_failure_is_one_shot_per_user(self):
db = FakeDB()
set_fake_config({"review_complete_fail_once": True}, db=db, email="a@example.com")
assert fw_config.consume_review_complete_failure("b@example.com", db=db) is False
assert fw_config.consume_review_complete_failure("a@example.com", db=db) is True
assert fw_config.consume_review_complete_failure("a@example.com", db=db) is False
@pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="ffmpeg not installed")
class TestBackingVocals:
def test_backing_audible_recommends_backing(self, tmp_path):
from backend.services.fake_workers.media import get_media
from backend.workers.screens_worker import _analyze_backing_vocals
media = get_media(30, "audible")
assert get_media(30, "silent").backing_vocals != media.backing_vocals
def analyse(stem):
storage = MagicMock()
storage.download_file.side_effect = lambda _src, dst: shutil.copy(stem, dst)
jm = MagicMock()
jm.get_job.return_value = SimpleNamespace(file_urls={"stems": {"backing_vocals": "stems/b.flac"}})
with patch("backend.services.audio_analysis_service.StorageService", return_value=storage):
asyncio.run(_analyze_backing_vocals("job1", jm, storage, MagicMock()))
calls = [c for c in jm.update_state_data.call_args_list if c[0][1] == "backing_vocals_analysis"]
return calls[-1][0][2]
audible = analyse(media.backing_vocals)
assert audible["has_audible_content"] is True
assert audible["recommended_selection"] in ("with_backing", "review_needed")
assert analyse(get_media(30, "silent").backing_vocals)["has_audible_content"] is False
class TestPipelineKnobs:
def test_auto_approval_payloads_drive_the_review_summary(self):
from backend.services.auto_approval.instrumental import auto_approval_summary
from backend.services.fake_workers.pipeline import auto_approval_payload
settings = SimpleNamespace(auto_approval_backing_keep_enabled=False, auto_approval_timing_gate_enabled=True)
def summary(kind, review_mode="auto"):
job = SimpleNamespace(
processing_metadata={"auto_approval": auto_approval_payload(kind)}, review_mode=review_mode,
backing_preference="auto", existing_instrumental_gcs_path=None, state_data={},
file_urls={"stems": {"instrumental_clean": "x"}},
)
return auto_approval_summary(job, settings)
assert auto_approval_payload("none") is None
assert summary("lyrics_confident")["lyrics"]["confident"] is True
assert summary("lyrics_confident")["backing"]["confident"] is False
assert summary("backing_confident")["backing"]["resolved_selection"] == "clean"
assert summary("backing_confident")["lyrics"]["confident"] is False
both = summary("both_unsure")
assert both["lyrics"]["confident"] is False and both["backing"]["confident"] is False
assert summary("lyrics_confident", "always_review")["lyrics"]["confident"] is False
def test_auto_approval_knob_writes_summary(self):
from backend.services.fake_workers import pipeline
jm = MagicMock()
job = SimpleNamespace(user_email="u@example.com", status=JobStatus.LYRICS_COMPLETE, review_mode="auto")
jm.get_job.return_value = job
cfg = FakeConfig(step_delay_seconds=0, auto_approval="lyrics_confident", review_mode="auto")
with patch.object(pipeline, "JobManager", return_value=jm), \
patch.object(pipeline, "StorageService"), \
patch.object(pipeline, "get_fake_config", return_value=cfg), \
patch.object(pipeline, "get_media", return_value=MagicMock()), \
patch("builtins.open", MagicMock()), \
patch("backend.workers.screens_worker._upload_screens", AsyncMock()), \
patch("backend.workers.screens_worker._transcode_review_audio", AsyncMock()):
assert asyncio.run(pipeline.run_screens("job1")) is True
writes = [c[0] for c in jm.update_processing_metadata.call_args_list]
assert writes[0][1] == "auto_approval"
assert writes[0][2]["lyrics"]["verdict"] == "auto"
# parked for a human, not auto-completed
assert jm.transition_to_state.call_args_list[-1][1]["new_status"] == JobStatus.AWAITING_REVIEW
def test_stems_delay(self):
from backend.services.fake_workers import pipeline
order = []
jm = MagicMock()
jm.get_job.return_value = SimpleNamespace(user_email="u@example.com")
jm.mark_audio_complete.side_effect = lambda *_: order.append("audio_complete")
jm.advance_to_screens_if_ready = AsyncMock()
jm.resume_video_if_waiting_for_stems = AsyncMock()
async def upload(*_a, **_k):
order.append("upload")
async def sleep(seconds):
order.append(("sleep", seconds))
cfg = FakeConfig(step_delay_seconds=0, stems_delay_seconds=2)
with patch.object(pipeline, "JobManager", return_value=jm), \
patch.object(pipeline, "StorageService"), \
patch.object(pipeline, "get_fake_config", return_value=cfg), \
patch.object(pipeline, "get_media", return_value=MagicMock()), \
patch.object(pipeline.asyncio, "sleep", sleep), \
patch("backend.workers.audio_worker.upload_separation_results", upload), \
patch("backend.workers.audio_worker._transcode_review_stems", AsyncMock()), \
patch("backend.workers.screens_worker._analyze_backing_vocals", AsyncMock()):
assert asyncio.run(pipeline.run_audio("job1")) is True
assert order == [("sleep", 2), "upload", "audio_complete"]
def test_audio_worker_does_not_block_other_fake_workers(self):
"""Each dispatched fake runs on its own thread, so one worker's delay never holds up the others."""
from backend.services import fake_workers
seen = []
started = threading.Event()
async def fake_run(kind, job_id):
if kind == "audio":
started.set()
await asyncio.sleep(0.3)
seen.append(kind)
return True
with patch("backend.services.fake_workers.pipeline.run", fake_run):
fake_workers.dispatch("audio", "j")
assert started.wait(2)
fake_workers.dispatch("lyrics", "j")
for t in list(fake_workers._threads):
t.join(timeout=5)
assert seen == ["lyrics", "audio"]
class TestLyricsWorkerStoresGaps:
def test_vocal_gaps_go_to_state_data_not_corrections_json(self):
from backend.services.fake_workers import pipeline
jm, uploaded = MagicMock(), {}
jm.get_job.return_value = SimpleNamespace(user_email="u@example.com", artist="A", title="T")
jm.advance_to_screens_if_ready = AsyncMock()
storage = MagicMock()
def upload(path, dest):
import json
if dest.endswith("corrections.json"):
uploaded.update(json.load(open(path)))
return dest
storage.upload_file.side_effect = upload
cfg = FakeConfig(step_delay_seconds=0, review_fixture="corrections")
with patch.object(pipeline, "JobManager", return_value=jm), \
patch.object(pipeline, "StorageService", return_value=storage), \
patch.object(pipeline, "get_fake_config", return_value=cfg):
assert asyncio.run(pipeline.run_lyrics("job1")) is True
assert "vocal_gaps" not in uploaded
keys = {c[0][1] for c in jm.update_state_data.call_args_list}
assert "vocal_gaps" in keys
# --------------------------------------------------------------------------- routes
@pytest.fixture
def review_client():
from backend.api.dependencies import require_review_auth
from backend.main import app
async def allow():
return ("job1", "full")
app.dependency_overrides[require_review_auth] = allow
yield TestClient(app)
app.dependency_overrides.pop(require_review_auth, None)
class TestReviewRoutes:
def test_complete_fail_once(self, review_client):
db = FakeDB()
set_fake_config({"review_complete_fail_once": True}, db=db, email="u@example.com")
jm = MagicMock()
jm.get_job.return_value = SimpleNamespace(user_email="u@example.com")
ws = MagicMock()
ws.trigger_render_video_worker = AsyncMock(return_value=True)
with patch("backend.api.routes.review.JobManager", return_value=jm), \
patch("backend.services.fake_workers.fake_workers_enabled", return_value=True), \
patch("backend.services.fake_workers.config._default_db", return_value=db), \
patch("backend.api.routes.review._save_review_completion", return_value="clean"), \
patch("backend.services.worker_service.get_worker_service", return_value=ws):
body = {"instrumental_selection": "clean"}
assert review_client.post("/api/review/job1/complete", json=body).status_code == 503
second = review_client.post("/api/review/job1/complete", json=body)
assert second.status_code == 200
assert second.json()["instrumental_selection"] == "clean"
def test_complete_hook_inert_without_fake_workers(self, review_client):
db = FakeDB()
set_fake_config({"review_complete_fail_once": True}, db=db, email="u@example.com")
ws = MagicMock()
ws.trigger_render_video_worker = AsyncMock(return_value=True)
with patch("backend.services.fake_workers.config._default_db", return_value=db), \
patch("backend.api.routes.review._save_review_completion", return_value="clean"), \
patch("backend.services.worker_service.get_worker_service", return_value=ws):
resp = review_client.post("/api/review/job1/complete", json={"instrumental_selection": "clean"})
assert resp.status_code == 200
assert get_fake_config(db, email="u@example.com").review_complete_fail_once is True
def test_audio_range(self, review_client):
data = bytes(range(256)) * 4
jm = MagicMock()
jm.get_job.return_value = SimpleNamespace(input_media_gcs_path="jobs/job1/input.flac")
transcoding = MagicMock()
transcoding.get_review_audio_bytes_async = AsyncMock(return_value=(data, "audio/ogg"))
with patch("backend.api.routes.review.JobManager", return_value=jm), \
patch("backend.api.routes.review._dev_audio_proxy_enabled", return_value=True), \
patch("backend.services.audio_transcoding_service.AudioTranscodingService",
return_value=transcoding):
ranged = review_client.get("/api/review/job1/audio", headers={"Range": "bytes=0-99"})
full = review_client.get("/api/review/job1/audio")
assert ranged.status_code == 206
assert ranged.content == data[:100]
assert ranged.headers["content-range"] == f"bytes 0-99/{len(data)}"
assert full.status_code == 200 and full.headers["accept-ranges"] == "bytes"
class TestReviewResultEndpoint:
@pytest.fixture
def client(self):
from backend.api.routes import test_support
app = FastAPI()
app.include_router(test_support.router, prefix="/api")
return TestClient(app)
def _job(self, **state):
return SimpleNamespace(status=JobStatus.REVIEW_COMPLETE, state_data=state, file_urls={})
def test_returns_submitted_review(self, client):
saved = {"corrected_segments": [
{"text": "Hi there", "singer": 2, "words": [
{"id": "a", "text": "Hi", "start_time": 1.0, "end_time": 1.5},
{"id": "b", "text": "there", "start_time": 1.6, "end_time": 2.0},
]},
]}
jm, storage = MagicMock(), MagicMock()
jm.get_job.return_value = self._job(instrumental_selection="with_backing", is_duet=True)
storage.file_exists.return_value = True
storage.download_json.return_value = saved
with patch("backend.services.job_manager.JobManager", return_value=jm), \
patch("backend.services.storage_service.StorageService", return_value=storage):
resp = client.get("/api/test/jobs/job1/review-result")
assert resp.status_code == 200
assert resp.json() == {
"status": "review_complete", "instrumental_selection": "with_backing", "is_duet": True,
"lines": [{"text": "Hi there", "singer": 2, "words": [
{"text": "Hi", "start_time": 1.0, "end_time": 1.5},
{"text": "there", "start_time": 1.6, "end_time": 2.0},
]}],
}
storage.file_exists.assert_called_with("jobs/job1/lyrics/corrections_updated.json")
def test_before_a_review_lines_are_empty(self, client):
jm, storage = MagicMock(), MagicMock()
jm.get_job.return_value = self._job()
storage.file_exists.return_value = False
with patch("backend.services.job_manager.JobManager", return_value=jm), \
patch("backend.services.storage_service.StorageService", return_value=storage):
body = client.get("/api/test/jobs/job1/review-result").json()
assert body["lines"] == [] and body["is_duet"] is False and body["instrumental_selection"] is None
def test_unknown_job_404(self, client):
jm = MagicMock()
jm.get_job.return_value = None
with patch("backend.services.job_manager.JobManager", return_value=jm):
assert client.get("/api/test/jobs/nope/review-result").status_code == 404
@@ -1,7 +1,7 @@
"""Tests for backend.services.timing_sanitizer."""
import pytest
from backend.services.timing_sanitizer import sanitize_corrections
from backend.services.timing_sanitizer import find_missing_timings, sanitize_corrections
def _sample_corrections():
@@ -57,14 +57,52 @@ def test_missing_segments_key_is_noop():
assert cleaned == {"foo": "bar"}
def test_non_finite_segment_bounds_left_untouched():
def test_missing_segment_bounds_come_from_its_words():
payload = {"corrected_segments": [
{"id": "s", "start_time": None, "end_time": None, "text": "x",
"words": [{"id": "w", "text": "x", "start_time": 3, "end_time": 5}]}
{"id": "s", "start_time": None, "end_time": None, "text": "x y",
"words": [{"id": "w", "text": "x", "start_time": 3, "end_time": 5},
{"id": "v", "text": "y", "start_time": 5.5, "end_time": 6}]}
]}
cleaned, count = sanitize_corrections(payload)
assert count == 0
assert cleaned["corrected_segments"][0]["words"][0]["start_time"] == 3
seg = cleaned["corrected_segments"][0]
assert (seg["start_time"], seg["end_time"]) == (3, 6)
assert count == 2
assert seg["words"][0]["start_time"] == 3
def test_segment_without_end_time_key_is_filled():
"""JSON.stringify drops undefined, so the key itself can be missing (job 16792df7)."""
payload = {"corrected_segments": [
{"id": "s", "start_time": 1.0, "text": "x",
"words": [{"id": "w", "text": "x", "start_time": 1.0, "end_time": 1.4}]}
]}
cleaned, _ = sanitize_corrections(payload)
assert cleaned["corrected_segments"][0]["end_time"] == 1.4
assert find_missing_timings(cleaned) is None
def test_untimed_segment_takes_its_neighbours_gap_and_words_get_filled():
payload = {"corrected_segments": [
{"id": "a", "start_time": 0.0, "end_time": 2.0, "text": "a",
"words": [{"id": "a1", "text": "a", "start_time": 0.0, "end_time": 2.0}]},
{"id": "b", "text": "new line",
"words": [{"id": "b1", "text": "new"}, {"id": "b2", "text": "line"}]},
{"id": "c", "start_time": 5.0, "end_time": 6.0, "text": "c",
"words": [{"id": "c1", "text": "c", "start_time": 5.0, "end_time": 6.0}]},
]}
cleaned, _ = sanitize_corrections(payload)
seg = cleaned["corrected_segments"][1]
assert (seg["start_time"], seg["end_time"]) == (2.0, 5.0)
assert all(2.0 <= w["start_time"] <= w["end_time"] <= 5.0 for w in seg["words"])
assert find_missing_timings(cleaned) is None
def test_line_with_no_timing_anywhere_is_reported():
payload = {"corrected_segments": [
{"id": "b", "text": "lonely line", "words": [{"id": "b1", "text": "lonely"}]},
]}
cleaned, _ = sanitize_corrections(payload)
assert find_missing_timings(cleaned) == "lonely line"
def test_start_past_segment_end_uses_prev_end():
+14
View File
@@ -65,3 +65,17 @@ class TestMagicLinkRedirectPath:
def test_none_and_unknown(self):
assert _magic_link_redirect_path(None) is None
assert _magic_link_redirect_path("something_else") is None
class TestBoardDeepLinkPurpose:
def test_request_purpose_redirects_with_upvote(self):
assert _magic_link_redirect_path("requests_board:abc12345") == "/requests?request=abc12345&upvote=1"
def test_malformed_request_id_falls_back_to_board(self):
assert _magic_link_redirect_path("requests_board:../x?y") == "/requests"
def test_is_board_purpose(self):
from backend.api.routes.users import _is_board_purpose
assert _is_board_purpose("requests_board") and _is_board_purpose("requests_board:abc12345")
assert not _is_board_purpose(None) and not _is_board_purpose("job_review:abc12345")
+64 -3
View File
@@ -100,15 +100,76 @@ class TestProcessAudioDownload:
"""Tests for the main process_audio_download function."""
@pytest.mark.asyncio
async def test_returns_false_when_job_not_found(self):
async def test_deleted_job_at_start_exits_cleanly(self, caplog):
"""Job doc gone (user deleted it) -> INFO + success, so main() exits 0 (no retry)."""
import logging
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"):
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
caplog.at_level(logging.DEBUG):
mock_jm = MagicMock()
mock_jm.get_job.return_value = None
mock_jm_cls.return_value = mock_jm
result = await process_audio_download("nonexistent-job")
assert result is False
assert result is True
mock_dl.assert_not_awaited()
mock_jm.fail_job.assert_not_called()
assert not [r for r in caplog.records if r.levelno >= logging.ERROR]
assert any("deleted" in r.message and r.levelno == logging.INFO for r in caplog.records)
@pytest.mark.asyncio
async def test_job_deleted_mid_download_stops_without_writes(self, caplog):
"""Job 6ffe88ad (2026-10-14): the user deleted the job while the download ran.
After the download, the job doc is gone: no further writes, no fail_job,
no worker triggers, nothing at ERROR, and success so Cloud Run won't retry.
"""
import logging
job = _make_job()
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory, \
caplog.at_level(logging.DEBUG):
mock_jm = MagicMock()
mock_jm.get_job.side_effect = [job, None, None, None]
mock_jm_cls.return_value = mock_jm
mock_dl.return_value = ("uploads/test-job-123/audio/song.mp3", "song.mp3")
result = await process_audio_download("test-job-123")
assert result is True
mock_jm.update_job.assert_not_called()
mock_jm.update_file_url.assert_not_called()
mock_jm.transition_to_state.assert_not_called()
mock_jm.fail_job.assert_not_called()
mock_ws_factory.assert_not_called()
assert not [r for r in caplog.records if r.levelno >= logging.ERROR]
@pytest.mark.asyncio
async def test_notfound_on_write_after_delete_exits_cleanly(self, caplog):
"""A Firestore NotFound from a write (job deleted between read and write) is not an error."""
import logging
from google.api_core.exceptions import NotFound
job = _make_job()
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
caplog.at_level(logging.DEBUG):
mock_jm = MagicMock()
# entry read + post-download re-read see the job; it's gone by the write
mock_jm.get_job.side_effect = [job, job, None]
mock_jm.update_job.side_effect = NotFound("No document to update")
mock_jm_cls.return_value = mock_jm
mock_dl.return_value = ("uploads/test-job-123/audio/song.mp3", "song.mp3")
result = await process_audio_download("test-job-123")
assert result is True
mock_jm.fail_job.assert_not_called()
assert not [r for r in caplog.records if r.levelno >= logging.ERROR]
@pytest.mark.asyncio
async def test_returns_false_when_no_download_params(self):
+2
View File
@@ -1058,6 +1058,8 @@ class TestAudioSearchThemePreparation:
has_theme_preparation_call = (
# Check for import or call of theme preparation function
'_prepare_theme_for_job(' in audio_search_code or
# called off the event loop: asyncio.to_thread(_prepare_theme_for_job, ...)
'_prepare_theme_for_job,' in audio_search_code or
'prepare_job_style(' in audio_search_code
)
+132 -14
View File
@@ -119,7 +119,7 @@ class TestChangeToPrivate:
call_order = []
mock_redist = AsyncMock(return_value=True, side_effect=lambda *a, **k: call_order.append("redist") or True)
mock_delete = AsyncMock(side_effect=lambda *a, **k: call_order.append("delete"))
mock_delete = MagicMock(side_effect=lambda *a, **k: call_order.append("delete"))
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_public_outputs", mock_delete), \
patch("backend.workers.video_worker.redistribute_video", mock_redist):
@@ -146,7 +146,7 @@ class TestChangeToPrivate:
service = VisibilityChangeService(job_manager=mock_job_manager)
job = _make_job(is_private=False, state_data={})
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_public_outputs", new_callable=AsyncMock), \
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_public_outputs"), \
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=True):
await service.change_to_private("test-123", job, "user@example.com")
@@ -175,7 +175,7 @@ class TestChangeToPublic:
"dropbox_link": "https://dropbox.com/test",
})
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs"), \
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {"bg": "bg.png"}, None)) as mock_theme, \
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
@@ -205,7 +205,7 @@ class TestChangeToPublic:
service = VisibilityChangeService(job_manager=mock_job_manager)
job = _make_job(is_private=True, state_data={})
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs"), \
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {"bg": "bg.png"}, None)), \
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
@@ -233,7 +233,7 @@ class TestChangeToPublic:
service = VisibilityChangeService(job_manager=mock_job_manager)
job = _make_job(is_private=True, state_data={})
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs"), \
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {"bg": "bg.png"}, None)), \
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
@@ -277,7 +277,7 @@ class TestChangeToPublic:
service = VisibilityChangeService(job_manager=mock_job_manager)
job = _make_job(is_private=True, state_data={})
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs"), \
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("p.json", {}, None)), \
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
@@ -301,7 +301,7 @@ class TestChangeToPublic:
service = VisibilityChangeService(job_manager=mock_job_manager)
job = _make_job(is_private=True, state_data={})
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs"), \
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {}, None)), \
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
@@ -321,6 +321,96 @@ class TestChangeToPublic:
assert payload["is_private"] is True
class TestChangeToPublicClaim:
"""change_to_public claims visibility_change_in_progress atomically before deleting anything."""
@pytest.mark.asyncio
async def test_lost_claim_deletes_nothing(self):
from backend.services.visibility_change_service import VisibilityChangeInProgress
mock_job_manager = MagicMock()
mock_job_manager.firestore.try_set_job_state_flag.return_value = False
service = VisibilityChangeService(job_manager=mock_job_manager)
job = _make_job(is_private=True, state_data={})
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs") as mock_delete:
with pytest.raises(VisibilityChangeInProgress):
await service.change_to_public("test-123", job, "user@example.com")
mock_delete.assert_not_called()
mock_job_manager.firestore.try_set_job_state_flag.assert_called_once_with("test-123", "visibility_change_in_progress")
@pytest.mark.asyncio
async def test_failed_reset_releases_the_claim(self):
mock_job_manager = MagicMock()
mock_job_manager.firestore.try_set_job_state_flag.return_value = True
mock_job_ref = MagicMock()
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
service = VisibilityChangeService(job_manager=mock_job_manager)
job = _make_job(is_private=True, state_data={})
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs",
side_effect=RuntimeError("dropbox down")):
with pytest.raises(RuntimeError, match="dropbox down"):
await service.change_to_public("test-123", job, "user@example.com")
released = mock_job_ref.update.call_args_list[-1].args[0]
assert list(released) == ["state_data.visibility_change_in_progress"]
@pytest.mark.asyncio
async def test_trigger_exception_rolls_back_like_a_failed_trigger(self):
mock_job_manager = MagicMock()
mock_job_ref = MagicMock()
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
service = VisibilityChangeService(job_manager=mock_job_manager)
job = _make_job(is_private=True, state_data={})
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs"), \
patch("backend.services.visibility_change_service.StorageService"), \
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("p", {}, None)), \
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
mock_worker_svc.return_value.trigger_screens_worker = AsyncMock(side_effect=ConnectionError("tasks down"))
with pytest.raises(RuntimeError, match="Failed to trigger screens worker"):
await service.change_to_public("test-123", job, "user@example.com")
rollback = mock_job_ref.update.call_args_list[-1].args[0]
assert rollback["status"] == "complete"
assert "state_data.visibility_change_in_progress" in rollback
class TestChangeToPrivateClaim:
@pytest.mark.asyncio
async def test_lost_claim_touches_nothing(self):
from backend.services.visibility_change_service import VisibilityChangeInProgress
mock_job_manager = MagicMock()
mock_job_manager.firestore.try_set_job_state_flag.return_value = False
mock_job_ref = MagicMock()
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
service = VisibilityChangeService(job_manager=mock_job_manager)
job = _make_job(is_private=False, state_data={"brand_code": "NOMAD-0001"})
redist = AsyncMock(return_value=True)
with patch("backend.workers.video_worker.redistribute_video", redist):
with pytest.raises(VisibilityChangeInProgress):
await service.change_to_private("test-123", job, "user@example.com")
redist.assert_not_awaited()
mock_job_ref.update.assert_not_called()
@pytest.mark.asyncio
async def test_chained_continuation_keeps_its_existing_claim(self):
mock_job_manager = MagicMock()
mock_job_ref = MagicMock()
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
service = VisibilityChangeService(job_manager=mock_job_manager)
job = _make_job(is_private=False, state_data={"brand_code": "NOMAD-0001", "visibility_change_in_progress": True})
with patch("backend.workers.video_worker.redistribute_video", AsyncMock(return_value=True)), \
patch("backend.services.visibility_change_service.VisibilityChangeService._delete_public_outputs"):
result = await service.change_to_private(
"test-123", job, "user@example.com", regenerate_if_missing=False, holds_claim=True)
assert result["status"] == "success"
mock_job_manager.firestore.try_set_job_state_flag.assert_not_called()
class TestChangeToPrivateErrors:
"""Test error handling in public -> private flow."""
@@ -339,7 +429,7 @@ class TestChangeToPrivateErrors:
"gdrive_files": {"mp4": "id1"},
})
mock_delete = AsyncMock()
mock_delete = MagicMock()
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_public_outputs", mock_delete), \
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=False):
@@ -373,7 +463,7 @@ class TestDeleteDistributedOutputs:
mock_brand_svc = MagicMock()
mock_bcs.return_value = mock_brand_svc
await service._delete_distributed_outputs("test-123", job, keep_gcs_finals=True)
service._delete_distributed_outputs("test-123", job, keep_gcs_finals=True)
mock_brand_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
@@ -398,7 +488,7 @@ class TestDeleteDistributedOutputs:
mock_brand_svc = MagicMock()
mock_bcs.return_value = mock_brand_svc
await service._delete_public_outputs("test-123", public_outputs)
service._delete_public_outputs("test-123", public_outputs)
# No public YouTube/Dropbox/GDrive present → all deletions "succeed" →
# the public number is recycled and the mirror is cleaned.
@@ -432,7 +522,7 @@ class TestDeleteDistributedOutputs:
mock_brand_svc = MagicMock()
mock_bcs.return_value = mock_brand_svc
await service._delete_public_outputs("test-123", public_outputs)
service._delete_public_outputs("test-123", public_outputs)
mock_brand_svc.recycle_brand_code.assert_not_called()
@@ -459,7 +549,7 @@ class TestDeleteDistributedOutputs:
mock_yt.return_value = MagicMock(is_configured=False)
mock_dbx.return_value = MagicMock(is_configured=False)
await service._delete_distributed_outputs("test-123", job, keep_gcs_finals=True)
service._delete_distributed_outputs("test-123", job, keep_gcs_finals=True)
update_call = mock_job_ref.update.call_args
payload = update_call.args[0]
@@ -482,7 +572,7 @@ class TestDeleteDistributedOutputs:
mock_storage.delete_folder.return_value = 3
mock_storage_cls.return_value = mock_storage
await service._delete_distributed_outputs("test-123", job, keep_gcs_finals=False)
service._delete_distributed_outputs("test-123", job, keep_gcs_finals=False)
mock_storage.delete_folder.assert_called_once_with("jobs/test-123/finals/")
@@ -499,7 +589,7 @@ class TestDeleteDistributedOutputs:
mock_storage = MagicMock()
mock_storage_cls.return_value = mock_storage
await service._delete_distributed_outputs("test-123", job, keep_gcs_finals=True)
service._delete_distributed_outputs("test-123", job, keep_gcs_finals=True)
mock_storage.delete_folder.assert_not_called()
@@ -511,3 +601,31 @@ class TestStateTransitions:
from backend.models.job import STATE_TRANSITIONS, JobStatus
allowed = STATE_TRANSITIONS[JobStatus.COMPLETE]
assert JobStatus.LYRICS_COMPLETE in allowed
def test_route_maps_lost_visibility_claim_to_409():
from fastapi.testclient import TestClient
from backend.api.dependencies import require_auth
from backend.main import app
from backend.services.auth_service import AuthResult, UserType
from backend.services.visibility_change_service import VisibilityChangeInProgress
async def override():
return AuthResult(is_valid=True, user_type=UserType.UNLIMITED, remaining_uses=-1, message="Valid",
user_email="user@example.com", is_admin=False)
app.dependency_overrides[require_auth] = override
try:
job = _make_job(is_private=True, state_data={})
job.user_email = "user@example.com"
job_manager = MagicMock()
job_manager.get_job.return_value = job
with patch("backend.api.routes.jobs.JobManager", return_value=job_manager), \
patch.object(VisibilityChangeService, "change_to_public",
AsyncMock(side_effect=VisibilityChangeInProgress("A visibility change is already in progress for this job"))):
resp = TestClient(app).post(f"/api/jobs/{job.job_id}/change-visibility", json={"target_visibility": "public"})
finally:
app.dependency_overrides.clear()
assert resp.status_code == 409, resp.text
assert "already in progress" in resp.json()["detail"]
@@ -0,0 +1,43 @@
"""Worker Cloud Run Jobs must dispatch follow-on video/render work as Cloud Run
Jobs, never via Cloud Tasks -> a BackgroundTask on the API service (which runs
the video worker on the API's event loop: 52s + 81s freezes, 2026-10-19)."""
import importlib
import pytest
def _settings(monkeypatch, **env):
for key in ("CLOUD_RUN_JOB", "USE_CLOUD_RUN_JOBS_FOR_VIDEO", "USE_CLOUD_RUN_JOBS_FOR_RENDER"):
monkeypatch.delenv(key, raising=False)
for key, value in env.items():
monkeypatch.setenv(key, value)
import backend.config as config
return importlib.reload(config).Settings()
@pytest.fixture(autouse=True)
def _restore_config(monkeypatch):
yield
monkeypatch.undo()
import backend.config as config
importlib.reload(config)
def test_inside_cloud_run_job_defaults_to_cloud_run_jobs(monkeypatch):
s = _settings(monkeypatch, CLOUD_RUN_JOB="audio-separation-job")
assert s.use_cloud_run_jobs_for_video is True
assert s.use_cloud_run_jobs_for_render is True
def test_outside_cloud_run_job_default_unchanged(monkeypatch):
s = _settings(monkeypatch)
assert s.use_cloud_run_jobs_for_video is False
assert s.use_cloud_run_jobs_for_render is False
def test_explicit_env_still_wins_inside_a_job(monkeypatch):
s = _settings(monkeypatch, CLOUD_RUN_JOB="x", USE_CLOUD_RUN_JOBS_FOR_VIDEO="false",
USE_CLOUD_RUN_JOBS_FOR_RENDER="false")
assert s.use_cloud_run_jobs_for_video is False
assert s.use_cloud_run_jobs_for_render is False
+21
View File
@@ -121,6 +121,27 @@ class TestDiscordNotificationServicePostMessage:
timeout=30
)
@patch("backend.services.discord_service.requests.post")
def test_post_message_suppress_embeds_sets_flag(self, mock_post):
"""suppress_embeds sends flags=4 (SUPPRESS_EMBEDS) so URLs don't unfurl."""
mock_post.return_value = MagicMock()
url = "https://discord.com/api/webhooks/123456789/abcdef"
service = DiscordNotificationService(webhook_url=url)
assert service.post_message("see https://cloud.google.com/run", suppress_embeds=True) is True
payload = mock_post.call_args.kwargs["json"]
assert payload["flags"] == 4
assert payload["allowed_mentions"] == {"parse": []}
@patch("backend.services.discord_service.requests.post")
def test_video_notification_keeps_embed(self, mock_post):
"""The YouTube 'New upload' post wants its video preview card."""
mock_post.return_value = MagicMock()
service = DiscordNotificationService(webhook_url="https://discord.com/api/webhooks/1/a")
service.post_video_notification("https://youtu.be/abc")
assert "flags" not in mock_post.call_args.kwargs["json"]
def test_post_message_no_webhook_raises(self):
"""Test that posting without webhook URL raises ValueError."""
service = DiscordNotificationService()
@@ -0,0 +1,12 @@
"""karaoke-decide's search service and index-build job must be watched by the error monitor."""
from backend.services.error_monitor import config, monitor
def test_decide_search_resources_monitored():
assert "karaoke-decide-search" in config.MONITORED_CLOUD_RUN_SERVICES
assert "song-index-build" in config.MONITORED_CLOUD_RUN_JOBS
def test_monitor_log_query_covers_them():
assert "karaoke-decide-search" in monitor.RESOURCE_TYPE_FILTERS["cloud_run_revision"][1]
assert "song-index-build" in monitor.RESOURCE_TYPE_FILTERS["cloud_run_job"][1]
+133
View File
@@ -0,0 +1,133 @@
"""Fake match judge / free-text resolve under FAKE_WORKERS (local E2E stack; never calls Gemini)."""
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from backend.api.dependencies import require_auth
from backend.api.routes import catalog, kjbox
from backend.services.fake_workers import config as fw_config
from backend.services.fake_workers.config import FakeConfig, set_fake_config
from backend.services.match_judge.verdict import MatchVerdict
from backend.tests.test_fake_workers import FakeDB
EMAIL = "mobile-test@example.com"
@pytest.fixture
def db(monkeypatch):
d = FakeDB()
monkeypatch.setattr(fw_config, "_default_db", lambda: d)
return d
@pytest.fixture
def client(monkeypatch):
app = FastAPI()
app.include_router(catalog.router, prefix="/api")
app.include_router(kjbox.router, prefix="/api")
app.dependency_overrides[require_auth] = lambda: SimpleNamespace(user_email=EMAIL, token_id="t")
monkeypatch.setattr(catalog, "_check_rate_limit", lambda *a, **k: None)
return TestClient(app)
def _fake(monkeypatch, on):
monkeypatch.setattr("backend.services.fake_workers.fake_workers_enabled", lambda settings=None: on)
settings = SimpleNamespace(kjbox_partner_secret="s", decide_partner_secret="", fake_workers=on)
monkeypatch.setattr(kjbox, "get_settings", lambda: settings)
def _judge(client):
return client.post("/api/catalog/match-judge", json={"artist": "abba", "title": "danceing queen"})
def test_validate_rejects_unknown_judge_kind():
with pytest.raises(ValueError, match="judge_kind"):
FakeConfig(judge_kind="bogus").validate()
for k in ("none", "cosmetic", "content", "ambiguous"):
FakeConfig(judge_kind=k).validate()
def test_set_fake_config_rejects_unknown_judge_kind(db):
with pytest.raises(ValueError):
set_fake_config({"judge_kind": "maybe"}, db=db)
def test_match_judge_content_uses_per_user_config(monkeypatch, client, db):
_fake(monkeypatch, True)
set_fake_config({"judge_kind": "content", "judge_canonical_artist": "ABBA",
"judge_canonical_title": "Dancing Queen"}, db=db, email=EMAIL)
with patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock) as real:
r = _judge(client)
assert r.status_code == 200
data = r.json()
assert data["kind"] == "content"
assert (data["canonical_artist"], data["canonical_title"]) == ("ABBA", "Dancing Queen")
real.assert_not_called()
def test_match_judge_fast_pass_defers_ai_kinds_like_the_real_judge(monkeypatch, client, db):
"""The real fast pass is catalog-only: it settles cosmetic/none, else answers needs_ai (clients then call full)."""
_fake(monkeypatch, True)
fast = lambda: client.post("/api/catalog/match-judge", # noqa: E731
json={"artist": "abba", "title": "danceing queen", "stage": "fast"}).json()
for kind in ("content", "ambiguous"):
set_fake_config({"judge_kind": kind}, db=db, email=EMAIL)
data = fast()
assert data["needs_ai"] is True and data["kind"] == "none" and data["confident"] is False
assert _judge(client).json()["kind"] == kind # the full pass carries the verdict
set_fake_config({"judge_kind": "cosmetic", "judge_canonical_artist": "ABBA",
"judge_canonical_title": "Dancing Queen"}, db=db, email=EMAIL)
data = fast()
assert data["kind"] == "cosmetic" and data["needs_ai"] is False
def test_match_judge_none_default(monkeypatch, client, db):
_fake(monkeypatch, True)
assert _judge(client).json()["kind"] == "none"
set_fake_config({"judge_kind": "content"}, db=db, email="someone-else@example.com")
assert _judge(client).json()["kind"] == "none" # other user's override doesn't leak
def test_match_judge_ambiguous_has_alternatives(monkeypatch, client, db):
_fake(monkeypatch, True)
set_fake_config({"judge_kind": "ambiguous", "judge_canonical_artist": "A",
"judge_canonical_title": "T"}, db=db, email=EMAIL)
data = _judge(client).json()
assert data["kind"] == "ambiguous" and len(data["alternatives"]) == 2
def test_match_judge_real_path_when_fake_off(monkeypatch, client, db):
_fake(monkeypatch, False)
set_fake_config({"judge_kind": "content"}, db=db, email=EMAIL)
verdict = MatchVerdict("cosmetic", True, "ABBA", "Dancing Queen", engine="catalog")
with patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock,
return_value=verdict) as real:
r = _judge(client)
real.assert_awaited_once()
assert r.json()["kind"] == "cosmetic"
def test_resolve_uses_global_config_without_gemini(monkeypatch, client, db):
_fake(monkeypatch, True)
set_fake_config({"judge_kind": "content", "judge_canonical_artist": "ABBA",
"judge_canonical_title": "Dancing Queen"}, db=db)
with patch("backend.services.match_judge.free_text.resolve_and_tidy", new_callable=AsyncMock) as real:
r = client.post("/api/kjbox/catalog/resolve", json={"query": "abba danceing queen"},
headers={"X-Kjbox-Secret": "s"})
assert r.status_code == 200
data = r.json()
assert data["kind"] == "content" and data["confident"] is True
assert (data["canonical_artist"], data["canonical_title"]) == ("ABBA", "Dancing Queen")
assert data["typed_title"] == "abba danceing queen" and "needs_ai" not in data
real.assert_not_called()
def test_resolve_none_and_not_cached_across_config_changes(monkeypatch, client, db):
_fake(monkeypatch, True)
h = {"X-Kjbox-Secret": "s"}
assert client.post("/api/kjbox/catalog/resolve", json={"query": "zzz"}, headers=h).json()["kind"] == "none"
set_fake_config({"judge_kind": "cosmetic"}, db=db)
assert client.post("/api/kjbox/catalog/resolve", json={"query": "zzz"}, headers=h).json()["kind"] == "cosmetic"
+40
View File
@@ -492,3 +492,43 @@ class TestFakeSearchConfidence:
with open(FRONTEND_FIXTURE) as f:
assert json.load(f) == frontend_fixture()
# --------------------------------------------------------------------------- kjbox quick version
class TestKjboxQuickVersion:
def _run_audio(self, request_metadata):
from backend.services.fake_workers import pipeline
jm = MagicMock()
jm.get_job.return_value = SimpleNamespace(
job_id="job1", user_email="u@example.com", artist="A", title="T",
request_metadata=request_metadata, state_data={},
)
jm.advance_to_screens_if_ready = AsyncMock()
jm.resume_video_if_waiting_for_stems = AsyncMock()
storage = MagicMock()
media = MagicMock(final_mp4=__file__, duration=30)
with patch.object(pipeline, "JobManager", return_value=jm), \
patch.object(pipeline, "StorageService", return_value=storage), \
patch.object(pipeline, "_media_for", return_value=media), \
patch.object(pipeline, "get_fake_config", return_value=FakeConfig(step_delay_seconds=0)), \
patch("backend.workers.audio_worker.upload_separation_results", AsyncMock()), \
patch("backend.workers.audio_worker._transcode_review_stems", AsyncMock()), \
patch("backend.workers.screens_worker._analyze_backing_vocals", AsyncMock()), \
patch("backend.workers.worker_logging.create_job_logger"):
assert asyncio.run(pipeline.run("audio", "job1")) is True
return jm, storage
def test_fake_workers_emit_quick_version_for_kjbox_jobs(self):
jm, storage = self._run_audio({"client_id": "kjbox"})
jm.update_file_url.assert_called_once_with("job1", "quick", "video_mp4", "jobs/job1/quick/quick.mp4")
storage.upload_file.assert_called_once()
statuses = [c.args[2]["status"] for c in jm.update_state_data.call_args_list
if c.args[1] == "quick_version"]
assert statuses == ["separating", "rendering", "ready"]
def test_non_kjbox_jobs_get_no_quick_version(self):
jm, storage = self._run_audio({"client_id": "web"})
jm.update_file_url.assert_not_called()
assert not [c for c in jm.update_state_data.call_args_list if c.args[1] == "quick_version"]
@@ -0,0 +1,57 @@
"""Job-list queries must fail fast instead of hanging for the 300s gRPC default.
Regression: `GET /api/jobs?fields=summary` logged "Error listing jobs summary:
Timeout of 300.0s exceeded" — a stalled RunQuery stream held a threadpool
thread for 5 minutes because Query.stream()'s default retry/timeout is 300s.
"""
from unittest.mock import MagicMock, patch
import pytest
@pytest.fixture
def service_and_query():
with patch("backend.services.firestore_service.firestore"):
from backend.services.firestore_service import FirestoreService
svc = FirestoreService()
query = MagicMock()
# Every chained builder call returns the same query mock.
query.where.return_value = query
query.order_by.return_value = query
query.limit.return_value = query
query.select.return_value = query
query.stream.return_value = iter([])
svc.db = MagicMock()
svc.db.collection.return_value = query
return svc, query
def _assert_bounded(query):
from backend.services.firestore_service import LIST_QUERY_TIMEOUT_SECONDS
assert LIST_QUERY_TIMEOUT_SECONDS <= 30
query.stream.assert_called_once()
kwargs = query.stream.call_args.kwargs
assert kwargs["timeout"] == LIST_QUERY_TIMEOUT_SECONDS
retry = kwargs["retry"]
# google.api_core Retry exposes its overall deadline as .timeout
assert retry is not None
assert retry.timeout <= LIST_QUERY_TIMEOUT_SECONDS
def test_list_jobs_summary_stream_has_bounded_timeout(service_and_query):
svc, query = service_and_query
assert svc.list_jobs_summary(user_email="a@b.com", limit=10) == []
_assert_bounded(query)
def test_list_jobs_stream_has_bounded_timeout(service_and_query):
svc, query = service_and_query
assert svc.list_jobs(user_email="a@b.com", limit=10) == []
_assert_bounded(query)
def test_list_jobs_by_batch_id_stream_has_bounded_timeout(service_and_query):
svc, query = service_and_query
assert svc.list_jobs_by_batch_id("batch-1") == []
_assert_bounded(query)
+38 -1
View File
@@ -413,10 +413,47 @@ class TestStartReview:
def test_start_review_endpoint_exists(self, client, mock_job_manager, mock_job, auth_headers):
"""Test start review endpoint exists."""
response = client.post("/api/jobs/test123/start-review", headers=auth_headers)
response = client.post("/api/jobs/test123/start-review", json={}, headers=auth_headers)
# Should not be 404 or 405
assert response.status_code not in [404, 405]
def test_start_review_already_in_review_is_idempotent(self, client, mock_job_manager, mock_job, auth_headers):
"""A duplicate/concurrent open on an in_review job succeeds with no repeated side effects."""
mock_job.status = JobStatus.IN_REVIEW
response = client.post("/api/jobs/test123/start-review", json={}, headers=auth_headers)
assert response.status_code == 200
assert response.json() == {"status": "success", "job_status": "in_review"}
mock_job_manager.transition_to_state.assert_not_called()
mock_job_manager.record_review_started.assert_not_called()
def test_start_review_lost_race_is_success(self, client, mock_job_manager, mock_job, auth_headers):
"""Both requests saw awaiting_review; the loser's transition raises but job is in_review."""
from backend.exceptions import InvalidStateTransitionError
mock_job.status = JobStatus.AWAITING_REVIEW
in_review = mock_job.model_copy(update={"status": JobStatus.IN_REVIEW})
mock_job_manager.get_job.side_effect = [mock_job, in_review]
mock_job_manager.transition_to_state.side_effect = InvalidStateTransitionError(
message="Invalid state transition in_review -> in_review"
)
response = client.post("/api/jobs/test123/start-review", json={}, headers=auth_headers)
assert response.status_code == 200
assert response.json() == {"status": "success", "job_status": "in_review"}
mock_job_manager.record_review_started.assert_not_called()
def test_start_review_invalid_transition_otherwise_still_errors(self, client, mock_job_manager, mock_job, auth_headers):
from backend.exceptions import InvalidStateTransitionError
mock_job.status = JobStatus.AWAITING_REVIEW
mock_job_manager.transition_to_state.side_effect = InvalidStateTransitionError(message="nope")
with pytest.raises(InvalidStateTransitionError):
client.post("/api/jobs/test123/start-review", json={}, headers=auth_headers)
def test_start_review_from_awaiting_records_once(self, client, mock_job_manager, mock_job, auth_headers):
mock_job.status = JobStatus.AWAITING_REVIEW
mock_job_manager.transition_to_state.return_value = True
response = client.post("/api/jobs/test123/start-review", json={}, headers=auth_headers)
assert response.status_code == 200
mock_job_manager.record_review_started.assert_called_once()
class TestSubmitEditLog:
"""Tests for POST /api/jobs/{job_id}/edit-log."""
+36
View File
@@ -774,3 +774,39 @@ class TestCatalogResolve:
assert client.post("/api/kjbox/catalog/resolve", json={"query": "x"}).status_code == 403
assert self._post(client, "").status_code == 422
assert self._post(client, " ").status_code == 422
def _local_stack_env(monkeypatch, **overrides):
import os
import subprocess
from pathlib import Path
script = Path(__file__).resolve().parents[2] / "scripts" / "local-stack.sh"
env = {k: v for k, v in os.environ.items()
if k not in ("KJBOX_PARTNER_SECRET", "DECIDE_GEN_PARTNER_SECRET")}
env.update(overrides)
out = subprocess.run([str(script), "env"], capture_output=True, text=True, check=True, env=env).stdout
return dict(line.split("=", 1) for line in out.splitlines() if "=" in line)
def test_kjbox_routes_accept_local_secret(monkeypatch):
"""With nothing set externally, local-stack.sh defaults KJBOX_PARTNER_SECRET to
local-stack-secret and the partner gate accepts exactly that value."""
from fastapi import HTTPException
env = _local_stack_env(monkeypatch)
local_secret = env["KJBOX_PARTNER_SECRET"]
assert local_secret == "local-stack-secret"
assert env["DECIDE_GEN_PARTNER_SECRET"] == "local-stack-secret"
monkeypatch.setattr(kjbox, "get_settings", lambda: SimpleNamespace(kjbox_partner_secret=local_secret))
assert kjbox.require_kjbox_partner(local_secret) == local_secret
with pytest.raises(HTTPException) as exc:
kjbox.require_kjbox_partner("wrong")
assert exc.value.status_code == 403
def test_local_stack_honours_external_partner_secrets(monkeypatch):
env = _local_stack_env(monkeypatch, KJBOX_PARTNER_SECRET="ext-kjbox", DECIDE_GEN_PARTNER_SECRET="ext-decide")
assert env["KJBOX_PARTNER_SECRET"] == "ext-kjbox"
assert env["DECIDE_GEN_PARTNER_SECRET"] == "ext-decide"
+102
View File
@@ -0,0 +1,102 @@
"""POST /api/kjbox/catalog/resolve: kjbox (X-Kjbox-Secret) and karaoke-decide (X-Partner-Secret)
share the verdict cache but have separate rate budgets."""
from types import SimpleNamespace
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from backend.api.routes import kjbox
KJ = {"X-Kjbox-Secret": "kj-secret"}
DECIDE = {"X-Partner-Secret": "decide-secret"}
@pytest.fixture
def calls(monkeypatch):
monkeypatch.setattr(kjbox, "_resolve_cache", {})
monkeypatch.setattr(kjbox, "_resolve_calls", [])
monkeypatch.setattr(kjbox, "_resolve_calls_decide", [])
seen = []
async def fake_resolve(query):
seen.append(query)
return {"kind": "content", "confident": True, "canonical_artist": "A", "canonical_title": "T",
"typed_artist": "", "typed_title": query, "alternatives": [], "engine": "ai", "reason": ""}
from backend.services.match_judge import free_text
monkeypatch.setattr(free_text, "resolve_and_tidy", fake_resolve)
return seen
def _client(monkeypatch, kjbox_secret="kj-secret", decide_secret="decide-secret"):
settings = SimpleNamespace(kjbox_partner_secret=kjbox_secret, decide_partner_secret=decide_secret,
fake_workers=False)
monkeypatch.setattr(kjbox, "get_settings", lambda: settings)
app = FastAPI()
app.include_router(kjbox.router, prefix="/api")
return TestClient(app)
def _post(client, q, headers):
return client.post("/api/kjbox/catalog/resolve", json={"query": q}, headers=headers)
def test_both_partners_accepted(monkeypatch, calls):
c = _client(monkeypatch)
assert _post(c, "q1", KJ).status_code == 200
assert _post(c, "q2", DECIDE).status_code == 200
def test_wrong_or_missing_secret_is_403(monkeypatch, calls):
c = _client(monkeypatch)
assert _post(c, "q", {"X-Partner-Secret": "nope"}).status_code == 403
assert _post(c, "q", {"X-Kjbox-Secret": "nope"}).status_code == 403
assert _post(c, "q", {}).status_code == 403
# each secret only works in its own header
assert _post(c, "q", {"X-Kjbox-Secret": "decide-secret"}).status_code == 403
assert _post(c, "q", {"X-Partner-Secret": "kj-secret"}).status_code == 403
def test_neither_configured_is_503(monkeypatch, calls):
c = _client(monkeypatch, kjbox_secret="", decide_secret="")
assert _post(c, "q", KJ).status_code == 503
def test_only_kjbox_configured_rejects_decide(monkeypatch, calls):
c = _client(monkeypatch, decide_secret="")
assert _post(c, "q", KJ).status_code == 200
assert _post(c, "q2", {"X-Partner-Secret": ""}).status_code == 403
assert _post(c, "q2", DECIDE).status_code == 403
def test_only_decide_configured(monkeypatch, calls):
c = _client(monkeypatch, kjbox_secret="")
assert _post(c, "q", DECIDE).status_code == 200
assert _post(c, "q2", KJ).status_code == 403
def test_decide_bucket_exhausts_independently(monkeypatch, calls):
c = _client(monkeypatch)
for i in range(60):
assert _post(c, f"d{i}", DECIDE).status_code == 200
assert _post(c, "d60", DECIDE).status_code == 429
assert _post(c, "k0", KJ).status_code == 200 # kjbox unaffected
assert _post(c, "d0", DECIDE).status_code == 200 # cache hit is free
def test_kjbox_bucket_exhaustion_does_not_starve_decide(monkeypatch, calls):
monkeypatch.setattr(kjbox, "_RESOLVE_PER_MINUTE", 2)
c = _client(monkeypatch)
assert _post(c, "k1", KJ).status_code == 200
assert _post(c, "k2", KJ).status_code == 200
assert _post(c, "k3", KJ).status_code == 429
assert _post(c, "d1", DECIDE).status_code == 200
def test_cache_shared_between_partners(monkeypatch, calls):
c = _client(monkeypatch)
_post(c, "Same Query", KJ)
r = _post(c, "same query", DECIDE)
assert r.status_code == 200 and r.json()["canonical_title"] == "T"
assert calls == ["Same Query"]
+109
View File
@@ -0,0 +1,109 @@
"""Job-log Firestore writes must not run on the API event loop (log_write_offload)."""
import asyncio
import queue
import threading
from unittest.mock import MagicMock
import pytest
from backend.services import log_write_offload
@pytest.fixture(autouse=True)
def _not_in_cloud_run_job(monkeypatch):
monkeypatch.delenv("CLOUD_RUN_JOB", raising=False)
yield
assert log_write_offload.drain(timeout=5)
def test_runs_inline_off_the_event_loop():
ran_on = []
log_write_offload.submit_or_run(lambda: ran_on.append(threading.get_ident()))
assert ran_on == [threading.get_ident()]
def test_offloads_from_a_running_event_loop():
release = threading.Event()
ran_on = []
def slow_write():
release.wait(5)
ran_on.append(threading.get_ident())
async def on_loop():
log_write_offload.submit_or_run(slow_write)
# submit returned without waiting for the (blocked) write
assert ran_on == []
return threading.get_ident()
loop_thread = asyncio.run(on_loop())
release.set()
assert log_write_offload.drain(timeout=5)
assert len(ran_on) == 1 and ran_on[0] != loop_thread
def test_runs_inline_on_the_loop_inside_a_cloud_run_job(monkeypatch):
monkeypatch.setenv("CLOUD_RUN_JOB", "video-encoding-job")
ran_on = []
async def on_loop():
log_write_offload.submit_or_run(lambda: ran_on.append(threading.get_ident()))
return threading.get_ident()
assert ran_on == [asyncio.run(on_loop())]
def test_offloaded_writes_keep_submission_order():
written = []
async def on_loop():
for i in range(50):
log_write_offload.submit_or_run(lambda i=i: written.append(i))
asyncio.run(on_loop())
assert log_write_offload.drain(timeout=5)
assert written == list(range(50))
def test_full_queue_drops_with_a_warning(monkeypatch, caplog):
release = threading.Event()
monkeypatch.setattr(log_write_offload, "_queue", queue.Queue(maxsize=1))
monkeypatch.setattr(log_write_offload, "_worker", None)
monkeypatch.setattr(log_write_offload, "_dropped", 0)
monkeypatch.setattr(log_write_offload, "_last_drop_warning", 0.0)
written = []
async def on_loop():
log_write_offload.submit_or_run(lambda: release.wait(5)) # occupies the writer
await asyncio.sleep(0.05)
log_write_offload.submit_or_run(lambda: written.append("queued")) # fills the queue
log_write_offload.submit_or_run(lambda: written.append("dropped")) # no room
with caplog.at_level("WARNING", logger=log_write_offload.__name__):
asyncio.run(on_loop())
release.set()
assert log_write_offload.drain(timeout=5)
assert written == ["queued"]
assert log_write_offload._dropped == 1
assert "dropped 1 job-log lines" in caplog.text
def test_firestore_append_log_does_not_write_on_the_loop_thread():
from backend.models.worker_log import WorkerLogEntry
from backend.services.firestore_service import FirestoreService
service = FirestoreService.__new__(FirestoreService)
service.collection = "jobs"
service.db = MagicMock()
doc_ref = service.db.collection.return_value.document.return_value.collection.return_value.document.return_value
set_threads = []
doc_ref.set.side_effect = lambda data: set_threads.append(threading.get_ident())
async def on_loop():
service.append_log_to_subcollection("job1", WorkerLogEntry.create(job_id="job1", worker="screens", level="INFO", message="hi"))
return threading.get_ident()
loop_thread = asyncio.run(on_loop())
assert log_write_offload.drain(timeout=5)
assert len(set_threads) == 1 and set_threads[0] != loop_thread
assert doc_ref.set.call_args.args[0]["message"] == "hi"
+35 -2
View File
@@ -427,7 +427,10 @@ class TestRequestAwareSeverity:
assert len(progress) == 3 # 1s, 5s, 15s samples
assert all(r.levelno == logging.WARNING for r in progress)
def test_in_flight_in_progress_sample_at_15s_is_error(self, caplog):
def test_in_flight_in_progress_samples_stay_warning(self, caplog):
"""A freeze used to log ERROR twice (the 15s "in progress" sample AND the
"ended" line), so the error monitor raised two alert patterns per freeze.
"in progress" is now always WARNING; "ended" alone carries the ERROR."""
caplog.set_level(logging.WARNING)
wd, clock, tracker, recorded = self._wd()
wd._loop_thread_id = 12345
@@ -438,7 +441,11 @@ class TestRequestAwareSeverity:
patch("backend.services.loop_watchdog.sys._current_frames", return_value={12345: None}):
self._stall(wd, clock, 16.0)
progress = [r for r in caplog.records if "in progress" in r.getMessage()]
assert [r.levelno for r in progress] == [logging.WARNING, logging.WARNING, logging.ERROR]
assert [r.levelno for r in progress] == [logging.WARNING, logging.WARNING, logging.WARNING]
ended = self._ended(caplog)
assert len(ended) == 1 and ended[0].levelno == logging.ERROR
errors = [r for r in caplog.records if r.levelno >= logging.ERROR]
assert len(errors) == 1 # one freeze -> one ERROR line -> one alert pattern
def test_in_flight_request_makes_it_error(self, caplog):
caplog.set_level(logging.WARNING)
@@ -513,3 +520,29 @@ class TestRequestTrackingMiddleware:
classes = [m.cls for m in app.user_middleware]
# add_middleware inserts at index 0 → outermost is first.
assert classes[0] is RequestTrackingMiddleware
class TestRecorderFailureIsBestEffort:
"""A failed stall-record write is best-effort: WARNING, never ERROR (ERROR pages #alerts)."""
def test_recorder_failure_logs_warning(self, caplog):
caplog.set_level(logging.DEBUG)
clock = FakeClock()
def failing_recorder(_record):
raise RuntimeError("firestore unavailable")
wd = LoopWatchdog(clock=clock, cpu_clock=clock, recorder=failing_recorder)
wd._loop_thread_id = None
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() # must not raise
failed = [r for r in caplog.records if "Failed to record loop stall" in r.getMessage()]
assert len(failed) == 1
assert failed[0].levelno == logging.WARNING
assert failed[0].exc_info is not None
+69 -2
View File
@@ -283,17 +283,20 @@ def test_preview_renders_sample_with_translations():
theme_service.get_theme_style_params.return_value = {"karaoke": {}}
with patch.object(tp, "get_theme_service", return_value=theme_service), \
patch.object(tp, "resolve_assets", side_effect=lambda s, t: s), \
patch.object(tp, "_gcs_get", return_value=None), \
patch.object(tp, "_gcs_put") as put, \
patch.object(tp, "render_karaoke_frame", return_value=b"jpeg") as render:
url = tp.render_translation_preview("fr")
tp.render_translation_preview("fr") # cached
assert url.startswith("data:image/jpeg;base64,")
render.assert_called_once()
assert render.call_args.kwargs["translations"] == tp.SAMPLES["fr"]["translations"]
put.assert_called_once()
assert put.call_args.args[0].startswith("themes/_translation_previews/nomad/fr-")
def test_concurrent_cold_previews_render_once():
import threading
import time as _time
from backend.services import translation_preview as tp
@@ -303,11 +306,13 @@ def test_concurrent_cold_previews_render_once():
theme_service.get_theme_style_params.return_value = {"karaoke": {}}
def slow_render(*a, **k):
_time.sleep(0.2)
threading.Event().wait(0.2) # not time.sleep: the module's no_sleep fixture stubs it
return b"jpeg"
with patch.object(tp, "get_theme_service", return_value=theme_service), \
patch.object(tp, "resolve_assets", side_effect=lambda s, t: s), \
patch.object(tp, "_gcs_get", return_value=None), \
patch.object(tp, "_gcs_put"), \
patch.object(tp, "render_karaoke_frame", side_effect=slow_render) as render:
threads = [threading.Thread(target=tp.render_translation_preview, args=("de",)) for _ in range(5)]
for t in threads:
@@ -315,3 +320,65 @@ def test_concurrent_cold_previews_render_once():
for t in threads:
t.join()
assert render.call_count == 1
def _preview_theme_service(style_params=None):
theme_service = MagicMock()
theme_service.get_default_theme_id.return_value = "nomad"
theme_service.get_theme_style_params.return_value = style_params or {"karaoke": {}}
return theme_service
def test_preview_served_from_gcs_without_rendering():
from backend.services import translation_preview as tp
tp._CACHE.clear()
with patch.object(tp, "get_theme_service", return_value=_preview_theme_service()), \
patch.object(tp, "_gcs_get", return_value=b"cached") as get, \
patch.object(tp, "render_karaoke_frame") as render:
url = tp.render_translation_preview("it")
render.assert_not_called()
assert url == "data:image/jpeg;base64,Y2FjaGVk"
assert get.call_args.args[0].startswith("themes/_translation_previews/nomad/it-")
def test_theme_change_gets_a_new_gcs_key():
from backend.services import translation_preview as tp
a = tp._gcs_path("nomad", "it", {"karaoke": {"font": "A"}})
b = tp._gcs_path("nomad", "it", {"karaoke": {"font": "B"}})
assert a != b and a == tp._gcs_path("nomad", "it", {"karaoke": {"font": "A"}})
def test_different_languages_never_render_concurrently():
"""Two concurrent 4K renders OOM-killed the API instance (10-09, 10-16)."""
import threading
from backend.services import translation_preview as tp
tp._CACHE.clear()
active, peak = [0], [0]
guard = threading.Lock()
def render(*a, **k):
with guard:
active[0] += 1
peak[0] = max(peak[0], active[0])
threading.Event().wait(0.05) # not time.sleep: the module's no_sleep fixture stubs it
with guard:
active[0] -= 1
return b"jpeg"
with patch.object(tp, "get_theme_service", return_value=_preview_theme_service()), \
patch.object(tp, "resolve_assets", side_effect=lambda s, t: s), \
patch.object(tp, "_gcs_get", return_value=None), \
patch.object(tp, "_gcs_put"), \
patch.object(tp, "render_karaoke_frame", side_effect=render) as mock_render:
threads = [threading.Thread(target=tp.render_translation_preview, args=(code,))
for code in ("de", "fr", "es", "it")]
for t in threads:
t.start()
for t in threads:
t.join()
assert mock_render.call_count == 4
assert peak[0] == 1
+107
View File
@@ -147,3 +147,110 @@ def test_description_resolved_to_a_song_is_content():
v, seen = _tidy("that song from titanic", ai, hit)
assert seen == [("Céline Dion", "My Heart Will Go On")]
assert v["kind"] == "content" and v["canonical_title"] == "My Heart Will Go On"
# ---- latency budget: a describe query must answer inside decide's resolve timeout
_TITANIC_AI = {"kind": "content", "confident": True, "typed_artist": "", "typed_title": "song from titanic",
"canonical_artist": "Céline Dion", "canonical_title": "My Heart Will Go On"}
def test_gemini_timeout_is_retried_once(monkeypatch):
import backend.services.match_judge.free_text as ft
monkeypatch.setattr(ft, "GEMINI_ATTEMPT_TIMEOUT_S", 0.05)
calls = []
async def gen(model, system_prompt, user_prompt):
calls.append(1)
if len(calls) == 1:
await asyncio.sleep(5) # the stalled first call (prod: 504 DEADLINE_EXCEEDED at ~10 s)
return _TITANIC_AI
v = asyncio.run(resolve_free_text("song from titanic", generate=gen, model="m"))
assert len(calls) == 2
assert v["kind"] == "content" and v["canonical_title"] == "My Heart Will Go On"
def test_transient_error_is_retried_then_gives_up():
calls = []
async def gen(model, system_prompt, user_prompt):
calls.append(1)
raise RuntimeError("504 DEADLINE_EXCEEDED")
v = asyncio.run(resolve_free_text("q", generate=gen, model="m"))
assert len(calls) == 2 and v["reason"] == "unavailable"
def test_quota_error_is_not_retried(monkeypatch):
import backend.services.gemini_client as gc
monkeypatch.setattr(gc, "_maybe_alert", lambda caller, exc: None)
calls = []
async def gen(model, system_prompt, user_prompt):
calls.append(1)
raise RuntimeError("429 RESOURCE_EXHAUSTED: exceeded your current quota")
v = asyncio.run(resolve_free_text("q", generate=gen, model="m"))
assert len(calls) == 1 and v["reason"] == "unavailable"
def test_slow_catalog_tidy_answers_with_ai_verdict_and_keeps_searching(monkeypatch):
"""Prod 2026-10-20: decide's catalog API cold-started (35-45 s), the tidy waited 10 s,
and decide's resolve gave up with {} although Gemini had answered in ~2 s."""
import backend.services.match_judge.free_text as ft
monkeypatch.setattr(ft, "CATALOG_TIDY_TIMEOUT_S", 0.05)
finished = []
async def gen(model, system_prompt, user_prompt):
return _TITANIC_AI
async def judge(artist, title):
await asyncio.sleep(0.2)
finished.append((artist, title))
return MatchVerdict("cosmetic", True, "Céline Dion", "My Heart Will Go On", engine="catalog")
async def main():
v = await resolve_and_tidy("song from titanic", generate=gen, judge=judge, model="m")
assert finished == [] # answered before the catalog search finished
await asyncio.sleep(0.3) # ...which kept running in the background
return v
v = asyncio.run(main())
assert v["kind"] == "content" and v["confident"] is True
assert (v["canonical_artist"], v["canonical_title"]) == ("Céline Dion", "My Heart Will Go On")
assert v["engine"] == "ai" and v["reason"] == "unavailable" # not cached: a later ask gets the tidy
assert finished == [("Céline Dion", "My Heart Will Go On")]
assert ft._background == set()
def test_client_error_is_not_retried():
class ClientError(Exception):
code = 400
calls = []
async def gen(model, system_prompt, user_prompt):
calls.append(1)
raise ClientError("400 INVALID_ARGUMENT")
v = asyncio.run(resolve_free_text("q", generate=gen, model="m"))
assert len(calls) == 1 and v["reason"] == "unavailable"
def test_sdk_deadline_respects_the_api_minimum(monkeypatch):
"""Prod 2026-10-20 (v0.279.6): a 7 s SDK timeout was rejected with 400 'Minimum allowed
deadline is 10s', so every uncached resolve failed. The per-attempt cap is client-side."""
import types
import backend.services.gemini_client as gc
import backend.services.match_judge.free_text as ft
from backend.config import settings
seen = {}
class FakeModels:
def generate_content(self, **kw):
return types.SimpleNamespace(text='{"kind": "none", "confident": false}')
def fake_client(timeout_ms=None):
seen["timeout_ms"] = timeout_ms
return types.SimpleNamespace(models=FakeModels())
monkeypatch.setattr(gc, "get_genai_client", fake_client)
monkeypatch.setattr(settings, "match_judge_timeout_ms", 5000, raising=False)
ft._blocking_generate("m", "sys", "user")
assert seen["timeout_ms"] >= ft.GEMINI_MIN_DEADLINE_MS
+47 -4
View File
@@ -205,6 +205,18 @@ BLOCKING_CALLS = {
"check_gdrive_credentials",
"check_all_credentials",
"trigger_gdrive_validation",
# 2026-10-18 #alerts triage: watchdog culprits in async routes
"upload_json", # GCS upload (complete_review: up to 21s)
"_prepare_theme_for_job", # GCS reads/writes (job creation)
"generate", # CustomLyricsService.generate → sync Gemini call (151s, 32 requests)
# 2026-10-19 watchdog culprits (7 days of EVENT_LOOP_STALL stacks): sync Firestore /
# GCS reads in the auth dependencies, tenant middleware and routes.
"validate_token_full", # require_auth: every authenticated request (up to 1.9s)
"validate_token",
"validate_session",
"get_tenant_config", # GCS read on a cache miss (tenant middleware, up to 1.2s)
"append_log_to_subcollection", # job-log write; on the loop it is offloaded, see log_write_offload
"append_worker_log",
}
_BLOCKING_MODULE_CALLS = {("requests", "get"), ("requests", "post"), ("requests", "put"),
("requests", "delete"), ("requests", "request"), ("time", "sleep")}
@@ -222,13 +234,14 @@ def _blocking_call_name(call: ast.Call) -> str | None:
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)."""
def find_blocking_calls_in_async_routes(source: str, routes_only: bool = True) -> list[str]:
"""`async def` routes (or, with routes_only=False, any `async def`) 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)):
if not (isinstance(fn, ast.AsyncFunctionDef) and (_is_route(fn) or not routes_only)):
continue
stack = list(fn.body)
while stack:
@@ -279,3 +292,33 @@ async def helper_ok():
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()"]
# Auth dependencies and middleware run on the event loop for (nearly) every request, so
# every `async def` in them is held to the same rule as a route, not just decorated ones.
ALWAYS_ON_LOOP_FILES = [BACKEND / "api" / "dependencies.py"] + sorted((BACKEND / "middleware").glob("*.py"))
def test_no_known_blocking_calls_in_async_dependencies_or_middleware():
offenders = []
for path in ALWAYS_ON_LOOP_FILES:
for hit in find_blocking_calls_in_async_routes(path.read_text(), routes_only=False):
offenders.append(f"{path.relative_to(BACKEND.parent)}::{hit}")
assert not offenders, (
"These `async def` dependencies/middleware call known-blocking functions on the "
"event loop, which stalls every request. Use `await asyncio.to_thread(fn, ...)`:\n "
+ "\n ".join(sorted(offenders))
)
def test_blocking_call_detector_scans_non_route_async_functions():
src = '''
async def require_auth(request):
return auth_service.validate_token_full(token)
async def fixed(request):
return await asyncio.to_thread(auth_service.validate_token_full, token)
'''
assert find_blocking_calls_in_async_routes(src) == []
hits = find_blocking_calls_in_async_routes(src, routes_only=False)
assert [h.split(" line")[0] for h in hits] == ["require_auth: validate_token_full()"]
+18
View File
@@ -106,6 +106,24 @@ def test_send_ops_alert_no_webhook_returns_false(monkeypatch):
assert ops_alerts.send_ops_alert("hi") is False
def test_send_ops_alert_suppresses_link_embeds(monkeypatch):
"""Ops alerts carry error text with URLs; Discord must not unfurl them."""
import backend.services.discord_service as discord_service
calls = []
class FakeService:
def post_message(self, message, webhook_url=None, suppress_embeds=False):
calls.append((message, webhook_url, suppress_embeds))
return True
monkeypatch.setattr(ops_alerts, "_is_enabled", lambda: True)
monkeypatch.setattr(ops_alerts, "_get_webhook_url", lambda: "https://discord.com/api/webhooks/1/a")
monkeypatch.setattr(discord_service, "get_discord_notification_service", lambda **kw: FakeService())
assert ops_alerts.send_ops_alert("boom https://cloud.google.com/x") is True
assert calls == [("boom https://cloud.google.com/x", "https://discord.com/api/webhooks/1/a", True)]
# ---------------------------------------------------------------------------
# notify_job_failed
# ---------------------------------------------------------------------------
@@ -56,7 +56,7 @@ def _job(job_id, status, *, minutes_stale=0, source_name=None, download_retry=No
def _mock_jm(*, downloading=None, pending=None, rendering=None, review_complete=None,
downloading_prep=None, jobs=None):
downloading_prep=None, instrumental_selected=None, jobs=None):
"""Wire a JobManager mock for the endpoint's 4 status queries.
downloading/rendering/review_complete use .where().stream(); pending uses
@@ -69,11 +69,13 @@ 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 []),
]
# Three .limit().stream() calls in order: download_pending_retry, then downloading
# Four .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)
# lyrics_complete (stalled storage-retention stems restore), then
# instrumental_selected (final encode parked on stems / lost video trigger)
where.limit.return_value.stream.side_effect = [
iter(pending or []), iter(downloading_prep or []), iter([]),
iter(instrumental_selected or []),
]
mock_jm.get_job.side_effect = lambda jid: (jobs or {}).get(jid)
mock_jm.transition_to_state.return_value = True
@@ -284,3 +286,72 @@ def test_fresh_review_complete_is_left_alone(client):
assert resp.status_code == 200
assert resp.json()["render_retriggered_jobs"] == []
mock_ws.trigger_render_video_worker.assert_not_awaited()
def _is_job(job_id, *, minutes_stale, audio_complete, stem_ready, selection="clean"):
job = _job(job_id, JobStatus.INSTRUMENTAL_SELECTED, minutes_stale=minutes_stale)
job.state_data.update({"instrumental_selection": selection, "audio_complete": audio_complete})
if stem_ready:
job.file_urls = {"stems": {"instrumental_clean": "gs://b/clean.flac",
"instrumental_with_backing": "gs://b/backing.flac"}}
return job
def _run_is(client, job):
mock_jm = _mock_jm(
instrumental_selected=[_doc(job.job_id, JobStatus.INSTRUMENTAL_SELECTED)],
jobs={job.job_id: job},
)
mock_ws = MagicMock()
mock_ws.trigger_video_worker = AsyncMock(return_value=True)
with patch("backend.api.routes.internal.JobManager", return_value=mock_jm), \
patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
resp = client.post("/api/internal/recover-stuck-jobs")
assert resp.status_code == 200
return resp.json(), mock_jm, mock_ws
def test_instrumental_selected_with_stems_ready_retriggers_video(client):
"""Parked/lost video trigger: stems landed but no encode started -> re-trigger."""
body, mock_jm, mock_ws = _run_is(
client, _is_job("is1", minutes_stale=15, audio_complete=True, stem_ready=True))
assert body["video_retriggered_jobs"] == ["is1"]
mock_ws.trigger_video_worker.assert_awaited_once_with("is1")
mock_jm.claim_video_stems_wait.assert_called_once_with("is1")
def test_instrumental_selected_fresh_is_left_alone(client):
body, _, mock_ws = _run_is(
client, _is_job("is2", minutes_stale=2, audio_complete=True, stem_ready=True))
assert body["video_retriggered_jobs"] == []
mock_ws.trigger_video_worker.assert_not_awaited()
def test_instrumental_selected_still_separating_waits(client):
"""Separation still running (<60 min): neither re-trigger nor fail."""
body, mock_jm, mock_ws = _run_is(
client, _is_job("is3", minutes_stale=30, audio_complete=False, stem_ready=False))
assert body["video_retriggered_jobs"] == []
assert body["stems_wait_failed_jobs"] == []
mock_ws.trigger_video_worker.assert_not_awaited()
mock_jm.mark_job_failed.assert_not_called()
def test_instrumental_selected_stems_never_ready_fails_loudly(client):
"""Separation never finished (>60 min): fail so the job isn't stuck silently."""
body, mock_jm, mock_ws = _run_is(
client, _is_job("is4", minutes_stale=90, audio_complete=False, stem_ready=False))
assert body["stems_wait_failed_jobs"] == ["is4"]
mock_jm.mark_job_failed.assert_called_once()
assert mock_jm.mark_job_failed.call_args.kwargs["error_details"]["stage"] == "video_waiting_for_stems"
mock_ws.trigger_video_worker.assert_not_awaited()
def test_instrumental_selected_older_than_24h_is_never_revived(client):
body, mock_jm, mock_ws = _run_is(
client, _is_job("is5", minutes_stale=25 * 60, audio_complete=True, stem_ready=True))
assert body["video_retriggered_jobs"] == []
assert body["stems_wait_failed_jobs"] == []
mock_ws.trigger_video_worker.assert_not_awaited()
mock_jm.mark_job_failed.assert_not_called()
+117
View File
@@ -2490,3 +2490,120 @@ class TestVocalsPeaksEndpoint:
with pytest.raises(HTTPException) as exc_info:
self._run(stems={}, audio_complete=True)
assert exc_info.value.status_code == 404
class TestCorrectionDataReviewTransitionIdempotent:
"""GET correction-data opens review; concurrent opens (iOS) must not 500."""
def _run(self, status, transition_side_effect=None, transition_return=True, reread_status=None):
from backend.exceptions import InvalidStateTransitionError # noqa: F401
helper = TestReplayCorrectionData()
client = helper._client_with_auth("full")
try:
with patch("backend.api.routes.review.JobManager") as jm, \
patch("backend.api.routes.review.StorageService") as storage_cls, \
patch("backend.api.routes.review._get_audio_hash", return_value="h1"):
job = helper._completed_job()
job.status = status
job.user_email = "u@example.com"
if reread_status is None:
jm.return_value.get_job.return_value = job
else:
reread = MagicMock()
reread.status = reread_status
jm.return_value.get_job.side_effect = [job, reread]
jm.return_value.transition_to_state.side_effect = transition_side_effect
jm.return_value.transition_to_state.return_value = transition_return
storage = storage_cls.return_value
storage.file_exists.return_value = True
storage.download_json.side_effect = lambda p: {"corrected_segments": [], "metadata": {}}
resp = client.get("/api/review/job1/correction-data")
return resp, jm.return_value
finally:
helper._teardown()
def test_already_in_review_does_not_transition(self):
from backend.models.job import JobStatus
resp, jm = self._run(JobStatus.IN_REVIEW)
assert resp.status_code == 200
jm.transition_to_state.assert_not_called()
jm.record_review_started.assert_not_called()
def test_awaiting_review_transitions_and_records_once(self):
from backend.models.job import JobStatus
resp, jm = self._run(JobStatus.AWAITING_REVIEW)
assert resp.status_code == 200
jm.transition_to_state.assert_called_once()
jm.record_review_started.assert_called_once()
def test_lost_race_returns_data_without_side_effects(self):
from backend.exceptions import InvalidStateTransitionError
from backend.models.job import JobStatus
resp, jm = self._run(
JobStatus.AWAITING_REVIEW,
transition_side_effect=InvalidStateTransitionError(
message="Invalid state transition in_review -> in_review"),
reread_status=JobStatus.IN_REVIEW,
)
assert resp.status_code == 200
jm.record_review_started.assert_not_called()
def test_other_invalid_transition_still_errors(self):
from backend.exceptions import InvalidStateTransitionError
from backend.models.job import JobStatus
resp, jm = self._run(
JobStatus.AWAITING_REVIEW,
transition_side_effect=InvalidStateTransitionError(message="nope"),
reread_status=JobStatus.CANCELLED,
)
assert resp.status_code == 500
jm.record_review_started.assert_not_called()
class TestPreviewVideoMissingTimings:
"""POST /preview-video with an untimed in-browser edit: fill it, or 422 naming the line (was a 500 KeyError)."""
@pytest.fixture(autouse=True)
def auth_overrides(self):
from backend.main import app
from backend.api.dependencies import require_review_auth
async def mock_require_review_auth(job_id: str = "test123"):
return (job_id, "full")
app.dependency_overrides[require_review_auth] = mock_require_review_auth
yield
app.dependency_overrides.pop(require_review_auth, None)
def _post(self, test_client, payload):
from backend.models.job import JobStatus
mock_job = MagicMock()
mock_job.status = JobStatus.IN_REVIEW
encoding = MagicMock()
encoding.is_preview_enabled = False # local render path
render = AsyncMock(return_value="hash123")
with patch("backend.api.routes.review.JobManager") as mock_jm, \
patch("backend.api.routes.review.StorageService"), \
patch("backend.api.routes.review.get_encoding_service", return_value=encoding), \
patch("backend.api.routes.review._render_preview_locally", render):
mock_jm.return_value.get_job.return_value = mock_job
resp = test_client.post("/api/review/test123/preview-video", json=payload)
return resp, render
def test_unrecoverable_line_is_a_422_naming_it(self, test_client):
payload = {"corrections": [], "corrected_segments": [
{"id": "s", "text": "lonely line", "words": [{"id": "w", "text": "lonely"}]}]}
resp, render = self._post(test_client, payload)
assert resp.status_code == 422, resp.text
assert "lonely line" in resp.json()["detail"]
render.assert_not_awaited()
def test_fillable_gaps_reach_the_renderer_filled(self, test_client):
payload = {"corrections": [], "corrected_segments": [
{"id": "s", "text": "x", "start_time": 1.0,
"words": [{"id": "w", "text": "x", "start_time": 1.0, "end_time": 1.5}]}]}
resp, render = self._post(test_client, payload)
assert resp.status_code == 200, resp.text
sent = render.await_args.args[1]
assert sent["corrected_segments"][0]["end_time"] == 1.5
@@ -162,6 +162,50 @@ class TestStorePayment:
assert stored["currency"] == "usd"
assert stored["customer_email"] == ""
def test_payment_link_session_with_null_customer_email(self, service):
"""A Stripe Payment Link checkout has no gen metadata and customer_email=None.
Regression: 2026-10-13 a $36 Payment Link tip crashed store_payment on
``None.lower()`` so it never reached stripe_payments / revenue numbers.
"""
session = {
"id": "cs_live_paymentlink",
"amount_total": 3600,
"currency": "usd",
"livemode": True,
"metadata": {},
"customer_email": None,
"customer_details": {"email": "Friend@Example.com ", "name": "A Friend"},
"payment_link": "plink_123",
"payment_intent": "pi_123",
"line_items": {"data": [{"description": "Custom Karaoke Service"}]},
}
assert service.store_payment(session) is True
stored = service.db.collection.return_value.document.return_value.set.call_args[0][0]
assert stored["customer_email"] == "friend@example.com"
assert stored["customer_name"] == "A Friend"
assert stored["order_type"] == "payment_link"
assert stored["payment_link_id"] == "plink_123"
assert stored["product_description"] == "Custom Karaoke Service"
assert stored["credits_granted"] == 0
assert stored["amount_total"] == 3600
def test_none_valued_fields_do_not_crash(self, service):
"""Stripe sends explicit nulls (metadata/customer_details/total_details)."""
session = {
"id": "cs_nulls",
"amount_total": 500,
"metadata": None,
"customer_email": None,
"customer_details": None,
"total_details": None,
}
assert service.store_payment(session) is True
stored = service.db.collection.return_value.document.return_value.set.call_args[0][0]
assert stored["customer_email"] == ""
def test_returns_false_on_firestore_error(self, service):
"""Test that Firestore errors are caught and return False."""
service.db.collection.side_effect = Exception("Firestore down")
@@ -0,0 +1,94 @@
"""Stripe webhook: checkouts that didn't come from gen (e.g. a Stripe Payment Link).
A Payment Link session carries no gen metadata (no user_email / credits /
order_type) and customer_email=None. It must not log ERROR (the error monitor
pages #alerts on every new ERROR pattern) and must still be stored in
stripe_payments so revenue reporting includes it.
"""
import logging
from unittest.mock import MagicMock, patch
import pytest
from backend.services.stripe_service import StripeService
PAYMENT_LINK_SESSION = {
"id": "cs_live_plink_test",
"object": "checkout.session",
"amount_total": 3600,
"currency": "usd",
"livemode": True,
"metadata": {},
"customer_email": None,
"customer_details": {"email": "friend@example.com", "name": "A Friend"},
"payment_link": "plink_123",
}
class TestIsGenCheckout:
def test_payment_link_session_is_not_gen(self):
assert StripeService.is_gen_checkout(PAYMENT_LINK_SESSION) is False
def test_credit_purchase_is_gen(self):
session = {"metadata": {"user_email": "a@b.com", "credits": "5", "package_id": "5_credits"}}
assert StripeService.is_gen_checkout(session) is True
def test_made_for_you_is_gen(self):
assert StripeService.is_gen_checkout({"metadata": {"order_type": "made_for_you"}}) is True
def test_null_metadata_is_not_gen(self):
assert StripeService.is_gen_checkout({"metadata": None}) is False
@pytest.mark.asyncio
async def test_payment_link_checkout_logs_info_and_stores_payment(caplog):
from backend.api.routes import users as users_routes
event = {"id": "evt_1", "type": "checkout.session.completed",
"data": {"object": dict(PAYMENT_LINK_SESSION)}}
stripe_service = MagicMock()
stripe_service.verify_webhook_signature.return_value = (True, event, "ok")
user_service = MagicMock()
user_service.is_stripe_session_processed.return_value = False
user_service.get_user_doc_ref.return_value = None
email_service = MagicMock()
admin_service = MagicMock()
request = MagicMock()
async def body():
return b"{}"
request.body = body
expanded = dict(PAYMENT_LINK_SESSION)
with patch("backend.services.stripe_admin_service.get_stripe_admin_service",
return_value=admin_service), \
patch("stripe.checkout.Session.retrieve", return_value=expanded), \
caplog.at_level(logging.DEBUG):
result = await users_routes.stripe_webhook(
request=request,
stripe_signature="sig",
stripe_service=stripe_service,
user_service=user_service,
email_service=email_service,
)
assert result["status"] == "received"
# Never treated as a credit purchase
stripe_service.handle_checkout_completed.assert_not_called()
user_service.add_credits.assert_not_called()
# Session marked processed so a redelivered event is skipped
user_service._mark_stripe_session_processed.assert_called_once_with(
stripe_session_id="cs_live_plink_test", email="friend@example.com", amount=0,
)
# Still recorded for revenue reporting
admin_service.store_payment.assert_called_once()
# Logged at INFO, nothing at ERROR
assert any("non-gen checkout" in r.message and r.levelno == logging.INFO for r in caplog.records)
assert not [r for r in caplog.records if r.levelno >= logging.ERROR]
# The success audit row carries the fallback email
final_call = admin_service.log_webhook_event.call_args_list[-1]
assert final_call.kwargs["customer_email"] == "friend@example.com"
assert final_call.kwargs["status"] == "success"
+132
View File
@@ -0,0 +1,132 @@
"""Final encode waits for stem separation instead of failing (2026-10-19).
Review can finish before separation does. The video worker used to fail its
prerequisites ("Missing instrumental: instrumental_clean") 3x and leave the job at
instrumental_selected forever. Now it parks the job, the audio worker resumes it
when the stems land, and an atomic claim on the flag makes the park/resume race
safe.
"""
from datetime import datetime, timezone
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from backend.models.job import Job, JobStatus
from backend.services.job_health_service import selected_stem_pending
from backend.services.job_manager import JobManager
from backend.workers.video_worker import _park_until_stems_ready
def _job(*, status=JobStatus.INSTRUMENTAL_SELECTED, selection="clean", audio_complete=False,
stems=None, waiting=None):
sd = {"instrumental_selection": selection, "audio_complete": audio_complete}
if waiting is not None:
sd["video_waiting_for_stems"] = waiting
return Job(
job_id="j1", artist="A", title="B", status=status,
created_at=datetime.now(timezone.utc), updated_at=datetime.now(timezone.utc),
state_data=sd, file_urls={"stems": stems or {}},
)
READY = {"instrumental_clean": "gs://b/c.flac", "instrumental_with_backing": "gs://b/w.flac"}
class TestSelectedStemPending:
def test_pending_when_stem_missing_and_separation_running(self):
assert selected_stem_pending(_job()) is True
def test_with_backing_selection_checks_its_own_stem(self):
assert selected_stem_pending(_job(selection="with_backing",
stems={"instrumental_clean": "x"})) is True
def test_not_pending_once_stem_exists(self):
assert selected_stem_pending(_job(stems=READY)) is False
def test_not_pending_when_separation_finished_without_stem(self):
"""audio_complete but no stem = a real failure; let prerequisites reject it."""
assert selected_stem_pending(_job(audio_complete=True)) is False
def test_custom_instrumental_never_waits(self):
assert selected_stem_pending(_job(selection="custom")) is False
@pytest.mark.parametrize("status", [JobStatus.GENERATING_VIDEO, JobStatus.COMPLETE, JobStatus.FAILED])
def test_wrong_status_never_parks(self, status):
assert selected_stem_pending(_job(status=status)) is False
class TestParkUntilStemsReady:
def _jm(self, refreshed, claim=False):
jm = MagicMock()
jm.get_job.return_value = refreshed
jm.claim_video_stems_wait.return_value = claim
return jm
def test_not_pending_continues_without_touching_the_flag(self):
jm = self._jm(None)
parked, job = _park_until_stems_ready("j1", _job(stems=READY), jm, MagicMock())
assert parked is False and job.file_urls["stems"] == READY
jm.park_video_for_stems.assert_not_called()
def test_still_pending_after_refresh_parks(self):
jm = self._jm(_job())
parked, _ = _park_until_stems_ready("j1", _job(), jm, MagicMock())
assert parked is True
jm.park_video_for_stems.assert_called_once_with("j1")
jm.claim_video_stems_wait.assert_not_called()
def test_stems_landed_while_parking_and_we_win_the_claim_continues(self):
jm = self._jm(_job(stems=READY, audio_complete=True), claim=True)
parked, job = _park_until_stems_ready("j1", _job(), jm, MagicMock())
assert parked is False
assert job.file_urls["stems"] == READY # continues with the refreshed job
def test_stems_landed_but_audio_worker_already_resumed_exits(self):
jm = self._jm(_job(stems=READY, audio_complete=True), claim=False)
parked, _ = _park_until_stems_ready("j1", _job(), jm, MagicMock())
assert parked is True # the audio worker dispatched a fresh run
class TestResumeVideoIfWaitingForStems:
def _jm(self, *, claimed, job):
jm = JobManager.__new__(JobManager)
jm.firestore = MagicMock()
jm.firestore.claim_job_state_flag.return_value = claimed
jm.get_job = MagicMock(return_value=job)
return jm
@pytest.mark.asyncio
async def test_resumes_parked_job(self):
jm = self._jm(claimed=True, job=_job(stems=READY, audio_complete=True))
ws = MagicMock(trigger_video_worker=AsyncMock(return_value=True))
with patch("backend.services.worker_service.get_worker_service", return_value=ws):
assert await jm.resume_video_if_waiting_for_stems("j1") is True
jm.firestore.claim_job_state_flag.assert_called_once_with("j1", "video_waiting_for_stems")
ws.trigger_video_worker.assert_awaited_once_with("j1")
@pytest.mark.asyncio
async def test_no_flag_no_trigger(self):
"""Normal ordering (stems before review): nothing parked, nothing to do."""
jm = self._jm(claimed=False, job=_job())
ws = MagicMock(trigger_video_worker=AsyncMock(return_value=True))
with patch("backend.services.worker_service.get_worker_service", return_value=ws):
assert await jm.resume_video_if_waiting_for_stems("j1") is False
ws.trigger_video_worker.assert_not_awaited()
@pytest.mark.asyncio
async def test_job_moved_on_is_not_resumed(self):
jm = self._jm(claimed=True, job=_job(status=JobStatus.FAILED))
ws = MagicMock(trigger_video_worker=AsyncMock(return_value=True))
with patch("backend.services.worker_service.get_worker_service", return_value=ws):
assert await jm.resume_video_if_waiting_for_stems("j1") is False
ws.trigger_video_worker.assert_not_awaited()
def test_park_sets_flag_and_user_facing_message():
jm = JobManager.__new__(JobManager)
jm.update_job = MagicMock()
jm.park_video_for_stems("j1")
updates = jm.update_job.call_args.args[1]
assert updates["state_data.video_waiting_for_stems"] is True
assert "starts automatically" in updates["message"]
+307
View File
@@ -0,0 +1,307 @@
"""Unit tests for the YouTube comment auto-reply decision core (no network)."""
from datetime import datetime, timezone
import pytest
from backend.services import youtube_comment_bot as bot
OWNER = bot.NOMAD_CHANNEL_ID
def _item(text="can you make Paper Moons by The Lanterns?", author_channel="UCviewer",
replies=None, total_replies=None, published="2026-10-01T12:00:00Z", vid="vid1"):
replies = replies or []
return {
"id": "thread1",
"snippet": {
"videoId": vid,
"totalReplyCount": len(replies) if total_replies is None else total_replies,
"topLevelComment": {
"id": "c1",
"snippet": {
"authorDisplayName": "Viewer",
"authorChannelId": {"value": author_channel},
"textOriginal": text,
"publishedAt": published,
},
},
},
"replies": {"comments": [
{"snippet": {"authorChannelId": {"value": ch}, "textOriginal": t}} for ch, t in replies
]},
}
class FakeBoard:
def __init__(self, existing=None):
self.existing = existing or {}
self.added = []
def canonicalize(self, artist, title):
return artist.strip(), title.strip()
def find_open_or_published(self, artist, title):
return self.existing.get(bot.song_key(artist, title))
def add_from_comment(self, artist, title, thread):
m = bot.BoardMatch(f"new{len(self.added)}", artist, title, "open")
self.added.append((artist, title, thread.comment_id))
self.existing[bot.song_key(artist, title)] = m
return m
def gen_returning(data, translation=None):
calls = []
def _gen(system_prompt, user_prompt, schema):
calls.append((system_prompt, user_prompt, schema))
if schema is None:
return {"text": translation if translation is not None else user_prompt.split("\n\n", 1)[1]}
return data
_gen.calls = calls
return _gen
REQUEST = {"is_song_request": True, "songs": [{"artist": "The Lanterns", "title": "Paper Moons"}],
"language": "en", "confidence": 0.95, "reason": "asks to make it"}
def _decide(thread, gen, board=None, index=None, **kw):
return bot.decide(thread, video_title="X - Y (Karaoke)", index=index or bot.ChannelIndex(),
board=board or FakeBoard(), generate=gen, **kw)
class TestThreadFromApi:
def test_parses_owner_replies_only(self):
t = bot.thread_from_api(_item(replies=[("UCother", "me too"), (OWNER, "on it!")]))
assert t.owner_replies == ["on it!"]
assert t.comment_id == "c1" and t.video_id == "vid1" and t.total_reply_count == 2
def test_published_parses_rfc3339(self):
assert bot.thread_from_api(_item()).published == datetime(2026, 10, 1, 12, tzinfo=timezone.utc)
class TestSkips:
def test_own_comment(self):
gen = gen_returning(REQUEST)
d = _decide(bot.thread_from_api(_item(author_channel=OWNER)), gen)
assert (d.action, d.reason) == ("skip", "own_comment") and not gen.calls
def test_already_replied_by_channel(self):
gen = gen_returning(REQUEST)
d = _decide(bot.thread_from_api(_item(replies=[(OWNER, "added!")])), gen)
assert d.reason == "already_replied" and not gen.calls
def test_too_old(self):
d = _decide(bot.thread_from_api(_item()), gen_returning(REQUEST),
not_before=datetime(2026, 10, 2, tzinfo=timezone.utc))
assert d.reason == "too_old"
def test_not_a_request(self):
d = _decide(bot.thread_from_api(_item(text="love this")),
gen_returning({"is_song_request": False, "songs": [], "language": "en", "confidence": 0.9}))
assert d.reason == "not_a_request"
def test_low_confidence_does_not_touch_board(self):
board = FakeBoard()
d = _decide(bot.thread_from_api(_item()), gen_returning({**REQUEST, "confidence": 0.5}), board=board)
assert d.reason == "low_confidence" and board.added == []
def test_classifier_exception_skips(self):
def boom(*a):
raise RuntimeError("quota")
d = _decide(bot.thread_from_api(_item()), boom)
assert (d.action, d.reason) == ("skip", "classifier_error")
def test_request_flag_without_songs_is_not_request(self):
d = _decide(bot.thread_from_api(_item()), gen_returning({**REQUEST, "songs": []}))
assert d.reason == "not_a_request"
class TestRouting:
def test_new_board_request(self):
board = FakeBoard()
d = _decide(bot.thread_from_api(_item()), gen_returning(REQUEST), board=board)
assert d.action == "reply"
assert [s.kind for s in d.songs] == ["board_new"]
assert board.added == [("The Lanterns", "Paper Moons", "c1")]
assert "request=new0" in d.reply_text and "utm_medium=comment_reply" in d.reply_text
assert '"Paper Moons" by The Lanterns' in d.reply_text
def test_existing_board_request_is_linked_not_duplicated(self):
key = bot.song_key("The Lanterns", "Paper Moons")
board = FakeBoard({key: bot.BoardMatch("r9", "The Lanterns", "Paper Moons", "open")})
d = _decide(bot.thread_from_api(_item()), gen_returning(REQUEST), board=board)
assert d.songs[0].kind == "board_existing" and board.added == []
assert "request=r9" in d.reply_text
def test_published_board_request_links_video(self):
key = bot.song_key("The Lanterns", "Paper Moons")
board = FakeBoard({key: bot.BoardMatch("r9", "The Lanterns", "Paper Moons", "published",
"https://youtu.be/pub1")})
d = _decide(bot.thread_from_api(_item()), gen_returning(REQUEST), board=board)
assert d.songs[0].kind == "board_published"
assert "Already made" in d.reply_text and "https://youtu.be/pub1" in d.reply_text
def test_existing_channel_video_wins(self):
index = bot.ChannelIndex({bot.song_key("The Lanterns", "Paper Moons"): "vidX"})
board = FakeBoard()
d = _decide(bot.thread_from_api(_item()), gen_returning(REQUEST), board=board, index=index)
assert d.songs[0].kind == "existing_video" and board.added == []
assert "https://youtu.be/vidX" in d.reply_text
def test_multiple_songs_mixed_and_deduped(self):
data = {**REQUEST, "songs": [{"artist": "The Lanterns", "title": "Paper Moons"},
{"artist": "the lanterns", "title": "paper moons"},
{"artist": "Glass Harbor", "title": "Tin Sky"}]}
index = bot.ChannelIndex({bot.song_key("Glass Harbor", "Tin Sky"): "vidG"})
d = _decide(bot.thread_from_api(_item()), gen_returning(data), index=index)
assert [s.kind for s in d.songs] == ["board_new", "existing_video"]
assert d.reply_text.index("Already made") < d.reply_text.index("requests board")
def test_caps_songs(self):
data = {**REQUEST, "songs": [{"artist": f"A{i}", "title": f"T{i}"} for i in range(6)]}
d = _decide(bot.thread_from_api(_item()), gen_returning(data))
assert len(d.songs) == bot.MAX_SONGS_PER_COMMENT
class TestVagueRequest:
VAGUE = {"is_song_request": False, "is_vague_request": True, "songs": [], "language": "en",
"confidence": 0.9}
def test_vague_ask_gets_generic_board_link_and_no_board_write(self):
board = FakeBoard()
d = _decide(bot.thread_from_api(_item(text="more johnnie please")), gen_returning(self.VAGUE), board=board)
assert (d.action, d.reason) == ("reply", "vague_request")
assert board.added == [] and d.songs == []
assert "request=" not in d.reply_text and "utm_medium=comment_reply" in d.reply_text
def test_low_confidence_vague_skips(self):
d = _decide(bot.thread_from_api(_item(text="more?")), gen_returning({**self.VAGUE, "confidence": 0.5}))
assert d.reason == "low_confidence"
def test_vague_flag_ignored_when_songs_named(self):
c = bot.parse_classification({**REQUEST, "is_vague_request": True})
assert c.is_song_request and not c.is_vague_request
class TestTranslation:
def test_non_english_translated_when_urls_survive(self):
def gen(system_prompt, user_prompt, schema):
if schema is None:
text = user_prompt.split("\n\n", 1)[1]
return {"text": "¡Gracias! " + " ".join(bot._URL_RE.findall(text))}
return {**REQUEST, "language": "es"}
d = _decide(bot.thread_from_api(_item(text="¿puedes hacer Paper Moons?")), gen)
assert d.reply_text.startswith("¡Gracias!") and d.reply_text_en != d.reply_text
def test_falls_back_to_english_if_url_mangled(self):
d = _decide(bot.thread_from_api(_item()), gen_returning({**REQUEST, "language": "es"},
translation="Gracias sin enlace"))
assert d.reply_text == d.reply_text_en
def test_english_never_calls_translator(self):
gen = gen_returning(REQUEST)
_decide(bot.thread_from_api(_item()), gen)
assert all(schema is not None for _, _, schema in gen.calls)
class TestParseClassification:
@pytest.mark.parametrize("data", [None, [], "x", {"songs": "nope"}])
def test_malformed(self, data):
c = bot.parse_classification(data)
assert not c.is_song_request and c.songs == []
def test_confidence_clamped_and_blank_songs_dropped(self):
c = bot.parse_classification({"is_song_request": True, "confidence": 3,
"songs": [{"artist": "", "title": "x"}, {"artist": "A", "title": "B"}]})
assert c.confidence == 1.0 and [s.title for s in c.songs] == ["B"]
class TestUnsafeNames:
@pytest.mark.parametrize("title", [
"Win free stuff at http://evil.example", "visit www.spam.test", "free-gift.com",
"dm @scammer", "<b>x</b>", "line one\nline two", "x" * 101,
])
def test_unsafe_song_names_are_dropped(self, title):
c = bot.parse_classification({**REQUEST, "songs": [{"artist": "The Lanterns", "title": title}]})
assert c.songs == [] and not c.is_song_request
def test_unsafe_artist_dropped_but_safe_song_kept(self):
c = bot.parse_classification({**REQUEST, "songs": [
{"artist": "spam.xyz", "title": "Paper Moons"}, {"artist": "Glass Harbor", "title": "Tin Sky"}]})
assert [s.title for s in c.songs] == ["Tin Sky"]
def test_normal_punctuation_survives(self):
c = bot.parse_classification({**REQUEST, "songs": [{"artist": "fun.", "title": "Walking the Dog II"},
{"artist": "Los Campesinos!", "title": "kms"}]})
assert len(c.songs) == 2
class TestChannelIndex:
def test_from_entries_high_confidence_non_translated_only(self):
idx = bot.ChannelIndex.from_entries([
{"video_id": "v1", "yt_title": "A - B (Karaoke)", "artist": "A", "song_title": "B",
"parse_confidence": "high"},
{"video_id": "v2", "yt_title": "C - D karaoke", "artist": "C", "song_title": "D",
"parse_confidence": "medium"},
{"video_id": "v3", "yt_title": "A - B (With Translation into Spanish) (Karaoke)",
"artist": "A", "song_title": "B", "parse_confidence": "high",
"translation_language_name": "Spanish"},
])
assert idx.find("a", "b") == "v1" and idx.find("C", "D") is None
assert set(idx.titles) == {"v1", "v2", "v3"}
class FakeYouTube:
"""Minimal chainable stand-in for the googleapiclient resource."""
def __init__(self, pages, reply_pages=None):
self.pages = pages
self.reply_pages = reply_pages or []
self.inserted = []
def commentThreads(self):
return self
def comments(self):
return self
def list(self, **kw):
self._kw = kw
return self
def insert(self, **kw):
self.inserted.append(kw)
self._kw = {"insert": True}
return self
def execute(self):
if self._kw.get("insert"):
return {"id": "reply1"}
if "parentId" in self._kw:
return self.reply_pages.pop(0)
return self.pages.pop(0)
class TestApiHelpers:
def test_iter_stops_before_cutoff(self):
yt = FakeYouTube([
{"items": [_item(published="2026-10-05T00:00:00Z")], "nextPageToken": "p2"},
{"items": [_item(published="2026-09-01T00:00:00Z"), _item(published="2026-08-01T00:00:00Z")],
"nextPageToken": "p3"},
])
got = list(bot.iter_comment_threads(yt, stop_before=datetime(2026, 9, 15, tzinfo=timezone.utc)))
assert len(got) == 1 and yt.pages == []
def test_load_thread_fetches_truncated_owner_replies(self):
yt = FakeYouTube([], reply_pages=[{"items": [
{"snippet": {"authorChannelId": {"value": OWNER}, "textOriginal": "done"}}]}])
t = bot.load_thread(yt, _item(replies=[("UCa", "x")], total_replies=7))
assert t.owner_replies == ["done"]
def test_post_reply(self):
yt = FakeYouTube([])
assert bot.post_reply(yt, "c1", "hi") == "reply1"
assert yt.inserted[0]["body"]["snippet"] == {"parentId": "c1", "textOriginal": "hi"}
@@ -0,0 +1,238 @@
"""Unit tests for the YouTube comment bot worker (Firestore, YouTube and Gemini faked)."""
import json
from datetime import datetime, timezone
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from google.api_core import exceptions as gcloud_exceptions
from backend.services import youtube_comment_bot as bot
from backend.workers import youtube_comment_bot_worker as w
SCOPES = ["https://www.googleapis.com/auth/youtube", w.FORCE_SSL_SCOPE]
REQUEST = {"is_song_request": True, "songs": [{"artist": "The Lanterns", "title": "Paper Moons"}],
"language": "en", "confidence": 0.95}
NOT_REQUEST = {"is_song_request": False, "songs": [], "language": "en", "confidence": 0.95}
class FakeDoc:
def __init__(self, store, key):
self.store, self.key = store, key
def get(self):
data = self.store.get(self.key)
return SimpleNamespace(exists=data is not None, to_dict=lambda: dict(data or {}))
def set(self, data, merge=False):
self.store[self.key] = {**(self.store.get(self.key) or {}), **data} if merge else dict(data)
def create(self, data):
if self.key in self.store:
raise gcloud_exceptions.Conflict("exists")
self.store[self.key] = dict(data)
def update(self, data):
self.store[self.key].update(data)
class FakeDB:
def __init__(self):
self.store = {}
def collection(self, name):
return SimpleNamespace(document=lambda doc_id: FakeDoc(self.store, (name, doc_id)))
def _item(cid, text="can you make Paper Moons by The Lanterns?", published="2026-10-21T12:00:00Z"):
return {"id": f"t-{cid}", "snippet": {"videoId": "vid1", "totalReplyCount": 0, "topLevelComment": {
"id": cid, "snippet": {"authorDisplayName": "Viewer", "authorChannelId": {"value": "UCviewer"},
"textOriginal": text, "publishedAt": published}}}, "replies": {"comments": []}}
class FakeYouTube:
def __init__(self, items):
self.items = items
self.inserted = []
self._kw = {}
def commentThreads(self):
return self
def comments(self):
return self
def list(self, **kw):
self._kw = kw
return self
def insert(self, **kw):
self.inserted.append(kw["body"]["snippet"])
self._kw = {"insert": True}
return self
def execute(self):
if self._kw.get("insert"):
return {"id": f"reply{len(self.inserted)}"}
return {"items": self.items}
class FakeBoard:
def __init__(self, *a):
self.added = []
def canonicalize(self, artist, title):
return artist, title
def find_open_or_published(self, artist, title):
return None
def add_from_comment(self, artist, title, thread):
self.added.append(thread.comment_id)
return bot.BoardMatch(f"r-{thread.comment_id}", artist, title, "open")
@pytest.fixture
def env(monkeypatch):
settings = SimpleNamespace(
youtube_comment_autoreply_enabled=True, youtube_comment_autoreply_max_replies=20,
youtube_comment_autoreply_min_confidence=0.8, youtube_comment_autoreply_start="2026-10-01",
get_secret=lambda name: json.dumps({"refresh_token": "x", "scopes": SCOPES})
if name == w.CREDENTIALS_SECRET else None,
)
db = FakeDB()
yt = FakeYouTube([_item("c1"), _item("c2", text="love this")])
quota = MagicMock()
quota.check_quota_available.return_value = (True, 9000, "")
boards = []
def make_board(service):
b = FakeBoard()
boards.append(b)
return b
responses = {"can you make Paper Moons by The Lanterns?": REQUEST, "love this": NOT_REQUEST}
def gen(system_prompt, user_prompt, schema):
return responses[user_prompt.split("Comment: ", 1)[1]]
monkeypatch.setattr(w, "get_settings", lambda: settings)
monkeypatch.setattr(w, "get_firestore_client", lambda: db)
monkeypatch.setattr(w, "get_youtube_quota_service", lambda: quota)
monkeypatch.setattr(w.ytb, "build_youtube", lambda creds: yt)
monkeypatch.setattr(w, "_channel_index", lambda db, youtube: bot.ChannelIndex())
monkeypatch.setattr(w, "ServiceBoard", make_board)
monkeypatch.setattr(w, "DryRunBoard", make_board)
monkeypatch.setattr(w.bot, "gemini_generate", lambda: gen)
monkeypatch.setattr(w, "_post_noise", MagicMock())
monkeypatch.setattr(w, "_alert", MagicMock())
with patch("backend.services.song_request_service.SongRequestService"):
yield SimpleNamespace(settings=settings, db=db, yt=yt, quota=quota, boards=boards)
def _actions(db):
return {k[1]: v for k, v in db.store.items() if k[0] == w.ACTIONS_COLLECTION}
def test_disabled_does_nothing(env):
env.settings.youtube_comment_autoreply_enabled = False
assert w.run_comment_bot_sync() == {"status": "disabled"}
assert env.yt.inserted == []
def test_replies_once_and_records_actions(env):
summary = w.run_comment_bot_sync()
assert summary["replied"] == 1 and summary["skipped"] == {"not_a_request": 1}
assert len(env.yt.inserted) == 1 and env.yt.inserted[0]["parentId"] == "c1"
assert "request=r-c1" in env.yt.inserted[0]["textOriginal"]
acts = _actions(env.db)
assert acts["c1"]["action"] == "replied" and acts["c1"]["reply_id"] == "reply1"
assert acts["c2"]["action"] == "skip"
env.quota.record_upload.assert_called_once_with("comment-reply:c1", units=w.REPLY_COST)
w._post_noise.assert_called_once()
def test_second_run_never_double_replies(env):
w.run_comment_bot_sync()
w.run_comment_bot_sync()
assert len(env.yt.inserted) == 1
def test_concurrent_claim_skips_post(env):
env.db.store[(w.ACTIONS_COLLECTION, "c1")] = {"action": "replying"}
w.run_comment_bot_sync()
assert env.yt.inserted == []
def test_dry_run_writes_and_posts_nothing_even_when_disabled(env):
env.settings.youtube_comment_autoreply_enabled = False
summary = w.run_comment_bot_sync(dry_run=True)
assert summary["actions"][0]["comment_id"] == "c1"
assert env.yt.inserted == [] and env.db.store == {}
def test_go_live_start_fixed_on_first_run_and_old_comments_ignored(env):
env.yt.items = [_item("old", published="2026-09-01T00:00:00Z")]
summary = w.run_comment_bot_sync()
assert summary["replied"] == 0 and env.yt.inserted == []
state = env.db.store[(w.STATE_COLLECTION, w.STATE_DOC)]
assert state["go_live_at"] == datetime(2026, 10, 1, tzinfo=timezone.utc)
def test_max_replies_cap_leaves_rest_for_next_run(env):
env.yt.items = [_item("c1"), _item("c3", published="2026-10-21T11:00:00Z")]
summary = w.run_comment_bot_sync(max_replies=1)
assert summary["replied"] == 1 and "c3" not in _actions(env.db)
assert env.boards[-1].added == ["c1"] # nothing classified/added past the cap
state = env.db.store[(w.STATE_COLLECTION, w.STATE_DOC)]
assert state["incomplete"] and state["high_water"] == datetime(2026, 10, 1, tzinfo=timezone.utc)
summary = w.run_comment_bot_sync(max_replies=1) # next run picks up the rest
assert summary["replied"] == 1 and _actions(env.db)["c3"]["action"] == "replied"
assert not env.db.store[(w.STATE_COLLECTION, w.STATE_DOC)]["incomplete"]
def test_quota_exhausted_stops_without_posting(env):
env.quota.check_quota_available.return_value = (False, 10, "low")
w.run_comment_bot_sync()
assert env.yt.inserted == [] and "c1" not in _actions(env.db)
def test_missing_scope_alerts_and_stops(env):
env.settings.get_secret = lambda name: json.dumps({"scopes": SCOPES[:1]})
assert w.run_comment_bot_sync()["status"] == "missing_scope"
w._alert.assert_called_once()
def test_post_failure_marks_and_alerts(env):
def boom(**kw):
raise RuntimeError("403 forbidden")
env.yt.insert = boom
summary = w.run_comment_bot_sync()
assert summary["errors"] == 1 and _actions(env.db)["c1"]["action"] == "reply_failed"
w._alert.assert_called_once()
def test_classifier_error_is_retried_next_run(env):
def flaky(system_prompt, user_prompt, schema):
raise RuntimeError("503 UNAVAILABLE")
with patch.object(w.bot, "gemini_generate", lambda: flaky):
summary = w.run_comment_bot_sync()
assert summary["skipped"] == {"classifier_error": 2} and _actions(env.db) == {}
state = env.db.store[(w.STATE_COLLECTION, w.STATE_DOC)]
assert state["high_water"] <= datetime(2026, 10, 21, 12, tzinfo=timezone.utc)
summary = w.run_comment_bot_sync() # Gemini back: replies now
assert summary["replied"] == 1
def test_configured_start_parsing():
s = SimpleNamespace(youtube_comment_autoreply_start="2026-04-22")
assert w._configured_start(s) == datetime(2026, 4, 22, tzinfo=timezone.utc)
assert w._configured_start(SimpleNamespace(youtube_comment_autoreply_start="")) is None
assert w._configured_start(SimpleNamespace(youtube_comment_autoreply_start="nope")) is None
def test_post_noise_disables_discord_mentions(monkeypatch):
sent = []
monkeypatch.setattr(w.requests, "post", lambda url, json, timeout: sent.append(json) or SimpleNamespace(ok=True))
w._post_noise(SimpleNamespace(get_secret=lambda name: "https://discord.test/hook"), "@everyone hi")
assert sent[0]["allowed_mentions"] == {"parse": []}
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "خطأ في إنشاء بيانات الشكل الموجي: {error}",
"waveformNoAudio": "لا يوجد صوت متاح للشكل الموجي",
"sessionSaveError": "بيانات التصحيح مطلوبة",
"invalidIsDuetFlag": "يجب أن يكون is_duet قيمة منطقية (true أو false)"
"invalidIsDuetFlag": "يجب أن يكون is_duet قيمة منطقية (true أو false)",
"previewMissingTimings": "يحتوي السطر \"{line}\" على كلمة بلا توقيت. قم بمزامنة هذا السطر، ثم حاول المعاينة مرة أخرى."
},
"audioSearch": {
"notEnabled": "البحث الصوتي غير مفعل لهذا المستأجر",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "Error en generar les dades de la forma d'ona: {error}",
"waveformNoAudio": "No hi ha àudio disponible per a la forma d'ona",
"sessionSaveError": "Es requereixen dades de correcció",
"invalidIsDuetFlag": "is_duet ha de ser un booleà (cert o fals)"
"invalidIsDuetFlag": "is_duet ha de ser un booleà (cert o fals)",
"previewMissingTimings": "La línia \"{line}\" té una paraula sense temporització. Sincronitza aquesta línia i torna a provar la previsualització."
},
"audioSearch": {
"notEnabled": "La cerca d'àudio no està activada per a aquest tenant",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "Chyba při generování dat křivky: {error}",
"waveformNoAudio": "Pro křivku není k dispozici žádný zvuk",
"sessionSaveError": "Jsou vyžadována data oprav",
"invalidIsDuetFlag": "is_duet musí být typu boolean (true nebo false)"
"invalidIsDuetFlag": "is_duet musí být typu boolean (true nebo false)",
"previewMissingTimings": "Řádek „{line}“ obsahuje slovo bez časování. Synchronizuj tento řádek a zkus náhled znovu."
},
"audioSearch": {
"notEnabled": "Vyhledávání zvuku není pro tohoto tenanta povoleno",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "Fejl ved generering af bølgeformsdata: {error}",
"waveformNoAudio": "Ingen lyd tilgængelig til bølgeform",
"sessionSaveError": "Rettelsesdata er påkrævet",
"invalidIsDuetFlag": "is_duet skal være en boolsk værdi (sand eller falsk)"
"invalidIsDuetFlag": "is_duet skal være en boolsk værdi (sand eller falsk)",
"previewMissingTimings": "Linjen \"{line}\" har et ord uden timing. Synkroniser den linje, og prøv derefter forhåndsvisningen igen."
},
"audioSearch": {
"notEnabled": "Lydsøgning er ikke aktiveret for denne lejer",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "Fehler beim Generieren der Wellenform-Daten: {error}",
"waveformNoAudio": "Kein Audio für Wellenform verfügbar",
"sessionSaveError": "Korrekturdaten sind erforderlich",
"invalidIsDuetFlag": "is_duet muss ein Boolean sein (true oder false)"
"invalidIsDuetFlag": "is_duet muss ein Boolean sein (true oder false)",
"previewMissingTimings": "Die Zeile \"{line}\" enthält ein Wort ohne Timing. Synchronisiere diese Zeile und versuche die Vorschau dann erneut."
},
"audioSearch": {
"notEnabled": "Die Audiosuche ist für diesen Mandanten nicht aktiviert",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "Σφάλμα κατά τη δημιουργία δεδομένων κυματομορφής: {error}",
"waveformNoAudio": "Δεν υπάρχει διαθέσιμος ήχος για την κυματομορφή",
"sessionSaveError": "Απαιτούνται δεδομένα διόρθωσης",
"invalidIsDuetFlag": "Το is_duet πρέπει να είναι boolean (true ή false)"
"invalidIsDuetFlag": "Το is_duet πρέπει να είναι boolean (true ή false)",
"previewMissingTimings": "Η γραμμή «{line}» περιέχει μια λέξη χωρίς συγχρονισμό. Συγχρόνισε αυτή τη γραμμή και δοκίμασε ξανά την προεπισκόπηση."
},
"audioSearch": {
"notEnabled": "Η αναζήτηση ήχου δεν είναι ενεργοποιημένη για αυτόν τον μισθωτή",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "Error generating waveform data: {error}",
"waveformNoAudio": "No audio available for waveform",
"sessionSaveError": "Correction data is required",
"invalidIsDuetFlag": "is_duet must be a boolean (true or false)"
"invalidIsDuetFlag": "is_duet must be a boolean (true or false)",
"previewMissingTimings": "The line \"{line}\" has a word with no timing. Sync that line, then try the preview again."
},
"audioSearch": {
"notEnabled": "Audio search is not enabled for this tenant",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "Error al generar los datos de la forma de onda: {error}",
"waveformNoAudio": "No hay audio disponible para la forma de onda",
"sessionSaveError": "Se requieren datos de corrección",
"invalidIsDuetFlag": "is_duet debe ser un booleano (true o false)"
"invalidIsDuetFlag": "is_duet debe ser un booleano (true o false)",
"previewMissingTimings": "La línea \"{line}\" tiene una palabra sin sincronizar. Sincroniza esa línea y vuelve a intentar la vista previa."
},
"audioSearch": {
"notEnabled": "La búsqueda de audio no está habilitada para este inquilino",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "Virhe luotaessa aaltomuotodataa: {error}",
"waveformNoAudio": "Ääntä ei ole saatavilla aaltomuotoa varten",
"sessionSaveError": "Korjaustiedot vaaditaan",
"invalidIsDuetFlag": "is_duet täytyy olla totuusarvo (true tai false)"
"invalidIsDuetFlag": "is_duet täytyy olla totuusarvo (true tai false)",
"previewMissingTimings": "Rivillä \"{line}\" on sana, jolla ei ole ajoitusta. Synkronoi kyseinen rivi ja yritä esikatselua uudelleen."
},
"audioSearch": {
"notEnabled": "Äänihaku ei ole käytössä tälle asiakkaalle",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "Erreur lors de la génération des données de forme d'onde : {error}",
"waveformNoAudio": "Aucun audio disponible pour la forme d'onde",
"sessionSaveError": "Les données de correction sont requises",
"invalidIsDuetFlag": "is_duet doit être un booléen (true ou false)"
"invalidIsDuetFlag": "is_duet doit être un booléen (true ou false)",
"previewMissingTimings": "La ligne « {line} » contient un mot sans synchronisation. Synchronise cette ligne, puis réessaie l'aperçu."
},
"audioSearch": {
"notEnabled": "La recherche audio n'est pas activée pour ce compte",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "שגיאה ביצירת נתוני גל הקול: {error}",
"waveformNoAudio": "אין אודיו זמין עבור גל הקול",
"sessionSaveError": "נדרשים נתוני תיקון",
"invalidIsDuetFlag": "is_duet חייב להיות ערך בוליאני (true או false)"
"invalidIsDuetFlag": "is_duet חייב להיות ערך בוליאני (true או false)",
"previewMissingTimings": "בשורה \"{line}\" יש מילה ללא תזמון. סנכרנו את השורה הזו ונסו שוב את התצוגה המקדימה."
},
"audioSearch": {
"notEnabled": "חיפוש אודיו אינו מופעל עבור חשבון זה",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "वेवफ़ॉर्म डेटा जनरेट करने में त्रुटि: {error}",
"waveformNoAudio": "वेवफ़ॉर्म के लिए कोई ऑडियो उपलब्ध नहीं है",
"sessionSaveError": "करेक्शन डेटा आवश्यक है",
"invalidIsDuetFlag": "is_duet एक boolean (true या false) होना चाहिए"
"invalidIsDuetFlag": "is_duet एक boolean (true या false) होना चाहिए",
"previewMissingTimings": "पंक्ति \"{line}\" में एक ऐसा शब्द है जिसकी टाइमिंग नहीं है। उस पंक्ति को सिंक करो, फिर प्रीव्यू दोबारा आज़माओ।"
},
"audioSearch": {
"notEnabled": "इस टेनेंट के लिए ऑडियो सर्च सक्षम नहीं है",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "Pogreška pri generiranju podataka valnog oblika: {error}",
"waveformNoAudio": "Nema dostupnog zvuka za valni oblik",
"sessionSaveError": "Podaci o ispravcima su obavezni",
"invalidIsDuetFlag": "is_duet mora biti boolean (true ili false)"
"invalidIsDuetFlag": "is_duet mora biti boolean (true ili false)",
"previewMissingTimings": "Redak \"{line}\" sadrži riječ bez vremenskog označavanja. Sinkroniziraj taj redak, a zatim ponovno pokušaj pregled."
},
"audioSearch": {
"notEnabled": "Pretraživanje zvuka nije omogućeno za ovog zakupca",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "Hiba a hullámforma adatok generálásakor: {error}",
"waveformNoAudio": "Nincs elérhető hang a hullámformához",
"sessionSaveError": "Javítási adatok szükségesek",
"invalidIsDuetFlag": "Az is_duet értékének logikai (boolean) típusúnak kell lennie (true vagy false)"
"invalidIsDuetFlag": "Az is_duet értékének logikai (boolean) típusúnak kell lennie (true vagy false)",
"previewMissingTimings": "A(z) „{line}” sorban van egy időzítés nélküli szó. Szinkronizáld azt a sort, majd próbáld újra az előnézetet."
},
"audioSearch": {
"notEnabled": "A hangkeresés nincs engedélyezve ehhez a bérlőhöz",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "Kesalahan saat membuat data bentuk gelombang: {error}",
"waveformNoAudio": "Tidak ada audio yang tersedia untuk bentuk gelombang",
"sessionSaveError": "Data koreksi diperlukan",
"invalidIsDuetFlag": "is_duet harus berupa boolean (true atau false)"
"invalidIsDuetFlag": "is_duet harus berupa boolean (true atau false)",
"previewMissingTimings": "Baris \"{line}\" memiliki kata tanpa waktu. Sinkronkan baris tersebut, lalu coba pratinjau lagi."
},
"audioSearch": {
"notEnabled": "Pencarian audio tidak diaktifkan untuk tenant ini",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "Errore durante la generazione dei dati della forma d'onda: {error}",
"waveformNoAudio": "Nessun audio disponibile per la forma d'onda",
"sessionSaveError": "I dati di correzione sono richiesti",
"invalidIsDuetFlag": "is_duet deve essere un booleano (true o false)"
"invalidIsDuetFlag": "is_duet deve essere un booleano (true o false)",
"previewMissingTimings": "La riga \"{line}\" contiene una parola senza tempo. Sincronizza quella riga, poi riprova l'anteprima."
},
"audioSearch": {
"notEnabled": "La ricerca audio non è abilitata per questo tenant",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "波形データの生成中にエラーが発生しました: {error}",
"waveformNoAudio": "波形用のオーディオがありません",
"sessionSaveError": "修正データが必要です",
"invalidIsDuetFlag": "is_duet はブール値 (true または false) である必要があります"
"invalidIsDuetFlag": "is_duet はブール値 (true または false) である必要があります",
"previewMissingTimings": "「{line}」の行にタイミングが設定されていない単語があります。その行を同期してから、もう一度プレビューしてください。"
},
"audioSearch": {
"notEnabled": "このテナントではオーディオ検索が有効になっていません",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "파형 데이터 생성 중 오류 발생: {error}",
"waveformNoAudio": "파형에 사용할 오디오가 없습니다",
"sessionSaveError": "수정 데이터가 필요합니다",
"invalidIsDuetFlag": "is_duet은 불리언(true 또는 false)이어야 합니다."
"invalidIsDuetFlag": "is_duet은 불리언(true 또는 false)이어야 합니다.",
"previewMissingTimings": "\"{line}\" 줄에 타이밍이 없는 단어가 있습니다. 해당 줄을 동기화한 후 미리보기를 다시 시도해 주세요."
},
"audioSearch": {
"notEnabled": "이 테넌트에서는 오디오 검색이 활성화되어 있지 않습니다",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "Ralat menjana data bentuk gelombang: {error}",
"waveformNoAudio": "Tiada audio tersedia untuk bentuk gelombang",
"sessionSaveError": "Data pembetulan diperlukan",
"invalidIsDuetFlag": "is_duet mestilah boolean (benar atau salah)"
"invalidIsDuetFlag": "is_duet mestilah boolean (benar atau salah)",
"previewMissingTimings": "Baris \"{line}\" mempunyai perkataan tanpa pemasaan. Segerakkan baris itu, kemudian cuba pratonton semula."
},
"audioSearch": {
"notEnabled": "Carian audio tidak didayakan untuk penyewa ini",
+2 -1
View File
@@ -81,7 +81,8 @@
"waveformGenerationError": "Feil ved generering av bølgeformdata: {error}",
"waveformNoAudio": "Ingen lyd tilgjengelig for bølgeform",
"sessionSaveError": "Korreksjonsdata er påkrevd",
"invalidIsDuetFlag": "is_duet må være en boolean (true eller false)"
"invalidIsDuetFlag": "is_duet må være en boolean (true eller false)",
"previewMissingTimings": "Linjen «{line}» har et ord uten timing. Synkroniser den linjen, og prøv forhåndsvisningen på nytt."
},
"audioSearch": {
"notEnabled": "Lydsøk er ikke aktivert for denne kontoen",
Loaded 100 of 219 files, more files were not shown because too many files have changed in this diff. Show more